blob: 93ae6f1c44b53cdd884a7f4c848e20da106a86f9 [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;
519 bool hadMacroDefinition = Bits & 0x01;
520 Bits >>= 1;
521
522 assert(Bits == 0 && "Extra bits in the identifier?");
523 DataLen -= 8;
524
525 // Build the IdentifierInfo itself and link the identifier ID with
526 // the new IdentifierInfo.
527 IdentifierInfo *II = KnownII;
528 if (!II) {
Douglas Gregor479633c2013-01-23 18:53:14 +0000529 II = &Reader.getIdentifierTable().getOwn(StringRef(k));
Guy Benyei7f92f2d2012-12-18 14:30:41 +0000530 KnownII = II;
531 }
532 Reader.markIdentifierUpToDate(II);
Douglas Gregorf4e955b2013-02-11 18:16:18 +0000533 if (!II->isFromAST()) {
534 bool WasInteresting = isInterestingIdentifier(*II);
535 II->setIsFromAST();
536 if (WasInteresting)
537 II->setChangedSinceDeserialization();
538 }
Guy Benyei7f92f2d2012-12-18 14:30:41 +0000539
540 // Set or check the various bits in the IdentifierInfo structure.
541 // Token IDs are read-only.
Argyrios Kyrtzidis1ebefc72013-02-27 01:13:51 +0000542 if (HasRevertedTokenIDToIdentifier && II->getTokenID() != tok::identifier)
Guy Benyei7f92f2d2012-12-18 14:30:41 +0000543 II->RevertTokenIDToIdentifier();
544 II->setObjCOrBuiltinID(ObjCOrBuiltinID);
545 assert(II->isExtensionToken() == ExtensionToken &&
546 "Incorrect extension token flag");
547 (void)ExtensionToken;
548 if (Poisoned)
549 II->setIsPoisoned(true);
550 assert(II->isCPlusPlusOperatorKeyword() == CPlusPlusOperatorKeyword &&
551 "Incorrect C++ operator keyword flag");
552 (void)CPlusPlusOperatorKeyword;
553
554 // If this identifier is a macro, deserialize the macro
555 // definition.
556 if (hadMacroDefinition) {
Argyrios Kyrtzidisdc1088f2013-01-19 03:14:56 +0000557 SmallVector<MacroID, 4> MacroIDs;
558 while (uint32_t LocalID = ReadUnalignedLE32(d)) {
559 MacroIDs.push_back(Reader.getGlobalMacroID(F, LocalID));
560 DataLen -= 4;
561 }
Guy Benyei7f92f2d2012-12-18 14:30:41 +0000562 DataLen -= 4;
Argyrios Kyrtzidisdc1088f2013-01-19 03:14:56 +0000563 Reader.setIdentifierIsMacro(II, MacroIDs);
Guy Benyei7f92f2d2012-12-18 14:30:41 +0000564 }
565
566 Reader.SetIdentifierInfo(ID, II);
567
568 // Read all of the declarations visible at global scope with this
569 // name.
570 if (DataLen > 0) {
571 SmallVector<uint32_t, 4> DeclIDs;
572 for (; DataLen > 0; DataLen -= 4)
573 DeclIDs.push_back(Reader.getGlobalDeclID(F, ReadUnalignedLE32(d)));
574 Reader.SetGloballyVisibleDecls(II, DeclIDs);
575 }
576
577 return II;
578}
579
580unsigned
581ASTDeclContextNameLookupTrait::ComputeHash(const DeclNameKey &Key) const {
582 llvm::FoldingSetNodeID ID;
583 ID.AddInteger(Key.Kind);
584
585 switch (Key.Kind) {
586 case DeclarationName::Identifier:
587 case DeclarationName::CXXLiteralOperatorName:
588 ID.AddString(((IdentifierInfo*)Key.Data)->getName());
589 break;
590 case DeclarationName::ObjCZeroArgSelector:
591 case DeclarationName::ObjCOneArgSelector:
592 case DeclarationName::ObjCMultiArgSelector:
593 ID.AddInteger(serialization::ComputeHash(Selector(Key.Data)));
594 break;
595 case DeclarationName::CXXOperatorName:
596 ID.AddInteger((OverloadedOperatorKind)Key.Data);
597 break;
598 case DeclarationName::CXXConstructorName:
599 case DeclarationName::CXXDestructorName:
600 case DeclarationName::CXXConversionFunctionName:
601 case DeclarationName::CXXUsingDirective:
602 break;
603 }
604
605 return ID.ComputeHash();
606}
607
608ASTDeclContextNameLookupTrait::internal_key_type
609ASTDeclContextNameLookupTrait::GetInternalKey(
610 const external_key_type& Name) const {
611 DeclNameKey Key;
612 Key.Kind = Name.getNameKind();
613 switch (Name.getNameKind()) {
614 case DeclarationName::Identifier:
615 Key.Data = (uint64_t)Name.getAsIdentifierInfo();
616 break;
617 case DeclarationName::ObjCZeroArgSelector:
618 case DeclarationName::ObjCOneArgSelector:
619 case DeclarationName::ObjCMultiArgSelector:
620 Key.Data = (uint64_t)Name.getObjCSelector().getAsOpaquePtr();
621 break;
622 case DeclarationName::CXXOperatorName:
623 Key.Data = Name.getCXXOverloadedOperator();
624 break;
625 case DeclarationName::CXXLiteralOperatorName:
626 Key.Data = (uint64_t)Name.getCXXLiteralIdentifier();
627 break;
628 case DeclarationName::CXXConstructorName:
629 case DeclarationName::CXXDestructorName:
630 case DeclarationName::CXXConversionFunctionName:
631 case DeclarationName::CXXUsingDirective:
632 Key.Data = 0;
633 break;
634 }
635
636 return Key;
637}
638
639std::pair<unsigned, unsigned>
640ASTDeclContextNameLookupTrait::ReadKeyDataLength(const unsigned char*& d) {
641 using namespace clang::io;
642 unsigned KeyLen = ReadUnalignedLE16(d);
643 unsigned DataLen = ReadUnalignedLE16(d);
644 return std::make_pair(KeyLen, DataLen);
645}
646
647ASTDeclContextNameLookupTrait::internal_key_type
648ASTDeclContextNameLookupTrait::ReadKey(const unsigned char* d, unsigned) {
649 using namespace clang::io;
650
651 DeclNameKey Key;
652 Key.Kind = (DeclarationName::NameKind)*d++;
653 switch (Key.Kind) {
654 case DeclarationName::Identifier:
655 Key.Data = (uint64_t)Reader.getLocalIdentifier(F, ReadUnalignedLE32(d));
656 break;
657 case DeclarationName::ObjCZeroArgSelector:
658 case DeclarationName::ObjCOneArgSelector:
659 case DeclarationName::ObjCMultiArgSelector:
660 Key.Data =
661 (uint64_t)Reader.getLocalSelector(F, ReadUnalignedLE32(d))
662 .getAsOpaquePtr();
663 break;
664 case DeclarationName::CXXOperatorName:
665 Key.Data = *d++; // OverloadedOperatorKind
666 break;
667 case DeclarationName::CXXLiteralOperatorName:
668 Key.Data = (uint64_t)Reader.getLocalIdentifier(F, ReadUnalignedLE32(d));
669 break;
670 case DeclarationName::CXXConstructorName:
671 case DeclarationName::CXXDestructorName:
672 case DeclarationName::CXXConversionFunctionName:
673 case DeclarationName::CXXUsingDirective:
674 Key.Data = 0;
675 break;
676 }
677
678 return Key;
679}
680
681ASTDeclContextNameLookupTrait::data_type
682ASTDeclContextNameLookupTrait::ReadData(internal_key_type,
683 const unsigned char* d,
684 unsigned DataLen) {
685 using namespace clang::io;
686 unsigned NumDecls = ReadUnalignedLE16(d);
Argyrios Kyrtzidise8b61cf2013-01-11 22:29:49 +0000687 LE32DeclID *Start = reinterpret_cast<LE32DeclID *>(
688 const_cast<unsigned char *>(d));
Guy Benyei7f92f2d2012-12-18 14:30:41 +0000689 return std::make_pair(Start, Start + NumDecls);
690}
691
692bool ASTReader::ReadDeclContextStorage(ModuleFile &M,
Chris Lattner8f9a1eb2013-01-20 00:56:42 +0000693 BitstreamCursor &Cursor,
Guy Benyei7f92f2d2012-12-18 14:30:41 +0000694 const std::pair<uint64_t, uint64_t> &Offsets,
695 DeclContextInfo &Info) {
696 SavedStreamPosition SavedPosition(Cursor);
697 // First the lexical decls.
698 if (Offsets.first != 0) {
699 Cursor.JumpToBit(Offsets.first);
700
701 RecordData Record;
Chris Lattnerb3ce3572013-01-20 02:38:54 +0000702 StringRef Blob;
Guy Benyei7f92f2d2012-12-18 14:30:41 +0000703 unsigned Code = Cursor.ReadCode();
Chris Lattnerb3ce3572013-01-20 02:38:54 +0000704 unsigned RecCode = Cursor.readRecord(Code, Record, &Blob);
Guy Benyei7f92f2d2012-12-18 14:30:41 +0000705 if (RecCode != DECL_CONTEXT_LEXICAL) {
706 Error("Expected lexical block");
707 return true;
708 }
709
Chris Lattnerb3ce3572013-01-20 02:38:54 +0000710 Info.LexicalDecls = reinterpret_cast<const KindDeclIDPair*>(Blob.data());
711 Info.NumLexicalDecls = Blob.size() / sizeof(KindDeclIDPair);
Guy Benyei7f92f2d2012-12-18 14:30:41 +0000712 }
713
714 // Now the lookup table.
715 if (Offsets.second != 0) {
716 Cursor.JumpToBit(Offsets.second);
717
718 RecordData Record;
Chris Lattnerb3ce3572013-01-20 02:38:54 +0000719 StringRef Blob;
Guy Benyei7f92f2d2012-12-18 14:30:41 +0000720 unsigned Code = Cursor.ReadCode();
Chris Lattnerb3ce3572013-01-20 02:38:54 +0000721 unsigned RecCode = Cursor.readRecord(Code, Record, &Blob);
Guy Benyei7f92f2d2012-12-18 14:30:41 +0000722 if (RecCode != DECL_CONTEXT_VISIBLE) {
723 Error("Expected visible lookup table block");
724 return true;
725 }
726 Info.NameLookupTableData
727 = ASTDeclContextNameLookupTable::Create(
Chris Lattnerb3ce3572013-01-20 02:38:54 +0000728 (const unsigned char *)Blob.data() + Record[0],
729 (const unsigned char *)Blob.data(),
Guy Benyei7f92f2d2012-12-18 14:30:41 +0000730 ASTDeclContextNameLookupTrait(*this, M));
731 }
732
733 return false;
734}
735
736void ASTReader::Error(StringRef Msg) {
737 Error(diag::err_fe_pch_malformed, Msg);
738}
739
740void ASTReader::Error(unsigned DiagID,
741 StringRef Arg1, StringRef Arg2) {
742 if (Diags.isDiagnosticInFlight())
743 Diags.SetDelayedDiagnostic(DiagID, Arg1, Arg2);
744 else
745 Diag(DiagID) << Arg1 << Arg2;
746}
747
748//===----------------------------------------------------------------------===//
749// Source Manager Deserialization
750//===----------------------------------------------------------------------===//
751
752/// \brief Read the line table in the source manager block.
753/// \returns true if there was an error.
754bool ASTReader::ParseLineTable(ModuleFile &F,
755 SmallVectorImpl<uint64_t> &Record) {
756 unsigned Idx = 0;
757 LineTableInfo &LineTable = SourceMgr.getLineTable();
758
759 // Parse the file names
760 std::map<int, int> FileIDs;
761 for (int I = 0, N = Record[Idx++]; I != N; ++I) {
762 // Extract the file name
763 unsigned FilenameLen = Record[Idx++];
764 std::string Filename(&Record[Idx], &Record[Idx] + FilenameLen);
765 Idx += FilenameLen;
766 MaybeAddSystemRootToFilename(F, Filename);
767 FileIDs[I] = LineTable.getLineTableFilenameID(Filename);
768 }
769
770 // Parse the line entries
771 std::vector<LineEntry> Entries;
772 while (Idx < Record.size()) {
773 int FID = Record[Idx++];
774 assert(FID >= 0 && "Serialized line entries for non-local file.");
775 // Remap FileID from 1-based old view.
776 FID += F.SLocEntryBaseID - 1;
777
778 // Extract the line entries
779 unsigned NumEntries = Record[Idx++];
780 assert(NumEntries && "Numentries is 00000");
781 Entries.clear();
782 Entries.reserve(NumEntries);
783 for (unsigned I = 0; I != NumEntries; ++I) {
784 unsigned FileOffset = Record[Idx++];
785 unsigned LineNo = Record[Idx++];
786 int FilenameID = FileIDs[Record[Idx++]];
787 SrcMgr::CharacteristicKind FileKind
788 = (SrcMgr::CharacteristicKind)Record[Idx++];
789 unsigned IncludeOffset = Record[Idx++];
790 Entries.push_back(LineEntry::get(FileOffset, LineNo, FilenameID,
791 FileKind, IncludeOffset));
792 }
793 LineTable.AddEntry(FileID::get(FID), Entries);
794 }
795
796 return false;
797}
798
799/// \brief Read a source manager block
800bool ASTReader::ReadSourceManagerBlock(ModuleFile &F) {
801 using namespace SrcMgr;
802
Chris Lattner8f9a1eb2013-01-20 00:56:42 +0000803 BitstreamCursor &SLocEntryCursor = F.SLocEntryCursor;
Guy Benyei7f92f2d2012-12-18 14:30:41 +0000804
805 // Set the source-location entry cursor to the current position in
806 // the stream. This cursor will be used to read the contents of the
807 // source manager block initially, and then lazily read
808 // source-location entries as needed.
809 SLocEntryCursor = F.Stream;
810
811 // The stream itself is going to skip over the source manager block.
812 if (F.Stream.SkipBlock()) {
813 Error("malformed block record in AST file");
814 return true;
815 }
816
817 // Enter the source manager block.
818 if (SLocEntryCursor.EnterSubBlock(SOURCE_MANAGER_BLOCK_ID)) {
819 Error("malformed source manager block record in AST file");
820 return true;
821 }
822
823 RecordData Record;
824 while (true) {
Chris Lattner88bde502013-01-19 21:39:22 +0000825 llvm::BitstreamEntry E = SLocEntryCursor.advanceSkippingSubblocks();
826
827 switch (E.Kind) {
828 case llvm::BitstreamEntry::SubBlock: // Handled for us already.
829 case llvm::BitstreamEntry::Error:
830 Error("malformed block record in AST file");
831 return true;
832 case llvm::BitstreamEntry::EndBlock:
Guy Benyei7f92f2d2012-12-18 14:30:41 +0000833 return false;
Chris Lattner88bde502013-01-19 21:39:22 +0000834 case llvm::BitstreamEntry::Record:
835 // The interesting case.
836 break;
Guy Benyei7f92f2d2012-12-18 14:30:41 +0000837 }
Chris Lattner88bde502013-01-19 21:39:22 +0000838
Guy Benyei7f92f2d2012-12-18 14:30:41 +0000839 // Read a record.
Guy Benyei7f92f2d2012-12-18 14:30:41 +0000840 Record.clear();
Chris Lattner125eb3e2013-01-21 18:28:26 +0000841 StringRef Blob;
842 switch (SLocEntryCursor.readRecord(E.ID, Record, &Blob)) {
Guy Benyei7f92f2d2012-12-18 14:30:41 +0000843 default: // Default behavior: ignore.
844 break;
845
846 case SM_SLOC_FILE_ENTRY:
847 case SM_SLOC_BUFFER_ENTRY:
848 case SM_SLOC_EXPANSION_ENTRY:
849 // Once we hit one of the source location entries, we're done.
850 return false;
851 }
852 }
853}
854
855/// \brief If a header file is not found at the path that we expect it to be
856/// and the PCH file was moved from its original location, try to resolve the
857/// file by assuming that header+PCH were moved together and the header is in
858/// the same place relative to the PCH.
859static std::string
860resolveFileRelativeToOriginalDir(const std::string &Filename,
861 const std::string &OriginalDir,
862 const std::string &CurrDir) {
863 assert(OriginalDir != CurrDir &&
864 "No point trying to resolve the file if the PCH dir didn't change");
865 using namespace llvm::sys;
866 SmallString<128> filePath(Filename);
867 fs::make_absolute(filePath);
868 assert(path::is_absolute(OriginalDir));
869 SmallString<128> currPCHPath(CurrDir);
870
871 path::const_iterator fileDirI = path::begin(path::parent_path(filePath)),
872 fileDirE = path::end(path::parent_path(filePath));
873 path::const_iterator origDirI = path::begin(OriginalDir),
874 origDirE = path::end(OriginalDir);
875 // Skip the common path components from filePath and OriginalDir.
876 while (fileDirI != fileDirE && origDirI != origDirE &&
877 *fileDirI == *origDirI) {
878 ++fileDirI;
879 ++origDirI;
880 }
881 for (; origDirI != origDirE; ++origDirI)
882 path::append(currPCHPath, "..");
883 path::append(currPCHPath, fileDirI, fileDirE);
884 path::append(currPCHPath, path::filename(Filename));
885 return currPCHPath.str();
886}
887
888bool ASTReader::ReadSLocEntry(int ID) {
889 if (ID == 0)
890 return false;
891
892 if (unsigned(-ID) - 2 >= getTotalNumSLocs() || ID > 0) {
893 Error("source location entry ID out-of-range for AST file");
894 return true;
895 }
896
897 ModuleFile *F = GlobalSLocEntryMap.find(-ID)->second;
898 F->SLocEntryCursor.JumpToBit(F->SLocEntryOffsets[ID - F->SLocEntryBaseID]);
Chris Lattner8f9a1eb2013-01-20 00:56:42 +0000899 BitstreamCursor &SLocEntryCursor = F->SLocEntryCursor;
Guy Benyei7f92f2d2012-12-18 14:30:41 +0000900 unsigned BaseOffset = F->SLocEntryBaseOffset;
901
902 ++NumSLocEntriesRead;
Chris Lattner88bde502013-01-19 21:39:22 +0000903 llvm::BitstreamEntry Entry = SLocEntryCursor.advance();
904 if (Entry.Kind != llvm::BitstreamEntry::Record) {
Guy Benyei7f92f2d2012-12-18 14:30:41 +0000905 Error("incorrectly-formatted source location entry in AST file");
906 return true;
907 }
Chris Lattner88bde502013-01-19 21:39:22 +0000908
Guy Benyei7f92f2d2012-12-18 14:30:41 +0000909 RecordData Record;
Chris Lattnerb3ce3572013-01-20 02:38:54 +0000910 StringRef Blob;
911 switch (SLocEntryCursor.readRecord(Entry.ID, Record, &Blob)) {
Guy Benyei7f92f2d2012-12-18 14:30:41 +0000912 default:
913 Error("incorrectly-formatted source location entry in AST file");
914 return true;
915
916 case SM_SLOC_FILE_ENTRY: {
917 // We will detect whether a file changed and return 'Failure' for it, but
918 // we will also try to fail gracefully by setting up the SLocEntry.
919 unsigned InputID = Record[4];
920 InputFile IF = getInputFile(*F, InputID);
Argyrios Kyrtzidis8504b7b2013-03-01 03:26:04 +0000921 const FileEntry *File = IF.getFile();
922 bool OverriddenBuffer = IF.isOverridden();
Guy Benyei7f92f2d2012-12-18 14:30:41 +0000923
Argyrios Kyrtzidis8504b7b2013-03-01 03:26:04 +0000924 // Note that we only check if a File was returned. If it was out-of-date
925 // we have complained but we will continue creating a FileID to recover
926 // gracefully.
927 if (!File)
Guy Benyei7f92f2d2012-12-18 14:30:41 +0000928 return true;
929
930 SourceLocation IncludeLoc = ReadSourceLocation(*F, Record[1]);
931 if (IncludeLoc.isInvalid() && F->Kind != MK_MainFile) {
932 // This is the module's main file.
933 IncludeLoc = getImportLocation(F);
934 }
935 SrcMgr::CharacteristicKind
936 FileCharacter = (SrcMgr::CharacteristicKind)Record[2];
937 FileID FID = SourceMgr.createFileID(File, IncludeLoc, FileCharacter,
938 ID, BaseOffset + Record[0]);
939 SrcMgr::FileInfo &FileInfo =
940 const_cast<SrcMgr::FileInfo&>(SourceMgr.getSLocEntry(FID).getFile());
941 FileInfo.NumCreatedFIDs = Record[5];
942 if (Record[3])
943 FileInfo.setHasLineDirectives();
944
945 const DeclID *FirstDecl = F->FileSortedDecls + Record[6];
946 unsigned NumFileDecls = Record[7];
947 if (NumFileDecls) {
948 assert(F->FileSortedDecls && "FILE_SORTED_DECLS not encountered yet ?");
949 FileDeclIDs[FID] = FileDeclsInfo(F, llvm::makeArrayRef(FirstDecl,
950 NumFileDecls));
951 }
952
953 const SrcMgr::ContentCache *ContentCache
954 = SourceMgr.getOrCreateContentCache(File,
955 /*isSystemFile=*/FileCharacter != SrcMgr::C_User);
956 if (OverriddenBuffer && !ContentCache->BufferOverridden &&
957 ContentCache->ContentsEntry == ContentCache->OrigEntry) {
958 unsigned Code = SLocEntryCursor.ReadCode();
959 Record.clear();
Chris Lattnerb3ce3572013-01-20 02:38:54 +0000960 unsigned RecCode = SLocEntryCursor.readRecord(Code, Record, &Blob);
Guy Benyei7f92f2d2012-12-18 14:30:41 +0000961
962 if (RecCode != SM_SLOC_BUFFER_BLOB) {
963 Error("AST record has invalid code");
964 return true;
965 }
966
967 llvm::MemoryBuffer *Buffer
Chris Lattnerb3ce3572013-01-20 02:38:54 +0000968 = llvm::MemoryBuffer::getMemBuffer(Blob.drop_back(1), File->getName());
Guy Benyei7f92f2d2012-12-18 14:30:41 +0000969 SourceMgr.overrideFileContents(File, Buffer);
970 }
971
972 break;
973 }
974
975 case SM_SLOC_BUFFER_ENTRY: {
Chris Lattnerb3ce3572013-01-20 02:38:54 +0000976 const char *Name = Blob.data();
Guy Benyei7f92f2d2012-12-18 14:30:41 +0000977 unsigned Offset = Record[0];
978 SrcMgr::CharacteristicKind
979 FileCharacter = (SrcMgr::CharacteristicKind)Record[2];
980 SourceLocation IncludeLoc = ReadSourceLocation(*F, Record[1]);
981 if (IncludeLoc.isInvalid() && F->Kind == MK_Module) {
982 IncludeLoc = getImportLocation(F);
983 }
984 unsigned Code = SLocEntryCursor.ReadCode();
985 Record.clear();
986 unsigned RecCode
Chris Lattnerb3ce3572013-01-20 02:38:54 +0000987 = SLocEntryCursor.readRecord(Code, Record, &Blob);
Guy Benyei7f92f2d2012-12-18 14:30:41 +0000988
989 if (RecCode != SM_SLOC_BUFFER_BLOB) {
990 Error("AST record has invalid code");
991 return true;
992 }
993
994 llvm::MemoryBuffer *Buffer
Chris Lattnerb3ce3572013-01-20 02:38:54 +0000995 = llvm::MemoryBuffer::getMemBuffer(Blob.drop_back(1), Name);
Guy Benyei7f92f2d2012-12-18 14:30:41 +0000996 SourceMgr.createFileIDForMemBuffer(Buffer, FileCharacter, ID,
997 BaseOffset + Offset, IncludeLoc);
998 break;
999 }
1000
1001 case SM_SLOC_EXPANSION_ENTRY: {
1002 SourceLocation SpellingLoc = ReadSourceLocation(*F, Record[1]);
1003 SourceMgr.createExpansionLoc(SpellingLoc,
1004 ReadSourceLocation(*F, Record[2]),
1005 ReadSourceLocation(*F, Record[3]),
1006 Record[4],
1007 ID,
1008 BaseOffset + Record[0]);
1009 break;
1010 }
1011 }
1012
1013 return false;
1014}
1015
1016std::pair<SourceLocation, StringRef> ASTReader::getModuleImportLoc(int ID) {
1017 if (ID == 0)
1018 return std::make_pair(SourceLocation(), "");
1019
1020 if (unsigned(-ID) - 2 >= getTotalNumSLocs() || ID > 0) {
1021 Error("source location entry ID out-of-range for AST file");
1022 return std::make_pair(SourceLocation(), "");
1023 }
1024
1025 // Find which module file this entry lands in.
1026 ModuleFile *M = GlobalSLocEntryMap.find(-ID)->second;
1027 if (M->Kind != MK_Module)
1028 return std::make_pair(SourceLocation(), "");
1029
1030 // FIXME: Can we map this down to a particular submodule? That would be
1031 // ideal.
1032 return std::make_pair(M->ImportLoc, llvm::sys::path::stem(M->FileName));
1033}
1034
1035/// \brief Find the location where the module F is imported.
1036SourceLocation ASTReader::getImportLocation(ModuleFile *F) {
1037 if (F->ImportLoc.isValid())
1038 return F->ImportLoc;
1039
1040 // Otherwise we have a PCH. It's considered to be "imported" at the first
1041 // location of its includer.
1042 if (F->ImportedBy.empty() || !F->ImportedBy[0]) {
1043 // Main file is the importer. We assume that it is the first entry in the
1044 // entry table. We can't ask the manager, because at the time of PCH loading
1045 // the main file entry doesn't exist yet.
1046 // The very first entry is the invalid instantiation loc, which takes up
1047 // offsets 0 and 1.
1048 return SourceLocation::getFromRawEncoding(2U);
1049 }
1050 //return F->Loaders[0]->FirstLoc;
1051 return F->ImportedBy[0]->FirstLoc;
1052}
1053
1054/// ReadBlockAbbrevs - Enter a subblock of the specified BlockID with the
1055/// specified cursor. Read the abbreviations that are at the top of the block
1056/// and then leave the cursor pointing into the block.
Chris Lattner8f9a1eb2013-01-20 00:56:42 +00001057bool ASTReader::ReadBlockAbbrevs(BitstreamCursor &Cursor, unsigned BlockID) {
Guy Benyei7f92f2d2012-12-18 14:30:41 +00001058 if (Cursor.EnterSubBlock(BlockID)) {
1059 Error("malformed block record in AST file");
1060 return Failure;
1061 }
1062
1063 while (true) {
1064 uint64_t Offset = Cursor.GetCurrentBitNo();
1065 unsigned Code = Cursor.ReadCode();
1066
1067 // We expect all abbrevs to be at the start of the block.
1068 if (Code != llvm::bitc::DEFINE_ABBREV) {
1069 Cursor.JumpToBit(Offset);
1070 return false;
1071 }
1072 Cursor.ReadAbbrevRecord();
1073 }
1074}
1075
Argyrios Kyrtzidisdc1088f2013-01-19 03:14:56 +00001076void ASTReader::ReadMacroRecord(ModuleFile &F, uint64_t Offset,
Argyrios Kyrtzidis9818a1d2013-02-20 00:54:57 +00001077 MacroDirective *Hint) {
Chris Lattner8f9a1eb2013-01-20 00:56:42 +00001078 BitstreamCursor &Stream = F.MacroCursor;
Guy Benyei7f92f2d2012-12-18 14:30:41 +00001079
1080 // Keep track of where we are in the stream, then jump back there
1081 // after reading this macro.
1082 SavedStreamPosition SavedPosition(Stream);
1083
1084 Stream.JumpToBit(Offset);
1085 RecordData Record;
1086 SmallVector<IdentifierInfo*, 16> MacroArgs;
1087 MacroInfo *Macro = 0;
1088
Douglas Gregord3b036e2013-01-18 04:34:14 +00001089 // RAII object to add the loaded macro information once we're done
1090 // adding tokens.
1091 struct AddLoadedMacroInfoRAII {
1092 Preprocessor &PP;
Argyrios Kyrtzidis9818a1d2013-02-20 00:54:57 +00001093 MacroDirective *Hint;
1094 MacroDirective *MD;
Douglas Gregord3b036e2013-01-18 04:34:14 +00001095 IdentifierInfo *II;
1096
Argyrios Kyrtzidis9818a1d2013-02-20 00:54:57 +00001097 AddLoadedMacroInfoRAII(Preprocessor &PP, MacroDirective *Hint)
1098 : PP(PP), Hint(Hint), MD(), II() { }
Douglas Gregord3b036e2013-01-18 04:34:14 +00001099 ~AddLoadedMacroInfoRAII( ) {
Argyrios Kyrtzidis9818a1d2013-02-20 00:54:57 +00001100 if (MD) {
Douglas Gregord3b036e2013-01-18 04:34:14 +00001101 // Finally, install the macro.
Argyrios Kyrtzidis9818a1d2013-02-20 00:54:57 +00001102 PP.addLoadedMacroInfo(II, MD, Hint);
Douglas Gregord3b036e2013-01-18 04:34:14 +00001103 }
1104 }
Argyrios Kyrtzidisdc1088f2013-01-19 03:14:56 +00001105 } AddLoadedMacroInfo(PP, Hint);
Douglas Gregord3b036e2013-01-18 04:34:14 +00001106
Guy Benyei7f92f2d2012-12-18 14:30:41 +00001107 while (true) {
Chris Lattner99a5af02013-01-20 00:00:22 +00001108 // Advance to the next record, but if we get to the end of the block, don't
1109 // pop it (removing all the abbreviations from the cursor) since we want to
1110 // be able to reseek within the block and read entries.
Chris Lattner8f9a1eb2013-01-20 00:56:42 +00001111 unsigned Flags = BitstreamCursor::AF_DontPopBlockAtEnd;
Chris Lattner99a5af02013-01-20 00:00:22 +00001112 llvm::BitstreamEntry Entry = Stream.advanceSkippingSubblocks(Flags);
1113
1114 switch (Entry.Kind) {
1115 case llvm::BitstreamEntry::SubBlock: // Handled for us already.
1116 case llvm::BitstreamEntry::Error:
1117 Error("malformed block record in AST file");
Guy Benyei7f92f2d2012-12-18 14:30:41 +00001118 return;
Chris Lattner99a5af02013-01-20 00:00:22 +00001119 case llvm::BitstreamEntry::EndBlock:
1120 return;
1121 case llvm::BitstreamEntry::Record:
1122 // The interesting case.
1123 break;
Guy Benyei7f92f2d2012-12-18 14:30:41 +00001124 }
1125
1126 // Read a record.
Guy Benyei7f92f2d2012-12-18 14:30:41 +00001127 Record.clear();
1128 PreprocessorRecordTypes RecType =
Chris Lattnerb3ce3572013-01-20 02:38:54 +00001129 (PreprocessorRecordTypes)Stream.readRecord(Entry.ID, Record);
Guy Benyei7f92f2d2012-12-18 14:30:41 +00001130 switch (RecType) {
1131 case PP_MACRO_OBJECT_LIKE:
1132 case PP_MACRO_FUNCTION_LIKE: {
1133 // If we already have a macro, that means that we've hit the end
1134 // of the definition of the macro we were looking for. We're
1135 // done.
1136 if (Macro)
1137 return;
1138
1139 IdentifierInfo *II = getLocalIdentifier(F, Record[0]);
1140 if (II == 0) {
1141 Error("macro must have a name in AST file");
1142 return;
1143 }
1144
1145 unsigned GlobalID = getGlobalMacroID(F, Record[1]);
1146
1147 // If this macro has already been loaded, don't do so again.
1148 if (MacrosLoaded[GlobalID - NUM_PREDEF_MACRO_IDS])
1149 return;
1150
1151 SubmoduleID GlobalSubmoduleID = getGlobalSubmoduleID(F, Record[2]);
1152 unsigned NextIndex = 3;
1153 SourceLocation Loc = ReadSourceLocation(F, Record, NextIndex);
1154 MacroInfo *MI = PP.AllocateMacroInfo(Loc);
Argyrios Kyrtzidis9818a1d2013-02-20 00:54:57 +00001155 // FIXME: Location should be import location in case of module.
1156 MacroDirective *MD = PP.AllocateMacroDirective(MI, Loc,
1157 /*isImported=*/true);
Argyrios Kyrtzidis8169b672013-01-07 19:16:23 +00001158 MI->setDefinitionEndLoc(ReadSourceLocation(F, Record, NextIndex));
Guy Benyei7f92f2d2012-12-18 14:30:41 +00001159
1160 // Record this macro.
Argyrios Kyrtzidis9818a1d2013-02-20 00:54:57 +00001161 MacrosLoaded[GlobalID - NUM_PREDEF_MACRO_IDS] = MD;
Guy Benyei7f92f2d2012-12-18 14:30:41 +00001162
1163 SourceLocation UndefLoc = ReadSourceLocation(F, Record, NextIndex);
1164 if (UndefLoc.isValid())
Argyrios Kyrtzidis9818a1d2013-02-20 00:54:57 +00001165 MD->setUndefLoc(UndefLoc);
Guy Benyei7f92f2d2012-12-18 14:30:41 +00001166
1167 MI->setIsUsed(Record[NextIndex++]);
Guy Benyei7f92f2d2012-12-18 14:30:41 +00001168
1169 bool IsPublic = Record[NextIndex++];
Argyrios Kyrtzidis9818a1d2013-02-20 00:54:57 +00001170 MD->setVisibility(IsPublic, ReadSourceLocation(F, Record, NextIndex));
Guy Benyei7f92f2d2012-12-18 14:30:41 +00001171
1172 if (RecType == PP_MACRO_FUNCTION_LIKE) {
1173 // Decode function-like macro info.
1174 bool isC99VarArgs = Record[NextIndex++];
1175 bool isGNUVarArgs = Record[NextIndex++];
1176 bool hasCommaPasting = Record[NextIndex++];
1177 MacroArgs.clear();
1178 unsigned NumArgs = Record[NextIndex++];
1179 for (unsigned i = 0; i != NumArgs; ++i)
1180 MacroArgs.push_back(getLocalIdentifier(F, Record[NextIndex++]));
1181
1182 // Install function-like macro info.
1183 MI->setIsFunctionLike();
1184 if (isC99VarArgs) MI->setIsC99Varargs();
1185 if (isGNUVarArgs) MI->setIsGNUVarargs();
1186 if (hasCommaPasting) MI->setHasCommaPasting();
1187 MI->setArgumentList(MacroArgs.data(), MacroArgs.size(),
1188 PP.getPreprocessorAllocator());
1189 }
1190
1191 if (DeserializationListener)
Argyrios Kyrtzidis9818a1d2013-02-20 00:54:57 +00001192 DeserializationListener->MacroRead(GlobalID, MD);
Guy Benyei7f92f2d2012-12-18 14:30:41 +00001193
1194 // If an update record marked this as undefined, do so now.
1195 // FIXME: Only if the submodule this update came from is visible?
1196 MacroUpdatesMap::iterator Update = MacroUpdates.find(GlobalID);
1197 if (Update != MacroUpdates.end()) {
Argyrios Kyrtzidis9818a1d2013-02-20 00:54:57 +00001198 if (MD->getUndefLoc().isInvalid()) {
Guy Benyei7f92f2d2012-12-18 14:30:41 +00001199 for (unsigned I = 0, N = Update->second.size(); I != N; ++I) {
1200 bool Hidden = false;
1201 if (unsigned SubmoduleID = Update->second[I].first) {
1202 if (Module *Owner = getSubmodule(SubmoduleID)) {
1203 if (Owner->NameVisibility == Module::Hidden) {
1204 // Note that this #undef is hidden.
1205 Hidden = true;
1206
1207 // Record this hiding for later.
1208 HiddenNamesMap[Owner].push_back(
Argyrios Kyrtzidis9818a1d2013-02-20 00:54:57 +00001209 HiddenName(II, MD, Update->second[I].second.UndefLoc));
Guy Benyei7f92f2d2012-12-18 14:30:41 +00001210 }
1211 }
1212 }
1213
1214 if (!Hidden) {
Argyrios Kyrtzidis9818a1d2013-02-20 00:54:57 +00001215 MD->setUndefLoc(Update->second[I].second.UndefLoc);
Guy Benyei7f92f2d2012-12-18 14:30:41 +00001216 if (PPMutationListener *Listener = PP.getPPMutationListener())
Argyrios Kyrtzidis9818a1d2013-02-20 00:54:57 +00001217 Listener->UndefinedMacro(MD);
Guy Benyei7f92f2d2012-12-18 14:30:41 +00001218 break;
1219 }
1220 }
1221 }
1222 MacroUpdates.erase(Update);
1223 }
1224
1225 // Determine whether this macro definition is visible.
Argyrios Kyrtzidis9818a1d2013-02-20 00:54:57 +00001226 bool Hidden = !MD->isPublic();
Guy Benyei7f92f2d2012-12-18 14:30:41 +00001227 if (!Hidden && GlobalSubmoduleID) {
1228 if (Module *Owner = getSubmodule(GlobalSubmoduleID)) {
1229 if (Owner->NameVisibility == Module::Hidden) {
1230 // The owning module is not visible, and this macro definition
1231 // should not be, either.
1232 Hidden = true;
1233
1234 // Note that this macro definition was hidden because its owning
1235 // module is not yet visible.
Argyrios Kyrtzidis9818a1d2013-02-20 00:54:57 +00001236 HiddenNamesMap[Owner].push_back(HiddenName(II, MD));
Guy Benyei7f92f2d2012-12-18 14:30:41 +00001237 }
1238 }
1239 }
Argyrios Kyrtzidis9818a1d2013-02-20 00:54:57 +00001240 MD->setHidden(Hidden);
Guy Benyei7f92f2d2012-12-18 14:30:41 +00001241
Argyrios Kyrtzidisdc1088f2013-01-19 03:14:56 +00001242 // Make sure we install the macro once we're done.
Argyrios Kyrtzidis9818a1d2013-02-20 00:54:57 +00001243 AddLoadedMacroInfo.MD = MD;
Argyrios Kyrtzidisdc1088f2013-01-19 03:14:56 +00001244 AddLoadedMacroInfo.II = II;
Douglas Gregord3b036e2013-01-18 04:34:14 +00001245
Guy Benyei7f92f2d2012-12-18 14:30:41 +00001246 // Remember that we saw this macro last so that we add the tokens that
1247 // form its body to it.
1248 Macro = MI;
1249
1250 if (NextIndex + 1 == Record.size() && PP.getPreprocessingRecord() &&
1251 Record[NextIndex]) {
1252 // We have a macro definition. Register the association
1253 PreprocessedEntityID
1254 GlobalID = getGlobalPreprocessedEntityID(F, Record[NextIndex]);
1255 PreprocessingRecord &PPRec = *PP.getPreprocessingRecord();
Argyrios Kyrtzidis0b849d32013-02-22 18:35:59 +00001256 PreprocessingRecord::PPEntityID
1257 PPID = PPRec.getPPEntityID(GlobalID-1, /*isLoaded=*/true);
1258 MacroDefinition *PPDef =
1259 cast_or_null<MacroDefinition>(PPRec.getPreprocessedEntity(PPID));
1260 if (PPDef)
1261 PPRec.RegisterMacroDefinition(Macro, PPDef);
Guy Benyei7f92f2d2012-12-18 14:30:41 +00001262 }
1263
1264 ++NumMacrosRead;
1265 break;
1266 }
1267
1268 case PP_TOKEN: {
1269 // If we see a TOKEN before a PP_MACRO_*, then the file is
1270 // erroneous, just pretend we didn't see this.
1271 if (Macro == 0) break;
1272
1273 Token Tok;
1274 Tok.startToken();
1275 Tok.setLocation(ReadSourceLocation(F, Record[0]));
1276 Tok.setLength(Record[1]);
1277 if (IdentifierInfo *II = getLocalIdentifier(F, Record[2]))
1278 Tok.setIdentifierInfo(II);
1279 Tok.setKind((tok::TokenKind)Record[3]);
1280 Tok.setFlag((Token::TokenFlags)Record[4]);
1281 Macro->AddTokenToBody(Tok);
1282 break;
1283 }
1284 }
1285 }
1286}
1287
1288PreprocessedEntityID
1289ASTReader::getGlobalPreprocessedEntityID(ModuleFile &M, unsigned LocalID) const {
1290 ContinuousRangeMap<uint32_t, int, 2>::const_iterator
1291 I = M.PreprocessedEntityRemap.find(LocalID - NUM_PREDEF_PP_ENTITY_IDS);
1292 assert(I != M.PreprocessedEntityRemap.end()
1293 && "Invalid index into preprocessed entity index remap");
1294
1295 return LocalID + I->second;
1296}
1297
Argyrios Kyrtzidised3802e2013-03-06 18:12:47 +00001298unsigned HeaderFileInfoTrait::ComputeHash(internal_key_ref ikey) {
1299 return llvm::hash_combine(ikey.Size, ikey.ModTime);
Guy Benyei7f92f2d2012-12-18 14:30:41 +00001300}
1301
1302HeaderFileInfoTrait::internal_key_type
Argyrios Kyrtzidised3802e2013-03-06 18:12:47 +00001303HeaderFileInfoTrait::GetInternalKey(const FileEntry *FE) {
1304 internal_key_type ikey = { FE->getSize(), FE->getModificationTime(),
1305 FE->getName() };
1306 return ikey;
1307}
Guy Benyei7f92f2d2012-12-18 14:30:41 +00001308
Argyrios Kyrtzidised3802e2013-03-06 18:12:47 +00001309bool HeaderFileInfoTrait::EqualKey(internal_key_ref a, internal_key_ref b) {
1310 if (a.Size != b.Size || a.ModTime != b.ModTime)
Guy Benyei7f92f2d2012-12-18 14:30:41 +00001311 return false;
1312
Argyrios Kyrtzidised3802e2013-03-06 18:12:47 +00001313 if (strcmp(a.Filename, b.Filename) == 0)
1314 return true;
1315
Guy Benyei7f92f2d2012-12-18 14:30:41 +00001316 // Determine whether the actual files are equivalent.
Argyrios Kyrtzidis1c1508b2013-03-04 20:33:40 +00001317 FileManager &FileMgr = Reader.getFileManager();
Argyrios Kyrtzidised3802e2013-03-06 18:12:47 +00001318 const FileEntry *FEA = FileMgr.getFile(a.Filename);
1319 const FileEntry *FEB = FileMgr.getFile(b.Filename);
Argyrios Kyrtzidis1c1508b2013-03-04 20:33:40 +00001320 return (FEA && FEA == FEB);
Guy Benyei7f92f2d2012-12-18 14:30:41 +00001321}
1322
1323std::pair<unsigned, unsigned>
1324HeaderFileInfoTrait::ReadKeyDataLength(const unsigned char*& d) {
1325 unsigned KeyLen = (unsigned) clang::io::ReadUnalignedLE16(d);
1326 unsigned DataLen = (unsigned) *d++;
Argyrios Kyrtzidised3802e2013-03-06 18:12:47 +00001327 return std::make_pair(KeyLen, DataLen);
Guy Benyei7f92f2d2012-12-18 14:30:41 +00001328}
Argyrios Kyrtzidised3802e2013-03-06 18:12:47 +00001329
1330HeaderFileInfoTrait::internal_key_type
1331HeaderFileInfoTrait::ReadKey(const unsigned char *d, unsigned) {
1332 internal_key_type ikey;
1333 ikey.Size = off_t(clang::io::ReadUnalignedLE64(d));
1334 ikey.ModTime = time_t(clang::io::ReadUnalignedLE64(d));
1335 ikey.Filename = (const char *)d;
1336 return ikey;
1337}
1338
Guy Benyei7f92f2d2012-12-18 14:30:41 +00001339HeaderFileInfoTrait::data_type
Argyrios Kyrtzidised3802e2013-03-06 18:12:47 +00001340HeaderFileInfoTrait::ReadData(internal_key_ref, const unsigned char *d,
Guy Benyei7f92f2d2012-12-18 14:30:41 +00001341 unsigned DataLen) {
1342 const unsigned char *End = d + DataLen;
1343 using namespace clang::io;
1344 HeaderFileInfo HFI;
1345 unsigned Flags = *d++;
1346 HFI.isImport = (Flags >> 5) & 0x01;
1347 HFI.isPragmaOnce = (Flags >> 4) & 0x01;
1348 HFI.DirInfo = (Flags >> 2) & 0x03;
1349 HFI.Resolved = (Flags >> 1) & 0x01;
1350 HFI.IndexHeaderMapHeader = Flags & 0x01;
1351 HFI.NumIncludes = ReadUnalignedLE16(d);
1352 HFI.ControllingMacroID = Reader.getGlobalIdentifierID(M,
1353 ReadUnalignedLE32(d));
1354 if (unsigned FrameworkOffset = ReadUnalignedLE32(d)) {
1355 // The framework offset is 1 greater than the actual offset,
1356 // since 0 is used as an indicator for "no framework name".
1357 StringRef FrameworkName(FrameworkStrings + FrameworkOffset - 1);
1358 HFI.Framework = HS->getUniqueFrameworkName(FrameworkName);
1359 }
1360
1361 assert(End == d && "Wrong data length in HeaderFileInfo deserialization");
1362 (void)End;
1363
1364 // This HeaderFileInfo was externally loaded.
1365 HFI.External = true;
1366 return HFI;
1367}
1368
Argyrios Kyrtzidisdc1088f2013-01-19 03:14:56 +00001369void ASTReader::setIdentifierIsMacro(IdentifierInfo *II, ArrayRef<MacroID> IDs){
Guy Benyei7f92f2d2012-12-18 14:30:41 +00001370 II->setHadMacroDefinition(true);
1371 assert(NumCurrentElementsDeserializing > 0 &&"Missing deserialization guard");
Argyrios Kyrtzidisdc1088f2013-01-19 03:14:56 +00001372 PendingMacroIDs[II].append(IDs.begin(), IDs.end());
Guy Benyei7f92f2d2012-12-18 14:30:41 +00001373}
1374
1375void ASTReader::ReadDefinedMacros() {
1376 // Note that we are loading defined macros.
1377 Deserializing Macros(this);
1378
1379 for (ModuleReverseIterator I = ModuleMgr.rbegin(),
1380 E = ModuleMgr.rend(); I != E; ++I) {
Chris Lattner8f9a1eb2013-01-20 00:56:42 +00001381 BitstreamCursor &MacroCursor = (*I)->MacroCursor;
Guy Benyei7f92f2d2012-12-18 14:30:41 +00001382
1383 // If there was no preprocessor block, skip this file.
1384 if (!MacroCursor.getBitStreamReader())
1385 continue;
1386
Chris Lattner8f9a1eb2013-01-20 00:56:42 +00001387 BitstreamCursor Cursor = MacroCursor;
Guy Benyei7f92f2d2012-12-18 14:30:41 +00001388 Cursor.JumpToBit((*I)->MacroStartOffset);
1389
1390 RecordData Record;
1391 while (true) {
Chris Lattner88bde502013-01-19 21:39:22 +00001392 llvm::BitstreamEntry E = Cursor.advanceSkippingSubblocks();
1393
1394 switch (E.Kind) {
1395 case llvm::BitstreamEntry::SubBlock: // Handled for us already.
1396 case llvm::BitstreamEntry::Error:
1397 Error("malformed block record in AST file");
1398 return;
1399 case llvm::BitstreamEntry::EndBlock:
1400 goto NextCursor;
1401
1402 case llvm::BitstreamEntry::Record:
Chris Lattner88bde502013-01-19 21:39:22 +00001403 Record.clear();
Chris Lattnerb3ce3572013-01-20 02:38:54 +00001404 switch (Cursor.readRecord(E.ID, Record)) {
Chris Lattner88bde502013-01-19 21:39:22 +00001405 default: // Default behavior: ignore.
1406 break;
1407
1408 case PP_MACRO_OBJECT_LIKE:
1409 case PP_MACRO_FUNCTION_LIKE:
1410 getLocalIdentifier(**I, Record[0]);
1411 break;
1412
1413 case PP_TOKEN:
1414 // Ignore tokens.
1415 break;
Guy Benyei7f92f2d2012-12-18 14:30:41 +00001416 }
Guy Benyei7f92f2d2012-12-18 14:30:41 +00001417 break;
1418 }
1419 }
Chris Lattner88bde502013-01-19 21:39:22 +00001420 NextCursor: ;
Guy Benyei7f92f2d2012-12-18 14:30:41 +00001421 }
1422}
1423
1424namespace {
1425 /// \brief Visitor class used to look up identifirs in an AST file.
1426 class IdentifierLookupVisitor {
1427 StringRef Name;
1428 unsigned PriorGeneration;
Douglas Gregore1698072013-01-25 00:38:33 +00001429 unsigned &NumIdentifierLookups;
1430 unsigned &NumIdentifierLookupHits;
Guy Benyei7f92f2d2012-12-18 14:30:41 +00001431 IdentifierInfo *Found;
Douglas Gregore1698072013-01-25 00:38:33 +00001432
Guy Benyei7f92f2d2012-12-18 14:30:41 +00001433 public:
Douglas Gregore1698072013-01-25 00:38:33 +00001434 IdentifierLookupVisitor(StringRef Name, unsigned PriorGeneration,
1435 unsigned &NumIdentifierLookups,
1436 unsigned &NumIdentifierLookupHits)
Douglas Gregor188bdcd2013-01-25 23:32:03 +00001437 : Name(Name), PriorGeneration(PriorGeneration),
Douglas Gregore1698072013-01-25 00:38:33 +00001438 NumIdentifierLookups(NumIdentifierLookups),
1439 NumIdentifierLookupHits(NumIdentifierLookupHits),
1440 Found()
1441 {
1442 }
Guy Benyei7f92f2d2012-12-18 14:30:41 +00001443
1444 static bool visit(ModuleFile &M, void *UserData) {
1445 IdentifierLookupVisitor *This
1446 = static_cast<IdentifierLookupVisitor *>(UserData);
1447
1448 // If we've already searched this module file, skip it now.
1449 if (M.Generation <= This->PriorGeneration)
1450 return true;
Douglas Gregor1a49d972013-01-25 01:03:03 +00001451
Guy Benyei7f92f2d2012-12-18 14:30:41 +00001452 ASTIdentifierLookupTable *IdTable
1453 = (ASTIdentifierLookupTable *)M.IdentifierLookupTable;
1454 if (!IdTable)
1455 return false;
1456
1457 ASTIdentifierLookupTrait Trait(IdTable->getInfoObj().getReader(),
1458 M, This->Found);
Douglas Gregore1698072013-01-25 00:38:33 +00001459 ++This->NumIdentifierLookups;
1460 ASTIdentifierLookupTable::iterator Pos = IdTable->find(This->Name,&Trait);
Guy Benyei7f92f2d2012-12-18 14:30:41 +00001461 if (Pos == IdTable->end())
1462 return false;
1463
1464 // Dereferencing the iterator has the effect of building the
1465 // IdentifierInfo node and populating it with the various
1466 // declarations it needs.
Douglas Gregore1698072013-01-25 00:38:33 +00001467 ++This->NumIdentifierLookupHits;
Guy Benyei7f92f2d2012-12-18 14:30:41 +00001468 This->Found = *Pos;
1469 return true;
1470 }
1471
1472 // \brief Retrieve the identifier info found within the module
1473 // files.
1474 IdentifierInfo *getIdentifierInfo() const { return Found; }
1475 };
1476}
1477
1478void ASTReader::updateOutOfDateIdentifier(IdentifierInfo &II) {
1479 // Note that we are loading an identifier.
1480 Deserializing AnIdentifier(this);
1481
1482 unsigned PriorGeneration = 0;
1483 if (getContext().getLangOpts().Modules)
1484 PriorGeneration = IdentifierGeneration[&II];
Douglas Gregor1a49d972013-01-25 01:03:03 +00001485
1486 // If there is a global index, look there first to determine which modules
1487 // provably do not have any results for this identifier.
Douglas Gregor188bdcd2013-01-25 23:32:03 +00001488 GlobalModuleIndex::HitSet Hits;
1489 GlobalModuleIndex::HitSet *HitsPtr = 0;
Douglas Gregor1a49d972013-01-25 01:03:03 +00001490 if (!loadGlobalIndex()) {
Douglas Gregor188bdcd2013-01-25 23:32:03 +00001491 if (GlobalIndex->lookupIdentifier(II.getName(), Hits)) {
1492 HitsPtr = &Hits;
Douglas Gregor1a49d972013-01-25 01:03:03 +00001493 }
1494 }
1495
Douglas Gregor188bdcd2013-01-25 23:32:03 +00001496 IdentifierLookupVisitor Visitor(II.getName(), PriorGeneration,
Douglas Gregore1698072013-01-25 00:38:33 +00001497 NumIdentifierLookups,
1498 NumIdentifierLookupHits);
Douglas Gregor188bdcd2013-01-25 23:32:03 +00001499 ModuleMgr.visit(IdentifierLookupVisitor::visit, &Visitor, HitsPtr);
Guy Benyei7f92f2d2012-12-18 14:30:41 +00001500 markIdentifierUpToDate(&II);
1501}
1502
1503void ASTReader::markIdentifierUpToDate(IdentifierInfo *II) {
1504 if (!II)
1505 return;
1506
1507 II->setOutOfDate(false);
1508
1509 // Update the generation for this identifier.
1510 if (getContext().getLangOpts().Modules)
1511 IdentifierGeneration[II] = CurrentGeneration;
1512}
1513
Argyrios Kyrtzidis8504b7b2013-03-01 03:26:04 +00001514InputFile ASTReader::getInputFile(ModuleFile &F, unsigned ID, bool Complain) {
Guy Benyei7f92f2d2012-12-18 14:30:41 +00001515 // If this ID is bogus, just return an empty input file.
1516 if (ID == 0 || ID > F.InputFilesLoaded.size())
1517 return InputFile();
1518
1519 // If we've already loaded this input file, return it.
Argyrios Kyrtzidis8504b7b2013-03-01 03:26:04 +00001520 if (F.InputFilesLoaded[ID-1].getFile())
Guy Benyei7f92f2d2012-12-18 14:30:41 +00001521 return F.InputFilesLoaded[ID-1];
1522
1523 // Go find this input file.
Chris Lattner8f9a1eb2013-01-20 00:56:42 +00001524 BitstreamCursor &Cursor = F.InputFilesCursor;
Guy Benyei7f92f2d2012-12-18 14:30:41 +00001525 SavedStreamPosition SavedPosition(Cursor);
1526 Cursor.JumpToBit(F.InputFileOffsets[ID-1]);
1527
1528 unsigned Code = Cursor.ReadCode();
1529 RecordData Record;
Chris Lattnerb3ce3572013-01-20 02:38:54 +00001530 StringRef Blob;
1531 switch ((InputFileRecordTypes)Cursor.readRecord(Code, Record, &Blob)) {
Guy Benyei7f92f2d2012-12-18 14:30:41 +00001532 case INPUT_FILE: {
1533 unsigned StoredID = Record[0];
1534 assert(ID == StoredID && "Bogus stored ID or offset");
1535 (void)StoredID;
1536 off_t StoredSize = (off_t)Record[1];
1537 time_t StoredTime = (time_t)Record[2];
1538 bool Overridden = (bool)Record[3];
1539
1540 // Get the file entry for this input file.
Chris Lattnerb3ce3572013-01-20 02:38:54 +00001541 StringRef OrigFilename = Blob;
Guy Benyei7f92f2d2012-12-18 14:30:41 +00001542 std::string Filename = OrigFilename;
1543 MaybeAddSystemRootToFilename(F, Filename);
1544 const FileEntry *File
1545 = Overridden? FileMgr.getVirtualFile(Filename, StoredSize, StoredTime)
1546 : FileMgr.getFile(Filename, /*OpenFile=*/false);
1547
1548 // If we didn't find the file, resolve it relative to the
1549 // original directory from which this AST file was created.
1550 if (File == 0 && !F.OriginalDir.empty() && !CurrentDir.empty() &&
1551 F.OriginalDir != CurrentDir) {
1552 std::string Resolved = resolveFileRelativeToOriginalDir(Filename,
1553 F.OriginalDir,
1554 CurrentDir);
1555 if (!Resolved.empty())
1556 File = FileMgr.getFile(Resolved);
1557 }
1558
1559 // For an overridden file, create a virtual file with the stored
1560 // size/timestamp.
1561 if (Overridden && File == 0) {
1562 File = FileMgr.getVirtualFile(Filename, StoredSize, StoredTime);
1563 }
1564
1565 if (File == 0) {
1566 if (Complain) {
1567 std::string ErrorStr = "could not find file '";
1568 ErrorStr += Filename;
1569 ErrorStr += "' referenced by AST file";
1570 Error(ErrorStr.c_str());
1571 }
1572 return InputFile();
1573 }
Argyrios Kyrtzidis8504b7b2013-03-01 03:26:04 +00001574
Guy Benyei7f92f2d2012-12-18 14:30:41 +00001575 // Check if there was a request to override the contents of the file
1576 // that was part of the precompiled header. Overridding such a file
1577 // can lead to problems when lexing using the source locations from the
1578 // PCH.
1579 SourceManager &SM = getSourceManager();
1580 if (!Overridden && SM.isFileOverridden(File)) {
Argyrios Kyrtzidis8504b7b2013-03-01 03:26:04 +00001581 if (Complain)
1582 Error(diag::err_fe_pch_file_overridden, Filename);
Guy Benyei7f92f2d2012-12-18 14:30:41 +00001583 // After emitting the diagnostic, recover by disabling the override so
1584 // that the original file will be used.
1585 SM.disableFileContentsOverride(File);
1586 // The FileEntry is a virtual file entry with the size of the contents
1587 // that would override the original contents. Set it to the original's
1588 // size/time.
1589 FileMgr.modifyFileEntry(const_cast<FileEntry*>(File),
1590 StoredSize, StoredTime);
1591 }
1592
Argyrios Kyrtzidis8504b7b2013-03-01 03:26:04 +00001593 bool IsOutOfDate = false;
Guy Benyei7f92f2d2012-12-18 14:30:41 +00001594
Argyrios Kyrtzidis8504b7b2013-03-01 03:26:04 +00001595 // For an overridden file, there is nothing to validate.
1596 if (!Overridden && (StoredSize != File->getSize()
Guy Benyei7f92f2d2012-12-18 14:30:41 +00001597#if !defined(LLVM_ON_WIN32)
1598 // In our regression testing, the Windows file system seems to
1599 // have inconsistent modification times that sometimes
1600 // erroneously trigger this error-handling path.
1601 || StoredTime != File->getModificationTime()
1602#endif
1603 )) {
1604 if (Complain)
Argyrios Kyrtzidisf8f373f2013-03-08 20:42:38 +00001605 Error(diag::err_fe_pch_file_modified, Filename, F.FileName);
Argyrios Kyrtzidis8504b7b2013-03-01 03:26:04 +00001606 IsOutOfDate = true;
Guy Benyei7f92f2d2012-12-18 14:30:41 +00001607 }
1608
Argyrios Kyrtzidis8504b7b2013-03-01 03:26:04 +00001609 InputFile IF = InputFile(File, Overridden, IsOutOfDate);
1610
1611 // Note that we've loaded this input file.
1612 F.InputFilesLoaded[ID-1] = IF;
1613 return IF;
Guy Benyei7f92f2d2012-12-18 14:30:41 +00001614 }
1615 }
1616
1617 return InputFile();
1618}
1619
1620const FileEntry *ASTReader::getFileEntry(StringRef filenameStrRef) {
1621 ModuleFile &M = ModuleMgr.getPrimaryModule();
1622 std::string Filename = filenameStrRef;
1623 MaybeAddSystemRootToFilename(M, Filename);
1624 const FileEntry *File = FileMgr.getFile(Filename);
1625 if (File == 0 && !M.OriginalDir.empty() && !CurrentDir.empty() &&
1626 M.OriginalDir != CurrentDir) {
1627 std::string resolved = resolveFileRelativeToOriginalDir(Filename,
1628 M.OriginalDir,
1629 CurrentDir);
1630 if (!resolved.empty())
1631 File = FileMgr.getFile(resolved);
1632 }
1633
1634 return File;
1635}
1636
1637/// \brief If we are loading a relocatable PCH file, and the filename is
1638/// not an absolute path, add the system root to the beginning of the file
1639/// name.
1640void ASTReader::MaybeAddSystemRootToFilename(ModuleFile &M,
1641 std::string &Filename) {
1642 // If this is not a relocatable PCH file, there's nothing to do.
1643 if (!M.RelocatablePCH)
1644 return;
1645
1646 if (Filename.empty() || llvm::sys::path::is_absolute(Filename))
1647 return;
1648
1649 if (isysroot.empty()) {
1650 // If no system root was given, default to '/'
1651 Filename.insert(Filename.begin(), '/');
1652 return;
1653 }
1654
1655 unsigned Length = isysroot.size();
1656 if (isysroot[Length - 1] != '/')
1657 Filename.insert(Filename.begin(), '/');
1658
1659 Filename.insert(Filename.begin(), isysroot.begin(), isysroot.end());
1660}
1661
1662ASTReader::ASTReadResult
1663ASTReader::ReadControlBlock(ModuleFile &F,
Dmitri Gribenkocfa88f82013-01-12 19:30:44 +00001664 SmallVectorImpl<ImportedModule> &Loaded,
Guy Benyei7f92f2d2012-12-18 14:30:41 +00001665 unsigned ClientLoadCapabilities) {
Chris Lattner8f9a1eb2013-01-20 00:56:42 +00001666 BitstreamCursor &Stream = F.Stream;
Guy Benyei7f92f2d2012-12-18 14:30:41 +00001667
1668 if (Stream.EnterSubBlock(CONTROL_BLOCK_ID)) {
1669 Error("malformed block record in AST file");
1670 return Failure;
1671 }
1672
1673 // Read all of the records and blocks in the control block.
1674 RecordData Record;
Chris Lattner88bde502013-01-19 21:39:22 +00001675 while (1) {
1676 llvm::BitstreamEntry Entry = Stream.advance();
1677
1678 switch (Entry.Kind) {
1679 case llvm::BitstreamEntry::Error:
1680 Error("malformed block record in AST file");
1681 return Failure;
1682 case llvm::BitstreamEntry::EndBlock:
Argyrios Kyrtzidis398253a2013-03-06 18:12:50 +00001683 // Validate all of the non-system input files.
Guy Benyei7f92f2d2012-12-18 14:30:41 +00001684 if (!DisableValidation) {
1685 bool Complain = (ClientLoadCapabilities & ARR_OutOfDate) == 0;
Argyrios Kyrtzidis398253a2013-03-06 18:12:50 +00001686 // All user input files reside at the index range [0, Record[1]).
1687 // Record is the one from INPUT_FILE_OFFSETS.
1688 for (unsigned I = 0, N = Record[1]; I < N; ++I) {
Argyrios Kyrtzidis8504b7b2013-03-01 03:26:04 +00001689 InputFile IF = getInputFile(F, I+1, Complain);
1690 if (!IF.getFile() || IF.isOutOfDate())
Guy Benyei7f92f2d2012-12-18 14:30:41 +00001691 return OutOfDate;
Argyrios Kyrtzidis8504b7b2013-03-01 03:26:04 +00001692 }
Guy Benyei7f92f2d2012-12-18 14:30:41 +00001693 }
Guy Benyei7f92f2d2012-12-18 14:30:41 +00001694 return Success;
Chris Lattner88bde502013-01-19 21:39:22 +00001695
1696 case llvm::BitstreamEntry::SubBlock:
1697 switch (Entry.ID) {
Guy Benyei7f92f2d2012-12-18 14:30:41 +00001698 case INPUT_FILES_BLOCK_ID:
1699 F.InputFilesCursor = Stream;
1700 if (Stream.SkipBlock() || // Skip with the main cursor
1701 // Read the abbreviations
1702 ReadBlockAbbrevs(F.InputFilesCursor, INPUT_FILES_BLOCK_ID)) {
1703 Error("malformed block record in AST file");
1704 return Failure;
1705 }
1706 continue;
Chris Lattner88bde502013-01-19 21:39:22 +00001707
Guy Benyei7f92f2d2012-12-18 14:30:41 +00001708 default:
Chris Lattner88bde502013-01-19 21:39:22 +00001709 if (Stream.SkipBlock()) {
1710 Error("malformed block record in AST file");
1711 return Failure;
1712 }
1713 continue;
Guy Benyei7f92f2d2012-12-18 14:30:41 +00001714 }
Chris Lattner88bde502013-01-19 21:39:22 +00001715
1716 case llvm::BitstreamEntry::Record:
1717 // The interesting case.
1718 break;
Guy Benyei7f92f2d2012-12-18 14:30:41 +00001719 }
1720
1721 // Read and process a record.
1722 Record.clear();
Chris Lattnerb3ce3572013-01-20 02:38:54 +00001723 StringRef Blob;
1724 switch ((ControlRecordTypes)Stream.readRecord(Entry.ID, Record, &Blob)) {
Guy Benyei7f92f2d2012-12-18 14:30:41 +00001725 case METADATA: {
1726 if (Record[0] != VERSION_MAJOR && !DisableValidation) {
1727 if ((ClientLoadCapabilities & ARR_VersionMismatch) == 0)
1728 Diag(Record[0] < VERSION_MAJOR? diag::warn_pch_version_too_old
1729 : diag::warn_pch_version_too_new);
1730 return VersionMismatch;
1731 }
1732
1733 bool hasErrors = Record[5];
1734 if (hasErrors && !DisableValidation && !AllowASTWithCompilerErrors) {
1735 Diag(diag::err_pch_with_compiler_errors);
1736 return HadErrors;
1737 }
1738
1739 F.RelocatablePCH = Record[4];
1740
1741 const std::string &CurBranch = getClangFullRepositoryVersion();
Chris Lattnerb3ce3572013-01-20 02:38:54 +00001742 StringRef ASTBranch = Blob;
Guy Benyei7f92f2d2012-12-18 14:30:41 +00001743 if (StringRef(CurBranch) != ASTBranch && !DisableValidation) {
1744 if ((ClientLoadCapabilities & ARR_VersionMismatch) == 0)
1745 Diag(diag::warn_pch_different_branch) << ASTBranch << CurBranch;
1746 return VersionMismatch;
1747 }
1748 break;
1749 }
1750
1751 case IMPORTS: {
1752 // Load each of the imported PCH files.
1753 unsigned Idx = 0, N = Record.size();
1754 while (Idx < N) {
1755 // Read information about the AST file.
1756 ModuleKind ImportedKind = (ModuleKind)Record[Idx++];
1757 // The import location will be the local one for now; we will adjust
1758 // all import locations of module imports after the global source
1759 // location info are setup.
1760 SourceLocation ImportLoc =
1761 SourceLocation::getFromRawEncoding(Record[Idx++]);
1762 unsigned Length = Record[Idx++];
1763 SmallString<128> ImportedFile(Record.begin() + Idx,
1764 Record.begin() + Idx + Length);
1765 Idx += Length;
1766
1767 // Load the AST file.
1768 switch(ReadASTCore(ImportedFile, ImportedKind, ImportLoc, &F, Loaded,
1769 ClientLoadCapabilities)) {
1770 case Failure: return Failure;
1771 // If we have to ignore the dependency, we'll have to ignore this too.
1772 case OutOfDate: return OutOfDate;
1773 case VersionMismatch: return VersionMismatch;
1774 case ConfigurationMismatch: return ConfigurationMismatch;
1775 case HadErrors: return HadErrors;
1776 case Success: break;
1777 }
1778 }
1779 break;
1780 }
1781
1782 case LANGUAGE_OPTIONS: {
1783 bool Complain = (ClientLoadCapabilities & ARR_ConfigurationMismatch) == 0;
1784 if (Listener && &F == *ModuleMgr.begin() &&
1785 ParseLanguageOptions(Record, Complain, *Listener) &&
1786 !DisableValidation)
1787 return ConfigurationMismatch;
1788 break;
1789 }
1790
1791 case TARGET_OPTIONS: {
1792 bool Complain = (ClientLoadCapabilities & ARR_ConfigurationMismatch)==0;
1793 if (Listener && &F == *ModuleMgr.begin() &&
1794 ParseTargetOptions(Record, Complain, *Listener) &&
1795 !DisableValidation)
1796 return ConfigurationMismatch;
1797 break;
1798 }
1799
1800 case DIAGNOSTIC_OPTIONS: {
1801 bool Complain = (ClientLoadCapabilities & ARR_ConfigurationMismatch)==0;
1802 if (Listener && &F == *ModuleMgr.begin() &&
1803 ParseDiagnosticOptions(Record, Complain, *Listener) &&
1804 !DisableValidation)
1805 return ConfigurationMismatch;
1806 break;
1807 }
1808
1809 case FILE_SYSTEM_OPTIONS: {
1810 bool Complain = (ClientLoadCapabilities & ARR_ConfigurationMismatch)==0;
1811 if (Listener && &F == *ModuleMgr.begin() &&
1812 ParseFileSystemOptions(Record, Complain, *Listener) &&
1813 !DisableValidation)
1814 return ConfigurationMismatch;
1815 break;
1816 }
1817
1818 case HEADER_SEARCH_OPTIONS: {
1819 bool Complain = (ClientLoadCapabilities & ARR_ConfigurationMismatch)==0;
1820 if (Listener && &F == *ModuleMgr.begin() &&
1821 ParseHeaderSearchOptions(Record, Complain, *Listener) &&
1822 !DisableValidation)
1823 return ConfigurationMismatch;
1824 break;
1825 }
1826
1827 case PREPROCESSOR_OPTIONS: {
1828 bool Complain = (ClientLoadCapabilities & ARR_ConfigurationMismatch)==0;
1829 if (Listener && &F == *ModuleMgr.begin() &&
1830 ParsePreprocessorOptions(Record, Complain, *Listener,
1831 SuggestedPredefines) &&
1832 !DisableValidation)
1833 return ConfigurationMismatch;
1834 break;
1835 }
1836
1837 case ORIGINAL_FILE:
1838 F.OriginalSourceFileID = FileID::get(Record[0]);
Chris Lattnerb3ce3572013-01-20 02:38:54 +00001839 F.ActualOriginalSourceFileName = Blob;
Guy Benyei7f92f2d2012-12-18 14:30:41 +00001840 F.OriginalSourceFileName = F.ActualOriginalSourceFileName;
1841 MaybeAddSystemRootToFilename(F, F.OriginalSourceFileName);
1842 break;
1843
1844 case ORIGINAL_FILE_ID:
1845 F.OriginalSourceFileID = FileID::get(Record[0]);
1846 break;
1847
1848 case ORIGINAL_PCH_DIR:
Chris Lattnerb3ce3572013-01-20 02:38:54 +00001849 F.OriginalDir = Blob;
Guy Benyei7f92f2d2012-12-18 14:30:41 +00001850 break;
1851
1852 case INPUT_FILE_OFFSETS:
Chris Lattnerb3ce3572013-01-20 02:38:54 +00001853 F.InputFileOffsets = (const uint32_t *)Blob.data();
Guy Benyei7f92f2d2012-12-18 14:30:41 +00001854 F.InputFilesLoaded.resize(Record[0]);
1855 break;
1856 }
1857 }
Guy Benyei7f92f2d2012-12-18 14:30:41 +00001858}
1859
1860bool ASTReader::ReadASTBlock(ModuleFile &F) {
Chris Lattner8f9a1eb2013-01-20 00:56:42 +00001861 BitstreamCursor &Stream = F.Stream;
Guy Benyei7f92f2d2012-12-18 14:30:41 +00001862
1863 if (Stream.EnterSubBlock(AST_BLOCK_ID)) {
1864 Error("malformed block record in AST file");
1865 return true;
1866 }
1867
1868 // Read all of the records and blocks for the AST file.
1869 RecordData Record;
Chris Lattner88bde502013-01-19 21:39:22 +00001870 while (1) {
1871 llvm::BitstreamEntry Entry = Stream.advance();
1872
1873 switch (Entry.Kind) {
1874 case llvm::BitstreamEntry::Error:
1875 Error("error at end of module block in AST file");
1876 return true;
1877 case llvm::BitstreamEntry::EndBlock: {
Guy Benyei7f92f2d2012-12-18 14:30:41 +00001878 DeclContext *DC = Context.getTranslationUnitDecl();
1879 if (!DC->hasExternalVisibleStorage() && DC->hasExternalLexicalStorage())
1880 DC->setMustBuildLookupTable();
Chris Lattner88bde502013-01-19 21:39:22 +00001881
Guy Benyei7f92f2d2012-12-18 14:30:41 +00001882 return false;
1883 }
Chris Lattner88bde502013-01-19 21:39:22 +00001884 case llvm::BitstreamEntry::SubBlock:
1885 switch (Entry.ID) {
Guy Benyei7f92f2d2012-12-18 14:30:41 +00001886 case DECLTYPES_BLOCK_ID:
1887 // We lazily load the decls block, but we want to set up the
1888 // DeclsCursor cursor to point into it. Clone our current bitcode
1889 // cursor to it, enter the block and read the abbrevs in that block.
1890 // With the main cursor, we just skip over it.
1891 F.DeclsCursor = Stream;
1892 if (Stream.SkipBlock() || // Skip with the main cursor.
1893 // Read the abbrevs.
1894 ReadBlockAbbrevs(F.DeclsCursor, DECLTYPES_BLOCK_ID)) {
1895 Error("malformed block record in AST file");
1896 return true;
1897 }
1898 break;
Chris Lattner88bde502013-01-19 21:39:22 +00001899
Guy Benyei7f92f2d2012-12-18 14:30:41 +00001900 case DECL_UPDATES_BLOCK_ID:
1901 if (Stream.SkipBlock()) {
1902 Error("malformed block record in AST file");
1903 return true;
1904 }
1905 break;
Chris Lattner88bde502013-01-19 21:39:22 +00001906
Guy Benyei7f92f2d2012-12-18 14:30:41 +00001907 case PREPROCESSOR_BLOCK_ID:
1908 F.MacroCursor = Stream;
1909 if (!PP.getExternalSource())
1910 PP.setExternalSource(this);
Chris Lattner88bde502013-01-19 21:39:22 +00001911
Guy Benyei7f92f2d2012-12-18 14:30:41 +00001912 if (Stream.SkipBlock() ||
1913 ReadBlockAbbrevs(F.MacroCursor, PREPROCESSOR_BLOCK_ID)) {
1914 Error("malformed block record in AST file");
1915 return true;
1916 }
1917 F.MacroStartOffset = F.MacroCursor.GetCurrentBitNo();
1918 break;
Chris Lattner88bde502013-01-19 21:39:22 +00001919
Guy Benyei7f92f2d2012-12-18 14:30:41 +00001920 case PREPROCESSOR_DETAIL_BLOCK_ID:
1921 F.PreprocessorDetailCursor = Stream;
1922 if (Stream.SkipBlock() ||
Chris Lattner88bde502013-01-19 21:39:22 +00001923 ReadBlockAbbrevs(F.PreprocessorDetailCursor,
Guy Benyei7f92f2d2012-12-18 14:30:41 +00001924 PREPROCESSOR_DETAIL_BLOCK_ID)) {
Chris Lattner88bde502013-01-19 21:39:22 +00001925 Error("malformed preprocessor detail record in AST file");
1926 return true;
1927 }
Guy Benyei7f92f2d2012-12-18 14:30:41 +00001928 F.PreprocessorDetailStartOffset
Chris Lattner88bde502013-01-19 21:39:22 +00001929 = F.PreprocessorDetailCursor.GetCurrentBitNo();
1930
Guy Benyei7f92f2d2012-12-18 14:30:41 +00001931 if (!PP.getPreprocessingRecord())
1932 PP.createPreprocessingRecord();
1933 if (!PP.getPreprocessingRecord()->getExternalSource())
1934 PP.getPreprocessingRecord()->SetExternalSource(*this);
1935 break;
1936
1937 case SOURCE_MANAGER_BLOCK_ID:
1938 if (ReadSourceManagerBlock(F))
1939 return true;
1940 break;
Chris Lattner88bde502013-01-19 21:39:22 +00001941
Guy Benyei7f92f2d2012-12-18 14:30:41 +00001942 case SUBMODULE_BLOCK_ID:
1943 if (ReadSubmoduleBlock(F))
1944 return true;
1945 break;
Chris Lattner88bde502013-01-19 21:39:22 +00001946
Guy Benyei7f92f2d2012-12-18 14:30:41 +00001947 case COMMENTS_BLOCK_ID: {
Chris Lattner8f9a1eb2013-01-20 00:56:42 +00001948 BitstreamCursor C = Stream;
Guy Benyei7f92f2d2012-12-18 14:30:41 +00001949 if (Stream.SkipBlock() ||
1950 ReadBlockAbbrevs(C, COMMENTS_BLOCK_ID)) {
1951 Error("malformed comments block in AST file");
1952 return true;
1953 }
1954 CommentsCursors.push_back(std::make_pair(C, &F));
1955 break;
1956 }
Chris Lattner88bde502013-01-19 21:39:22 +00001957
Guy Benyei7f92f2d2012-12-18 14:30:41 +00001958 default:
Chris Lattner88bde502013-01-19 21:39:22 +00001959 if (Stream.SkipBlock()) {
1960 Error("malformed block record in AST file");
1961 return true;
1962 }
1963 break;
Guy Benyei7f92f2d2012-12-18 14:30:41 +00001964 }
1965 continue;
Chris Lattner88bde502013-01-19 21:39:22 +00001966
1967 case llvm::BitstreamEntry::Record:
1968 // The interesting case.
1969 break;
Guy Benyei7f92f2d2012-12-18 14:30:41 +00001970 }
1971
1972 // Read and process a record.
1973 Record.clear();
Chris Lattnerb3ce3572013-01-20 02:38:54 +00001974 StringRef Blob;
1975 switch ((ASTRecordTypes)Stream.readRecord(Entry.ID, Record, &Blob)) {
Guy Benyei7f92f2d2012-12-18 14:30:41 +00001976 default: // Default behavior: ignore.
1977 break;
1978
1979 case TYPE_OFFSET: {
1980 if (F.LocalNumTypes != 0) {
1981 Error("duplicate TYPE_OFFSET record in AST file");
1982 return true;
1983 }
Chris Lattnerb3ce3572013-01-20 02:38:54 +00001984 F.TypeOffsets = (const uint32_t *)Blob.data();
Guy Benyei7f92f2d2012-12-18 14:30:41 +00001985 F.LocalNumTypes = Record[0];
1986 unsigned LocalBaseTypeIndex = Record[1];
1987 F.BaseTypeIndex = getTotalNumTypes();
1988
1989 if (F.LocalNumTypes > 0) {
1990 // Introduce the global -> local mapping for types within this module.
1991 GlobalTypeMap.insert(std::make_pair(getTotalNumTypes(), &F));
1992
1993 // Introduce the local -> global mapping for types within this module.
1994 F.TypeRemap.insertOrReplace(
1995 std::make_pair(LocalBaseTypeIndex,
1996 F.BaseTypeIndex - LocalBaseTypeIndex));
1997
1998 TypesLoaded.resize(TypesLoaded.size() + F.LocalNumTypes);
1999 }
2000 break;
2001 }
2002
2003 case DECL_OFFSET: {
2004 if (F.LocalNumDecls != 0) {
2005 Error("duplicate DECL_OFFSET record in AST file");
2006 return true;
2007 }
Chris Lattnerb3ce3572013-01-20 02:38:54 +00002008 F.DeclOffsets = (const DeclOffset *)Blob.data();
Guy Benyei7f92f2d2012-12-18 14:30:41 +00002009 F.LocalNumDecls = Record[0];
2010 unsigned LocalBaseDeclID = Record[1];
2011 F.BaseDeclID = getTotalNumDecls();
2012
2013 if (F.LocalNumDecls > 0) {
2014 // Introduce the global -> local mapping for declarations within this
2015 // module.
2016 GlobalDeclMap.insert(
2017 std::make_pair(getTotalNumDecls() + NUM_PREDEF_DECL_IDS, &F));
2018
2019 // Introduce the local -> global mapping for declarations within this
2020 // module.
2021 F.DeclRemap.insertOrReplace(
2022 std::make_pair(LocalBaseDeclID, F.BaseDeclID - LocalBaseDeclID));
2023
2024 // Introduce the global -> local mapping for declarations within this
2025 // module.
2026 F.GlobalToLocalDeclIDs[&F] = LocalBaseDeclID;
2027
2028 DeclsLoaded.resize(DeclsLoaded.size() + F.LocalNumDecls);
2029 }
2030 break;
2031 }
2032
2033 case TU_UPDATE_LEXICAL: {
2034 DeclContext *TU = Context.getTranslationUnitDecl();
2035 DeclContextInfo &Info = F.DeclContextInfos[TU];
Chris Lattnerb3ce3572013-01-20 02:38:54 +00002036 Info.LexicalDecls = reinterpret_cast<const KindDeclIDPair *>(Blob.data());
Guy Benyei7f92f2d2012-12-18 14:30:41 +00002037 Info.NumLexicalDecls
Chris Lattnerb3ce3572013-01-20 02:38:54 +00002038 = static_cast<unsigned int>(Blob.size() / sizeof(KindDeclIDPair));
Guy Benyei7f92f2d2012-12-18 14:30:41 +00002039 TU->setHasExternalLexicalStorage(true);
2040 break;
2041 }
2042
2043 case UPDATE_VISIBLE: {
2044 unsigned Idx = 0;
2045 serialization::DeclID ID = ReadDeclID(F, Record, Idx);
2046 ASTDeclContextNameLookupTable *Table =
2047 ASTDeclContextNameLookupTable::Create(
Chris Lattnerb3ce3572013-01-20 02:38:54 +00002048 (const unsigned char *)Blob.data() + Record[Idx++],
2049 (const unsigned char *)Blob.data(),
Guy Benyei7f92f2d2012-12-18 14:30:41 +00002050 ASTDeclContextNameLookupTrait(*this, F));
2051 if (ID == PREDEF_DECL_TRANSLATION_UNIT_ID) { // Is it the TU?
2052 DeclContext *TU = Context.getTranslationUnitDecl();
2053 F.DeclContextInfos[TU].NameLookupTableData = Table;
2054 TU->setHasExternalVisibleStorage(true);
2055 } else
2056 PendingVisibleUpdates[ID].push_back(std::make_pair(Table, &F));
2057 break;
2058 }
2059
2060 case IDENTIFIER_TABLE:
Chris Lattnerb3ce3572013-01-20 02:38:54 +00002061 F.IdentifierTableData = Blob.data();
Guy Benyei7f92f2d2012-12-18 14:30:41 +00002062 if (Record[0]) {
2063 F.IdentifierLookupTable
2064 = ASTIdentifierLookupTable::Create(
2065 (const unsigned char *)F.IdentifierTableData + Record[0],
2066 (const unsigned char *)F.IdentifierTableData,
2067 ASTIdentifierLookupTrait(*this, F));
2068
2069 PP.getIdentifierTable().setExternalIdentifierLookup(this);
2070 }
2071 break;
2072
2073 case IDENTIFIER_OFFSET: {
2074 if (F.LocalNumIdentifiers != 0) {
2075 Error("duplicate IDENTIFIER_OFFSET record in AST file");
2076 return true;
2077 }
Chris Lattnerb3ce3572013-01-20 02:38:54 +00002078 F.IdentifierOffsets = (const uint32_t *)Blob.data();
Guy Benyei7f92f2d2012-12-18 14:30:41 +00002079 F.LocalNumIdentifiers = Record[0];
2080 unsigned LocalBaseIdentifierID = Record[1];
2081 F.BaseIdentifierID = getTotalNumIdentifiers();
2082
2083 if (F.LocalNumIdentifiers > 0) {
2084 // Introduce the global -> local mapping for identifiers within this
2085 // module.
2086 GlobalIdentifierMap.insert(std::make_pair(getTotalNumIdentifiers() + 1,
2087 &F));
2088
2089 // Introduce the local -> global mapping for identifiers within this
2090 // module.
2091 F.IdentifierRemap.insertOrReplace(
2092 std::make_pair(LocalBaseIdentifierID,
2093 F.BaseIdentifierID - LocalBaseIdentifierID));
2094
2095 IdentifiersLoaded.resize(IdentifiersLoaded.size()
2096 + F.LocalNumIdentifiers);
2097 }
2098 break;
2099 }
2100
2101 case EXTERNAL_DEFINITIONS:
2102 for (unsigned I = 0, N = Record.size(); I != N; ++I)
2103 ExternalDefinitions.push_back(getGlobalDeclID(F, Record[I]));
2104 break;
2105
2106 case SPECIAL_TYPES:
Douglas Gregorf5cfc892013-02-01 23:45:03 +00002107 if (SpecialTypes.empty()) {
2108 for (unsigned I = 0, N = Record.size(); I != N; ++I)
2109 SpecialTypes.push_back(getGlobalTypeID(F, Record[I]));
2110 break;
2111 }
2112
2113 if (SpecialTypes.size() != Record.size()) {
2114 Error("invalid special-types record");
2115 return true;
2116 }
2117
2118 for (unsigned I = 0, N = Record.size(); I != N; ++I) {
2119 serialization::TypeID ID = getGlobalTypeID(F, Record[I]);
2120 if (!SpecialTypes[I])
2121 SpecialTypes[I] = ID;
2122 // FIXME: If ID && SpecialTypes[I] != ID, do we need a separate
2123 // merge step?
2124 }
Guy Benyei7f92f2d2012-12-18 14:30:41 +00002125 break;
2126
2127 case STATISTICS:
2128 TotalNumStatements += Record[0];
2129 TotalNumMacros += Record[1];
2130 TotalLexicalDeclContexts += Record[2];
2131 TotalVisibleDeclContexts += Record[3];
2132 break;
2133
2134 case UNUSED_FILESCOPED_DECLS:
2135 for (unsigned I = 0, N = Record.size(); I != N; ++I)
2136 UnusedFileScopedDecls.push_back(getGlobalDeclID(F, Record[I]));
2137 break;
2138
2139 case DELEGATING_CTORS:
2140 for (unsigned I = 0, N = Record.size(); I != N; ++I)
2141 DelegatingCtorDecls.push_back(getGlobalDeclID(F, Record[I]));
2142 break;
2143
2144 case WEAK_UNDECLARED_IDENTIFIERS:
2145 if (Record.size() % 4 != 0) {
2146 Error("invalid weak identifiers record");
2147 return true;
2148 }
2149
2150 // FIXME: Ignore weak undeclared identifiers from non-original PCH
2151 // files. This isn't the way to do it :)
2152 WeakUndeclaredIdentifiers.clear();
2153
2154 // Translate the weak, undeclared identifiers into global IDs.
2155 for (unsigned I = 0, N = Record.size(); I < N; /* in loop */) {
2156 WeakUndeclaredIdentifiers.push_back(
2157 getGlobalIdentifierID(F, Record[I++]));
2158 WeakUndeclaredIdentifiers.push_back(
2159 getGlobalIdentifierID(F, Record[I++]));
2160 WeakUndeclaredIdentifiers.push_back(
2161 ReadSourceLocation(F, Record, I).getRawEncoding());
2162 WeakUndeclaredIdentifiers.push_back(Record[I++]);
2163 }
2164 break;
2165
Richard Smith5ea6ef42013-01-10 23:43:47 +00002166 case LOCALLY_SCOPED_EXTERN_C_DECLS:
Guy Benyei7f92f2d2012-12-18 14:30:41 +00002167 for (unsigned I = 0, N = Record.size(); I != N; ++I)
Richard Smith5ea6ef42013-01-10 23:43:47 +00002168 LocallyScopedExternCDecls.push_back(getGlobalDeclID(F, Record[I]));
Guy Benyei7f92f2d2012-12-18 14:30:41 +00002169 break;
2170
2171 case SELECTOR_OFFSETS: {
Chris Lattnerb3ce3572013-01-20 02:38:54 +00002172 F.SelectorOffsets = (const uint32_t *)Blob.data();
Guy Benyei7f92f2d2012-12-18 14:30:41 +00002173 F.LocalNumSelectors = Record[0];
2174 unsigned LocalBaseSelectorID = Record[1];
2175 F.BaseSelectorID = getTotalNumSelectors();
2176
2177 if (F.LocalNumSelectors > 0) {
2178 // Introduce the global -> local mapping for selectors within this
2179 // module.
2180 GlobalSelectorMap.insert(std::make_pair(getTotalNumSelectors()+1, &F));
2181
2182 // Introduce the local -> global mapping for selectors within this
2183 // module.
2184 F.SelectorRemap.insertOrReplace(
2185 std::make_pair(LocalBaseSelectorID,
2186 F.BaseSelectorID - LocalBaseSelectorID));
2187
2188 SelectorsLoaded.resize(SelectorsLoaded.size() + F.LocalNumSelectors);
2189 }
2190 break;
2191 }
2192
2193 case METHOD_POOL:
Chris Lattnerb3ce3572013-01-20 02:38:54 +00002194 F.SelectorLookupTableData = (const unsigned char *)Blob.data();
Guy Benyei7f92f2d2012-12-18 14:30:41 +00002195 if (Record[0])
2196 F.SelectorLookupTable
2197 = ASTSelectorLookupTable::Create(
2198 F.SelectorLookupTableData + Record[0],
2199 F.SelectorLookupTableData,
2200 ASTSelectorLookupTrait(*this, F));
2201 TotalNumMethodPoolEntries += Record[1];
2202 break;
2203
2204 case REFERENCED_SELECTOR_POOL:
2205 if (!Record.empty()) {
2206 for (unsigned Idx = 0, N = Record.size() - 1; Idx < N; /* in loop */) {
2207 ReferencedSelectorsData.push_back(getGlobalSelectorID(F,
2208 Record[Idx++]));
2209 ReferencedSelectorsData.push_back(ReadSourceLocation(F, Record, Idx).
2210 getRawEncoding());
2211 }
2212 }
2213 break;
2214
2215 case PP_COUNTER_VALUE:
2216 if (!Record.empty() && Listener)
2217 Listener->ReadCounter(F, Record[0]);
2218 break;
2219
2220 case FILE_SORTED_DECLS:
Chris Lattnerb3ce3572013-01-20 02:38:54 +00002221 F.FileSortedDecls = (const DeclID *)Blob.data();
Guy Benyei7f92f2d2012-12-18 14:30:41 +00002222 F.NumFileSortedDecls = Record[0];
2223 break;
2224
2225 case SOURCE_LOCATION_OFFSETS: {
Chris Lattnerb3ce3572013-01-20 02:38:54 +00002226 F.SLocEntryOffsets = (const uint32_t *)Blob.data();
Guy Benyei7f92f2d2012-12-18 14:30:41 +00002227 F.LocalNumSLocEntries = Record[0];
2228 unsigned SLocSpaceSize = Record[1];
2229 llvm::tie(F.SLocEntryBaseID, F.SLocEntryBaseOffset) =
2230 SourceMgr.AllocateLoadedSLocEntries(F.LocalNumSLocEntries,
2231 SLocSpaceSize);
2232 // Make our entry in the range map. BaseID is negative and growing, so
2233 // we invert it. Because we invert it, though, we need the other end of
2234 // the range.
2235 unsigned RangeStart =
2236 unsigned(-F.SLocEntryBaseID) - F.LocalNumSLocEntries + 1;
2237 GlobalSLocEntryMap.insert(std::make_pair(RangeStart, &F));
2238 F.FirstLoc = SourceLocation::getFromRawEncoding(F.SLocEntryBaseOffset);
2239
2240 // SLocEntryBaseOffset is lower than MaxLoadedOffset and decreasing.
2241 assert((F.SLocEntryBaseOffset & (1U << 31U)) == 0);
2242 GlobalSLocOffsetMap.insert(
2243 std::make_pair(SourceManager::MaxLoadedOffset - F.SLocEntryBaseOffset
2244 - SLocSpaceSize,&F));
2245
2246 // Initialize the remapping table.
2247 // Invalid stays invalid.
2248 F.SLocRemap.insert(std::make_pair(0U, 0));
2249 // This module. Base was 2 when being compiled.
2250 F.SLocRemap.insert(std::make_pair(2U,
2251 static_cast<int>(F.SLocEntryBaseOffset - 2)));
2252
2253 TotalNumSLocEntries += F.LocalNumSLocEntries;
2254 break;
2255 }
2256
2257 case MODULE_OFFSET_MAP: {
2258 // Additional remapping information.
Chris Lattnerb3ce3572013-01-20 02:38:54 +00002259 const unsigned char *Data = (const unsigned char*)Blob.data();
2260 const unsigned char *DataEnd = Data + Blob.size();
Guy Benyei7f92f2d2012-12-18 14:30:41 +00002261
2262 // Continuous range maps we may be updating in our module.
2263 ContinuousRangeMap<uint32_t, int, 2>::Builder SLocRemap(F.SLocRemap);
2264 ContinuousRangeMap<uint32_t, int, 2>::Builder
2265 IdentifierRemap(F.IdentifierRemap);
2266 ContinuousRangeMap<uint32_t, int, 2>::Builder
2267 MacroRemap(F.MacroRemap);
2268 ContinuousRangeMap<uint32_t, int, 2>::Builder
2269 PreprocessedEntityRemap(F.PreprocessedEntityRemap);
2270 ContinuousRangeMap<uint32_t, int, 2>::Builder
2271 SubmoduleRemap(F.SubmoduleRemap);
2272 ContinuousRangeMap<uint32_t, int, 2>::Builder
2273 SelectorRemap(F.SelectorRemap);
2274 ContinuousRangeMap<uint32_t, int, 2>::Builder DeclRemap(F.DeclRemap);
2275 ContinuousRangeMap<uint32_t, int, 2>::Builder TypeRemap(F.TypeRemap);
2276
2277 while(Data < DataEnd) {
2278 uint16_t Len = io::ReadUnalignedLE16(Data);
2279 StringRef Name = StringRef((const char*)Data, Len);
2280 Data += Len;
2281 ModuleFile *OM = ModuleMgr.lookup(Name);
2282 if (!OM) {
2283 Error("SourceLocation remap refers to unknown module");
2284 return true;
2285 }
2286
2287 uint32_t SLocOffset = io::ReadUnalignedLE32(Data);
2288 uint32_t IdentifierIDOffset = io::ReadUnalignedLE32(Data);
2289 uint32_t MacroIDOffset = io::ReadUnalignedLE32(Data);
2290 uint32_t PreprocessedEntityIDOffset = io::ReadUnalignedLE32(Data);
2291 uint32_t SubmoduleIDOffset = io::ReadUnalignedLE32(Data);
2292 uint32_t SelectorIDOffset = io::ReadUnalignedLE32(Data);
2293 uint32_t DeclIDOffset = io::ReadUnalignedLE32(Data);
2294 uint32_t TypeIndexOffset = io::ReadUnalignedLE32(Data);
2295
2296 // Source location offset is mapped to OM->SLocEntryBaseOffset.
2297 SLocRemap.insert(std::make_pair(SLocOffset,
2298 static_cast<int>(OM->SLocEntryBaseOffset - SLocOffset)));
2299 IdentifierRemap.insert(
2300 std::make_pair(IdentifierIDOffset,
2301 OM->BaseIdentifierID - IdentifierIDOffset));
2302 MacroRemap.insert(std::make_pair(MacroIDOffset,
2303 OM->BaseMacroID - MacroIDOffset));
2304 PreprocessedEntityRemap.insert(
2305 std::make_pair(PreprocessedEntityIDOffset,
2306 OM->BasePreprocessedEntityID - PreprocessedEntityIDOffset));
2307 SubmoduleRemap.insert(std::make_pair(SubmoduleIDOffset,
2308 OM->BaseSubmoduleID - SubmoduleIDOffset));
2309 SelectorRemap.insert(std::make_pair(SelectorIDOffset,
2310 OM->BaseSelectorID - SelectorIDOffset));
2311 DeclRemap.insert(std::make_pair(DeclIDOffset,
2312 OM->BaseDeclID - DeclIDOffset));
2313
2314 TypeRemap.insert(std::make_pair(TypeIndexOffset,
2315 OM->BaseTypeIndex - TypeIndexOffset));
2316
2317 // Global -> local mappings.
2318 F.GlobalToLocalDeclIDs[OM] = DeclIDOffset;
2319 }
2320 break;
2321 }
2322
2323 case SOURCE_MANAGER_LINE_TABLE:
2324 if (ParseLineTable(F, Record))
2325 return true;
2326 break;
2327
2328 case SOURCE_LOCATION_PRELOADS: {
2329 // Need to transform from the local view (1-based IDs) to the global view,
2330 // which is based off F.SLocEntryBaseID.
2331 if (!F.PreloadSLocEntries.empty()) {
2332 Error("Multiple SOURCE_LOCATION_PRELOADS records in AST file");
2333 return true;
2334 }
2335
2336 F.PreloadSLocEntries.swap(Record);
2337 break;
2338 }
2339
2340 case EXT_VECTOR_DECLS:
2341 for (unsigned I = 0, N = Record.size(); I != N; ++I)
2342 ExtVectorDecls.push_back(getGlobalDeclID(F, Record[I]));
2343 break;
2344
2345 case VTABLE_USES:
2346 if (Record.size() % 3 != 0) {
2347 Error("Invalid VTABLE_USES record");
2348 return true;
2349 }
2350
2351 // Later tables overwrite earlier ones.
2352 // FIXME: Modules will have some trouble with this. This is clearly not
2353 // the right way to do this.
2354 VTableUses.clear();
2355
2356 for (unsigned Idx = 0, N = Record.size(); Idx != N; /* In loop */) {
2357 VTableUses.push_back(getGlobalDeclID(F, Record[Idx++]));
2358 VTableUses.push_back(
2359 ReadSourceLocation(F, Record, Idx).getRawEncoding());
2360 VTableUses.push_back(Record[Idx++]);
2361 }
2362 break;
2363
2364 case DYNAMIC_CLASSES:
2365 for (unsigned I = 0, N = Record.size(); I != N; ++I)
2366 DynamicClasses.push_back(getGlobalDeclID(F, Record[I]));
2367 break;
2368
2369 case PENDING_IMPLICIT_INSTANTIATIONS:
2370 if (PendingInstantiations.size() % 2 != 0) {
2371 Error("Invalid existing PendingInstantiations");
2372 return true;
2373 }
2374
2375 if (Record.size() % 2 != 0) {
2376 Error("Invalid PENDING_IMPLICIT_INSTANTIATIONS block");
2377 return true;
2378 }
2379
2380 for (unsigned I = 0, N = Record.size(); I != N; /* in loop */) {
2381 PendingInstantiations.push_back(getGlobalDeclID(F, Record[I++]));
2382 PendingInstantiations.push_back(
2383 ReadSourceLocation(F, Record, I).getRawEncoding());
2384 }
2385 break;
2386
2387 case SEMA_DECL_REFS:
2388 // Later tables overwrite earlier ones.
2389 // FIXME: Modules will have some trouble with this.
2390 SemaDeclRefs.clear();
2391 for (unsigned I = 0, N = Record.size(); I != N; ++I)
2392 SemaDeclRefs.push_back(getGlobalDeclID(F, Record[I]));
2393 break;
2394
2395 case PPD_ENTITIES_OFFSETS: {
Chris Lattnerb3ce3572013-01-20 02:38:54 +00002396 F.PreprocessedEntityOffsets = (const PPEntityOffset *)Blob.data();
2397 assert(Blob.size() % sizeof(PPEntityOffset) == 0);
2398 F.NumPreprocessedEntities = Blob.size() / sizeof(PPEntityOffset);
Guy Benyei7f92f2d2012-12-18 14:30:41 +00002399
2400 unsigned LocalBasePreprocessedEntityID = Record[0];
2401
2402 unsigned StartingID;
2403 if (!PP.getPreprocessingRecord())
2404 PP.createPreprocessingRecord();
2405 if (!PP.getPreprocessingRecord()->getExternalSource())
2406 PP.getPreprocessingRecord()->SetExternalSource(*this);
2407 StartingID
2408 = PP.getPreprocessingRecord()
2409 ->allocateLoadedEntities(F.NumPreprocessedEntities);
2410 F.BasePreprocessedEntityID = StartingID;
2411
2412 if (F.NumPreprocessedEntities > 0) {
2413 // Introduce the global -> local mapping for preprocessed entities in
2414 // this module.
2415 GlobalPreprocessedEntityMap.insert(std::make_pair(StartingID, &F));
2416
2417 // Introduce the local -> global mapping for preprocessed entities in
2418 // this module.
2419 F.PreprocessedEntityRemap.insertOrReplace(
2420 std::make_pair(LocalBasePreprocessedEntityID,
2421 F.BasePreprocessedEntityID - LocalBasePreprocessedEntityID));
2422 }
2423
2424 break;
2425 }
2426
2427 case DECL_UPDATE_OFFSETS: {
2428 if (Record.size() % 2 != 0) {
2429 Error("invalid DECL_UPDATE_OFFSETS block in AST file");
2430 return true;
2431 }
2432 for (unsigned I = 0, N = Record.size(); I != N; I += 2)
2433 DeclUpdateOffsets[getGlobalDeclID(F, Record[I])]
2434 .push_back(std::make_pair(&F, Record[I+1]));
2435 break;
2436 }
2437
2438 case DECL_REPLACEMENTS: {
2439 if (Record.size() % 3 != 0) {
2440 Error("invalid DECL_REPLACEMENTS block in AST file");
2441 return true;
2442 }
2443 for (unsigned I = 0, N = Record.size(); I != N; I += 3)
2444 ReplacedDecls[getGlobalDeclID(F, Record[I])]
2445 = ReplacedDeclInfo(&F, Record[I+1], Record[I+2]);
2446 break;
2447 }
2448
2449 case OBJC_CATEGORIES_MAP: {
2450 if (F.LocalNumObjCCategoriesInMap != 0) {
2451 Error("duplicate OBJC_CATEGORIES_MAP record in AST file");
2452 return true;
2453 }
2454
2455 F.LocalNumObjCCategoriesInMap = Record[0];
Chris Lattnerb3ce3572013-01-20 02:38:54 +00002456 F.ObjCCategoriesMap = (const ObjCCategoriesInfo *)Blob.data();
Guy Benyei7f92f2d2012-12-18 14:30:41 +00002457 break;
2458 }
2459
2460 case OBJC_CATEGORIES:
2461 F.ObjCCategories.swap(Record);
2462 break;
2463
2464 case CXX_BASE_SPECIFIER_OFFSETS: {
2465 if (F.LocalNumCXXBaseSpecifiers != 0) {
2466 Error("duplicate CXX_BASE_SPECIFIER_OFFSETS record in AST file");
2467 return true;
2468 }
2469
2470 F.LocalNumCXXBaseSpecifiers = Record[0];
Chris Lattnerb3ce3572013-01-20 02:38:54 +00002471 F.CXXBaseSpecifiersOffsets = (const uint32_t *)Blob.data();
Guy Benyei7f92f2d2012-12-18 14:30:41 +00002472 NumCXXBaseSpecifiersLoaded += F.LocalNumCXXBaseSpecifiers;
2473 break;
2474 }
2475
2476 case DIAG_PRAGMA_MAPPINGS:
2477 if (F.PragmaDiagMappings.empty())
2478 F.PragmaDiagMappings.swap(Record);
2479 else
2480 F.PragmaDiagMappings.insert(F.PragmaDiagMappings.end(),
2481 Record.begin(), Record.end());
2482 break;
2483
2484 case CUDA_SPECIAL_DECL_REFS:
2485 // Later tables overwrite earlier ones.
2486 // FIXME: Modules will have trouble with this.
2487 CUDASpecialDeclRefs.clear();
2488 for (unsigned I = 0, N = Record.size(); I != N; ++I)
2489 CUDASpecialDeclRefs.push_back(getGlobalDeclID(F, Record[I]));
2490 break;
2491
2492 case HEADER_SEARCH_TABLE: {
Chris Lattnerb3ce3572013-01-20 02:38:54 +00002493 F.HeaderFileInfoTableData = Blob.data();
Guy Benyei7f92f2d2012-12-18 14:30:41 +00002494 F.LocalNumHeaderFileInfos = Record[1];
Guy Benyei7f92f2d2012-12-18 14:30:41 +00002495 if (Record[0]) {
2496 F.HeaderFileInfoTable
2497 = HeaderFileInfoLookupTable::Create(
2498 (const unsigned char *)F.HeaderFileInfoTableData + Record[0],
2499 (const unsigned char *)F.HeaderFileInfoTableData,
2500 HeaderFileInfoTrait(*this, F,
2501 &PP.getHeaderSearchInfo(),
Chris Lattnerb3ce3572013-01-20 02:38:54 +00002502 Blob.data() + Record[2]));
Guy Benyei7f92f2d2012-12-18 14:30:41 +00002503
2504 PP.getHeaderSearchInfo().SetExternalSource(this);
2505 if (!PP.getHeaderSearchInfo().getExternalLookup())
2506 PP.getHeaderSearchInfo().SetExternalLookup(this);
2507 }
2508 break;
2509 }
2510
2511 case FP_PRAGMA_OPTIONS:
2512 // Later tables overwrite earlier ones.
2513 FPPragmaOptions.swap(Record);
2514 break;
2515
2516 case OPENCL_EXTENSIONS:
2517 // Later tables overwrite earlier ones.
2518 OpenCLExtensions.swap(Record);
2519 break;
2520
2521 case TENTATIVE_DEFINITIONS:
2522 for (unsigned I = 0, N = Record.size(); I != N; ++I)
2523 TentativeDefinitions.push_back(getGlobalDeclID(F, Record[I]));
2524 break;
2525
2526 case KNOWN_NAMESPACES:
2527 for (unsigned I = 0, N = Record.size(); I != N; ++I)
2528 KnownNamespaces.push_back(getGlobalDeclID(F, Record[I]));
2529 break;
Nick Lewycky01a41142013-01-26 00:35:08 +00002530
Nick Lewyckycd0655b2013-02-01 08:13:20 +00002531 case UNDEFINED_BUT_USED:
2532 if (UndefinedButUsed.size() % 2 != 0) {
2533 Error("Invalid existing UndefinedButUsed");
Nick Lewycky01a41142013-01-26 00:35:08 +00002534 return true;
2535 }
2536
2537 if (Record.size() % 2 != 0) {
Nick Lewyckycd0655b2013-02-01 08:13:20 +00002538 Error("invalid undefined-but-used record");
Nick Lewycky01a41142013-01-26 00:35:08 +00002539 return true;
2540 }
2541 for (unsigned I = 0, N = Record.size(); I != N; /* in loop */) {
Nick Lewyckycd0655b2013-02-01 08:13:20 +00002542 UndefinedButUsed.push_back(getGlobalDeclID(F, Record[I++]));
2543 UndefinedButUsed.push_back(
Nick Lewycky01a41142013-01-26 00:35:08 +00002544 ReadSourceLocation(F, Record, I).getRawEncoding());
2545 }
2546 break;
2547
Guy Benyei7f92f2d2012-12-18 14:30:41 +00002548 case IMPORTED_MODULES: {
2549 if (F.Kind != MK_Module) {
2550 // If we aren't loading a module (which has its own exports), make
2551 // all of the imported modules visible.
2552 // FIXME: Deal with macros-only imports.
2553 for (unsigned I = 0, N = Record.size(); I != N; ++I) {
2554 if (unsigned GlobalID = getGlobalSubmoduleID(F, Record[I]))
2555 ImportedModules.push_back(GlobalID);
2556 }
2557 }
2558 break;
2559 }
2560
2561 case LOCAL_REDECLARATIONS: {
2562 F.RedeclarationChains.swap(Record);
2563 break;
2564 }
2565
2566 case LOCAL_REDECLARATIONS_MAP: {
2567 if (F.LocalNumRedeclarationsInMap != 0) {
2568 Error("duplicate LOCAL_REDECLARATIONS_MAP record in AST file");
2569 return true;
2570 }
2571
2572 F.LocalNumRedeclarationsInMap = Record[0];
Chris Lattnerb3ce3572013-01-20 02:38:54 +00002573 F.RedeclarationsMap = (const LocalRedeclarationsInfo *)Blob.data();
Guy Benyei7f92f2d2012-12-18 14:30:41 +00002574 break;
2575 }
2576
2577 case MERGED_DECLARATIONS: {
2578 for (unsigned Idx = 0; Idx < Record.size(); /* increment in loop */) {
2579 GlobalDeclID CanonID = getGlobalDeclID(F, Record[Idx++]);
2580 SmallVectorImpl<GlobalDeclID> &Decls = StoredMergedDecls[CanonID];
2581 for (unsigned N = Record[Idx++]; N > 0; --N)
2582 Decls.push_back(getGlobalDeclID(F, Record[Idx++]));
2583 }
2584 break;
2585 }
2586
2587 case MACRO_OFFSET: {
2588 if (F.LocalNumMacros != 0) {
2589 Error("duplicate MACRO_OFFSET record in AST file");
2590 return true;
2591 }
Chris Lattnerb3ce3572013-01-20 02:38:54 +00002592 F.MacroOffsets = (const uint32_t *)Blob.data();
Guy Benyei7f92f2d2012-12-18 14:30:41 +00002593 F.LocalNumMacros = Record[0];
2594 unsigned LocalBaseMacroID = Record[1];
2595 F.BaseMacroID = getTotalNumMacros();
2596
2597 if (F.LocalNumMacros > 0) {
2598 // Introduce the global -> local mapping for macros within this module.
2599 GlobalMacroMap.insert(std::make_pair(getTotalNumMacros() + 1, &F));
2600
2601 // Introduce the local -> global mapping for macros within this module.
2602 F.MacroRemap.insertOrReplace(
2603 std::make_pair(LocalBaseMacroID,
2604 F.BaseMacroID - LocalBaseMacroID));
2605
2606 MacrosLoaded.resize(MacrosLoaded.size() + F.LocalNumMacros);
2607 }
2608 break;
2609 }
2610
2611 case MACRO_UPDATES: {
2612 for (unsigned I = 0, N = Record.size(); I != N; /* in loop */) {
2613 MacroID ID = getGlobalMacroID(F, Record[I++]);
2614 if (I == N)
2615 break;
2616
2617 SourceLocation UndefLoc = ReadSourceLocation(F, Record, I);
2618 SubmoduleID SubmoduleID = getGlobalSubmoduleID(F, Record[I++]);;
2619 MacroUpdate Update;
2620 Update.UndefLoc = UndefLoc;
2621 MacroUpdates[ID].push_back(std::make_pair(SubmoduleID, Update));
2622 }
2623 break;
2624 }
2625 }
2626 }
Guy Benyei7f92f2d2012-12-18 14:30:41 +00002627}
2628
Douglas Gregor2cbd4272013-02-12 23:36:21 +00002629/// \brief Move the given method to the back of the global list of methods.
2630static void moveMethodToBackOfGlobalList(Sema &S, ObjCMethodDecl *Method) {
2631 // Find the entry for this selector in the method pool.
2632 Sema::GlobalMethodPool::iterator Known
2633 = S.MethodPool.find(Method->getSelector());
2634 if (Known == S.MethodPool.end())
2635 return;
2636
2637 // Retrieve the appropriate method list.
2638 ObjCMethodList &Start = Method->isInstanceMethod()? Known->second.first
2639 : Known->second.second;
2640 bool Found = false;
2641 for (ObjCMethodList *List = &Start; List; List = List->Next) {
2642 if (!Found) {
2643 if (List->Method == Method) {
2644 Found = true;
2645 } else {
2646 // Keep searching.
2647 continue;
2648 }
2649 }
2650
2651 if (List->Next)
2652 List->Method = List->Next->Method;
2653 else
2654 List->Method = Method;
2655 }
2656}
2657
Guy Benyei7f92f2d2012-12-18 14:30:41 +00002658void ASTReader::makeNamesVisible(const HiddenNames &Names) {
2659 for (unsigned I = 0, N = Names.size(); I != N; ++I) {
2660 switch (Names[I].getKind()) {
Douglas Gregor2cbd4272013-02-12 23:36:21 +00002661 case HiddenName::Declaration: {
2662 Decl *D = Names[I].getDecl();
2663 bool wasHidden = D->Hidden;
2664 D->Hidden = false;
Guy Benyei7f92f2d2012-12-18 14:30:41 +00002665
Douglas Gregor2cbd4272013-02-12 23:36:21 +00002666 if (wasHidden && SemaObj) {
2667 if (ObjCMethodDecl *Method = dyn_cast<ObjCMethodDecl>(D)) {
2668 moveMethodToBackOfGlobalList(*SemaObj, Method);
2669 }
2670 }
2671 break;
2672 }
Guy Benyei7f92f2d2012-12-18 14:30:41 +00002673 case HiddenName::MacroVisibility: {
Argyrios Kyrtzidis9818a1d2013-02-20 00:54:57 +00002674 std::pair<IdentifierInfo *, MacroDirective *> Macro = Names[I].getMacro();
Guy Benyei7f92f2d2012-12-18 14:30:41 +00002675 Macro.second->setHidden(!Macro.second->isPublic());
2676 if (Macro.second->isDefined()) {
2677 PP.makeLoadedMacroInfoVisible(Macro.first, Macro.second);
2678 }
2679 break;
2680 }
2681
2682 case HiddenName::MacroUndef: {
Argyrios Kyrtzidis9818a1d2013-02-20 00:54:57 +00002683 std::pair<IdentifierInfo *, MacroDirective *> Macro = Names[I].getMacro();
Guy Benyei7f92f2d2012-12-18 14:30:41 +00002684 if (Macro.second->isDefined()) {
2685 Macro.second->setUndefLoc(Names[I].getMacroUndefLoc());
2686 if (PPMutationListener *Listener = PP.getPPMutationListener())
2687 Listener->UndefinedMacro(Macro.second);
2688 PP.makeLoadedMacroInfoVisible(Macro.first, Macro.second);
2689 }
2690 break;
2691 }
2692 }
2693 }
2694}
2695
2696void ASTReader::makeModuleVisible(Module *Mod,
Argyrios Kyrtzidis5ebcb202013-02-01 16:36:12 +00002697 Module::NameVisibilityKind NameVisibility,
2698 SourceLocation ImportLoc) {
Guy Benyei7f92f2d2012-12-18 14:30:41 +00002699 llvm::SmallPtrSet<Module *, 4> Visited;
Dmitri Gribenkocfa88f82013-01-12 19:30:44 +00002700 SmallVector<Module *, 4> Stack;
Guy Benyei7f92f2d2012-12-18 14:30:41 +00002701 Stack.push_back(Mod);
2702 while (!Stack.empty()) {
2703 Mod = Stack.back();
2704 Stack.pop_back();
2705
2706 if (NameVisibility <= Mod->NameVisibility) {
2707 // This module already has this level of visibility (or greater), so
2708 // there is nothing more to do.
2709 continue;
2710 }
2711
2712 if (!Mod->isAvailable()) {
2713 // Modules that aren't available cannot be made visible.
2714 continue;
2715 }
2716
2717 // Update the module's name visibility.
2718 Mod->NameVisibility = NameVisibility;
2719
2720 // If we've already deserialized any names from this module,
2721 // mark them as visible.
2722 HiddenNamesMapType::iterator Hidden = HiddenNamesMap.find(Mod);
2723 if (Hidden != HiddenNamesMap.end()) {
2724 makeNamesVisible(Hidden->second);
2725 HiddenNamesMap.erase(Hidden);
2726 }
2727
2728 // Push any non-explicit submodules onto the stack to be marked as
2729 // visible.
2730 for (Module::submodule_iterator Sub = Mod->submodule_begin(),
2731 SubEnd = Mod->submodule_end();
2732 Sub != SubEnd; ++Sub) {
2733 if (!(*Sub)->IsExplicit && Visited.insert(*Sub))
2734 Stack.push_back(*Sub);
2735 }
2736
2737 // Push any exported modules onto the stack to be marked as visible.
Argyrios Kyrtzidis21a00042013-02-19 19:34:40 +00002738 SmallVector<Module *, 16> Exports;
2739 Mod->getExportedModules(Exports);
2740 for (SmallVectorImpl<Module *>::iterator
2741 I = Exports.begin(), E = Exports.end(); I != E; ++I) {
2742 Module *Exported = *I;
2743 if (Visited.insert(Exported))
2744 Stack.push_back(Exported);
Guy Benyei7f92f2d2012-12-18 14:30:41 +00002745 }
2746 }
2747}
2748
Douglas Gregor1a49d972013-01-25 01:03:03 +00002749bool ASTReader::loadGlobalIndex() {
2750 if (GlobalIndex)
2751 return false;
2752
2753 if (TriedLoadingGlobalIndex || !UseGlobalIndex ||
2754 !Context.getLangOpts().Modules)
2755 return true;
2756
2757 // Try to load the global index.
2758 TriedLoadingGlobalIndex = true;
2759 StringRef ModuleCachePath
2760 = getPreprocessor().getHeaderSearchInfo().getModuleCachePath();
2761 std::pair<GlobalModuleIndex *, GlobalModuleIndex::ErrorCode> Result
2762 = GlobalModuleIndex::readIndex(FileMgr, ModuleCachePath);
2763 if (!Result.first)
2764 return true;
2765
2766 GlobalIndex.reset(Result.first);
Douglas Gregor188bdcd2013-01-25 23:32:03 +00002767 ModuleMgr.setGlobalIndex(GlobalIndex.get());
Douglas Gregor1a49d972013-01-25 01:03:03 +00002768 return false;
2769}
2770
2771bool ASTReader::isGlobalIndexUnavailable() const {
2772 return Context.getLangOpts().Modules && UseGlobalIndex &&
2773 !hasGlobalIndex() && TriedLoadingGlobalIndex;
2774}
2775
Guy Benyei7f92f2d2012-12-18 14:30:41 +00002776ASTReader::ASTReadResult ASTReader::ReadAST(const std::string &FileName,
2777 ModuleKind Type,
2778 SourceLocation ImportLoc,
2779 unsigned ClientLoadCapabilities) {
2780 // Bump the generation number.
2781 unsigned PreviousGeneration = CurrentGeneration++;
2782
2783 unsigned NumModules = ModuleMgr.size();
Dmitri Gribenkocfa88f82013-01-12 19:30:44 +00002784 SmallVector<ImportedModule, 4> Loaded;
Guy Benyei7f92f2d2012-12-18 14:30:41 +00002785 switch(ASTReadResult ReadResult = ReadASTCore(FileName, Type, ImportLoc,
2786 /*ImportedBy=*/0, Loaded,
2787 ClientLoadCapabilities)) {
2788 case Failure:
2789 case OutOfDate:
2790 case VersionMismatch:
2791 case ConfigurationMismatch:
2792 case HadErrors:
2793 ModuleMgr.removeModules(ModuleMgr.begin() + NumModules, ModuleMgr.end());
Douglas Gregor1a49d972013-01-25 01:03:03 +00002794
2795 // If we find that any modules are unusable, the global index is going
2796 // to be out-of-date. Just remove it.
2797 GlobalIndex.reset();
Douglas Gregor188bdcd2013-01-25 23:32:03 +00002798 ModuleMgr.setGlobalIndex(0);
Guy Benyei7f92f2d2012-12-18 14:30:41 +00002799 return ReadResult;
2800
2801 case Success:
2802 break;
2803 }
2804
2805 // Here comes stuff that we only do once the entire chain is loaded.
2806
2807 // Load the AST blocks of all of the modules that we loaded.
Dmitri Gribenkocfa88f82013-01-12 19:30:44 +00002808 for (SmallVectorImpl<ImportedModule>::iterator M = Loaded.begin(),
2809 MEnd = Loaded.end();
Guy Benyei7f92f2d2012-12-18 14:30:41 +00002810 M != MEnd; ++M) {
2811 ModuleFile &F = *M->Mod;
2812
2813 // Read the AST block.
2814 if (ReadASTBlock(F))
2815 return Failure;
2816
2817 // Once read, set the ModuleFile bit base offset and update the size in
2818 // bits of all files we've seen.
2819 F.GlobalBitOffset = TotalModulesSizeInBits;
2820 TotalModulesSizeInBits += F.SizeInBits;
2821 GlobalBitOffsetsMap.insert(std::make_pair(F.GlobalBitOffset, &F));
2822
2823 // Preload SLocEntries.
2824 for (unsigned I = 0, N = F.PreloadSLocEntries.size(); I != N; ++I) {
2825 int Index = int(F.PreloadSLocEntries[I] - 1) + F.SLocEntryBaseID;
2826 // Load it through the SourceManager and don't call ReadSLocEntry()
2827 // directly because the entry may have already been loaded in which case
2828 // calling ReadSLocEntry() directly would trigger an assertion in
2829 // SourceManager.
2830 SourceMgr.getLoadedSLocEntryByID(Index);
2831 }
2832 }
2833
2834 // Setup the import locations.
Dmitri Gribenkocfa88f82013-01-12 19:30:44 +00002835 for (SmallVectorImpl<ImportedModule>::iterator M = Loaded.begin(),
2836 MEnd = Loaded.end();
Guy Benyei7f92f2d2012-12-18 14:30:41 +00002837 M != MEnd; ++M) {
2838 ModuleFile &F = *M->Mod;
Argyrios Kyrtzidis8b136d82013-02-01 16:36:14 +00002839 F.DirectImportLoc = ImportLoc;
Guy Benyei7f92f2d2012-12-18 14:30:41 +00002840 if (!M->ImportedBy)
2841 F.ImportLoc = M->ImportLoc;
2842 else
2843 F.ImportLoc = ReadSourceLocation(*M->ImportedBy,
2844 M->ImportLoc.getRawEncoding());
2845 }
2846
2847 // Mark all of the identifiers in the identifier table as being out of date,
2848 // so that various accessors know to check the loaded modules when the
2849 // identifier is used.
2850 for (IdentifierTable::iterator Id = PP.getIdentifierTable().begin(),
2851 IdEnd = PP.getIdentifierTable().end();
2852 Id != IdEnd; ++Id)
2853 Id->second->setOutOfDate(true);
2854
2855 // Resolve any unresolved module exports.
2856 for (unsigned I = 0, N = UnresolvedModuleImportExports.size(); I != N; ++I) {
2857 UnresolvedModuleImportExport &Unresolved = UnresolvedModuleImportExports[I];
2858 SubmoduleID GlobalID = getGlobalSubmoduleID(*Unresolved.File,Unresolved.ID);
2859 Module *ResolvedMod = getSubmodule(GlobalID);
2860
2861 if (Unresolved.IsImport) {
2862 if (ResolvedMod)
2863 Unresolved.Mod->Imports.push_back(ResolvedMod);
2864 continue;
2865 }
2866
2867 if (ResolvedMod || Unresolved.IsWildcard)
2868 Unresolved.Mod->Exports.push_back(
2869 Module::ExportDecl(ResolvedMod, Unresolved.IsWildcard));
2870 }
2871 UnresolvedModuleImportExports.clear();
2872
2873 InitializeContext();
2874
2875 if (DeserializationListener)
2876 DeserializationListener->ReaderInitialized(this);
2877
2878 ModuleFile &PrimaryModule = ModuleMgr.getPrimaryModule();
2879 if (!PrimaryModule.OriginalSourceFileID.isInvalid()) {
2880 PrimaryModule.OriginalSourceFileID
2881 = FileID::get(PrimaryModule.SLocEntryBaseID
2882 + PrimaryModule.OriginalSourceFileID.getOpaqueValue() - 1);
2883
2884 // If this AST file is a precompiled preamble, then set the
2885 // preamble file ID of the source manager to the file source file
2886 // from which the preamble was built.
2887 if (Type == MK_Preamble) {
2888 SourceMgr.setPreambleFileID(PrimaryModule.OriginalSourceFileID);
2889 } else if (Type == MK_MainFile) {
2890 SourceMgr.setMainFileID(PrimaryModule.OriginalSourceFileID);
2891 }
2892 }
2893
2894 // For any Objective-C class definitions we have already loaded, make sure
2895 // that we load any additional categories.
2896 for (unsigned I = 0, N = ObjCClassesLoaded.size(); I != N; ++I) {
2897 loadObjCCategories(ObjCClassesLoaded[I]->getGlobalID(),
2898 ObjCClassesLoaded[I],
2899 PreviousGeneration);
2900 }
Douglas Gregor1a49d972013-01-25 01:03:03 +00002901
Guy Benyei7f92f2d2012-12-18 14:30:41 +00002902 return Success;
2903}
2904
2905ASTReader::ASTReadResult
2906ASTReader::ReadASTCore(StringRef FileName,
2907 ModuleKind Type,
2908 SourceLocation ImportLoc,
2909 ModuleFile *ImportedBy,
Dmitri Gribenkocfa88f82013-01-12 19:30:44 +00002910 SmallVectorImpl<ImportedModule> &Loaded,
Guy Benyei7f92f2d2012-12-18 14:30:41 +00002911 unsigned ClientLoadCapabilities) {
2912 ModuleFile *M;
2913 bool NewModule;
2914 std::string ErrorStr;
2915 llvm::tie(M, NewModule) = ModuleMgr.addModule(FileName, Type, ImportLoc,
2916 ImportedBy, CurrentGeneration,
2917 ErrorStr);
2918
2919 if (!M) {
2920 // We couldn't load the module.
2921 std::string Msg = "Unable to load module \"" + FileName.str() + "\": "
2922 + ErrorStr;
2923 Error(Msg);
2924 return Failure;
2925 }
2926
2927 if (!NewModule) {
2928 // We've already loaded this module.
2929 return Success;
2930 }
2931
2932 // FIXME: This seems rather a hack. Should CurrentDir be part of the
2933 // module?
2934 if (FileName != "-") {
2935 CurrentDir = llvm::sys::path::parent_path(FileName);
2936 if (CurrentDir.empty()) CurrentDir = ".";
2937 }
2938
2939 ModuleFile &F = *M;
Chris Lattner8f9a1eb2013-01-20 00:56:42 +00002940 BitstreamCursor &Stream = F.Stream;
Guy Benyei7f92f2d2012-12-18 14:30:41 +00002941 Stream.init(F.StreamFile);
2942 F.SizeInBits = F.Buffer->getBufferSize() * 8;
2943
2944 // Sniff for the signature.
2945 if (Stream.Read(8) != 'C' ||
2946 Stream.Read(8) != 'P' ||
2947 Stream.Read(8) != 'C' ||
2948 Stream.Read(8) != 'H') {
2949 Diag(diag::err_not_a_pch_file) << FileName;
2950 return Failure;
2951 }
2952
2953 // This is used for compatibility with older PCH formats.
2954 bool HaveReadControlBlock = false;
2955
Chris Lattner99a5af02013-01-20 00:00:22 +00002956 while (1) {
2957 llvm::BitstreamEntry Entry = Stream.advance();
2958
2959 switch (Entry.Kind) {
2960 case llvm::BitstreamEntry::Error:
2961 case llvm::BitstreamEntry::EndBlock:
2962 case llvm::BitstreamEntry::Record:
Guy Benyei7f92f2d2012-12-18 14:30:41 +00002963 Error("invalid record at top-level of AST file");
2964 return Failure;
Chris Lattner99a5af02013-01-20 00:00:22 +00002965
2966 case llvm::BitstreamEntry::SubBlock:
2967 break;
Guy Benyei7f92f2d2012-12-18 14:30:41 +00002968 }
2969
Guy Benyei7f92f2d2012-12-18 14:30:41 +00002970 // We only know the control subblock ID.
Chris Lattner99a5af02013-01-20 00:00:22 +00002971 switch (Entry.ID) {
Guy Benyei7f92f2d2012-12-18 14:30:41 +00002972 case llvm::bitc::BLOCKINFO_BLOCK_ID:
2973 if (Stream.ReadBlockInfoBlock()) {
2974 Error("malformed BlockInfoBlock in AST file");
2975 return Failure;
2976 }
2977 break;
2978 case CONTROL_BLOCK_ID:
2979 HaveReadControlBlock = true;
2980 switch (ReadControlBlock(F, Loaded, ClientLoadCapabilities)) {
2981 case Success:
2982 break;
2983
2984 case Failure: return Failure;
2985 case OutOfDate: return OutOfDate;
2986 case VersionMismatch: return VersionMismatch;
2987 case ConfigurationMismatch: return ConfigurationMismatch;
2988 case HadErrors: return HadErrors;
2989 }
2990 break;
2991 case AST_BLOCK_ID:
2992 if (!HaveReadControlBlock) {
2993 if ((ClientLoadCapabilities & ARR_VersionMismatch) == 0)
2994 Diag(diag::warn_pch_version_too_old);
2995 return VersionMismatch;
2996 }
2997
2998 // Record that we've loaded this module.
2999 Loaded.push_back(ImportedModule(M, ImportedBy, ImportLoc));
3000 return Success;
3001
3002 default:
3003 if (Stream.SkipBlock()) {
3004 Error("malformed block record in AST file");
3005 return Failure;
3006 }
3007 break;
3008 }
3009 }
3010
3011 return Success;
3012}
3013
3014void ASTReader::InitializeContext() {
3015 // If there's a listener, notify them that we "read" the translation unit.
3016 if (DeserializationListener)
3017 DeserializationListener->DeclRead(PREDEF_DECL_TRANSLATION_UNIT_ID,
3018 Context.getTranslationUnitDecl());
3019
3020 // Make sure we load the declaration update records for the translation unit,
3021 // if there are any.
3022 loadDeclUpdateRecords(PREDEF_DECL_TRANSLATION_UNIT_ID,
3023 Context.getTranslationUnitDecl());
3024
3025 // FIXME: Find a better way to deal with collisions between these
3026 // built-in types. Right now, we just ignore the problem.
3027
3028 // Load the special types.
3029 if (SpecialTypes.size() >= NumSpecialTypeIDs) {
3030 if (unsigned String = SpecialTypes[SPECIAL_TYPE_CF_CONSTANT_STRING]) {
3031 if (!Context.CFConstantStringTypeDecl)
3032 Context.setCFConstantStringType(GetType(String));
3033 }
3034
3035 if (unsigned File = SpecialTypes[SPECIAL_TYPE_FILE]) {
3036 QualType FileType = GetType(File);
3037 if (FileType.isNull()) {
3038 Error("FILE type is NULL");
3039 return;
3040 }
3041
3042 if (!Context.FILEDecl) {
3043 if (const TypedefType *Typedef = FileType->getAs<TypedefType>())
3044 Context.setFILEDecl(Typedef->getDecl());
3045 else {
3046 const TagType *Tag = FileType->getAs<TagType>();
3047 if (!Tag) {
3048 Error("Invalid FILE type in AST file");
3049 return;
3050 }
3051 Context.setFILEDecl(Tag->getDecl());
3052 }
3053 }
3054 }
3055
3056 if (unsigned Jmp_buf = SpecialTypes[SPECIAL_TYPE_JMP_BUF]) {
3057 QualType Jmp_bufType = GetType(Jmp_buf);
3058 if (Jmp_bufType.isNull()) {
3059 Error("jmp_buf type is NULL");
3060 return;
3061 }
3062
3063 if (!Context.jmp_bufDecl) {
3064 if (const TypedefType *Typedef = Jmp_bufType->getAs<TypedefType>())
3065 Context.setjmp_bufDecl(Typedef->getDecl());
3066 else {
3067 const TagType *Tag = Jmp_bufType->getAs<TagType>();
3068 if (!Tag) {
3069 Error("Invalid jmp_buf type in AST file");
3070 return;
3071 }
3072 Context.setjmp_bufDecl(Tag->getDecl());
3073 }
3074 }
3075 }
3076
3077 if (unsigned Sigjmp_buf = SpecialTypes[SPECIAL_TYPE_SIGJMP_BUF]) {
3078 QualType Sigjmp_bufType = GetType(Sigjmp_buf);
3079 if (Sigjmp_bufType.isNull()) {
3080 Error("sigjmp_buf type is NULL");
3081 return;
3082 }
3083
3084 if (!Context.sigjmp_bufDecl) {
3085 if (const TypedefType *Typedef = Sigjmp_bufType->getAs<TypedefType>())
3086 Context.setsigjmp_bufDecl(Typedef->getDecl());
3087 else {
3088 const TagType *Tag = Sigjmp_bufType->getAs<TagType>();
3089 assert(Tag && "Invalid sigjmp_buf type in AST file");
3090 Context.setsigjmp_bufDecl(Tag->getDecl());
3091 }
3092 }
3093 }
3094
3095 if (unsigned ObjCIdRedef
3096 = SpecialTypes[SPECIAL_TYPE_OBJC_ID_REDEFINITION]) {
3097 if (Context.ObjCIdRedefinitionType.isNull())
3098 Context.ObjCIdRedefinitionType = GetType(ObjCIdRedef);
3099 }
3100
3101 if (unsigned ObjCClassRedef
3102 = SpecialTypes[SPECIAL_TYPE_OBJC_CLASS_REDEFINITION]) {
3103 if (Context.ObjCClassRedefinitionType.isNull())
3104 Context.ObjCClassRedefinitionType = GetType(ObjCClassRedef);
3105 }
3106
3107 if (unsigned ObjCSelRedef
3108 = SpecialTypes[SPECIAL_TYPE_OBJC_SEL_REDEFINITION]) {
3109 if (Context.ObjCSelRedefinitionType.isNull())
3110 Context.ObjCSelRedefinitionType = GetType(ObjCSelRedef);
3111 }
3112
3113 if (unsigned Ucontext_t = SpecialTypes[SPECIAL_TYPE_UCONTEXT_T]) {
3114 QualType Ucontext_tType = GetType(Ucontext_t);
3115 if (Ucontext_tType.isNull()) {
3116 Error("ucontext_t type is NULL");
3117 return;
3118 }
3119
3120 if (!Context.ucontext_tDecl) {
3121 if (const TypedefType *Typedef = Ucontext_tType->getAs<TypedefType>())
3122 Context.setucontext_tDecl(Typedef->getDecl());
3123 else {
3124 const TagType *Tag = Ucontext_tType->getAs<TagType>();
3125 assert(Tag && "Invalid ucontext_t type in AST file");
3126 Context.setucontext_tDecl(Tag->getDecl());
3127 }
3128 }
3129 }
3130 }
3131
3132 ReadPragmaDiagnosticMappings(Context.getDiagnostics());
3133
3134 // If there were any CUDA special declarations, deserialize them.
3135 if (!CUDASpecialDeclRefs.empty()) {
3136 assert(CUDASpecialDeclRefs.size() == 1 && "More decl refs than expected!");
3137 Context.setcudaConfigureCallDecl(
3138 cast<FunctionDecl>(GetDecl(CUDASpecialDeclRefs[0])));
3139 }
3140
3141 // Re-export any modules that were imported by a non-module AST file.
3142 for (unsigned I = 0, N = ImportedModules.size(); I != N; ++I) {
3143 if (Module *Imported = getSubmodule(ImportedModules[I]))
Argyrios Kyrtzidis5ebcb202013-02-01 16:36:12 +00003144 makeModuleVisible(Imported, Module::AllVisible,
3145 /*ImportLoc=*/SourceLocation());
Guy Benyei7f92f2d2012-12-18 14:30:41 +00003146 }
3147 ImportedModules.clear();
3148}
3149
3150void ASTReader::finalizeForWriting() {
3151 for (HiddenNamesMapType::iterator Hidden = HiddenNamesMap.begin(),
3152 HiddenEnd = HiddenNamesMap.end();
3153 Hidden != HiddenEnd; ++Hidden) {
3154 makeNamesVisible(Hidden->second);
3155 }
3156 HiddenNamesMap.clear();
3157}
3158
Chris Lattner8f9a1eb2013-01-20 00:56:42 +00003159/// SkipCursorToControlBlock - Given a cursor at the start of an AST file, scan
3160/// ahead and drop the cursor into the start of the CONTROL_BLOCK, returning
3161/// false on success and true on failure.
3162static bool SkipCursorToControlBlock(BitstreamCursor &Cursor) {
3163 while (1) {
3164 llvm::BitstreamEntry Entry = Cursor.advance();
3165 switch (Entry.Kind) {
3166 case llvm::BitstreamEntry::Error:
3167 case llvm::BitstreamEntry::EndBlock:
3168 return true;
3169
3170 case llvm::BitstreamEntry::Record:
3171 // Ignore top-level records.
3172 Cursor.skipRecord(Entry.ID);
3173 break;
3174
3175 case llvm::BitstreamEntry::SubBlock:
3176 if (Entry.ID == CONTROL_BLOCK_ID) {
3177 if (Cursor.EnterSubBlock(CONTROL_BLOCK_ID))
3178 return true;
3179 // Found it!
3180 return false;
3181 }
3182
3183 if (Cursor.SkipBlock())
3184 return true;
3185 }
3186 }
3187}
3188
Guy Benyei7f92f2d2012-12-18 14:30:41 +00003189/// \brief Retrieve the name of the original source file name
3190/// directly from the AST file, without actually loading the AST
3191/// file.
3192std::string ASTReader::getOriginalSourceFile(const std::string &ASTFileName,
3193 FileManager &FileMgr,
3194 DiagnosticsEngine &Diags) {
3195 // Open the AST file.
3196 std::string ErrStr;
3197 OwningPtr<llvm::MemoryBuffer> Buffer;
3198 Buffer.reset(FileMgr.getBufferForFile(ASTFileName, &ErrStr));
3199 if (!Buffer) {
3200 Diags.Report(diag::err_fe_unable_to_read_pch_file) << ASTFileName << ErrStr;
3201 return std::string();
3202 }
3203
3204 // Initialize the stream
3205 llvm::BitstreamReader StreamFile;
Chris Lattner8f9a1eb2013-01-20 00:56:42 +00003206 BitstreamCursor Stream;
Guy Benyei7f92f2d2012-12-18 14:30:41 +00003207 StreamFile.init((const unsigned char *)Buffer->getBufferStart(),
3208 (const unsigned char *)Buffer->getBufferEnd());
3209 Stream.init(StreamFile);
3210
3211 // Sniff for the signature.
3212 if (Stream.Read(8) != 'C' ||
3213 Stream.Read(8) != 'P' ||
3214 Stream.Read(8) != 'C' ||
3215 Stream.Read(8) != 'H') {
3216 Diags.Report(diag::err_fe_not_a_pch_file) << ASTFileName;
3217 return std::string();
3218 }
Chris Lattner8f9a1eb2013-01-20 00:56:42 +00003219
Chris Lattner88bde502013-01-19 21:39:22 +00003220 // Scan for the CONTROL_BLOCK_ID block.
Chris Lattner8f9a1eb2013-01-20 00:56:42 +00003221 if (SkipCursorToControlBlock(Stream)) {
3222 Diags.Report(diag::err_fe_pch_malformed_block) << ASTFileName;
3223 return std::string();
Chris Lattner88bde502013-01-19 21:39:22 +00003224 }
Guy Benyei7f92f2d2012-12-18 14:30:41 +00003225
Chris Lattner8f9a1eb2013-01-20 00:56:42 +00003226 // Scan for ORIGINAL_FILE inside the control block.
3227 RecordData Record;
Chris Lattner88bde502013-01-19 21:39:22 +00003228 while (1) {
Chris Lattner8f9a1eb2013-01-20 00:56:42 +00003229 llvm::BitstreamEntry Entry = Stream.advanceSkippingSubblocks();
Chris Lattner88bde502013-01-19 21:39:22 +00003230 if (Entry.Kind == llvm::BitstreamEntry::EndBlock)
3231 return std::string();
3232
3233 if (Entry.Kind != llvm::BitstreamEntry::Record) {
3234 Diags.Report(diag::err_fe_pch_malformed_block) << ASTFileName;
3235 return std::string();
Guy Benyei7f92f2d2012-12-18 14:30:41 +00003236 }
Chris Lattner88bde502013-01-19 21:39:22 +00003237
Guy Benyei7f92f2d2012-12-18 14:30:41 +00003238 Record.clear();
Chris Lattnerb3ce3572013-01-20 02:38:54 +00003239 StringRef Blob;
3240 if (Stream.readRecord(Entry.ID, Record, &Blob) == ORIGINAL_FILE)
3241 return Blob.str();
Guy Benyei7f92f2d2012-12-18 14:30:41 +00003242 }
Guy Benyei7f92f2d2012-12-18 14:30:41 +00003243}
3244
3245namespace {
3246 class SimplePCHValidator : public ASTReaderListener {
3247 const LangOptions &ExistingLangOpts;
3248 const TargetOptions &ExistingTargetOpts;
3249 const PreprocessorOptions &ExistingPPOpts;
3250 FileManager &FileMgr;
3251
3252 public:
3253 SimplePCHValidator(const LangOptions &ExistingLangOpts,
3254 const TargetOptions &ExistingTargetOpts,
3255 const PreprocessorOptions &ExistingPPOpts,
3256 FileManager &FileMgr)
3257 : ExistingLangOpts(ExistingLangOpts),
3258 ExistingTargetOpts(ExistingTargetOpts),
3259 ExistingPPOpts(ExistingPPOpts),
3260 FileMgr(FileMgr)
3261 {
3262 }
3263
3264 virtual bool ReadLanguageOptions(const LangOptions &LangOpts,
3265 bool Complain) {
3266 return checkLanguageOptions(ExistingLangOpts, LangOpts, 0);
3267 }
3268 virtual bool ReadTargetOptions(const TargetOptions &TargetOpts,
3269 bool Complain) {
3270 return checkTargetOptions(ExistingTargetOpts, TargetOpts, 0);
3271 }
3272 virtual bool ReadPreprocessorOptions(const PreprocessorOptions &PPOpts,
3273 bool Complain,
3274 std::string &SuggestedPredefines) {
3275 return checkPreprocessorOptions(ExistingPPOpts, PPOpts, 0, FileMgr,
3276 SuggestedPredefines);
3277 }
3278 };
3279}
3280
3281bool ASTReader::readASTFileControlBlock(StringRef Filename,
3282 FileManager &FileMgr,
3283 ASTReaderListener &Listener) {
3284 // Open the AST file.
3285 std::string ErrStr;
3286 OwningPtr<llvm::MemoryBuffer> Buffer;
3287 Buffer.reset(FileMgr.getBufferForFile(Filename, &ErrStr));
3288 if (!Buffer) {
3289 return true;
3290 }
3291
3292 // Initialize the stream
3293 llvm::BitstreamReader StreamFile;
Chris Lattner8f9a1eb2013-01-20 00:56:42 +00003294 BitstreamCursor Stream;
Guy Benyei7f92f2d2012-12-18 14:30:41 +00003295 StreamFile.init((const unsigned char *)Buffer->getBufferStart(),
3296 (const unsigned char *)Buffer->getBufferEnd());
3297 Stream.init(StreamFile);
3298
3299 // Sniff for the signature.
3300 if (Stream.Read(8) != 'C' ||
3301 Stream.Read(8) != 'P' ||
3302 Stream.Read(8) != 'C' ||
3303 Stream.Read(8) != 'H') {
3304 return true;
3305 }
3306
Chris Lattner8f9a1eb2013-01-20 00:56:42 +00003307 // Scan for the CONTROL_BLOCK_ID block.
3308 if (SkipCursorToControlBlock(Stream))
3309 return true;
3310
3311 // Scan for ORIGINAL_FILE inside the control block.
Guy Benyei7f92f2d2012-12-18 14:30:41 +00003312 RecordData Record;
Chris Lattner8f9a1eb2013-01-20 00:56:42 +00003313 while (1) {
3314 llvm::BitstreamEntry Entry = Stream.advanceSkippingSubblocks();
3315 if (Entry.Kind == llvm::BitstreamEntry::EndBlock)
3316 return false;
3317
3318 if (Entry.Kind != llvm::BitstreamEntry::Record)
3319 return true;
3320
Guy Benyei7f92f2d2012-12-18 14:30:41 +00003321 Record.clear();
Chris Lattnerb3ce3572013-01-20 02:38:54 +00003322 StringRef Blob;
3323 unsigned RecCode = Stream.readRecord(Entry.ID, Record, &Blob);
Chris Lattner8f9a1eb2013-01-20 00:56:42 +00003324 switch ((ControlRecordTypes)RecCode) {
3325 case METADATA: {
3326 if (Record[0] != VERSION_MAJOR)
3327 return true;
Guy Benyei7f92f2d2012-12-18 14:30:41 +00003328
Chris Lattner8f9a1eb2013-01-20 00:56:42 +00003329 const std::string &CurBranch = getClangFullRepositoryVersion();
Chris Lattnerb3ce3572013-01-20 02:38:54 +00003330 if (StringRef(CurBranch) != Blob)
Chris Lattner8f9a1eb2013-01-20 00:56:42 +00003331 return true;
Guy Benyei7f92f2d2012-12-18 14:30:41 +00003332
Chris Lattner8f9a1eb2013-01-20 00:56:42 +00003333 break;
3334 }
3335 case LANGUAGE_OPTIONS:
3336 if (ParseLanguageOptions(Record, false, Listener))
3337 return true;
3338 break;
Guy Benyei7f92f2d2012-12-18 14:30:41 +00003339
Chris Lattner8f9a1eb2013-01-20 00:56:42 +00003340 case TARGET_OPTIONS:
3341 if (ParseTargetOptions(Record, false, Listener))
3342 return true;
3343 break;
Guy Benyei7f92f2d2012-12-18 14:30:41 +00003344
Chris Lattner8f9a1eb2013-01-20 00:56:42 +00003345 case DIAGNOSTIC_OPTIONS:
3346 if (ParseDiagnosticOptions(Record, false, Listener))
3347 return true;
3348 break;
Guy Benyei7f92f2d2012-12-18 14:30:41 +00003349
Chris Lattner8f9a1eb2013-01-20 00:56:42 +00003350 case FILE_SYSTEM_OPTIONS:
3351 if (ParseFileSystemOptions(Record, false, Listener))
3352 return true;
3353 break;
Guy Benyei7f92f2d2012-12-18 14:30:41 +00003354
Chris Lattner8f9a1eb2013-01-20 00:56:42 +00003355 case HEADER_SEARCH_OPTIONS:
3356 if (ParseHeaderSearchOptions(Record, false, Listener))
3357 return true;
3358 break;
Guy Benyei7f92f2d2012-12-18 14:30:41 +00003359
Chris Lattner8f9a1eb2013-01-20 00:56:42 +00003360 case PREPROCESSOR_OPTIONS: {
3361 std::string IgnoredSuggestedPredefines;
3362 if (ParsePreprocessorOptions(Record, false, Listener,
3363 IgnoredSuggestedPredefines))
3364 return true;
3365 break;
3366 }
Guy Benyei7f92f2d2012-12-18 14:30:41 +00003367
Chris Lattner8f9a1eb2013-01-20 00:56:42 +00003368 default:
3369 // No other validation to perform.
3370 break;
Guy Benyei7f92f2d2012-12-18 14:30:41 +00003371 }
3372 }
Guy Benyei7f92f2d2012-12-18 14:30:41 +00003373}
3374
3375
3376bool ASTReader::isAcceptableASTFile(StringRef Filename,
3377 FileManager &FileMgr,
3378 const LangOptions &LangOpts,
3379 const TargetOptions &TargetOpts,
3380 const PreprocessorOptions &PPOpts) {
3381 SimplePCHValidator validator(LangOpts, TargetOpts, PPOpts, FileMgr);
3382 return !readASTFileControlBlock(Filename, FileMgr, validator);
3383}
3384
3385bool ASTReader::ReadSubmoduleBlock(ModuleFile &F) {
3386 // Enter the submodule block.
3387 if (F.Stream.EnterSubBlock(SUBMODULE_BLOCK_ID)) {
3388 Error("malformed submodule block record in AST file");
3389 return true;
3390 }
3391
3392 ModuleMap &ModMap = PP.getHeaderSearchInfo().getModuleMap();
3393 bool First = true;
3394 Module *CurrentModule = 0;
3395 RecordData Record;
3396 while (true) {
Chris Lattner8f9a1eb2013-01-20 00:56:42 +00003397 llvm::BitstreamEntry Entry = F.Stream.advanceSkippingSubblocks();
3398
3399 switch (Entry.Kind) {
3400 case llvm::BitstreamEntry::SubBlock: // Handled for us already.
3401 case llvm::BitstreamEntry::Error:
3402 Error("malformed block record in AST file");
3403 return true;
3404 case llvm::BitstreamEntry::EndBlock:
Guy Benyei7f92f2d2012-12-18 14:30:41 +00003405 return false;
Chris Lattner8f9a1eb2013-01-20 00:56:42 +00003406 case llvm::BitstreamEntry::Record:
3407 // The interesting case.
3408 break;
Guy Benyei7f92f2d2012-12-18 14:30:41 +00003409 }
Chris Lattner8f9a1eb2013-01-20 00:56:42 +00003410
Guy Benyei7f92f2d2012-12-18 14:30:41 +00003411 // Read a record.
Chris Lattnerb3ce3572013-01-20 02:38:54 +00003412 StringRef Blob;
Guy Benyei7f92f2d2012-12-18 14:30:41 +00003413 Record.clear();
Chris Lattnerb3ce3572013-01-20 02:38:54 +00003414 switch (F.Stream.readRecord(Entry.ID, Record, &Blob)) {
Guy Benyei7f92f2d2012-12-18 14:30:41 +00003415 default: // Default behavior: ignore.
3416 break;
3417
3418 case SUBMODULE_DEFINITION: {
3419 if (First) {
3420 Error("missing submodule metadata record at beginning of block");
3421 return true;
3422 }
3423
3424 if (Record.size() < 7) {
3425 Error("malformed module definition");
3426 return true;
3427 }
3428
Chris Lattnerb3ce3572013-01-20 02:38:54 +00003429 StringRef Name = Blob;
Guy Benyei7f92f2d2012-12-18 14:30:41 +00003430 SubmoduleID GlobalID = getGlobalSubmoduleID(F, Record[0]);
3431 SubmoduleID Parent = getGlobalSubmoduleID(F, Record[1]);
3432 bool IsFramework = Record[2];
3433 bool IsExplicit = Record[3];
3434 bool IsSystem = Record[4];
3435 bool InferSubmodules = Record[5];
3436 bool InferExplicitSubmodules = Record[6];
3437 bool InferExportWildcard = Record[7];
3438
3439 Module *ParentModule = 0;
3440 if (Parent)
3441 ParentModule = getSubmodule(Parent);
3442
3443 // Retrieve this (sub)module from the module map, creating it if
3444 // necessary.
3445 CurrentModule = ModMap.findOrCreateModule(Name, ParentModule,
3446 IsFramework,
3447 IsExplicit).first;
3448 SubmoduleID GlobalIndex = GlobalID - NUM_PREDEF_SUBMODULE_IDS;
3449 if (GlobalIndex >= SubmodulesLoaded.size() ||
3450 SubmodulesLoaded[GlobalIndex]) {
3451 Error("too many submodules");
3452 return true;
3453 }
Douglas Gregor8bf778e2013-02-06 22:40:31 +00003454
3455 if (const FileEntry *CurFile = CurrentModule->getASTFile()) {
3456 if (CurFile != F.File) {
3457 if (!Diags.isDiagnosticInFlight()) {
3458 Diag(diag::err_module_file_conflict)
3459 << CurrentModule->getTopLevelModuleName()
3460 << CurFile->getName()
3461 << F.File->getName();
3462 }
3463 return true;
3464 }
3465 }
Guy Benyei7f92f2d2012-12-18 14:30:41 +00003466 CurrentModule->setASTFile(F.File);
3467 CurrentModule->IsFromModuleFile = true;
3468 CurrentModule->IsSystem = IsSystem || CurrentModule->IsSystem;
3469 CurrentModule->InferSubmodules = InferSubmodules;
3470 CurrentModule->InferExplicitSubmodules = InferExplicitSubmodules;
3471 CurrentModule->InferExportWildcard = InferExportWildcard;
3472 if (DeserializationListener)
3473 DeserializationListener->ModuleRead(GlobalID, CurrentModule);
3474
3475 SubmodulesLoaded[GlobalIndex] = CurrentModule;
Douglas Gregorb6cbe512013-01-14 17:21:00 +00003476
3477 // Clear out link libraries; the module file has them.
3478 CurrentModule->LinkLibraries.clear();
Guy Benyei7f92f2d2012-12-18 14:30:41 +00003479 break;
3480 }
3481
3482 case SUBMODULE_UMBRELLA_HEADER: {
3483 if (First) {
3484 Error("missing submodule metadata record at beginning of block");
3485 return true;
3486 }
3487
3488 if (!CurrentModule)
3489 break;
3490
Chris Lattnerb3ce3572013-01-20 02:38:54 +00003491 if (const FileEntry *Umbrella = PP.getFileManager().getFile(Blob)) {
Guy Benyei7f92f2d2012-12-18 14:30:41 +00003492 if (!CurrentModule->getUmbrellaHeader())
3493 ModMap.setUmbrellaHeader(CurrentModule, Umbrella);
3494 else if (CurrentModule->getUmbrellaHeader() != Umbrella) {
3495 Error("mismatched umbrella headers in submodule");
3496 return true;
3497 }
3498 }
3499 break;
3500 }
3501
3502 case SUBMODULE_HEADER: {
3503 if (First) {
3504 Error("missing submodule metadata record at beginning of block");
3505 return true;
3506 }
3507
3508 if (!CurrentModule)
3509 break;
3510
3511 // FIXME: Be more lazy about this!
Chris Lattnerb3ce3572013-01-20 02:38:54 +00003512 if (const FileEntry *File = PP.getFileManager().getFile(Blob)) {
Guy Benyei7f92f2d2012-12-18 14:30:41 +00003513 if (std::find(CurrentModule->Headers.begin(),
3514 CurrentModule->Headers.end(),
3515 File) == CurrentModule->Headers.end())
3516 ModMap.addHeader(CurrentModule, File, false);
3517 }
3518 break;
3519 }
3520
3521 case SUBMODULE_EXCLUDED_HEADER: {
3522 if (First) {
3523 Error("missing submodule metadata record at beginning of block");
3524 return true;
3525 }
3526
3527 if (!CurrentModule)
3528 break;
3529
3530 // FIXME: Be more lazy about this!
Chris Lattnerb3ce3572013-01-20 02:38:54 +00003531 if (const FileEntry *File = PP.getFileManager().getFile(Blob)) {
Guy Benyei7f92f2d2012-12-18 14:30:41 +00003532 if (std::find(CurrentModule->Headers.begin(),
3533 CurrentModule->Headers.end(),
3534 File) == CurrentModule->Headers.end())
3535 ModMap.addHeader(CurrentModule, File, true);
3536 }
3537 break;
3538 }
3539
3540 case SUBMODULE_TOPHEADER: {
3541 if (First) {
3542 Error("missing submodule metadata record at beginning of block");
3543 return true;
3544 }
3545
3546 if (!CurrentModule)
3547 break;
3548
3549 // FIXME: Be more lazy about this!
Chris Lattnerb3ce3572013-01-20 02:38:54 +00003550 if (const FileEntry *File = PP.getFileManager().getFile(Blob))
Guy Benyei7f92f2d2012-12-18 14:30:41 +00003551 CurrentModule->TopHeaders.insert(File);
3552 break;
3553 }
3554
3555 case SUBMODULE_UMBRELLA_DIR: {
3556 if (First) {
3557 Error("missing submodule metadata record at beginning of block");
3558 return true;
3559 }
3560
3561 if (!CurrentModule)
3562 break;
3563
Guy Benyei7f92f2d2012-12-18 14:30:41 +00003564 if (const DirectoryEntry *Umbrella
Chris Lattnerb3ce3572013-01-20 02:38:54 +00003565 = PP.getFileManager().getDirectory(Blob)) {
Guy Benyei7f92f2d2012-12-18 14:30:41 +00003566 if (!CurrentModule->getUmbrellaDir())
3567 ModMap.setUmbrellaDir(CurrentModule, Umbrella);
3568 else if (CurrentModule->getUmbrellaDir() != Umbrella) {
3569 Error("mismatched umbrella directories in submodule");
3570 return true;
3571 }
3572 }
3573 break;
3574 }
3575
3576 case SUBMODULE_METADATA: {
3577 if (!First) {
3578 Error("submodule metadata record not at beginning of block");
3579 return true;
3580 }
3581 First = false;
3582
3583 F.BaseSubmoduleID = getTotalNumSubmodules();
3584 F.LocalNumSubmodules = Record[0];
3585 unsigned LocalBaseSubmoduleID = Record[1];
3586 if (F.LocalNumSubmodules > 0) {
3587 // Introduce the global -> local mapping for submodules within this
3588 // module.
3589 GlobalSubmoduleMap.insert(std::make_pair(getTotalNumSubmodules()+1,&F));
3590
3591 // Introduce the local -> global mapping for submodules within this
3592 // module.
3593 F.SubmoduleRemap.insertOrReplace(
3594 std::make_pair(LocalBaseSubmoduleID,
3595 F.BaseSubmoduleID - LocalBaseSubmoduleID));
3596
3597 SubmodulesLoaded.resize(SubmodulesLoaded.size() + F.LocalNumSubmodules);
3598 }
3599 break;
3600 }
3601
3602 case SUBMODULE_IMPORTS: {
3603 if (First) {
3604 Error("missing submodule metadata record at beginning of block");
3605 return true;
3606 }
3607
3608 if (!CurrentModule)
3609 break;
3610
3611 for (unsigned Idx = 0; Idx != Record.size(); ++Idx) {
3612 UnresolvedModuleImportExport Unresolved;
3613 Unresolved.File = &F;
3614 Unresolved.Mod = CurrentModule;
3615 Unresolved.ID = Record[Idx];
3616 Unresolved.IsImport = true;
3617 Unresolved.IsWildcard = false;
3618 UnresolvedModuleImportExports.push_back(Unresolved);
3619 }
3620 break;
3621 }
3622
3623 case SUBMODULE_EXPORTS: {
3624 if (First) {
3625 Error("missing submodule metadata record at beginning of block");
3626 return true;
3627 }
3628
3629 if (!CurrentModule)
3630 break;
3631
3632 for (unsigned Idx = 0; Idx + 1 < Record.size(); Idx += 2) {
3633 UnresolvedModuleImportExport Unresolved;
3634 Unresolved.File = &F;
3635 Unresolved.Mod = CurrentModule;
3636 Unresolved.ID = Record[Idx];
3637 Unresolved.IsImport = false;
3638 Unresolved.IsWildcard = Record[Idx + 1];
3639 UnresolvedModuleImportExports.push_back(Unresolved);
3640 }
3641
3642 // Once we've loaded the set of exports, there's no reason to keep
3643 // the parsed, unresolved exports around.
3644 CurrentModule->UnresolvedExports.clear();
3645 break;
3646 }
3647 case SUBMODULE_REQUIRES: {
3648 if (First) {
3649 Error("missing submodule metadata record at beginning of block");
3650 return true;
3651 }
3652
3653 if (!CurrentModule)
3654 break;
3655
Chris Lattnerb3ce3572013-01-20 02:38:54 +00003656 CurrentModule->addRequirement(Blob, Context.getLangOpts(),
Guy Benyei7f92f2d2012-12-18 14:30:41 +00003657 Context.getTargetInfo());
3658 break;
3659 }
Douglas Gregorb6cbe512013-01-14 17:21:00 +00003660
3661 case SUBMODULE_LINK_LIBRARY:
3662 if (First) {
3663 Error("missing submodule metadata record at beginning of block");
3664 return true;
3665 }
3666
3667 if (!CurrentModule)
3668 break;
3669
3670 CurrentModule->LinkLibraries.push_back(
Chris Lattnerb3ce3572013-01-20 02:38:54 +00003671 Module::LinkLibrary(Blob, Record[0]));
Douglas Gregorb6cbe512013-01-14 17:21:00 +00003672 break;
Guy Benyei7f92f2d2012-12-18 14:30:41 +00003673 }
3674 }
3675}
3676
3677/// \brief Parse the record that corresponds to a LangOptions data
3678/// structure.
3679///
3680/// This routine parses the language options from the AST file and then gives
3681/// them to the AST listener if one is set.
3682///
3683/// \returns true if the listener deems the file unacceptable, false otherwise.
3684bool ASTReader::ParseLanguageOptions(const RecordData &Record,
3685 bool Complain,
3686 ASTReaderListener &Listener) {
3687 LangOptions LangOpts;
3688 unsigned Idx = 0;
3689#define LANGOPT(Name, Bits, Default, Description) \
3690 LangOpts.Name = Record[Idx++];
3691#define ENUM_LANGOPT(Name, Type, Bits, Default, Description) \
3692 LangOpts.set##Name(static_cast<LangOptions::Type>(Record[Idx++]));
3693#include "clang/Basic/LangOptions.def"
Will Dietz4f45bc02013-01-18 11:30:38 +00003694#define SANITIZER(NAME, ID) LangOpts.Sanitize.ID = Record[Idx++];
3695#include "clang/Basic/Sanitizers.def"
Guy Benyei7f92f2d2012-12-18 14:30:41 +00003696
3697 ObjCRuntime::Kind runtimeKind = (ObjCRuntime::Kind) Record[Idx++];
3698 VersionTuple runtimeVersion = ReadVersionTuple(Record, Idx);
3699 LangOpts.ObjCRuntime = ObjCRuntime(runtimeKind, runtimeVersion);
3700
3701 unsigned Length = Record[Idx++];
3702 LangOpts.CurrentModule.assign(Record.begin() + Idx,
3703 Record.begin() + Idx + Length);
Dmitri Gribenko6ebf0912013-02-22 14:21:27 +00003704
3705 Idx += Length;
3706
3707 // Comment options.
3708 for (unsigned N = Record[Idx++]; N; --N) {
3709 LangOpts.CommentOpts.BlockCommandNames.push_back(
3710 ReadString(Record, Idx));
3711 }
3712
Guy Benyei7f92f2d2012-12-18 14:30:41 +00003713 return Listener.ReadLanguageOptions(LangOpts, Complain);
3714}
3715
3716bool ASTReader::ParseTargetOptions(const RecordData &Record,
3717 bool Complain,
3718 ASTReaderListener &Listener) {
3719 unsigned Idx = 0;
3720 TargetOptions TargetOpts;
3721 TargetOpts.Triple = ReadString(Record, Idx);
3722 TargetOpts.CPU = ReadString(Record, Idx);
3723 TargetOpts.ABI = ReadString(Record, Idx);
3724 TargetOpts.CXXABI = ReadString(Record, Idx);
3725 TargetOpts.LinkerVersion = ReadString(Record, Idx);
3726 for (unsigned N = Record[Idx++]; N; --N) {
3727 TargetOpts.FeaturesAsWritten.push_back(ReadString(Record, Idx));
3728 }
3729 for (unsigned N = Record[Idx++]; N; --N) {
3730 TargetOpts.Features.push_back(ReadString(Record, Idx));
3731 }
3732
3733 return Listener.ReadTargetOptions(TargetOpts, Complain);
3734}
3735
3736bool ASTReader::ParseDiagnosticOptions(const RecordData &Record, bool Complain,
3737 ASTReaderListener &Listener) {
3738 DiagnosticOptions DiagOpts;
3739 unsigned Idx = 0;
3740#define DIAGOPT(Name, Bits, Default) DiagOpts.Name = Record[Idx++];
3741#define ENUM_DIAGOPT(Name, Type, Bits, Default) \
3742 DiagOpts.set##Name(static_cast<Type>(Record[Idx++]));
3743#include "clang/Basic/DiagnosticOptions.def"
3744
3745 for (unsigned N = Record[Idx++]; N; --N) {
3746 DiagOpts.Warnings.push_back(ReadString(Record, Idx));
3747 }
3748
3749 return Listener.ReadDiagnosticOptions(DiagOpts, Complain);
3750}
3751
3752bool ASTReader::ParseFileSystemOptions(const RecordData &Record, bool Complain,
3753 ASTReaderListener &Listener) {
3754 FileSystemOptions FSOpts;
3755 unsigned Idx = 0;
3756 FSOpts.WorkingDir = ReadString(Record, Idx);
3757 return Listener.ReadFileSystemOptions(FSOpts, Complain);
3758}
3759
3760bool ASTReader::ParseHeaderSearchOptions(const RecordData &Record,
3761 bool Complain,
3762 ASTReaderListener &Listener) {
3763 HeaderSearchOptions HSOpts;
3764 unsigned Idx = 0;
3765 HSOpts.Sysroot = ReadString(Record, Idx);
3766
3767 // Include entries.
3768 for (unsigned N = Record[Idx++]; N; --N) {
3769 std::string Path = ReadString(Record, Idx);
3770 frontend::IncludeDirGroup Group
3771 = static_cast<frontend::IncludeDirGroup>(Record[Idx++]);
Guy Benyei7f92f2d2012-12-18 14:30:41 +00003772 bool IsFramework = Record[Idx++];
3773 bool IgnoreSysRoot = Record[Idx++];
Guy Benyei7f92f2d2012-12-18 14:30:41 +00003774 HSOpts.UserEntries.push_back(
Daniel Dunbar59fd6352013-01-30 00:34:26 +00003775 HeaderSearchOptions::Entry(Path, Group, IsFramework, IgnoreSysRoot));
Guy Benyei7f92f2d2012-12-18 14:30:41 +00003776 }
3777
3778 // System header prefixes.
3779 for (unsigned N = Record[Idx++]; N; --N) {
3780 std::string Prefix = ReadString(Record, Idx);
3781 bool IsSystemHeader = Record[Idx++];
3782 HSOpts.SystemHeaderPrefixes.push_back(
3783 HeaderSearchOptions::SystemHeaderPrefix(Prefix, IsSystemHeader));
3784 }
3785
3786 HSOpts.ResourceDir = ReadString(Record, Idx);
3787 HSOpts.ModuleCachePath = ReadString(Record, Idx);
3788 HSOpts.DisableModuleHash = Record[Idx++];
3789 HSOpts.UseBuiltinIncludes = Record[Idx++];
3790 HSOpts.UseStandardSystemIncludes = Record[Idx++];
3791 HSOpts.UseStandardCXXIncludes = Record[Idx++];
3792 HSOpts.UseLibcxx = Record[Idx++];
3793
3794 return Listener.ReadHeaderSearchOptions(HSOpts, Complain);
3795}
3796
3797bool ASTReader::ParsePreprocessorOptions(const RecordData &Record,
3798 bool Complain,
3799 ASTReaderListener &Listener,
3800 std::string &SuggestedPredefines) {
3801 PreprocessorOptions PPOpts;
3802 unsigned Idx = 0;
3803
3804 // Macro definitions/undefs
3805 for (unsigned N = Record[Idx++]; N; --N) {
3806 std::string Macro = ReadString(Record, Idx);
3807 bool IsUndef = Record[Idx++];
3808 PPOpts.Macros.push_back(std::make_pair(Macro, IsUndef));
3809 }
3810
3811 // Includes
3812 for (unsigned N = Record[Idx++]; N; --N) {
3813 PPOpts.Includes.push_back(ReadString(Record, Idx));
3814 }
3815
3816 // Macro Includes
3817 for (unsigned N = Record[Idx++]; N; --N) {
3818 PPOpts.MacroIncludes.push_back(ReadString(Record, Idx));
3819 }
3820
3821 PPOpts.UsePredefines = Record[Idx++];
3822 PPOpts.ImplicitPCHInclude = ReadString(Record, Idx);
3823 PPOpts.ImplicitPTHInclude = ReadString(Record, Idx);
3824 PPOpts.ObjCXXARCStandardLibrary =
3825 static_cast<ObjCXXARCStandardLibraryKind>(Record[Idx++]);
3826 SuggestedPredefines.clear();
3827 return Listener.ReadPreprocessorOptions(PPOpts, Complain,
3828 SuggestedPredefines);
3829}
3830
3831std::pair<ModuleFile *, unsigned>
3832ASTReader::getModulePreprocessedEntity(unsigned GlobalIndex) {
3833 GlobalPreprocessedEntityMapType::iterator
3834 I = GlobalPreprocessedEntityMap.find(GlobalIndex);
3835 assert(I != GlobalPreprocessedEntityMap.end() &&
3836 "Corrupted global preprocessed entity map");
3837 ModuleFile *M = I->second;
3838 unsigned LocalIndex = GlobalIndex - M->BasePreprocessedEntityID;
3839 return std::make_pair(M, LocalIndex);
3840}
3841
3842std::pair<PreprocessingRecord::iterator, PreprocessingRecord::iterator>
3843ASTReader::getModulePreprocessedEntities(ModuleFile &Mod) const {
3844 if (PreprocessingRecord *PPRec = PP.getPreprocessingRecord())
3845 return PPRec->getIteratorsForLoadedRange(Mod.BasePreprocessedEntityID,
3846 Mod.NumPreprocessedEntities);
3847
3848 return std::make_pair(PreprocessingRecord::iterator(),
3849 PreprocessingRecord::iterator());
3850}
3851
3852std::pair<ASTReader::ModuleDeclIterator, ASTReader::ModuleDeclIterator>
3853ASTReader::getModuleFileLevelDecls(ModuleFile &Mod) {
3854 return std::make_pair(ModuleDeclIterator(this, &Mod, Mod.FileSortedDecls),
3855 ModuleDeclIterator(this, &Mod,
3856 Mod.FileSortedDecls + Mod.NumFileSortedDecls));
3857}
3858
3859PreprocessedEntity *ASTReader::ReadPreprocessedEntity(unsigned Index) {
3860 PreprocessedEntityID PPID = Index+1;
3861 std::pair<ModuleFile *, unsigned> PPInfo = getModulePreprocessedEntity(Index);
3862 ModuleFile &M = *PPInfo.first;
3863 unsigned LocalIndex = PPInfo.second;
3864 const PPEntityOffset &PPOffs = M.PreprocessedEntityOffsets[LocalIndex];
3865
Guy Benyei7f92f2d2012-12-18 14:30:41 +00003866 if (!PP.getPreprocessingRecord()) {
3867 Error("no preprocessing record");
3868 return 0;
3869 }
3870
Chris Lattner8f9a1eb2013-01-20 00:56:42 +00003871 SavedStreamPosition SavedPosition(M.PreprocessorDetailCursor);
3872 M.PreprocessorDetailCursor.JumpToBit(PPOffs.BitOffset);
3873
3874 llvm::BitstreamEntry Entry =
3875 M.PreprocessorDetailCursor.advance(BitstreamCursor::AF_DontPopBlockAtEnd);
3876 if (Entry.Kind != llvm::BitstreamEntry::Record)
3877 return 0;
3878
Guy Benyei7f92f2d2012-12-18 14:30:41 +00003879 // Read the record.
3880 SourceRange Range(ReadSourceLocation(M, PPOffs.Begin),
3881 ReadSourceLocation(M, PPOffs.End));
3882 PreprocessingRecord &PPRec = *PP.getPreprocessingRecord();
Chris Lattnerb3ce3572013-01-20 02:38:54 +00003883 StringRef Blob;
Guy Benyei7f92f2d2012-12-18 14:30:41 +00003884 RecordData Record;
3885 PreprocessorDetailRecordTypes RecType =
Chris Lattnerb3ce3572013-01-20 02:38:54 +00003886 (PreprocessorDetailRecordTypes)M.PreprocessorDetailCursor.readRecord(
3887 Entry.ID, Record, &Blob);
Guy Benyei7f92f2d2012-12-18 14:30:41 +00003888 switch (RecType) {
3889 case PPD_MACRO_EXPANSION: {
3890 bool isBuiltin = Record[0];
3891 IdentifierInfo *Name = 0;
3892 MacroDefinition *Def = 0;
3893 if (isBuiltin)
3894 Name = getLocalIdentifier(M, Record[1]);
3895 else {
3896 PreprocessedEntityID
3897 GlobalID = getGlobalPreprocessedEntityID(M, Record[1]);
3898 Def =cast<MacroDefinition>(PPRec.getLoadedPreprocessedEntity(GlobalID-1));
3899 }
3900
3901 MacroExpansion *ME;
3902 if (isBuiltin)
3903 ME = new (PPRec) MacroExpansion(Name, Range);
3904 else
3905 ME = new (PPRec) MacroExpansion(Def, Range);
3906
3907 return ME;
3908 }
3909
3910 case PPD_MACRO_DEFINITION: {
3911 // Decode the identifier info and then check again; if the macro is
3912 // still defined and associated with the identifier,
3913 IdentifierInfo *II = getLocalIdentifier(M, Record[0]);
3914 MacroDefinition *MD
3915 = new (PPRec) MacroDefinition(II, Range);
3916
3917 if (DeserializationListener)
3918 DeserializationListener->MacroDefinitionRead(PPID, MD);
3919
3920 return MD;
3921 }
3922
3923 case PPD_INCLUSION_DIRECTIVE: {
Chris Lattnerb3ce3572013-01-20 02:38:54 +00003924 const char *FullFileNameStart = Blob.data() + Record[0];
3925 StringRef FullFileName(FullFileNameStart, Blob.size() - Record[0]);
Guy Benyei7f92f2d2012-12-18 14:30:41 +00003926 const FileEntry *File = 0;
3927 if (!FullFileName.empty())
3928 File = PP.getFileManager().getFile(FullFileName);
3929
3930 // FIXME: Stable encoding
3931 InclusionDirective::InclusionKind Kind
3932 = static_cast<InclusionDirective::InclusionKind>(Record[2]);
3933 InclusionDirective *ID
3934 = new (PPRec) InclusionDirective(PPRec, Kind,
Chris Lattnerb3ce3572013-01-20 02:38:54 +00003935 StringRef(Blob.data(), Record[0]),
Guy Benyei7f92f2d2012-12-18 14:30:41 +00003936 Record[1], Record[3],
3937 File,
3938 Range);
3939 return ID;
3940 }
3941 }
3942
3943 llvm_unreachable("Invalid PreprocessorDetailRecordTypes");
3944}
3945
3946/// \brief \arg SLocMapI points at a chunk of a module that contains no
3947/// preprocessed entities or the entities it contains are not the ones we are
3948/// looking for. Find the next module that contains entities and return the ID
3949/// of the first entry.
3950PreprocessedEntityID ASTReader::findNextPreprocessedEntity(
3951 GlobalSLocOffsetMapType::const_iterator SLocMapI) const {
3952 ++SLocMapI;
3953 for (GlobalSLocOffsetMapType::const_iterator
3954 EndI = GlobalSLocOffsetMap.end(); SLocMapI != EndI; ++SLocMapI) {
3955 ModuleFile &M = *SLocMapI->second;
3956 if (M.NumPreprocessedEntities)
3957 return M.BasePreprocessedEntityID;
3958 }
3959
3960 return getTotalNumPreprocessedEntities();
3961}
3962
3963namespace {
3964
3965template <unsigned PPEntityOffset::*PPLoc>
3966struct PPEntityComp {
3967 const ASTReader &Reader;
3968 ModuleFile &M;
3969
3970 PPEntityComp(const ASTReader &Reader, ModuleFile &M) : Reader(Reader), M(M) { }
3971
3972 bool operator()(const PPEntityOffset &L, const PPEntityOffset &R) const {
3973 SourceLocation LHS = getLoc(L);
3974 SourceLocation RHS = getLoc(R);
3975 return Reader.getSourceManager().isBeforeInTranslationUnit(LHS, RHS);
3976 }
3977
3978 bool operator()(const PPEntityOffset &L, SourceLocation RHS) const {
3979 SourceLocation LHS = getLoc(L);
3980 return Reader.getSourceManager().isBeforeInTranslationUnit(LHS, RHS);
3981 }
3982
3983 bool operator()(SourceLocation LHS, const PPEntityOffset &R) const {
3984 SourceLocation RHS = getLoc(R);
3985 return Reader.getSourceManager().isBeforeInTranslationUnit(LHS, RHS);
3986 }
3987
3988 SourceLocation getLoc(const PPEntityOffset &PPE) const {
3989 return Reader.ReadSourceLocation(M, PPE.*PPLoc);
3990 }
3991};
3992
3993}
3994
3995/// \brief Returns the first preprocessed entity ID that ends after \arg BLoc.
3996PreprocessedEntityID
3997ASTReader::findBeginPreprocessedEntity(SourceLocation BLoc) const {
3998 if (SourceMgr.isLocalSourceLocation(BLoc))
3999 return getTotalNumPreprocessedEntities();
4000
4001 GlobalSLocOffsetMapType::const_iterator
4002 SLocMapI = GlobalSLocOffsetMap.find(SourceManager::MaxLoadedOffset -
Argyrios Kyrtzidisee2d5fd2013-03-08 02:32:34 +00004003 BLoc.getOffset() - 1);
Guy Benyei7f92f2d2012-12-18 14:30:41 +00004004 assert(SLocMapI != GlobalSLocOffsetMap.end() &&
4005 "Corrupted global sloc offset map");
4006
4007 if (SLocMapI->second->NumPreprocessedEntities == 0)
4008 return findNextPreprocessedEntity(SLocMapI);
4009
4010 ModuleFile &M = *SLocMapI->second;
4011 typedef const PPEntityOffset *pp_iterator;
4012 pp_iterator pp_begin = M.PreprocessedEntityOffsets;
4013 pp_iterator pp_end = pp_begin + M.NumPreprocessedEntities;
4014
4015 size_t Count = M.NumPreprocessedEntities;
4016 size_t Half;
4017 pp_iterator First = pp_begin;
4018 pp_iterator PPI;
4019
4020 // Do a binary search manually instead of using std::lower_bound because
4021 // The end locations of entities may be unordered (when a macro expansion
4022 // is inside another macro argument), but for this case it is not important
4023 // whether we get the first macro expansion or its containing macro.
4024 while (Count > 0) {
4025 Half = Count/2;
4026 PPI = First;
4027 std::advance(PPI, Half);
4028 if (SourceMgr.isBeforeInTranslationUnit(ReadSourceLocation(M, PPI->End),
4029 BLoc)){
4030 First = PPI;
4031 ++First;
4032 Count = Count - Half - 1;
4033 } else
4034 Count = Half;
4035 }
4036
4037 if (PPI == pp_end)
4038 return findNextPreprocessedEntity(SLocMapI);
4039
4040 return M.BasePreprocessedEntityID + (PPI - pp_begin);
4041}
4042
4043/// \brief Returns the first preprocessed entity ID that begins after \arg ELoc.
4044PreprocessedEntityID
4045ASTReader::findEndPreprocessedEntity(SourceLocation ELoc) const {
4046 if (SourceMgr.isLocalSourceLocation(ELoc))
4047 return getTotalNumPreprocessedEntities();
4048
4049 GlobalSLocOffsetMapType::const_iterator
4050 SLocMapI = GlobalSLocOffsetMap.find(SourceManager::MaxLoadedOffset -
Argyrios Kyrtzidisee2d5fd2013-03-08 02:32:34 +00004051 ELoc.getOffset() - 1);
Guy Benyei7f92f2d2012-12-18 14:30:41 +00004052 assert(SLocMapI != GlobalSLocOffsetMap.end() &&
4053 "Corrupted global sloc offset map");
4054
4055 if (SLocMapI->second->NumPreprocessedEntities == 0)
4056 return findNextPreprocessedEntity(SLocMapI);
4057
4058 ModuleFile &M = *SLocMapI->second;
4059 typedef const PPEntityOffset *pp_iterator;
4060 pp_iterator pp_begin = M.PreprocessedEntityOffsets;
4061 pp_iterator pp_end = pp_begin + M.NumPreprocessedEntities;
4062 pp_iterator PPI =
4063 std::upper_bound(pp_begin, pp_end, ELoc,
4064 PPEntityComp<&PPEntityOffset::Begin>(*this, M));
4065
4066 if (PPI == pp_end)
4067 return findNextPreprocessedEntity(SLocMapI);
4068
4069 return M.BasePreprocessedEntityID + (PPI - pp_begin);
4070}
4071
4072/// \brief Returns a pair of [Begin, End) indices of preallocated
4073/// preprocessed entities that \arg Range encompasses.
4074std::pair<unsigned, unsigned>
4075 ASTReader::findPreprocessedEntitiesInRange(SourceRange Range) {
4076 if (Range.isInvalid())
4077 return std::make_pair(0,0);
4078 assert(!SourceMgr.isBeforeInTranslationUnit(Range.getEnd(),Range.getBegin()));
4079
4080 PreprocessedEntityID BeginID = findBeginPreprocessedEntity(Range.getBegin());
4081 PreprocessedEntityID EndID = findEndPreprocessedEntity(Range.getEnd());
4082 return std::make_pair(BeginID, EndID);
4083}
4084
4085/// \brief Optionally returns true or false if the preallocated preprocessed
4086/// entity with index \arg Index came from file \arg FID.
David Blaikiedc84cd52013-02-20 22:23:23 +00004087Optional<bool> ASTReader::isPreprocessedEntityInFileID(unsigned Index,
Guy Benyei7f92f2d2012-12-18 14:30:41 +00004088 FileID FID) {
4089 if (FID.isInvalid())
4090 return false;
4091
4092 std::pair<ModuleFile *, unsigned> PPInfo = getModulePreprocessedEntity(Index);
4093 ModuleFile &M = *PPInfo.first;
4094 unsigned LocalIndex = PPInfo.second;
4095 const PPEntityOffset &PPOffs = M.PreprocessedEntityOffsets[LocalIndex];
4096
4097 SourceLocation Loc = ReadSourceLocation(M, PPOffs.Begin);
4098 if (Loc.isInvalid())
4099 return false;
4100
4101 if (SourceMgr.isInFileID(SourceMgr.getFileLoc(Loc), FID))
4102 return true;
4103 else
4104 return false;
4105}
4106
4107namespace {
4108 /// \brief Visitor used to search for information about a header file.
4109 class HeaderFileInfoVisitor {
Guy Benyei7f92f2d2012-12-18 14:30:41 +00004110 const FileEntry *FE;
4111
David Blaikiedc84cd52013-02-20 22:23:23 +00004112 Optional<HeaderFileInfo> HFI;
Guy Benyei7f92f2d2012-12-18 14:30:41 +00004113
4114 public:
Argyrios Kyrtzidis36592b12013-03-06 18:12:44 +00004115 explicit HeaderFileInfoVisitor(const FileEntry *FE)
4116 : FE(FE) { }
Guy Benyei7f92f2d2012-12-18 14:30:41 +00004117
4118 static bool visit(ModuleFile &M, void *UserData) {
4119 HeaderFileInfoVisitor *This
4120 = static_cast<HeaderFileInfoVisitor *>(UserData);
4121
Guy Benyei7f92f2d2012-12-18 14:30:41 +00004122 HeaderFileInfoLookupTable *Table
4123 = static_cast<HeaderFileInfoLookupTable *>(M.HeaderFileInfoTable);
4124 if (!Table)
4125 return false;
4126
4127 // Look in the on-disk hash table for an entry for this file name.
Argyrios Kyrtzidised3802e2013-03-06 18:12:47 +00004128 HeaderFileInfoLookupTable::iterator Pos = Table->find(This->FE);
Guy Benyei7f92f2d2012-12-18 14:30:41 +00004129 if (Pos == Table->end())
4130 return false;
4131
4132 This->HFI = *Pos;
4133 return true;
4134 }
4135
David Blaikiedc84cd52013-02-20 22:23:23 +00004136 Optional<HeaderFileInfo> getHeaderFileInfo() const { return HFI; }
Guy Benyei7f92f2d2012-12-18 14:30:41 +00004137 };
4138}
4139
4140HeaderFileInfo ASTReader::GetHeaderFileInfo(const FileEntry *FE) {
Argyrios Kyrtzidis36592b12013-03-06 18:12:44 +00004141 HeaderFileInfoVisitor Visitor(FE);
Guy Benyei7f92f2d2012-12-18 14:30:41 +00004142 ModuleMgr.visit(&HeaderFileInfoVisitor::visit, &Visitor);
David Blaikiedc84cd52013-02-20 22:23:23 +00004143 if (Optional<HeaderFileInfo> HFI = Visitor.getHeaderFileInfo()) {
Guy Benyei7f92f2d2012-12-18 14:30:41 +00004144 if (Listener)
4145 Listener->ReadHeaderFileInfo(*HFI, FE->getUID());
4146 return *HFI;
4147 }
4148
4149 return HeaderFileInfo();
4150}
4151
4152void ASTReader::ReadPragmaDiagnosticMappings(DiagnosticsEngine &Diag) {
4153 // FIXME: Make it work properly with modules.
Dmitri Gribenkocfa88f82013-01-12 19:30:44 +00004154 SmallVector<DiagnosticsEngine::DiagState *, 32> DiagStates;
Guy Benyei7f92f2d2012-12-18 14:30:41 +00004155 for (ModuleIterator I = ModuleMgr.begin(), E = ModuleMgr.end(); I != E; ++I) {
4156 ModuleFile &F = *(*I);
4157 unsigned Idx = 0;
4158 DiagStates.clear();
4159 assert(!Diag.DiagStates.empty());
4160 DiagStates.push_back(&Diag.DiagStates.front()); // the command-line one.
4161 while (Idx < F.PragmaDiagMappings.size()) {
4162 SourceLocation Loc = ReadSourceLocation(F, F.PragmaDiagMappings[Idx++]);
4163 unsigned DiagStateID = F.PragmaDiagMappings[Idx++];
4164 if (DiagStateID != 0) {
4165 Diag.DiagStatePoints.push_back(
4166 DiagnosticsEngine::DiagStatePoint(DiagStates[DiagStateID-1],
4167 FullSourceLoc(Loc, SourceMgr)));
4168 continue;
4169 }
4170
4171 assert(DiagStateID == 0);
4172 // A new DiagState was created here.
4173 Diag.DiagStates.push_back(*Diag.GetCurDiagState());
4174 DiagnosticsEngine::DiagState *NewState = &Diag.DiagStates.back();
4175 DiagStates.push_back(NewState);
4176 Diag.DiagStatePoints.push_back(
4177 DiagnosticsEngine::DiagStatePoint(NewState,
4178 FullSourceLoc(Loc, SourceMgr)));
4179 while (1) {
4180 assert(Idx < F.PragmaDiagMappings.size() &&
4181 "Invalid data, didn't find '-1' marking end of diag/map pairs");
4182 if (Idx >= F.PragmaDiagMappings.size()) {
4183 break; // Something is messed up but at least avoid infinite loop in
4184 // release build.
4185 }
4186 unsigned DiagID = F.PragmaDiagMappings[Idx++];
4187 if (DiagID == (unsigned)-1) {
4188 break; // no more diag/map pairs for this location.
4189 }
4190 diag::Mapping Map = (diag::Mapping)F.PragmaDiagMappings[Idx++];
4191 DiagnosticMappingInfo MappingInfo = Diag.makeMappingInfo(Map, Loc);
4192 Diag.GetCurDiagState()->setMappingInfo(DiagID, MappingInfo);
4193 }
4194 }
4195 }
4196}
4197
4198/// \brief Get the correct cursor and offset for loading a type.
4199ASTReader::RecordLocation ASTReader::TypeCursorForIndex(unsigned Index) {
4200 GlobalTypeMapType::iterator I = GlobalTypeMap.find(Index);
4201 assert(I != GlobalTypeMap.end() && "Corrupted global type map");
4202 ModuleFile *M = I->second;
4203 return RecordLocation(M, M->TypeOffsets[Index - M->BaseTypeIndex]);
4204}
4205
4206/// \brief Read and return the type with the given index..
4207///
4208/// The index is the type ID, shifted and minus the number of predefs. This
4209/// routine actually reads the record corresponding to the type at the given
4210/// location. It is a helper routine for GetType, which deals with reading type
4211/// IDs.
4212QualType ASTReader::readTypeRecord(unsigned Index) {
4213 RecordLocation Loc = TypeCursorForIndex(Index);
Chris Lattner8f9a1eb2013-01-20 00:56:42 +00004214 BitstreamCursor &DeclsCursor = Loc.F->DeclsCursor;
Guy Benyei7f92f2d2012-12-18 14:30:41 +00004215
4216 // Keep track of where we are in the stream, then jump back there
4217 // after reading this type.
4218 SavedStreamPosition SavedPosition(DeclsCursor);
4219
4220 ReadingKindTracker ReadingKind(Read_Type, *this);
4221
4222 // Note that we are loading a type record.
4223 Deserializing AType(this);
4224
4225 unsigned Idx = 0;
4226 DeclsCursor.JumpToBit(Loc.Offset);
4227 RecordData Record;
4228 unsigned Code = DeclsCursor.ReadCode();
Chris Lattnerb3ce3572013-01-20 02:38:54 +00004229 switch ((TypeCode)DeclsCursor.readRecord(Code, Record)) {
Guy Benyei7f92f2d2012-12-18 14:30:41 +00004230 case TYPE_EXT_QUAL: {
4231 if (Record.size() != 2) {
4232 Error("Incorrect encoding of extended qualifier type");
4233 return QualType();
4234 }
4235 QualType Base = readType(*Loc.F, Record, Idx);
4236 Qualifiers Quals = Qualifiers::fromOpaqueValue(Record[Idx++]);
4237 return Context.getQualifiedType(Base, Quals);
4238 }
4239
4240 case TYPE_COMPLEX: {
4241 if (Record.size() != 1) {
4242 Error("Incorrect encoding of complex type");
4243 return QualType();
4244 }
4245 QualType ElemType = readType(*Loc.F, Record, Idx);
4246 return Context.getComplexType(ElemType);
4247 }
4248
4249 case TYPE_POINTER: {
4250 if (Record.size() != 1) {
4251 Error("Incorrect encoding of pointer type");
4252 return QualType();
4253 }
4254 QualType PointeeType = readType(*Loc.F, Record, Idx);
4255 return Context.getPointerType(PointeeType);
4256 }
4257
4258 case TYPE_BLOCK_POINTER: {
4259 if (Record.size() != 1) {
4260 Error("Incorrect encoding of block pointer type");
4261 return QualType();
4262 }
4263 QualType PointeeType = readType(*Loc.F, Record, Idx);
4264 return Context.getBlockPointerType(PointeeType);
4265 }
4266
4267 case TYPE_LVALUE_REFERENCE: {
4268 if (Record.size() != 2) {
4269 Error("Incorrect encoding of lvalue reference type");
4270 return QualType();
4271 }
4272 QualType PointeeType = readType(*Loc.F, Record, Idx);
4273 return Context.getLValueReferenceType(PointeeType, Record[1]);
4274 }
4275
4276 case TYPE_RVALUE_REFERENCE: {
4277 if (Record.size() != 1) {
4278 Error("Incorrect encoding of rvalue reference type");
4279 return QualType();
4280 }
4281 QualType PointeeType = readType(*Loc.F, Record, Idx);
4282 return Context.getRValueReferenceType(PointeeType);
4283 }
4284
4285 case TYPE_MEMBER_POINTER: {
4286 if (Record.size() != 2) {
4287 Error("Incorrect encoding of member pointer type");
4288 return QualType();
4289 }
4290 QualType PointeeType = readType(*Loc.F, Record, Idx);
4291 QualType ClassType = readType(*Loc.F, Record, Idx);
4292 if (PointeeType.isNull() || ClassType.isNull())
4293 return QualType();
4294
4295 return Context.getMemberPointerType(PointeeType, ClassType.getTypePtr());
4296 }
4297
4298 case TYPE_CONSTANT_ARRAY: {
4299 QualType ElementType = readType(*Loc.F, Record, Idx);
4300 ArrayType::ArraySizeModifier ASM = (ArrayType::ArraySizeModifier)Record[1];
4301 unsigned IndexTypeQuals = Record[2];
4302 unsigned Idx = 3;
4303 llvm::APInt Size = ReadAPInt(Record, Idx);
4304 return Context.getConstantArrayType(ElementType, Size,
4305 ASM, IndexTypeQuals);
4306 }
4307
4308 case TYPE_INCOMPLETE_ARRAY: {
4309 QualType ElementType = readType(*Loc.F, Record, Idx);
4310 ArrayType::ArraySizeModifier ASM = (ArrayType::ArraySizeModifier)Record[1];
4311 unsigned IndexTypeQuals = Record[2];
4312 return Context.getIncompleteArrayType(ElementType, ASM, IndexTypeQuals);
4313 }
4314
4315 case TYPE_VARIABLE_ARRAY: {
4316 QualType ElementType = readType(*Loc.F, Record, Idx);
4317 ArrayType::ArraySizeModifier ASM = (ArrayType::ArraySizeModifier)Record[1];
4318 unsigned IndexTypeQuals = Record[2];
4319 SourceLocation LBLoc = ReadSourceLocation(*Loc.F, Record[3]);
4320 SourceLocation RBLoc = ReadSourceLocation(*Loc.F, Record[4]);
4321 return Context.getVariableArrayType(ElementType, ReadExpr(*Loc.F),
4322 ASM, IndexTypeQuals,
4323 SourceRange(LBLoc, RBLoc));
4324 }
4325
4326 case TYPE_VECTOR: {
4327 if (Record.size() != 3) {
4328 Error("incorrect encoding of vector type in AST file");
4329 return QualType();
4330 }
4331
4332 QualType ElementType = readType(*Loc.F, Record, Idx);
4333 unsigned NumElements = Record[1];
4334 unsigned VecKind = Record[2];
4335 return Context.getVectorType(ElementType, NumElements,
4336 (VectorType::VectorKind)VecKind);
4337 }
4338
4339 case TYPE_EXT_VECTOR: {
4340 if (Record.size() != 3) {
4341 Error("incorrect encoding of extended vector type in AST file");
4342 return QualType();
4343 }
4344
4345 QualType ElementType = readType(*Loc.F, Record, Idx);
4346 unsigned NumElements = Record[1];
4347 return Context.getExtVectorType(ElementType, NumElements);
4348 }
4349
4350 case TYPE_FUNCTION_NO_PROTO: {
4351 if (Record.size() != 6) {
4352 Error("incorrect encoding of no-proto function type");
4353 return QualType();
4354 }
4355 QualType ResultType = readType(*Loc.F, Record, Idx);
4356 FunctionType::ExtInfo Info(Record[1], Record[2], Record[3],
4357 (CallingConv)Record[4], Record[5]);
4358 return Context.getFunctionNoProtoType(ResultType, Info);
4359 }
4360
4361 case TYPE_FUNCTION_PROTO: {
4362 QualType ResultType = readType(*Loc.F, Record, Idx);
4363
4364 FunctionProtoType::ExtProtoInfo EPI;
4365 EPI.ExtInfo = FunctionType::ExtInfo(/*noreturn*/ Record[1],
4366 /*hasregparm*/ Record[2],
4367 /*regparm*/ Record[3],
4368 static_cast<CallingConv>(Record[4]),
4369 /*produces*/ Record[5]);
4370
4371 unsigned Idx = 6;
4372 unsigned NumParams = Record[Idx++];
4373 SmallVector<QualType, 16> ParamTypes;
4374 for (unsigned I = 0; I != NumParams; ++I)
4375 ParamTypes.push_back(readType(*Loc.F, Record, Idx));
4376
4377 EPI.Variadic = Record[Idx++];
4378 EPI.HasTrailingReturn = Record[Idx++];
4379 EPI.TypeQuals = Record[Idx++];
4380 EPI.RefQualifier = static_cast<RefQualifierKind>(Record[Idx++]);
4381 ExceptionSpecificationType EST =
4382 static_cast<ExceptionSpecificationType>(Record[Idx++]);
4383 EPI.ExceptionSpecType = EST;
4384 SmallVector<QualType, 2> Exceptions;
4385 if (EST == EST_Dynamic) {
4386 EPI.NumExceptions = Record[Idx++];
4387 for (unsigned I = 0; I != EPI.NumExceptions; ++I)
4388 Exceptions.push_back(readType(*Loc.F, Record, Idx));
4389 EPI.Exceptions = Exceptions.data();
4390 } else if (EST == EST_ComputedNoexcept) {
4391 EPI.NoexceptExpr = ReadExpr(*Loc.F);
4392 } else if (EST == EST_Uninstantiated) {
4393 EPI.ExceptionSpecDecl = ReadDeclAs<FunctionDecl>(*Loc.F, Record, Idx);
4394 EPI.ExceptionSpecTemplate = ReadDeclAs<FunctionDecl>(*Loc.F, Record, Idx);
4395 } else if (EST == EST_Unevaluated) {
4396 EPI.ExceptionSpecDecl = ReadDeclAs<FunctionDecl>(*Loc.F, Record, Idx);
4397 }
Jordan Rosebea522f2013-03-08 21:51:21 +00004398 return Context.getFunctionType(ResultType, ParamTypes, EPI);
Guy Benyei7f92f2d2012-12-18 14:30:41 +00004399 }
4400
4401 case TYPE_UNRESOLVED_USING: {
4402 unsigned Idx = 0;
4403 return Context.getTypeDeclType(
4404 ReadDeclAs<UnresolvedUsingTypenameDecl>(*Loc.F, Record, Idx));
4405 }
4406
4407 case TYPE_TYPEDEF: {
4408 if (Record.size() != 2) {
4409 Error("incorrect encoding of typedef type");
4410 return QualType();
4411 }
4412 unsigned Idx = 0;
4413 TypedefNameDecl *Decl = ReadDeclAs<TypedefNameDecl>(*Loc.F, Record, Idx);
4414 QualType Canonical = readType(*Loc.F, Record, Idx);
4415 if (!Canonical.isNull())
4416 Canonical = Context.getCanonicalType(Canonical);
4417 return Context.getTypedefType(Decl, Canonical);
4418 }
4419
4420 case TYPE_TYPEOF_EXPR:
4421 return Context.getTypeOfExprType(ReadExpr(*Loc.F));
4422
4423 case TYPE_TYPEOF: {
4424 if (Record.size() != 1) {
4425 Error("incorrect encoding of typeof(type) in AST file");
4426 return QualType();
4427 }
4428 QualType UnderlyingType = readType(*Loc.F, Record, Idx);
4429 return Context.getTypeOfType(UnderlyingType);
4430 }
4431
4432 case TYPE_DECLTYPE: {
4433 QualType UnderlyingType = readType(*Loc.F, Record, Idx);
4434 return Context.getDecltypeType(ReadExpr(*Loc.F), UnderlyingType);
4435 }
4436
4437 case TYPE_UNARY_TRANSFORM: {
4438 QualType BaseType = readType(*Loc.F, Record, Idx);
4439 QualType UnderlyingType = readType(*Loc.F, Record, Idx);
4440 UnaryTransformType::UTTKind UKind = (UnaryTransformType::UTTKind)Record[2];
4441 return Context.getUnaryTransformType(BaseType, UnderlyingType, UKind);
4442 }
4443
4444 case TYPE_AUTO:
4445 return Context.getAutoType(readType(*Loc.F, Record, Idx));
4446
4447 case TYPE_RECORD: {
4448 if (Record.size() != 2) {
4449 Error("incorrect encoding of record type");
4450 return QualType();
4451 }
4452 unsigned Idx = 0;
4453 bool IsDependent = Record[Idx++];
4454 RecordDecl *RD = ReadDeclAs<RecordDecl>(*Loc.F, Record, Idx);
4455 RD = cast_or_null<RecordDecl>(RD->getCanonicalDecl());
4456 QualType T = Context.getRecordType(RD);
4457 const_cast<Type*>(T.getTypePtr())->setDependent(IsDependent);
4458 return T;
4459 }
4460
4461 case TYPE_ENUM: {
4462 if (Record.size() != 2) {
4463 Error("incorrect encoding of enum type");
4464 return QualType();
4465 }
4466 unsigned Idx = 0;
4467 bool IsDependent = Record[Idx++];
4468 QualType T
4469 = Context.getEnumType(ReadDeclAs<EnumDecl>(*Loc.F, Record, Idx));
4470 const_cast<Type*>(T.getTypePtr())->setDependent(IsDependent);
4471 return T;
4472 }
4473
4474 case TYPE_ATTRIBUTED: {
4475 if (Record.size() != 3) {
4476 Error("incorrect encoding of attributed type");
4477 return QualType();
4478 }
4479 QualType modifiedType = readType(*Loc.F, Record, Idx);
4480 QualType equivalentType = readType(*Loc.F, Record, Idx);
4481 AttributedType::Kind kind = static_cast<AttributedType::Kind>(Record[2]);
4482 return Context.getAttributedType(kind, modifiedType, equivalentType);
4483 }
4484
4485 case TYPE_PAREN: {
4486 if (Record.size() != 1) {
4487 Error("incorrect encoding of paren type");
4488 return QualType();
4489 }
4490 QualType InnerType = readType(*Loc.F, Record, Idx);
4491 return Context.getParenType(InnerType);
4492 }
4493
4494 case TYPE_PACK_EXPANSION: {
4495 if (Record.size() != 2) {
4496 Error("incorrect encoding of pack expansion type");
4497 return QualType();
4498 }
4499 QualType Pattern = readType(*Loc.F, Record, Idx);
4500 if (Pattern.isNull())
4501 return QualType();
David Blaikiedc84cd52013-02-20 22:23:23 +00004502 Optional<unsigned> NumExpansions;
Guy Benyei7f92f2d2012-12-18 14:30:41 +00004503 if (Record[1])
4504 NumExpansions = Record[1] - 1;
4505 return Context.getPackExpansionType(Pattern, NumExpansions);
4506 }
4507
4508 case TYPE_ELABORATED: {
4509 unsigned Idx = 0;
4510 ElaboratedTypeKeyword Keyword = (ElaboratedTypeKeyword)Record[Idx++];
4511 NestedNameSpecifier *NNS = ReadNestedNameSpecifier(*Loc.F, Record, Idx);
4512 QualType NamedType = readType(*Loc.F, Record, Idx);
4513 return Context.getElaboratedType(Keyword, NNS, NamedType);
4514 }
4515
4516 case TYPE_OBJC_INTERFACE: {
4517 unsigned Idx = 0;
4518 ObjCInterfaceDecl *ItfD
4519 = ReadDeclAs<ObjCInterfaceDecl>(*Loc.F, Record, Idx);
4520 return Context.getObjCInterfaceType(ItfD->getCanonicalDecl());
4521 }
4522
4523 case TYPE_OBJC_OBJECT: {
4524 unsigned Idx = 0;
4525 QualType Base = readType(*Loc.F, Record, Idx);
4526 unsigned NumProtos = Record[Idx++];
4527 SmallVector<ObjCProtocolDecl*, 4> Protos;
4528 for (unsigned I = 0; I != NumProtos; ++I)
4529 Protos.push_back(ReadDeclAs<ObjCProtocolDecl>(*Loc.F, Record, Idx));
4530 return Context.getObjCObjectType(Base, Protos.data(), NumProtos);
4531 }
4532
4533 case TYPE_OBJC_OBJECT_POINTER: {
4534 unsigned Idx = 0;
4535 QualType Pointee = readType(*Loc.F, Record, Idx);
4536 return Context.getObjCObjectPointerType(Pointee);
4537 }
4538
4539 case TYPE_SUBST_TEMPLATE_TYPE_PARM: {
4540 unsigned Idx = 0;
4541 QualType Parm = readType(*Loc.F, Record, Idx);
4542 QualType Replacement = readType(*Loc.F, Record, Idx);
4543 return
4544 Context.getSubstTemplateTypeParmType(cast<TemplateTypeParmType>(Parm),
4545 Replacement);
4546 }
4547
4548 case TYPE_SUBST_TEMPLATE_TYPE_PARM_PACK: {
4549 unsigned Idx = 0;
4550 QualType Parm = readType(*Loc.F, Record, Idx);
4551 TemplateArgument ArgPack = ReadTemplateArgument(*Loc.F, Record, Idx);
4552 return Context.getSubstTemplateTypeParmPackType(
4553 cast<TemplateTypeParmType>(Parm),
4554 ArgPack);
4555 }
4556
4557 case TYPE_INJECTED_CLASS_NAME: {
4558 CXXRecordDecl *D = ReadDeclAs<CXXRecordDecl>(*Loc.F, Record, Idx);
4559 QualType TST = readType(*Loc.F, Record, Idx); // probably derivable
4560 // FIXME: ASTContext::getInjectedClassNameType is not currently suitable
4561 // for AST reading, too much interdependencies.
4562 return
4563 QualType(new (Context, TypeAlignment) InjectedClassNameType(D, TST), 0);
4564 }
4565
4566 case TYPE_TEMPLATE_TYPE_PARM: {
4567 unsigned Idx = 0;
4568 unsigned Depth = Record[Idx++];
4569 unsigned Index = Record[Idx++];
4570 bool Pack = Record[Idx++];
4571 TemplateTypeParmDecl *D
4572 = ReadDeclAs<TemplateTypeParmDecl>(*Loc.F, Record, Idx);
4573 return Context.getTemplateTypeParmType(Depth, Index, Pack, D);
4574 }
4575
4576 case TYPE_DEPENDENT_NAME: {
4577 unsigned Idx = 0;
4578 ElaboratedTypeKeyword Keyword = (ElaboratedTypeKeyword)Record[Idx++];
4579 NestedNameSpecifier *NNS = ReadNestedNameSpecifier(*Loc.F, Record, Idx);
4580 const IdentifierInfo *Name = this->GetIdentifierInfo(*Loc.F, Record, Idx);
4581 QualType Canon = readType(*Loc.F, Record, Idx);
4582 if (!Canon.isNull())
4583 Canon = Context.getCanonicalType(Canon);
4584 return Context.getDependentNameType(Keyword, NNS, Name, Canon);
4585 }
4586
4587 case TYPE_DEPENDENT_TEMPLATE_SPECIALIZATION: {
4588 unsigned Idx = 0;
4589 ElaboratedTypeKeyword Keyword = (ElaboratedTypeKeyword)Record[Idx++];
4590 NestedNameSpecifier *NNS = ReadNestedNameSpecifier(*Loc.F, Record, Idx);
4591 const IdentifierInfo *Name = this->GetIdentifierInfo(*Loc.F, Record, Idx);
4592 unsigned NumArgs = Record[Idx++];
4593 SmallVector<TemplateArgument, 8> Args;
4594 Args.reserve(NumArgs);
4595 while (NumArgs--)
4596 Args.push_back(ReadTemplateArgument(*Loc.F, Record, Idx));
4597 return Context.getDependentTemplateSpecializationType(Keyword, NNS, Name,
4598 Args.size(), Args.data());
4599 }
4600
4601 case TYPE_DEPENDENT_SIZED_ARRAY: {
4602 unsigned Idx = 0;
4603
4604 // ArrayType
4605 QualType ElementType = readType(*Loc.F, Record, Idx);
4606 ArrayType::ArraySizeModifier ASM
4607 = (ArrayType::ArraySizeModifier)Record[Idx++];
4608 unsigned IndexTypeQuals = Record[Idx++];
4609
4610 // DependentSizedArrayType
4611 Expr *NumElts = ReadExpr(*Loc.F);
4612 SourceRange Brackets = ReadSourceRange(*Loc.F, Record, Idx);
4613
4614 return Context.getDependentSizedArrayType(ElementType, NumElts, ASM,
4615 IndexTypeQuals, Brackets);
4616 }
4617
4618 case TYPE_TEMPLATE_SPECIALIZATION: {
4619 unsigned Idx = 0;
4620 bool IsDependent = Record[Idx++];
4621 TemplateName Name = ReadTemplateName(*Loc.F, Record, Idx);
4622 SmallVector<TemplateArgument, 8> Args;
4623 ReadTemplateArgumentList(Args, *Loc.F, Record, Idx);
4624 QualType Underlying = readType(*Loc.F, Record, Idx);
4625 QualType T;
4626 if (Underlying.isNull())
4627 T = Context.getCanonicalTemplateSpecializationType(Name, Args.data(),
4628 Args.size());
4629 else
4630 T = Context.getTemplateSpecializationType(Name, Args.data(),
4631 Args.size(), Underlying);
4632 const_cast<Type*>(T.getTypePtr())->setDependent(IsDependent);
4633 return T;
4634 }
4635
4636 case TYPE_ATOMIC: {
4637 if (Record.size() != 1) {
4638 Error("Incorrect encoding of atomic type");
4639 return QualType();
4640 }
4641 QualType ValueType = readType(*Loc.F, Record, Idx);
4642 return Context.getAtomicType(ValueType);
4643 }
4644 }
4645 llvm_unreachable("Invalid TypeCode!");
4646}
4647
4648class clang::TypeLocReader : public TypeLocVisitor<TypeLocReader> {
4649 ASTReader &Reader;
4650 ModuleFile &F;
4651 const ASTReader::RecordData &Record;
4652 unsigned &Idx;
4653
4654 SourceLocation ReadSourceLocation(const ASTReader::RecordData &R,
4655 unsigned &I) {
4656 return Reader.ReadSourceLocation(F, R, I);
4657 }
4658
4659 template<typename T>
4660 T *ReadDeclAs(const ASTReader::RecordData &Record, unsigned &Idx) {
4661 return Reader.ReadDeclAs<T>(F, Record, Idx);
4662 }
4663
4664public:
4665 TypeLocReader(ASTReader &Reader, ModuleFile &F,
4666 const ASTReader::RecordData &Record, unsigned &Idx)
4667 : Reader(Reader), F(F), Record(Record), Idx(Idx)
4668 { }
4669
4670 // We want compile-time assurance that we've enumerated all of
4671 // these, so unfortunately we have to declare them first, then
4672 // define them out-of-line.
4673#define ABSTRACT_TYPELOC(CLASS, PARENT)
4674#define TYPELOC(CLASS, PARENT) \
4675 void Visit##CLASS##TypeLoc(CLASS##TypeLoc TyLoc);
4676#include "clang/AST/TypeLocNodes.def"
4677
4678 void VisitFunctionTypeLoc(FunctionTypeLoc);
4679 void VisitArrayTypeLoc(ArrayTypeLoc);
4680};
4681
4682void TypeLocReader::VisitQualifiedTypeLoc(QualifiedTypeLoc TL) {
4683 // nothing to do
4684}
4685void TypeLocReader::VisitBuiltinTypeLoc(BuiltinTypeLoc TL) {
4686 TL.setBuiltinLoc(ReadSourceLocation(Record, Idx));
4687 if (TL.needsExtraLocalData()) {
4688 TL.setWrittenTypeSpec(static_cast<DeclSpec::TST>(Record[Idx++]));
4689 TL.setWrittenSignSpec(static_cast<DeclSpec::TSS>(Record[Idx++]));
4690 TL.setWrittenWidthSpec(static_cast<DeclSpec::TSW>(Record[Idx++]));
4691 TL.setModeAttr(Record[Idx++]);
4692 }
4693}
4694void TypeLocReader::VisitComplexTypeLoc(ComplexTypeLoc TL) {
4695 TL.setNameLoc(ReadSourceLocation(Record, Idx));
4696}
4697void TypeLocReader::VisitPointerTypeLoc(PointerTypeLoc TL) {
4698 TL.setStarLoc(ReadSourceLocation(Record, Idx));
4699}
4700void TypeLocReader::VisitBlockPointerTypeLoc(BlockPointerTypeLoc TL) {
4701 TL.setCaretLoc(ReadSourceLocation(Record, Idx));
4702}
4703void TypeLocReader::VisitLValueReferenceTypeLoc(LValueReferenceTypeLoc TL) {
4704 TL.setAmpLoc(ReadSourceLocation(Record, Idx));
4705}
4706void TypeLocReader::VisitRValueReferenceTypeLoc(RValueReferenceTypeLoc TL) {
4707 TL.setAmpAmpLoc(ReadSourceLocation(Record, Idx));
4708}
4709void TypeLocReader::VisitMemberPointerTypeLoc(MemberPointerTypeLoc TL) {
4710 TL.setStarLoc(ReadSourceLocation(Record, Idx));
4711 TL.setClassTInfo(Reader.GetTypeSourceInfo(F, Record, Idx));
4712}
4713void TypeLocReader::VisitArrayTypeLoc(ArrayTypeLoc TL) {
4714 TL.setLBracketLoc(ReadSourceLocation(Record, Idx));
4715 TL.setRBracketLoc(ReadSourceLocation(Record, Idx));
4716 if (Record[Idx++])
4717 TL.setSizeExpr(Reader.ReadExpr(F));
4718 else
4719 TL.setSizeExpr(0);
4720}
4721void TypeLocReader::VisitConstantArrayTypeLoc(ConstantArrayTypeLoc TL) {
4722 VisitArrayTypeLoc(TL);
4723}
4724void TypeLocReader::VisitIncompleteArrayTypeLoc(IncompleteArrayTypeLoc TL) {
4725 VisitArrayTypeLoc(TL);
4726}
4727void TypeLocReader::VisitVariableArrayTypeLoc(VariableArrayTypeLoc TL) {
4728 VisitArrayTypeLoc(TL);
4729}
4730void TypeLocReader::VisitDependentSizedArrayTypeLoc(
4731 DependentSizedArrayTypeLoc TL) {
4732 VisitArrayTypeLoc(TL);
4733}
4734void TypeLocReader::VisitDependentSizedExtVectorTypeLoc(
4735 DependentSizedExtVectorTypeLoc TL) {
4736 TL.setNameLoc(ReadSourceLocation(Record, Idx));
4737}
4738void TypeLocReader::VisitVectorTypeLoc(VectorTypeLoc TL) {
4739 TL.setNameLoc(ReadSourceLocation(Record, Idx));
4740}
4741void TypeLocReader::VisitExtVectorTypeLoc(ExtVectorTypeLoc TL) {
4742 TL.setNameLoc(ReadSourceLocation(Record, Idx));
4743}
4744void TypeLocReader::VisitFunctionTypeLoc(FunctionTypeLoc TL) {
4745 TL.setLocalRangeBegin(ReadSourceLocation(Record, Idx));
4746 TL.setLParenLoc(ReadSourceLocation(Record, Idx));
4747 TL.setRParenLoc(ReadSourceLocation(Record, Idx));
4748 TL.setLocalRangeEnd(ReadSourceLocation(Record, Idx));
4749 for (unsigned i = 0, e = TL.getNumArgs(); i != e; ++i) {
4750 TL.setArg(i, ReadDeclAs<ParmVarDecl>(Record, Idx));
4751 }
4752}
4753void TypeLocReader::VisitFunctionProtoTypeLoc(FunctionProtoTypeLoc TL) {
4754 VisitFunctionTypeLoc(TL);
4755}
4756void TypeLocReader::VisitFunctionNoProtoTypeLoc(FunctionNoProtoTypeLoc TL) {
4757 VisitFunctionTypeLoc(TL);
4758}
4759void TypeLocReader::VisitUnresolvedUsingTypeLoc(UnresolvedUsingTypeLoc TL) {
4760 TL.setNameLoc(ReadSourceLocation(Record, Idx));
4761}
4762void TypeLocReader::VisitTypedefTypeLoc(TypedefTypeLoc TL) {
4763 TL.setNameLoc(ReadSourceLocation(Record, Idx));
4764}
4765void TypeLocReader::VisitTypeOfExprTypeLoc(TypeOfExprTypeLoc TL) {
4766 TL.setTypeofLoc(ReadSourceLocation(Record, Idx));
4767 TL.setLParenLoc(ReadSourceLocation(Record, Idx));
4768 TL.setRParenLoc(ReadSourceLocation(Record, Idx));
4769}
4770void TypeLocReader::VisitTypeOfTypeLoc(TypeOfTypeLoc TL) {
4771 TL.setTypeofLoc(ReadSourceLocation(Record, Idx));
4772 TL.setLParenLoc(ReadSourceLocation(Record, Idx));
4773 TL.setRParenLoc(ReadSourceLocation(Record, Idx));
4774 TL.setUnderlyingTInfo(Reader.GetTypeSourceInfo(F, Record, Idx));
4775}
4776void TypeLocReader::VisitDecltypeTypeLoc(DecltypeTypeLoc TL) {
4777 TL.setNameLoc(ReadSourceLocation(Record, Idx));
4778}
4779void TypeLocReader::VisitUnaryTransformTypeLoc(UnaryTransformTypeLoc TL) {
4780 TL.setKWLoc(ReadSourceLocation(Record, Idx));
4781 TL.setLParenLoc(ReadSourceLocation(Record, Idx));
4782 TL.setRParenLoc(ReadSourceLocation(Record, Idx));
4783 TL.setUnderlyingTInfo(Reader.GetTypeSourceInfo(F, Record, Idx));
4784}
4785void TypeLocReader::VisitAutoTypeLoc(AutoTypeLoc TL) {
4786 TL.setNameLoc(ReadSourceLocation(Record, Idx));
4787}
4788void TypeLocReader::VisitRecordTypeLoc(RecordTypeLoc TL) {
4789 TL.setNameLoc(ReadSourceLocation(Record, Idx));
4790}
4791void TypeLocReader::VisitEnumTypeLoc(EnumTypeLoc TL) {
4792 TL.setNameLoc(ReadSourceLocation(Record, Idx));
4793}
4794void TypeLocReader::VisitAttributedTypeLoc(AttributedTypeLoc TL) {
4795 TL.setAttrNameLoc(ReadSourceLocation(Record, Idx));
4796 if (TL.hasAttrOperand()) {
4797 SourceRange range;
4798 range.setBegin(ReadSourceLocation(Record, Idx));
4799 range.setEnd(ReadSourceLocation(Record, Idx));
4800 TL.setAttrOperandParensRange(range);
4801 }
4802 if (TL.hasAttrExprOperand()) {
4803 if (Record[Idx++])
4804 TL.setAttrExprOperand(Reader.ReadExpr(F));
4805 else
4806 TL.setAttrExprOperand(0);
4807 } else if (TL.hasAttrEnumOperand())
4808 TL.setAttrEnumOperandLoc(ReadSourceLocation(Record, Idx));
4809}
4810void TypeLocReader::VisitTemplateTypeParmTypeLoc(TemplateTypeParmTypeLoc TL) {
4811 TL.setNameLoc(ReadSourceLocation(Record, Idx));
4812}
4813void TypeLocReader::VisitSubstTemplateTypeParmTypeLoc(
4814 SubstTemplateTypeParmTypeLoc TL) {
4815 TL.setNameLoc(ReadSourceLocation(Record, Idx));
4816}
4817void TypeLocReader::VisitSubstTemplateTypeParmPackTypeLoc(
4818 SubstTemplateTypeParmPackTypeLoc TL) {
4819 TL.setNameLoc(ReadSourceLocation(Record, Idx));
4820}
4821void TypeLocReader::VisitTemplateSpecializationTypeLoc(
4822 TemplateSpecializationTypeLoc TL) {
4823 TL.setTemplateKeywordLoc(ReadSourceLocation(Record, Idx));
4824 TL.setTemplateNameLoc(ReadSourceLocation(Record, Idx));
4825 TL.setLAngleLoc(ReadSourceLocation(Record, Idx));
4826 TL.setRAngleLoc(ReadSourceLocation(Record, Idx));
4827 for (unsigned i = 0, e = TL.getNumArgs(); i != e; ++i)
4828 TL.setArgLocInfo(i,
4829 Reader.GetTemplateArgumentLocInfo(F,
4830 TL.getTypePtr()->getArg(i).getKind(),
4831 Record, Idx));
4832}
4833void TypeLocReader::VisitParenTypeLoc(ParenTypeLoc TL) {
4834 TL.setLParenLoc(ReadSourceLocation(Record, Idx));
4835 TL.setRParenLoc(ReadSourceLocation(Record, Idx));
4836}
4837void TypeLocReader::VisitElaboratedTypeLoc(ElaboratedTypeLoc TL) {
4838 TL.setElaboratedKeywordLoc(ReadSourceLocation(Record, Idx));
4839 TL.setQualifierLoc(Reader.ReadNestedNameSpecifierLoc(F, Record, Idx));
4840}
4841void TypeLocReader::VisitInjectedClassNameTypeLoc(InjectedClassNameTypeLoc TL) {
4842 TL.setNameLoc(ReadSourceLocation(Record, Idx));
4843}
4844void TypeLocReader::VisitDependentNameTypeLoc(DependentNameTypeLoc TL) {
4845 TL.setElaboratedKeywordLoc(ReadSourceLocation(Record, Idx));
4846 TL.setQualifierLoc(Reader.ReadNestedNameSpecifierLoc(F, Record, Idx));
4847 TL.setNameLoc(ReadSourceLocation(Record, Idx));
4848}
4849void TypeLocReader::VisitDependentTemplateSpecializationTypeLoc(
4850 DependentTemplateSpecializationTypeLoc TL) {
4851 TL.setElaboratedKeywordLoc(ReadSourceLocation(Record, Idx));
4852 TL.setQualifierLoc(Reader.ReadNestedNameSpecifierLoc(F, Record, Idx));
4853 TL.setTemplateKeywordLoc(ReadSourceLocation(Record, Idx));
4854 TL.setTemplateNameLoc(ReadSourceLocation(Record, Idx));
4855 TL.setLAngleLoc(ReadSourceLocation(Record, Idx));
4856 TL.setRAngleLoc(ReadSourceLocation(Record, Idx));
4857 for (unsigned I = 0, E = TL.getNumArgs(); I != E; ++I)
4858 TL.setArgLocInfo(I,
4859 Reader.GetTemplateArgumentLocInfo(F,
4860 TL.getTypePtr()->getArg(I).getKind(),
4861 Record, Idx));
4862}
4863void TypeLocReader::VisitPackExpansionTypeLoc(PackExpansionTypeLoc TL) {
4864 TL.setEllipsisLoc(ReadSourceLocation(Record, Idx));
4865}
4866void TypeLocReader::VisitObjCInterfaceTypeLoc(ObjCInterfaceTypeLoc TL) {
4867 TL.setNameLoc(ReadSourceLocation(Record, Idx));
4868}
4869void TypeLocReader::VisitObjCObjectTypeLoc(ObjCObjectTypeLoc TL) {
4870 TL.setHasBaseTypeAsWritten(Record[Idx++]);
4871 TL.setLAngleLoc(ReadSourceLocation(Record, Idx));
4872 TL.setRAngleLoc(ReadSourceLocation(Record, Idx));
4873 for (unsigned i = 0, e = TL.getNumProtocols(); i != e; ++i)
4874 TL.setProtocolLoc(i, ReadSourceLocation(Record, Idx));
4875}
4876void TypeLocReader::VisitObjCObjectPointerTypeLoc(ObjCObjectPointerTypeLoc TL) {
4877 TL.setStarLoc(ReadSourceLocation(Record, Idx));
4878}
4879void TypeLocReader::VisitAtomicTypeLoc(AtomicTypeLoc TL) {
4880 TL.setKWLoc(ReadSourceLocation(Record, Idx));
4881 TL.setLParenLoc(ReadSourceLocation(Record, Idx));
4882 TL.setRParenLoc(ReadSourceLocation(Record, Idx));
4883}
4884
4885TypeSourceInfo *ASTReader::GetTypeSourceInfo(ModuleFile &F,
4886 const RecordData &Record,
4887 unsigned &Idx) {
4888 QualType InfoTy = readType(F, Record, Idx);
4889 if (InfoTy.isNull())
4890 return 0;
4891
4892 TypeSourceInfo *TInfo = getContext().CreateTypeSourceInfo(InfoTy);
4893 TypeLocReader TLR(*this, F, Record, Idx);
4894 for (TypeLoc TL = TInfo->getTypeLoc(); !TL.isNull(); TL = TL.getNextTypeLoc())
4895 TLR.Visit(TL);
4896 return TInfo;
4897}
4898
4899QualType ASTReader::GetType(TypeID ID) {
4900 unsigned FastQuals = ID & Qualifiers::FastMask;
4901 unsigned Index = ID >> Qualifiers::FastWidth;
4902
4903 if (Index < NUM_PREDEF_TYPE_IDS) {
4904 QualType T;
4905 switch ((PredefinedTypeIDs)Index) {
4906 case PREDEF_TYPE_NULL_ID: return QualType();
4907 case PREDEF_TYPE_VOID_ID: T = Context.VoidTy; break;
4908 case PREDEF_TYPE_BOOL_ID: T = Context.BoolTy; break;
4909
4910 case PREDEF_TYPE_CHAR_U_ID:
4911 case PREDEF_TYPE_CHAR_S_ID:
4912 // FIXME: Check that the signedness of CharTy is correct!
4913 T = Context.CharTy;
4914 break;
4915
4916 case PREDEF_TYPE_UCHAR_ID: T = Context.UnsignedCharTy; break;
4917 case PREDEF_TYPE_USHORT_ID: T = Context.UnsignedShortTy; break;
4918 case PREDEF_TYPE_UINT_ID: T = Context.UnsignedIntTy; break;
4919 case PREDEF_TYPE_ULONG_ID: T = Context.UnsignedLongTy; break;
4920 case PREDEF_TYPE_ULONGLONG_ID: T = Context.UnsignedLongLongTy; break;
4921 case PREDEF_TYPE_UINT128_ID: T = Context.UnsignedInt128Ty; break;
4922 case PREDEF_TYPE_SCHAR_ID: T = Context.SignedCharTy; break;
4923 case PREDEF_TYPE_WCHAR_ID: T = Context.WCharTy; break;
4924 case PREDEF_TYPE_SHORT_ID: T = Context.ShortTy; break;
4925 case PREDEF_TYPE_INT_ID: T = Context.IntTy; break;
4926 case PREDEF_TYPE_LONG_ID: T = Context.LongTy; break;
4927 case PREDEF_TYPE_LONGLONG_ID: T = Context.LongLongTy; break;
4928 case PREDEF_TYPE_INT128_ID: T = Context.Int128Ty; break;
4929 case PREDEF_TYPE_HALF_ID: T = Context.HalfTy; break;
4930 case PREDEF_TYPE_FLOAT_ID: T = Context.FloatTy; break;
4931 case PREDEF_TYPE_DOUBLE_ID: T = Context.DoubleTy; break;
4932 case PREDEF_TYPE_LONGDOUBLE_ID: T = Context.LongDoubleTy; break;
4933 case PREDEF_TYPE_OVERLOAD_ID: T = Context.OverloadTy; break;
4934 case PREDEF_TYPE_BOUND_MEMBER: T = Context.BoundMemberTy; break;
4935 case PREDEF_TYPE_PSEUDO_OBJECT: T = Context.PseudoObjectTy; break;
4936 case PREDEF_TYPE_DEPENDENT_ID: T = Context.DependentTy; break;
4937 case PREDEF_TYPE_UNKNOWN_ANY: T = Context.UnknownAnyTy; break;
4938 case PREDEF_TYPE_NULLPTR_ID: T = Context.NullPtrTy; break;
4939 case PREDEF_TYPE_CHAR16_ID: T = Context.Char16Ty; break;
4940 case PREDEF_TYPE_CHAR32_ID: T = Context.Char32Ty; break;
4941 case PREDEF_TYPE_OBJC_ID: T = Context.ObjCBuiltinIdTy; break;
4942 case PREDEF_TYPE_OBJC_CLASS: T = Context.ObjCBuiltinClassTy; break;
4943 case PREDEF_TYPE_OBJC_SEL: T = Context.ObjCBuiltinSelTy; break;
Guy Benyeib13621d2012-12-18 14:38:23 +00004944 case PREDEF_TYPE_IMAGE1D_ID: T = Context.OCLImage1dTy; break;
4945 case PREDEF_TYPE_IMAGE1D_ARR_ID: T = Context.OCLImage1dArrayTy; break;
4946 case PREDEF_TYPE_IMAGE1D_BUFF_ID: T = Context.OCLImage1dBufferTy; break;
4947 case PREDEF_TYPE_IMAGE2D_ID: T = Context.OCLImage2dTy; break;
4948 case PREDEF_TYPE_IMAGE2D_ARR_ID: T = Context.OCLImage2dArrayTy; break;
4949 case PREDEF_TYPE_IMAGE3D_ID: T = Context.OCLImage3dTy; break;
Guy Benyei21f18c42013-02-07 10:55:47 +00004950 case PREDEF_TYPE_SAMPLER_ID: T = Context.OCLSamplerTy; break;
Guy Benyeie6b9d802013-01-20 12:31:11 +00004951 case PREDEF_TYPE_EVENT_ID: T = Context.OCLEventTy; break;
Guy Benyei7f92f2d2012-12-18 14:30:41 +00004952 case PREDEF_TYPE_AUTO_DEDUCT: T = Context.getAutoDeductType(); break;
4953
4954 case PREDEF_TYPE_AUTO_RREF_DEDUCT:
4955 T = Context.getAutoRRefDeductType();
4956 break;
4957
4958 case PREDEF_TYPE_ARC_UNBRIDGED_CAST:
4959 T = Context.ARCUnbridgedCastTy;
4960 break;
4961
4962 case PREDEF_TYPE_VA_LIST_TAG:
4963 T = Context.getVaListTagType();
4964 break;
4965
4966 case PREDEF_TYPE_BUILTIN_FN:
4967 T = Context.BuiltinFnTy;
4968 break;
4969 }
4970
4971 assert(!T.isNull() && "Unknown predefined type");
4972 return T.withFastQualifiers(FastQuals);
4973 }
4974
4975 Index -= NUM_PREDEF_TYPE_IDS;
4976 assert(Index < TypesLoaded.size() && "Type index out-of-range");
4977 if (TypesLoaded[Index].isNull()) {
4978 TypesLoaded[Index] = readTypeRecord(Index);
4979 if (TypesLoaded[Index].isNull())
4980 return QualType();
4981
4982 TypesLoaded[Index]->setFromAST();
4983 if (DeserializationListener)
4984 DeserializationListener->TypeRead(TypeIdx::fromTypeID(ID),
4985 TypesLoaded[Index]);
4986 }
4987
4988 return TypesLoaded[Index].withFastQualifiers(FastQuals);
4989}
4990
4991QualType ASTReader::getLocalType(ModuleFile &F, unsigned LocalID) {
4992 return GetType(getGlobalTypeID(F, LocalID));
4993}
4994
4995serialization::TypeID
4996ASTReader::getGlobalTypeID(ModuleFile &F, unsigned LocalID) const {
4997 unsigned FastQuals = LocalID & Qualifiers::FastMask;
4998 unsigned LocalIndex = LocalID >> Qualifiers::FastWidth;
4999
5000 if (LocalIndex < NUM_PREDEF_TYPE_IDS)
5001 return LocalID;
5002
5003 ContinuousRangeMap<uint32_t, int, 2>::iterator I
5004 = F.TypeRemap.find(LocalIndex - NUM_PREDEF_TYPE_IDS);
5005 assert(I != F.TypeRemap.end() && "Invalid index into type index remap");
5006
5007 unsigned GlobalIndex = LocalIndex + I->second;
5008 return (GlobalIndex << Qualifiers::FastWidth) | FastQuals;
5009}
5010
5011TemplateArgumentLocInfo
5012ASTReader::GetTemplateArgumentLocInfo(ModuleFile &F,
5013 TemplateArgument::ArgKind Kind,
5014 const RecordData &Record,
5015 unsigned &Index) {
5016 switch (Kind) {
5017 case TemplateArgument::Expression:
5018 return ReadExpr(F);
5019 case TemplateArgument::Type:
5020 return GetTypeSourceInfo(F, Record, Index);
5021 case TemplateArgument::Template: {
5022 NestedNameSpecifierLoc QualifierLoc = ReadNestedNameSpecifierLoc(F, Record,
5023 Index);
5024 SourceLocation TemplateNameLoc = ReadSourceLocation(F, Record, Index);
5025 return TemplateArgumentLocInfo(QualifierLoc, TemplateNameLoc,
5026 SourceLocation());
5027 }
5028 case TemplateArgument::TemplateExpansion: {
5029 NestedNameSpecifierLoc QualifierLoc = ReadNestedNameSpecifierLoc(F, Record,
5030 Index);
5031 SourceLocation TemplateNameLoc = ReadSourceLocation(F, Record, Index);
5032 SourceLocation EllipsisLoc = ReadSourceLocation(F, Record, Index);
5033 return TemplateArgumentLocInfo(QualifierLoc, TemplateNameLoc,
5034 EllipsisLoc);
5035 }
5036 case TemplateArgument::Null:
5037 case TemplateArgument::Integral:
5038 case TemplateArgument::Declaration:
5039 case TemplateArgument::NullPtr:
5040 case TemplateArgument::Pack:
5041 // FIXME: Is this right?
5042 return TemplateArgumentLocInfo();
5043 }
5044 llvm_unreachable("unexpected template argument loc");
5045}
5046
5047TemplateArgumentLoc
5048ASTReader::ReadTemplateArgumentLoc(ModuleFile &F,
5049 const RecordData &Record, unsigned &Index) {
5050 TemplateArgument Arg = ReadTemplateArgument(F, Record, Index);
5051
5052 if (Arg.getKind() == TemplateArgument::Expression) {
5053 if (Record[Index++]) // bool InfoHasSameExpr.
5054 return TemplateArgumentLoc(Arg, TemplateArgumentLocInfo(Arg.getAsExpr()));
5055 }
5056 return TemplateArgumentLoc(Arg, GetTemplateArgumentLocInfo(F, Arg.getKind(),
5057 Record, Index));
5058}
5059
5060Decl *ASTReader::GetExternalDecl(uint32_t ID) {
5061 return GetDecl(ID);
5062}
5063
5064uint64_t ASTReader::readCXXBaseSpecifiers(ModuleFile &M, const RecordData &Record,
5065 unsigned &Idx){
5066 if (Idx >= Record.size())
5067 return 0;
5068
5069 unsigned LocalID = Record[Idx++];
5070 return getGlobalBitOffset(M, M.CXXBaseSpecifiersOffsets[LocalID - 1]);
5071}
5072
5073CXXBaseSpecifier *ASTReader::GetExternalCXXBaseSpecifiers(uint64_t Offset) {
5074 RecordLocation Loc = getLocalBitOffset(Offset);
Chris Lattner8f9a1eb2013-01-20 00:56:42 +00005075 BitstreamCursor &Cursor = Loc.F->DeclsCursor;
Guy Benyei7f92f2d2012-12-18 14:30:41 +00005076 SavedStreamPosition SavedPosition(Cursor);
5077 Cursor.JumpToBit(Loc.Offset);
5078 ReadingKindTracker ReadingKind(Read_Decl, *this);
5079 RecordData Record;
5080 unsigned Code = Cursor.ReadCode();
Chris Lattnerb3ce3572013-01-20 02:38:54 +00005081 unsigned RecCode = Cursor.readRecord(Code, Record);
Guy Benyei7f92f2d2012-12-18 14:30:41 +00005082 if (RecCode != DECL_CXX_BASE_SPECIFIERS) {
5083 Error("Malformed AST file: missing C++ base specifiers");
5084 return 0;
5085 }
5086
5087 unsigned Idx = 0;
5088 unsigned NumBases = Record[Idx++];
5089 void *Mem = Context.Allocate(sizeof(CXXBaseSpecifier) * NumBases);
5090 CXXBaseSpecifier *Bases = new (Mem) CXXBaseSpecifier [NumBases];
5091 for (unsigned I = 0; I != NumBases; ++I)
5092 Bases[I] = ReadCXXBaseSpecifier(*Loc.F, Record, Idx);
5093 return Bases;
5094}
5095
5096serialization::DeclID
5097ASTReader::getGlobalDeclID(ModuleFile &F, LocalDeclID LocalID) const {
5098 if (LocalID < NUM_PREDEF_DECL_IDS)
5099 return LocalID;
5100
5101 ContinuousRangeMap<uint32_t, int, 2>::iterator I
5102 = F.DeclRemap.find(LocalID - NUM_PREDEF_DECL_IDS);
5103 assert(I != F.DeclRemap.end() && "Invalid index into decl index remap");
5104
5105 return LocalID + I->second;
5106}
5107
5108bool ASTReader::isDeclIDFromModule(serialization::GlobalDeclID ID,
5109 ModuleFile &M) const {
5110 GlobalDeclMapType::const_iterator I = GlobalDeclMap.find(ID);
5111 assert(I != GlobalDeclMap.end() && "Corrupted global declaration map");
5112 return &M == I->second;
5113}
5114
Douglas Gregor5a04f9f2013-01-21 15:25:38 +00005115ModuleFile *ASTReader::getOwningModuleFile(const Decl *D) {
Guy Benyei7f92f2d2012-12-18 14:30:41 +00005116 if (!D->isFromASTFile())
5117 return 0;
5118 GlobalDeclMapType::const_iterator I = GlobalDeclMap.find(D->getGlobalID());
5119 assert(I != GlobalDeclMap.end() && "Corrupted global declaration map");
5120 return I->second;
5121}
5122
5123SourceLocation ASTReader::getSourceLocationForDeclID(GlobalDeclID ID) {
5124 if (ID < NUM_PREDEF_DECL_IDS)
5125 return SourceLocation();
5126
5127 unsigned Index = ID - NUM_PREDEF_DECL_IDS;
5128
5129 if (Index > DeclsLoaded.size()) {
5130 Error("declaration ID out-of-range for AST file");
5131 return SourceLocation();
5132 }
5133
5134 if (Decl *D = DeclsLoaded[Index])
5135 return D->getLocation();
5136
5137 unsigned RawLocation = 0;
5138 RecordLocation Rec = DeclCursorForID(ID, RawLocation);
5139 return ReadSourceLocation(*Rec.F, RawLocation);
5140}
5141
5142Decl *ASTReader::GetDecl(DeclID ID) {
5143 if (ID < NUM_PREDEF_DECL_IDS) {
5144 switch ((PredefinedDeclIDs)ID) {
5145 case PREDEF_DECL_NULL_ID:
5146 return 0;
5147
5148 case PREDEF_DECL_TRANSLATION_UNIT_ID:
5149 return Context.getTranslationUnitDecl();
5150
5151 case PREDEF_DECL_OBJC_ID_ID:
5152 return Context.getObjCIdDecl();
5153
5154 case PREDEF_DECL_OBJC_SEL_ID:
5155 return Context.getObjCSelDecl();
5156
5157 case PREDEF_DECL_OBJC_CLASS_ID:
5158 return Context.getObjCClassDecl();
5159
5160 case PREDEF_DECL_OBJC_PROTOCOL_ID:
5161 return Context.getObjCProtocolDecl();
5162
5163 case PREDEF_DECL_INT_128_ID:
5164 return Context.getInt128Decl();
5165
5166 case PREDEF_DECL_UNSIGNED_INT_128_ID:
5167 return Context.getUInt128Decl();
5168
5169 case PREDEF_DECL_OBJC_INSTANCETYPE_ID:
5170 return Context.getObjCInstanceTypeDecl();
5171
5172 case PREDEF_DECL_BUILTIN_VA_LIST_ID:
5173 return Context.getBuiltinVaListDecl();
5174 }
5175 }
5176
5177 unsigned Index = ID - NUM_PREDEF_DECL_IDS;
5178
5179 if (Index >= DeclsLoaded.size()) {
5180 assert(0 && "declaration ID out-of-range for AST file");
5181 Error("declaration ID out-of-range for AST file");
5182 return 0;
5183 }
5184
5185 if (!DeclsLoaded[Index]) {
5186 ReadDeclRecord(ID);
5187 if (DeserializationListener)
5188 DeserializationListener->DeclRead(ID, DeclsLoaded[Index]);
5189 }
5190
5191 return DeclsLoaded[Index];
5192}
5193
5194DeclID ASTReader::mapGlobalIDToModuleFileGlobalID(ModuleFile &M,
5195 DeclID GlobalID) {
5196 if (GlobalID < NUM_PREDEF_DECL_IDS)
5197 return GlobalID;
5198
5199 GlobalDeclMapType::const_iterator I = GlobalDeclMap.find(GlobalID);
5200 assert(I != GlobalDeclMap.end() && "Corrupted global declaration map");
5201 ModuleFile *Owner = I->second;
5202
5203 llvm::DenseMap<ModuleFile *, serialization::DeclID>::iterator Pos
5204 = M.GlobalToLocalDeclIDs.find(Owner);
5205 if (Pos == M.GlobalToLocalDeclIDs.end())
5206 return 0;
5207
5208 return GlobalID - Owner->BaseDeclID + Pos->second;
5209}
5210
5211serialization::DeclID ASTReader::ReadDeclID(ModuleFile &F,
5212 const RecordData &Record,
5213 unsigned &Idx) {
5214 if (Idx >= Record.size()) {
5215 Error("Corrupted AST file");
5216 return 0;
5217 }
5218
5219 return getGlobalDeclID(F, Record[Idx++]);
5220}
5221
5222/// \brief Resolve the offset of a statement into a statement.
5223///
5224/// This operation will read a new statement from the external
5225/// source each time it is called, and is meant to be used via a
5226/// LazyOffsetPtr (which is used by Decls for the body of functions, etc).
5227Stmt *ASTReader::GetExternalDeclStmt(uint64_t Offset) {
5228 // Switch case IDs are per Decl.
5229 ClearSwitchCaseIDs();
5230
5231 // Offset here is a global offset across the entire chain.
5232 RecordLocation Loc = getLocalBitOffset(Offset);
5233 Loc.F->DeclsCursor.JumpToBit(Loc.Offset);
5234 return ReadStmtFromStream(*Loc.F);
5235}
5236
5237namespace {
5238 class FindExternalLexicalDeclsVisitor {
5239 ASTReader &Reader;
5240 const DeclContext *DC;
5241 bool (*isKindWeWant)(Decl::Kind);
5242
5243 SmallVectorImpl<Decl*> &Decls;
5244 bool PredefsVisited[NUM_PREDEF_DECL_IDS];
5245
5246 public:
5247 FindExternalLexicalDeclsVisitor(ASTReader &Reader, const DeclContext *DC,
5248 bool (*isKindWeWant)(Decl::Kind),
5249 SmallVectorImpl<Decl*> &Decls)
5250 : Reader(Reader), DC(DC), isKindWeWant(isKindWeWant), Decls(Decls)
5251 {
5252 for (unsigned I = 0; I != NUM_PREDEF_DECL_IDS; ++I)
5253 PredefsVisited[I] = false;
5254 }
5255
5256 static bool visit(ModuleFile &M, bool Preorder, void *UserData) {
5257 if (Preorder)
5258 return false;
5259
5260 FindExternalLexicalDeclsVisitor *This
5261 = static_cast<FindExternalLexicalDeclsVisitor *>(UserData);
5262
5263 ModuleFile::DeclContextInfosMap::iterator Info
5264 = M.DeclContextInfos.find(This->DC);
5265 if (Info == M.DeclContextInfos.end() || !Info->second.LexicalDecls)
5266 return false;
5267
5268 // Load all of the declaration IDs
5269 for (const KindDeclIDPair *ID = Info->second.LexicalDecls,
5270 *IDE = ID + Info->second.NumLexicalDecls;
5271 ID != IDE; ++ID) {
5272 if (This->isKindWeWant && !This->isKindWeWant((Decl::Kind)ID->first))
5273 continue;
5274
5275 // Don't add predefined declarations to the lexical context more
5276 // than once.
5277 if (ID->second < NUM_PREDEF_DECL_IDS) {
5278 if (This->PredefsVisited[ID->second])
5279 continue;
5280
5281 This->PredefsVisited[ID->second] = true;
5282 }
5283
5284 if (Decl *D = This->Reader.GetLocalDecl(M, ID->second)) {
5285 if (!This->DC->isDeclInLexicalTraversal(D))
5286 This->Decls.push_back(D);
5287 }
5288 }
5289
5290 return false;
5291 }
5292 };
5293}
5294
5295ExternalLoadResult ASTReader::FindExternalLexicalDecls(const DeclContext *DC,
5296 bool (*isKindWeWant)(Decl::Kind),
5297 SmallVectorImpl<Decl*> &Decls) {
5298 // There might be lexical decls in multiple modules, for the TU at
5299 // least. Walk all of the modules in the order they were loaded.
5300 FindExternalLexicalDeclsVisitor Visitor(*this, DC, isKindWeWant, Decls);
5301 ModuleMgr.visitDepthFirst(&FindExternalLexicalDeclsVisitor::visit, &Visitor);
5302 ++NumLexicalDeclContextsRead;
5303 return ELR_Success;
5304}
5305
5306namespace {
5307
5308class DeclIDComp {
5309 ASTReader &Reader;
5310 ModuleFile &Mod;
5311
5312public:
5313 DeclIDComp(ASTReader &Reader, ModuleFile &M) : Reader(Reader), Mod(M) {}
5314
5315 bool operator()(LocalDeclID L, LocalDeclID R) const {
5316 SourceLocation LHS = getLocation(L);
5317 SourceLocation RHS = getLocation(R);
5318 return Reader.getSourceManager().isBeforeInTranslationUnit(LHS, RHS);
5319 }
5320
5321 bool operator()(SourceLocation LHS, LocalDeclID R) const {
5322 SourceLocation RHS = getLocation(R);
5323 return Reader.getSourceManager().isBeforeInTranslationUnit(LHS, RHS);
5324 }
5325
5326 bool operator()(LocalDeclID L, SourceLocation RHS) const {
5327 SourceLocation LHS = getLocation(L);
5328 return Reader.getSourceManager().isBeforeInTranslationUnit(LHS, RHS);
5329 }
5330
5331 SourceLocation getLocation(LocalDeclID ID) const {
5332 return Reader.getSourceManager().getFileLoc(
5333 Reader.getSourceLocationForDeclID(Reader.getGlobalDeclID(Mod, ID)));
5334 }
5335};
5336
5337}
5338
5339void ASTReader::FindFileRegionDecls(FileID File,
5340 unsigned Offset, unsigned Length,
5341 SmallVectorImpl<Decl *> &Decls) {
5342 SourceManager &SM = getSourceManager();
5343
5344 llvm::DenseMap<FileID, FileDeclsInfo>::iterator I = FileDeclIDs.find(File);
5345 if (I == FileDeclIDs.end())
5346 return;
5347
5348 FileDeclsInfo &DInfo = I->second;
5349 if (DInfo.Decls.empty())
5350 return;
5351
5352 SourceLocation
5353 BeginLoc = SM.getLocForStartOfFile(File).getLocWithOffset(Offset);
5354 SourceLocation EndLoc = BeginLoc.getLocWithOffset(Length);
5355
5356 DeclIDComp DIDComp(*this, *DInfo.Mod);
5357 ArrayRef<serialization::LocalDeclID>::iterator
5358 BeginIt = std::lower_bound(DInfo.Decls.begin(), DInfo.Decls.end(),
5359 BeginLoc, DIDComp);
5360 if (BeginIt != DInfo.Decls.begin())
5361 --BeginIt;
5362
5363 // If we are pointing at a top-level decl inside an objc container, we need
5364 // to backtrack until we find it otherwise we will fail to report that the
5365 // region overlaps with an objc container.
5366 while (BeginIt != DInfo.Decls.begin() &&
5367 GetDecl(getGlobalDeclID(*DInfo.Mod, *BeginIt))
5368 ->isTopLevelDeclInObjCContainer())
5369 --BeginIt;
5370
5371 ArrayRef<serialization::LocalDeclID>::iterator
5372 EndIt = std::upper_bound(DInfo.Decls.begin(), DInfo.Decls.end(),
5373 EndLoc, DIDComp);
5374 if (EndIt != DInfo.Decls.end())
5375 ++EndIt;
5376
5377 for (ArrayRef<serialization::LocalDeclID>::iterator
5378 DIt = BeginIt; DIt != EndIt; ++DIt)
5379 Decls.push_back(GetDecl(getGlobalDeclID(*DInfo.Mod, *DIt)));
5380}
5381
5382namespace {
5383 /// \brief ModuleFile visitor used to perform name lookup into a
5384 /// declaration context.
5385 class DeclContextNameLookupVisitor {
5386 ASTReader &Reader;
Dmitri Gribenkocfa88f82013-01-12 19:30:44 +00005387 SmallVectorImpl<const DeclContext *> &Contexts;
Guy Benyei7f92f2d2012-12-18 14:30:41 +00005388 DeclarationName Name;
5389 SmallVectorImpl<NamedDecl *> &Decls;
5390
5391 public:
5392 DeclContextNameLookupVisitor(ASTReader &Reader,
5393 SmallVectorImpl<const DeclContext *> &Contexts,
5394 DeclarationName Name,
5395 SmallVectorImpl<NamedDecl *> &Decls)
5396 : Reader(Reader), Contexts(Contexts), Name(Name), Decls(Decls) { }
5397
5398 static bool visit(ModuleFile &M, void *UserData) {
5399 DeclContextNameLookupVisitor *This
5400 = static_cast<DeclContextNameLookupVisitor *>(UserData);
5401
5402 // Check whether we have any visible declaration information for
5403 // this context in this module.
5404 ModuleFile::DeclContextInfosMap::iterator Info;
5405 bool FoundInfo = false;
5406 for (unsigned I = 0, N = This->Contexts.size(); I != N; ++I) {
5407 Info = M.DeclContextInfos.find(This->Contexts[I]);
5408 if (Info != M.DeclContextInfos.end() &&
5409 Info->second.NameLookupTableData) {
5410 FoundInfo = true;
5411 break;
5412 }
5413 }
5414
5415 if (!FoundInfo)
5416 return false;
5417
5418 // Look for this name within this module.
5419 ASTDeclContextNameLookupTable *LookupTable =
5420 Info->second.NameLookupTableData;
5421 ASTDeclContextNameLookupTable::iterator Pos
5422 = LookupTable->find(This->Name);
5423 if (Pos == LookupTable->end())
5424 return false;
5425
5426 bool FoundAnything = false;
5427 ASTDeclContextNameLookupTrait::data_type Data = *Pos;
5428 for (; Data.first != Data.second; ++Data.first) {
5429 NamedDecl *ND = This->Reader.GetLocalDeclAs<NamedDecl>(M, *Data.first);
5430 if (!ND)
5431 continue;
5432
5433 if (ND->getDeclName() != This->Name) {
5434 // A name might be null because the decl's redeclarable part is
5435 // currently read before reading its name. The lookup is triggered by
5436 // building that decl (likely indirectly), and so it is later in the
5437 // sense of "already existing" and can be ignored here.
5438 continue;
5439 }
5440
5441 // Record this declaration.
5442 FoundAnything = true;
5443 This->Decls.push_back(ND);
5444 }
5445
5446 return FoundAnything;
5447 }
5448 };
5449}
5450
Douglas Gregor5a04f9f2013-01-21 15:25:38 +00005451/// \brief Retrieve the "definitive" module file for the definition of the
5452/// given declaration context, if there is one.
5453///
5454/// The "definitive" module file is the only place where we need to look to
5455/// find information about the declarations within the given declaration
5456/// context. For example, C++ and Objective-C classes, C structs/unions, and
5457/// Objective-C protocols, categories, and extensions are all defined in a
5458/// single place in the source code, so they have definitive module files
5459/// associated with them. C++ namespaces, on the other hand, can have
5460/// definitions in multiple different module files.
5461///
5462/// Note: this needs to be kept in sync with ASTWriter::AddedVisibleDecl's
5463/// NDEBUG checking.
5464static ModuleFile *getDefinitiveModuleFileFor(const DeclContext *DC,
5465 ASTReader &Reader) {
Douglas Gregore0d20662013-01-22 17:08:30 +00005466 if (const DeclContext *DefDC = getDefinitiveDeclContext(DC))
5467 return Reader.getOwningModuleFile(cast<Decl>(DefDC));
Douglas Gregor5a04f9f2013-01-21 15:25:38 +00005468
5469 return 0;
5470}
5471
Richard Smith3646c682013-02-07 03:30:24 +00005472bool
Guy Benyei7f92f2d2012-12-18 14:30:41 +00005473ASTReader::FindExternalVisibleDeclsByName(const DeclContext *DC,
5474 DeclarationName Name) {
5475 assert(DC->hasExternalVisibleStorage() &&
5476 "DeclContext has no visible decls in storage");
5477 if (!Name)
Richard Smith3646c682013-02-07 03:30:24 +00005478 return false;
Guy Benyei7f92f2d2012-12-18 14:30:41 +00005479
5480 SmallVector<NamedDecl *, 64> Decls;
5481
5482 // Compute the declaration contexts we need to look into. Multiple such
5483 // declaration contexts occur when two declaration contexts from disjoint
5484 // modules get merged, e.g., when two namespaces with the same name are
5485 // independently defined in separate modules.
5486 SmallVector<const DeclContext *, 2> Contexts;
5487 Contexts.push_back(DC);
5488
5489 if (DC->isNamespace()) {
5490 MergedDeclsMap::iterator Merged
5491 = MergedDecls.find(const_cast<Decl *>(cast<Decl>(DC)));
5492 if (Merged != MergedDecls.end()) {
5493 for (unsigned I = 0, N = Merged->second.size(); I != N; ++I)
5494 Contexts.push_back(cast<DeclContext>(GetDecl(Merged->second[I])));
5495 }
5496 }
5497
5498 DeclContextNameLookupVisitor Visitor(*this, Contexts, Name, Decls);
Douglas Gregor5a04f9f2013-01-21 15:25:38 +00005499
5500 // If we can definitively determine which module file to look into,
5501 // only look there. Otherwise, look in all module files.
5502 ModuleFile *Definitive;
5503 if (Contexts.size() == 1 &&
5504 (Definitive = getDefinitiveModuleFileFor(DC, *this))) {
5505 DeclContextNameLookupVisitor::visit(*Definitive, &Visitor);
5506 } else {
5507 ModuleMgr.visit(&DeclContextNameLookupVisitor::visit, &Visitor);
5508 }
Guy Benyei7f92f2d2012-12-18 14:30:41 +00005509 ++NumVisibleDeclContextsRead;
5510 SetExternalVisibleDeclsForName(DC, Name, Decls);
Richard Smith3646c682013-02-07 03:30:24 +00005511 return !Decls.empty();
Guy Benyei7f92f2d2012-12-18 14:30:41 +00005512}
5513
5514namespace {
5515 /// \brief ModuleFile visitor used to retrieve all visible names in a
5516 /// declaration context.
5517 class DeclContextAllNamesVisitor {
5518 ASTReader &Reader;
Dmitri Gribenkocfa88f82013-01-12 19:30:44 +00005519 SmallVectorImpl<const DeclContext *> &Contexts;
Guy Benyei7f92f2d2012-12-18 14:30:41 +00005520 llvm::DenseMap<DeclarationName, SmallVector<NamedDecl *, 8> > &Decls;
Argyrios Kyrtzidisca40f302012-12-19 22:21:18 +00005521 bool VisitAll;
Guy Benyei7f92f2d2012-12-18 14:30:41 +00005522
5523 public:
5524 DeclContextAllNamesVisitor(ASTReader &Reader,
5525 SmallVectorImpl<const DeclContext *> &Contexts,
5526 llvm::DenseMap<DeclarationName,
Argyrios Kyrtzidisca40f302012-12-19 22:21:18 +00005527 SmallVector<NamedDecl *, 8> > &Decls,
5528 bool VisitAll)
5529 : Reader(Reader), Contexts(Contexts), Decls(Decls), VisitAll(VisitAll) { }
Guy Benyei7f92f2d2012-12-18 14:30:41 +00005530
5531 static bool visit(ModuleFile &M, void *UserData) {
5532 DeclContextAllNamesVisitor *This
5533 = static_cast<DeclContextAllNamesVisitor *>(UserData);
5534
5535 // Check whether we have any visible declaration information for
5536 // this context in this module.
5537 ModuleFile::DeclContextInfosMap::iterator Info;
5538 bool FoundInfo = false;
5539 for (unsigned I = 0, N = This->Contexts.size(); I != N; ++I) {
5540 Info = M.DeclContextInfos.find(This->Contexts[I]);
5541 if (Info != M.DeclContextInfos.end() &&
5542 Info->second.NameLookupTableData) {
5543 FoundInfo = true;
5544 break;
5545 }
5546 }
5547
5548 if (!FoundInfo)
5549 return false;
5550
5551 ASTDeclContextNameLookupTable *LookupTable =
5552 Info->second.NameLookupTableData;
5553 bool FoundAnything = false;
5554 for (ASTDeclContextNameLookupTable::data_iterator
Douglas Gregora6b00fc2013-01-23 22:38:11 +00005555 I = LookupTable->data_begin(), E = LookupTable->data_end();
5556 I != E;
5557 ++I) {
Guy Benyei7f92f2d2012-12-18 14:30:41 +00005558 ASTDeclContextNameLookupTrait::data_type Data = *I;
5559 for (; Data.first != Data.second; ++Data.first) {
5560 NamedDecl *ND = This->Reader.GetLocalDeclAs<NamedDecl>(M,
5561 *Data.first);
5562 if (!ND)
5563 continue;
5564
5565 // Record this declaration.
5566 FoundAnything = true;
5567 This->Decls[ND->getDeclName()].push_back(ND);
5568 }
5569 }
5570
Argyrios Kyrtzidisca40f302012-12-19 22:21:18 +00005571 return FoundAnything && !This->VisitAll;
Guy Benyei7f92f2d2012-12-18 14:30:41 +00005572 }
5573 };
5574}
5575
5576void ASTReader::completeVisibleDeclsMap(const DeclContext *DC) {
5577 if (!DC->hasExternalVisibleStorage())
5578 return;
Dmitri Gribenkocfa88f82013-01-12 19:30:44 +00005579 llvm::DenseMap<DeclarationName, SmallVector<NamedDecl *, 8> > Decls;
Guy Benyei7f92f2d2012-12-18 14:30:41 +00005580
5581 // Compute the declaration contexts we need to look into. Multiple such
5582 // declaration contexts occur when two declaration contexts from disjoint
5583 // modules get merged, e.g., when two namespaces with the same name are
5584 // independently defined in separate modules.
5585 SmallVector<const DeclContext *, 2> Contexts;
5586 Contexts.push_back(DC);
5587
5588 if (DC->isNamespace()) {
5589 MergedDeclsMap::iterator Merged
5590 = MergedDecls.find(const_cast<Decl *>(cast<Decl>(DC)));
5591 if (Merged != MergedDecls.end()) {
5592 for (unsigned I = 0, N = Merged->second.size(); I != N; ++I)
5593 Contexts.push_back(cast<DeclContext>(GetDecl(Merged->second[I])));
5594 }
5595 }
5596
Argyrios Kyrtzidisca40f302012-12-19 22:21:18 +00005597 DeclContextAllNamesVisitor Visitor(*this, Contexts, Decls,
5598 /*VisitAll=*/DC->isFileContext());
Guy Benyei7f92f2d2012-12-18 14:30:41 +00005599 ModuleMgr.visit(&DeclContextAllNamesVisitor::visit, &Visitor);
5600 ++NumVisibleDeclContextsRead;
5601
5602 for (llvm::DenseMap<DeclarationName,
Dmitri Gribenkocfa88f82013-01-12 19:30:44 +00005603 SmallVector<NamedDecl *, 8> >::iterator
Guy Benyei7f92f2d2012-12-18 14:30:41 +00005604 I = Decls.begin(), E = Decls.end(); I != E; ++I) {
5605 SetExternalVisibleDeclsForName(DC, I->first, I->second);
5606 }
5607 const_cast<DeclContext *>(DC)->setHasExternalVisibleStorage(false);
5608}
5609
5610/// \brief Under non-PCH compilation the consumer receives the objc methods
5611/// before receiving the implementation, and codegen depends on this.
5612/// We simulate this by deserializing and passing to consumer the methods of the
5613/// implementation before passing the deserialized implementation decl.
5614static void PassObjCImplDeclToConsumer(ObjCImplDecl *ImplD,
5615 ASTConsumer *Consumer) {
5616 assert(ImplD && Consumer);
5617
5618 for (ObjCImplDecl::method_iterator
5619 I = ImplD->meth_begin(), E = ImplD->meth_end(); I != E; ++I)
5620 Consumer->HandleInterestingDecl(DeclGroupRef(*I));
5621
5622 Consumer->HandleInterestingDecl(DeclGroupRef(ImplD));
5623}
5624
5625void ASTReader::PassInterestingDeclsToConsumer() {
5626 assert(Consumer);
5627 while (!InterestingDecls.empty()) {
5628 Decl *D = InterestingDecls.front();
5629 InterestingDecls.pop_front();
5630
5631 PassInterestingDeclToConsumer(D);
5632 }
5633}
5634
5635void ASTReader::PassInterestingDeclToConsumer(Decl *D) {
5636 if (ObjCImplDecl *ImplD = dyn_cast<ObjCImplDecl>(D))
5637 PassObjCImplDeclToConsumer(ImplD, Consumer);
5638 else
5639 Consumer->HandleInterestingDecl(DeclGroupRef(D));
5640}
5641
5642void ASTReader::StartTranslationUnit(ASTConsumer *Consumer) {
5643 this->Consumer = Consumer;
5644
5645 if (!Consumer)
5646 return;
5647
5648 for (unsigned I = 0, N = ExternalDefinitions.size(); I != N; ++I) {
5649 // Force deserialization of this decl, which will cause it to be queued for
5650 // passing to the consumer.
5651 GetDecl(ExternalDefinitions[I]);
5652 }
5653 ExternalDefinitions.clear();
5654
5655 PassInterestingDeclsToConsumer();
5656}
5657
5658void ASTReader::PrintStats() {
5659 std::fprintf(stderr, "*** AST File Statistics:\n");
5660
5661 unsigned NumTypesLoaded
5662 = TypesLoaded.size() - std::count(TypesLoaded.begin(), TypesLoaded.end(),
5663 QualType());
5664 unsigned NumDeclsLoaded
5665 = DeclsLoaded.size() - std::count(DeclsLoaded.begin(), DeclsLoaded.end(),
5666 (Decl *)0);
5667 unsigned NumIdentifiersLoaded
5668 = IdentifiersLoaded.size() - std::count(IdentifiersLoaded.begin(),
5669 IdentifiersLoaded.end(),
5670 (IdentifierInfo *)0);
5671 unsigned NumMacrosLoaded
5672 = MacrosLoaded.size() - std::count(MacrosLoaded.begin(),
5673 MacrosLoaded.end(),
Argyrios Kyrtzidis9818a1d2013-02-20 00:54:57 +00005674 (MacroDirective *)0);
Guy Benyei7f92f2d2012-12-18 14:30:41 +00005675 unsigned NumSelectorsLoaded
5676 = SelectorsLoaded.size() - std::count(SelectorsLoaded.begin(),
5677 SelectorsLoaded.end(),
5678 Selector());
5679
5680 if (unsigned TotalNumSLocEntries = getTotalNumSLocs())
5681 std::fprintf(stderr, " %u/%u source location entries read (%f%%)\n",
5682 NumSLocEntriesRead, TotalNumSLocEntries,
5683 ((float)NumSLocEntriesRead/TotalNumSLocEntries * 100));
5684 if (!TypesLoaded.empty())
5685 std::fprintf(stderr, " %u/%u types read (%f%%)\n",
5686 NumTypesLoaded, (unsigned)TypesLoaded.size(),
5687 ((float)NumTypesLoaded/TypesLoaded.size() * 100));
5688 if (!DeclsLoaded.empty())
5689 std::fprintf(stderr, " %u/%u declarations read (%f%%)\n",
5690 NumDeclsLoaded, (unsigned)DeclsLoaded.size(),
5691 ((float)NumDeclsLoaded/DeclsLoaded.size() * 100));
5692 if (!IdentifiersLoaded.empty())
5693 std::fprintf(stderr, " %u/%u identifiers read (%f%%)\n",
5694 NumIdentifiersLoaded, (unsigned)IdentifiersLoaded.size(),
5695 ((float)NumIdentifiersLoaded/IdentifiersLoaded.size() * 100));
5696 if (!MacrosLoaded.empty())
5697 std::fprintf(stderr, " %u/%u macros read (%f%%)\n",
5698 NumMacrosLoaded, (unsigned)MacrosLoaded.size(),
5699 ((float)NumMacrosLoaded/MacrosLoaded.size() * 100));
5700 if (!SelectorsLoaded.empty())
5701 std::fprintf(stderr, " %u/%u selectors read (%f%%)\n",
5702 NumSelectorsLoaded, (unsigned)SelectorsLoaded.size(),
5703 ((float)NumSelectorsLoaded/SelectorsLoaded.size() * 100));
5704 if (TotalNumStatements)
5705 std::fprintf(stderr, " %u/%u statements read (%f%%)\n",
5706 NumStatementsRead, TotalNumStatements,
5707 ((float)NumStatementsRead/TotalNumStatements * 100));
5708 if (TotalNumMacros)
5709 std::fprintf(stderr, " %u/%u macros read (%f%%)\n",
5710 NumMacrosRead, TotalNumMacros,
5711 ((float)NumMacrosRead/TotalNumMacros * 100));
5712 if (TotalLexicalDeclContexts)
5713 std::fprintf(stderr, " %u/%u lexical declcontexts read (%f%%)\n",
5714 NumLexicalDeclContextsRead, TotalLexicalDeclContexts,
5715 ((float)NumLexicalDeclContextsRead/TotalLexicalDeclContexts
5716 * 100));
5717 if (TotalVisibleDeclContexts)
5718 std::fprintf(stderr, " %u/%u visible declcontexts read (%f%%)\n",
5719 NumVisibleDeclContextsRead, TotalVisibleDeclContexts,
5720 ((float)NumVisibleDeclContextsRead/TotalVisibleDeclContexts
5721 * 100));
5722 if (TotalNumMethodPoolEntries) {
5723 std::fprintf(stderr, " %u/%u method pool entries read (%f%%)\n",
5724 NumMethodPoolEntriesRead, TotalNumMethodPoolEntries,
5725 ((float)NumMethodPoolEntriesRead/TotalNumMethodPoolEntries
5726 * 100));
Guy Benyei7f92f2d2012-12-18 14:30:41 +00005727 }
Douglas Gregor95fb36e2013-01-28 17:54:36 +00005728 if (NumMethodPoolLookups) {
5729 std::fprintf(stderr, " %u/%u method pool lookups succeeded (%f%%)\n",
5730 NumMethodPoolHits, NumMethodPoolLookups,
5731 ((float)NumMethodPoolHits/NumMethodPoolLookups * 100.0));
5732 }
5733 if (NumMethodPoolTableLookups) {
5734 std::fprintf(stderr, " %u/%u method pool table lookups succeeded (%f%%)\n",
5735 NumMethodPoolTableHits, NumMethodPoolTableLookups,
5736 ((float)NumMethodPoolTableHits/NumMethodPoolTableLookups
5737 * 100.0));
5738 }
5739
Douglas Gregore1698072013-01-25 00:38:33 +00005740 if (NumIdentifierLookupHits) {
5741 std::fprintf(stderr,
5742 " %u / %u identifier table lookups succeeded (%f%%)\n",
5743 NumIdentifierLookupHits, NumIdentifierLookups,
5744 (double)NumIdentifierLookupHits*100.0/NumIdentifierLookups);
5745 }
5746
Douglas Gregor1a49d972013-01-25 01:03:03 +00005747 if (GlobalIndex) {
5748 std::fprintf(stderr, "\n");
5749 GlobalIndex->printStats();
5750 }
5751
Guy Benyei7f92f2d2012-12-18 14:30:41 +00005752 std::fprintf(stderr, "\n");
5753 dump();
5754 std::fprintf(stderr, "\n");
5755}
5756
5757template<typename Key, typename ModuleFile, unsigned InitialCapacity>
5758static void
5759dumpModuleIDMap(StringRef Name,
5760 const ContinuousRangeMap<Key, ModuleFile *,
5761 InitialCapacity> &Map) {
5762 if (Map.begin() == Map.end())
5763 return;
5764
5765 typedef ContinuousRangeMap<Key, ModuleFile *, InitialCapacity> MapType;
5766 llvm::errs() << Name << ":\n";
5767 for (typename MapType::const_iterator I = Map.begin(), IEnd = Map.end();
5768 I != IEnd; ++I) {
5769 llvm::errs() << " " << I->first << " -> " << I->second->FileName
5770 << "\n";
5771 }
5772}
5773
5774void ASTReader::dump() {
5775 llvm::errs() << "*** PCH/ModuleFile Remappings:\n";
5776 dumpModuleIDMap("Global bit offset map", GlobalBitOffsetsMap);
5777 dumpModuleIDMap("Global source location entry map", GlobalSLocEntryMap);
5778 dumpModuleIDMap("Global type map", GlobalTypeMap);
5779 dumpModuleIDMap("Global declaration map", GlobalDeclMap);
5780 dumpModuleIDMap("Global identifier map", GlobalIdentifierMap);
5781 dumpModuleIDMap("Global macro map", GlobalMacroMap);
5782 dumpModuleIDMap("Global submodule map", GlobalSubmoduleMap);
5783 dumpModuleIDMap("Global selector map", GlobalSelectorMap);
5784 dumpModuleIDMap("Global preprocessed entity map",
5785 GlobalPreprocessedEntityMap);
5786
5787 llvm::errs() << "\n*** PCH/Modules Loaded:";
5788 for (ModuleManager::ModuleConstIterator M = ModuleMgr.begin(),
5789 MEnd = ModuleMgr.end();
5790 M != MEnd; ++M)
5791 (*M)->dump();
5792}
5793
5794/// Return the amount of memory used by memory buffers, breaking down
5795/// by heap-backed versus mmap'ed memory.
5796void ASTReader::getMemoryBufferSizes(MemoryBufferSizes &sizes) const {
5797 for (ModuleConstIterator I = ModuleMgr.begin(),
5798 E = ModuleMgr.end(); I != E; ++I) {
5799 if (llvm::MemoryBuffer *buf = (*I)->Buffer.get()) {
5800 size_t bytes = buf->getBufferSize();
5801 switch (buf->getBufferKind()) {
5802 case llvm::MemoryBuffer::MemoryBuffer_Malloc:
5803 sizes.malloc_bytes += bytes;
5804 break;
5805 case llvm::MemoryBuffer::MemoryBuffer_MMap:
5806 sizes.mmap_bytes += bytes;
5807 break;
5808 }
5809 }
5810 }
5811}
5812
5813void ASTReader::InitializeSema(Sema &S) {
5814 SemaObj = &S;
5815 S.addExternalSource(this);
5816
5817 // Makes sure any declarations that were deserialized "too early"
5818 // still get added to the identifier's declaration chains.
5819 for (unsigned I = 0, N = PreloadedDecls.size(); I != N; ++I) {
Douglas Gregoraa945902013-02-18 15:53:43 +00005820 NamedDecl *ND = cast<NamedDecl>(PreloadedDecls[I]->getMostRecentDecl());
5821 SemaObj->pushExternalDeclIntoScope(ND, PreloadedDecls[I]->getDeclName());
Guy Benyei7f92f2d2012-12-18 14:30:41 +00005822 }
5823 PreloadedDecls.clear();
5824
5825 // Load the offsets of the declarations that Sema references.
5826 // They will be lazily deserialized when needed.
5827 if (!SemaDeclRefs.empty()) {
5828 assert(SemaDeclRefs.size() == 2 && "More decl refs than expected!");
5829 if (!SemaObj->StdNamespace)
5830 SemaObj->StdNamespace = SemaDeclRefs[0];
5831 if (!SemaObj->StdBadAlloc)
5832 SemaObj->StdBadAlloc = SemaDeclRefs[1];
5833 }
5834
5835 if (!FPPragmaOptions.empty()) {
5836 assert(FPPragmaOptions.size() == 1 && "Wrong number of FP_PRAGMA_OPTIONS");
5837 SemaObj->FPFeatures.fp_contract = FPPragmaOptions[0];
5838 }
5839
5840 if (!OpenCLExtensions.empty()) {
5841 unsigned I = 0;
5842#define OPENCLEXT(nm) SemaObj->OpenCLFeatures.nm = OpenCLExtensions[I++];
5843#include "clang/Basic/OpenCLExtensions.def"
5844
5845 assert(OpenCLExtensions.size() == I && "Wrong number of OPENCL_EXTENSIONS");
5846 }
5847}
5848
5849IdentifierInfo* ASTReader::get(const char *NameStart, const char *NameEnd) {
5850 // Note that we are loading an identifier.
5851 Deserializing AnIdentifier(this);
Douglas Gregor1a49d972013-01-25 01:03:03 +00005852 StringRef Name(NameStart, NameEnd - NameStart);
5853
5854 // If there is a global index, look there first to determine which modules
5855 // provably do not have any results for this identifier.
Douglas Gregor188bdcd2013-01-25 23:32:03 +00005856 GlobalModuleIndex::HitSet Hits;
5857 GlobalModuleIndex::HitSet *HitsPtr = 0;
Douglas Gregor1a49d972013-01-25 01:03:03 +00005858 if (!loadGlobalIndex()) {
Douglas Gregor188bdcd2013-01-25 23:32:03 +00005859 if (GlobalIndex->lookupIdentifier(Name, Hits)) {
5860 HitsPtr = &Hits;
Douglas Gregor1a49d972013-01-25 01:03:03 +00005861 }
5862 }
Douglas Gregor188bdcd2013-01-25 23:32:03 +00005863 IdentifierLookupVisitor Visitor(Name, /*PriorGeneration=*/0,
Douglas Gregore1698072013-01-25 00:38:33 +00005864 NumIdentifierLookups,
5865 NumIdentifierLookupHits);
Douglas Gregor188bdcd2013-01-25 23:32:03 +00005866 ModuleMgr.visit(IdentifierLookupVisitor::visit, &Visitor, HitsPtr);
Guy Benyei7f92f2d2012-12-18 14:30:41 +00005867 IdentifierInfo *II = Visitor.getIdentifierInfo();
5868 markIdentifierUpToDate(II);
5869 return II;
5870}
5871
5872namespace clang {
5873 /// \brief An identifier-lookup iterator that enumerates all of the
5874 /// identifiers stored within a set of AST files.
5875 class ASTIdentifierIterator : public IdentifierIterator {
5876 /// \brief The AST reader whose identifiers are being enumerated.
5877 const ASTReader &Reader;
5878
5879 /// \brief The current index into the chain of AST files stored in
5880 /// the AST reader.
5881 unsigned Index;
5882
5883 /// \brief The current position within the identifier lookup table
5884 /// of the current AST file.
5885 ASTIdentifierLookupTable::key_iterator Current;
5886
5887 /// \brief The end position within the identifier lookup table of
5888 /// the current AST file.
5889 ASTIdentifierLookupTable::key_iterator End;
5890
5891 public:
5892 explicit ASTIdentifierIterator(const ASTReader &Reader);
5893
5894 virtual StringRef Next();
5895 };
5896}
5897
5898ASTIdentifierIterator::ASTIdentifierIterator(const ASTReader &Reader)
5899 : Reader(Reader), Index(Reader.ModuleMgr.size() - 1) {
5900 ASTIdentifierLookupTable *IdTable
5901 = (ASTIdentifierLookupTable *)Reader.ModuleMgr[Index].IdentifierLookupTable;
5902 Current = IdTable->key_begin();
5903 End = IdTable->key_end();
5904}
5905
5906StringRef ASTIdentifierIterator::Next() {
5907 while (Current == End) {
5908 // If we have exhausted all of our AST files, we're done.
5909 if (Index == 0)
5910 return StringRef();
5911
5912 --Index;
5913 ASTIdentifierLookupTable *IdTable
5914 = (ASTIdentifierLookupTable *)Reader.ModuleMgr[Index].
5915 IdentifierLookupTable;
5916 Current = IdTable->key_begin();
5917 End = IdTable->key_end();
5918 }
5919
5920 // We have any identifiers remaining in the current AST file; return
5921 // the next one.
Douglas Gregor479633c2013-01-23 18:53:14 +00005922 StringRef Result = *Current;
Guy Benyei7f92f2d2012-12-18 14:30:41 +00005923 ++Current;
Douglas Gregor479633c2013-01-23 18:53:14 +00005924 return Result;
Guy Benyei7f92f2d2012-12-18 14:30:41 +00005925}
5926
5927IdentifierIterator *ASTReader::getIdentifiers() const {
5928 return new ASTIdentifierIterator(*this);
5929}
5930
5931namespace clang { namespace serialization {
5932 class ReadMethodPoolVisitor {
5933 ASTReader &Reader;
5934 Selector Sel;
5935 unsigned PriorGeneration;
Dmitri Gribenkocfa88f82013-01-12 19:30:44 +00005936 SmallVector<ObjCMethodDecl *, 4> InstanceMethods;
5937 SmallVector<ObjCMethodDecl *, 4> FactoryMethods;
Guy Benyei7f92f2d2012-12-18 14:30:41 +00005938
5939 public:
5940 ReadMethodPoolVisitor(ASTReader &Reader, Selector Sel,
5941 unsigned PriorGeneration)
5942 : Reader(Reader), Sel(Sel), PriorGeneration(PriorGeneration) { }
5943
5944 static bool visit(ModuleFile &M, void *UserData) {
5945 ReadMethodPoolVisitor *This
5946 = static_cast<ReadMethodPoolVisitor *>(UserData);
5947
5948 if (!M.SelectorLookupTable)
5949 return false;
5950
5951 // If we've already searched this module file, skip it now.
5952 if (M.Generation <= This->PriorGeneration)
5953 return true;
5954
Douglas Gregor95fb36e2013-01-28 17:54:36 +00005955 ++This->Reader.NumMethodPoolTableLookups;
Guy Benyei7f92f2d2012-12-18 14:30:41 +00005956 ASTSelectorLookupTable *PoolTable
5957 = (ASTSelectorLookupTable*)M.SelectorLookupTable;
5958 ASTSelectorLookupTable::iterator Pos = PoolTable->find(This->Sel);
5959 if (Pos == PoolTable->end())
5960 return false;
Douglas Gregor95fb36e2013-01-28 17:54:36 +00005961
5962 ++This->Reader.NumMethodPoolTableHits;
Guy Benyei7f92f2d2012-12-18 14:30:41 +00005963 ++This->Reader.NumSelectorsRead;
5964 // FIXME: Not quite happy with the statistics here. We probably should
5965 // disable this tracking when called via LoadSelector.
5966 // Also, should entries without methods count as misses?
5967 ++This->Reader.NumMethodPoolEntriesRead;
5968 ASTSelectorLookupTrait::data_type Data = *Pos;
5969 if (This->Reader.DeserializationListener)
5970 This->Reader.DeserializationListener->SelectorRead(Data.ID,
5971 This->Sel);
5972
5973 This->InstanceMethods.append(Data.Instance.begin(), Data.Instance.end());
5974 This->FactoryMethods.append(Data.Factory.begin(), Data.Factory.end());
5975 return true;
5976 }
5977
5978 /// \brief Retrieve the instance methods found by this visitor.
5979 ArrayRef<ObjCMethodDecl *> getInstanceMethods() const {
5980 return InstanceMethods;
5981 }
5982
5983 /// \brief Retrieve the instance methods found by this visitor.
5984 ArrayRef<ObjCMethodDecl *> getFactoryMethods() const {
5985 return FactoryMethods;
5986 }
5987 };
5988} } // end namespace clang::serialization
5989
5990/// \brief Add the given set of methods to the method list.
5991static void addMethodsToPool(Sema &S, ArrayRef<ObjCMethodDecl *> Methods,
5992 ObjCMethodList &List) {
5993 for (unsigned I = 0, N = Methods.size(); I != N; ++I) {
5994 S.addMethodToGlobalList(&List, Methods[I]);
5995 }
5996}
5997
5998void ASTReader::ReadMethodPool(Selector Sel) {
5999 // Get the selector generation and update it to the current generation.
6000 unsigned &Generation = SelectorGeneration[Sel];
6001 unsigned PriorGeneration = Generation;
6002 Generation = CurrentGeneration;
6003
6004 // Search for methods defined with this selector.
Douglas Gregor95fb36e2013-01-28 17:54:36 +00006005 ++NumMethodPoolLookups;
Guy Benyei7f92f2d2012-12-18 14:30:41 +00006006 ReadMethodPoolVisitor Visitor(*this, Sel, PriorGeneration);
6007 ModuleMgr.visit(&ReadMethodPoolVisitor::visit, &Visitor);
6008
6009 if (Visitor.getInstanceMethods().empty() &&
Douglas Gregor95fb36e2013-01-28 17:54:36 +00006010 Visitor.getFactoryMethods().empty())
Guy Benyei7f92f2d2012-12-18 14:30:41 +00006011 return;
Douglas Gregor95fb36e2013-01-28 17:54:36 +00006012
6013 ++NumMethodPoolHits;
6014
Guy Benyei7f92f2d2012-12-18 14:30:41 +00006015 if (!getSema())
6016 return;
6017
6018 Sema &S = *getSema();
6019 Sema::GlobalMethodPool::iterator Pos
6020 = S.MethodPool.insert(std::make_pair(Sel, Sema::GlobalMethods())).first;
6021
6022 addMethodsToPool(S, Visitor.getInstanceMethods(), Pos->second.first);
6023 addMethodsToPool(S, Visitor.getFactoryMethods(), Pos->second.second);
6024}
6025
6026void ASTReader::ReadKnownNamespaces(
6027 SmallVectorImpl<NamespaceDecl *> &Namespaces) {
6028 Namespaces.clear();
6029
6030 for (unsigned I = 0, N = KnownNamespaces.size(); I != N; ++I) {
6031 if (NamespaceDecl *Namespace
6032 = dyn_cast_or_null<NamespaceDecl>(GetDecl(KnownNamespaces[I])))
6033 Namespaces.push_back(Namespace);
6034 }
6035}
6036
Nick Lewyckycd0655b2013-02-01 08:13:20 +00006037void ASTReader::ReadUndefinedButUsed(
Nick Lewycky995e26b2013-01-31 03:23:57 +00006038 llvm::DenseMap<NamedDecl*, SourceLocation> &Undefined) {
Nick Lewyckycd0655b2013-02-01 08:13:20 +00006039 for (unsigned Idx = 0, N = UndefinedButUsed.size(); Idx != N;) {
6040 NamedDecl *D = cast<NamedDecl>(GetDecl(UndefinedButUsed[Idx++]));
Nick Lewycky01a41142013-01-26 00:35:08 +00006041 SourceLocation Loc =
Nick Lewyckycd0655b2013-02-01 08:13:20 +00006042 SourceLocation::getFromRawEncoding(UndefinedButUsed[Idx++]);
Nick Lewycky01a41142013-01-26 00:35:08 +00006043 Undefined.insert(std::make_pair(D, Loc));
6044 }
6045}
Nick Lewycky01a41142013-01-26 00:35:08 +00006046
Guy Benyei7f92f2d2012-12-18 14:30:41 +00006047void ASTReader::ReadTentativeDefinitions(
6048 SmallVectorImpl<VarDecl *> &TentativeDefs) {
6049 for (unsigned I = 0, N = TentativeDefinitions.size(); I != N; ++I) {
6050 VarDecl *Var = dyn_cast_or_null<VarDecl>(GetDecl(TentativeDefinitions[I]));
6051 if (Var)
6052 TentativeDefs.push_back(Var);
6053 }
6054 TentativeDefinitions.clear();
6055}
6056
6057void ASTReader::ReadUnusedFileScopedDecls(
6058 SmallVectorImpl<const DeclaratorDecl *> &Decls) {
6059 for (unsigned I = 0, N = UnusedFileScopedDecls.size(); I != N; ++I) {
6060 DeclaratorDecl *D
6061 = dyn_cast_or_null<DeclaratorDecl>(GetDecl(UnusedFileScopedDecls[I]));
6062 if (D)
6063 Decls.push_back(D);
6064 }
6065 UnusedFileScopedDecls.clear();
6066}
6067
6068void ASTReader::ReadDelegatingConstructors(
6069 SmallVectorImpl<CXXConstructorDecl *> &Decls) {
6070 for (unsigned I = 0, N = DelegatingCtorDecls.size(); I != N; ++I) {
6071 CXXConstructorDecl *D
6072 = dyn_cast_or_null<CXXConstructorDecl>(GetDecl(DelegatingCtorDecls[I]));
6073 if (D)
6074 Decls.push_back(D);
6075 }
6076 DelegatingCtorDecls.clear();
6077}
6078
6079void ASTReader::ReadExtVectorDecls(SmallVectorImpl<TypedefNameDecl *> &Decls) {
6080 for (unsigned I = 0, N = ExtVectorDecls.size(); I != N; ++I) {
6081 TypedefNameDecl *D
6082 = dyn_cast_or_null<TypedefNameDecl>(GetDecl(ExtVectorDecls[I]));
6083 if (D)
6084 Decls.push_back(D);
6085 }
6086 ExtVectorDecls.clear();
6087}
6088
6089void ASTReader::ReadDynamicClasses(SmallVectorImpl<CXXRecordDecl *> &Decls) {
6090 for (unsigned I = 0, N = DynamicClasses.size(); I != N; ++I) {
6091 CXXRecordDecl *D
6092 = dyn_cast_or_null<CXXRecordDecl>(GetDecl(DynamicClasses[I]));
6093 if (D)
6094 Decls.push_back(D);
6095 }
6096 DynamicClasses.clear();
6097}
6098
6099void
Richard Smith5ea6ef42013-01-10 23:43:47 +00006100ASTReader::ReadLocallyScopedExternCDecls(SmallVectorImpl<NamedDecl *> &Decls) {
6101 for (unsigned I = 0, N = LocallyScopedExternCDecls.size(); I != N; ++I) {
6102 NamedDecl *D
6103 = dyn_cast_or_null<NamedDecl>(GetDecl(LocallyScopedExternCDecls[I]));
Guy Benyei7f92f2d2012-12-18 14:30:41 +00006104 if (D)
6105 Decls.push_back(D);
6106 }
Richard Smith5ea6ef42013-01-10 23:43:47 +00006107 LocallyScopedExternCDecls.clear();
Guy Benyei7f92f2d2012-12-18 14:30:41 +00006108}
6109
6110void ASTReader::ReadReferencedSelectors(
6111 SmallVectorImpl<std::pair<Selector, SourceLocation> > &Sels) {
6112 if (ReferencedSelectorsData.empty())
6113 return;
6114
6115 // If there are @selector references added them to its pool. This is for
6116 // implementation of -Wselector.
6117 unsigned int DataSize = ReferencedSelectorsData.size()-1;
6118 unsigned I = 0;
6119 while (I < DataSize) {
6120 Selector Sel = DecodeSelector(ReferencedSelectorsData[I++]);
6121 SourceLocation SelLoc
6122 = SourceLocation::getFromRawEncoding(ReferencedSelectorsData[I++]);
6123 Sels.push_back(std::make_pair(Sel, SelLoc));
6124 }
6125 ReferencedSelectorsData.clear();
6126}
6127
6128void ASTReader::ReadWeakUndeclaredIdentifiers(
6129 SmallVectorImpl<std::pair<IdentifierInfo *, WeakInfo> > &WeakIDs) {
6130 if (WeakUndeclaredIdentifiers.empty())
6131 return;
6132
6133 for (unsigned I = 0, N = WeakUndeclaredIdentifiers.size(); I < N; /*none*/) {
6134 IdentifierInfo *WeakId
6135 = DecodeIdentifierInfo(WeakUndeclaredIdentifiers[I++]);
6136 IdentifierInfo *AliasId
6137 = DecodeIdentifierInfo(WeakUndeclaredIdentifiers[I++]);
6138 SourceLocation Loc
6139 = SourceLocation::getFromRawEncoding(WeakUndeclaredIdentifiers[I++]);
6140 bool Used = WeakUndeclaredIdentifiers[I++];
6141 WeakInfo WI(AliasId, Loc);
6142 WI.setUsed(Used);
6143 WeakIDs.push_back(std::make_pair(WeakId, WI));
6144 }
6145 WeakUndeclaredIdentifiers.clear();
6146}
6147
6148void ASTReader::ReadUsedVTables(SmallVectorImpl<ExternalVTableUse> &VTables) {
6149 for (unsigned Idx = 0, N = VTableUses.size(); Idx < N; /* In loop */) {
6150 ExternalVTableUse VT;
6151 VT.Record = dyn_cast_or_null<CXXRecordDecl>(GetDecl(VTableUses[Idx++]));
6152 VT.Location = SourceLocation::getFromRawEncoding(VTableUses[Idx++]);
6153 VT.DefinitionRequired = VTableUses[Idx++];
6154 VTables.push_back(VT);
6155 }
6156
6157 VTableUses.clear();
6158}
6159
6160void ASTReader::ReadPendingInstantiations(
6161 SmallVectorImpl<std::pair<ValueDecl *, SourceLocation> > &Pending) {
6162 for (unsigned Idx = 0, N = PendingInstantiations.size(); Idx < N;) {
6163 ValueDecl *D = cast<ValueDecl>(GetDecl(PendingInstantiations[Idx++]));
6164 SourceLocation Loc
6165 = SourceLocation::getFromRawEncoding(PendingInstantiations[Idx++]);
6166
6167 Pending.push_back(std::make_pair(D, Loc));
6168 }
6169 PendingInstantiations.clear();
6170}
6171
6172void ASTReader::LoadSelector(Selector Sel) {
6173 // It would be complicated to avoid reading the methods anyway. So don't.
6174 ReadMethodPool(Sel);
6175}
6176
6177void ASTReader::SetIdentifierInfo(IdentifierID ID, IdentifierInfo *II) {
6178 assert(ID && "Non-zero identifier ID required");
6179 assert(ID <= IdentifiersLoaded.size() && "identifier ID out of range");
6180 IdentifiersLoaded[ID - 1] = II;
6181 if (DeserializationListener)
6182 DeserializationListener->IdentifierRead(ID, II);
6183}
6184
6185/// \brief Set the globally-visible declarations associated with the given
6186/// identifier.
6187///
6188/// If the AST reader is currently in a state where the given declaration IDs
6189/// cannot safely be resolved, they are queued until it is safe to resolve
6190/// them.
6191///
6192/// \param II an IdentifierInfo that refers to one or more globally-visible
6193/// declarations.
6194///
6195/// \param DeclIDs the set of declaration IDs with the name @p II that are
6196/// visible at global scope.
6197///
Douglas Gregoraa945902013-02-18 15:53:43 +00006198/// \param Decls if non-null, this vector will be populated with the set of
6199/// deserialized declarations. These declarations will not be pushed into
6200/// scope.
Guy Benyei7f92f2d2012-12-18 14:30:41 +00006201void
6202ASTReader::SetGloballyVisibleDecls(IdentifierInfo *II,
6203 const SmallVectorImpl<uint32_t> &DeclIDs,
Douglas Gregoraa945902013-02-18 15:53:43 +00006204 SmallVectorImpl<Decl *> *Decls) {
6205 if (NumCurrentElementsDeserializing && !Decls) {
6206 PendingIdentifierInfos[II].append(DeclIDs.begin(), DeclIDs.end());
Guy Benyei7f92f2d2012-12-18 14:30:41 +00006207 return;
6208 }
6209
6210 for (unsigned I = 0, N = DeclIDs.size(); I != N; ++I) {
6211 NamedDecl *D = cast<NamedDecl>(GetDecl(DeclIDs[I]));
6212 if (SemaObj) {
Douglas Gregoraa945902013-02-18 15:53:43 +00006213 // If we're simply supposed to record the declarations, do so now.
6214 if (Decls) {
6215 Decls->push_back(D);
6216 continue;
6217 }
6218
Guy Benyei7f92f2d2012-12-18 14:30:41 +00006219 // Introduce this declaration into the translation-unit scope
6220 // and add it to the declaration chain for this identifier, so
6221 // that (unqualified) name lookup will find it.
Douglas Gregoraa945902013-02-18 15:53:43 +00006222 NamedDecl *ND = cast<NamedDecl>(D->getMostRecentDecl());
6223 SemaObj->pushExternalDeclIntoScope(ND, II);
Guy Benyei7f92f2d2012-12-18 14:30:41 +00006224 } else {
6225 // Queue this declaration so that it will be added to the
6226 // translation unit scope and identifier's declaration chain
6227 // once a Sema object is known.
6228 PreloadedDecls.push_back(D);
6229 }
6230 }
6231}
6232
Douglas Gregor8222b892013-01-21 16:52:34 +00006233IdentifierInfo *ASTReader::DecodeIdentifierInfo(IdentifierID ID) {
Guy Benyei7f92f2d2012-12-18 14:30:41 +00006234 if (ID == 0)
6235 return 0;
6236
6237 if (IdentifiersLoaded.empty()) {
6238 Error("no identifier table in AST file");
6239 return 0;
6240 }
6241
6242 ID -= 1;
6243 if (!IdentifiersLoaded[ID]) {
6244 GlobalIdentifierMapType::iterator I = GlobalIdentifierMap.find(ID + 1);
6245 assert(I != GlobalIdentifierMap.end() && "Corrupted global identifier map");
6246 ModuleFile *M = I->second;
6247 unsigned Index = ID - M->BaseIdentifierID;
6248 const char *Str = M->IdentifierTableData + M->IdentifierOffsets[Index];
6249
6250 // All of the strings in the AST file are preceded by a 16-bit length.
6251 // Extract that 16-bit length to avoid having to execute strlen().
6252 // NOTE: 'StrLenPtr' is an 'unsigned char*' so that we load bytes as
6253 // unsigned integers. This is important to avoid integer overflow when
6254 // we cast them to 'unsigned'.
6255 const unsigned char *StrLenPtr = (const unsigned char*) Str - 2;
6256 unsigned StrLen = (((unsigned) StrLenPtr[0])
6257 | (((unsigned) StrLenPtr[1]) << 8)) - 1;
Douglas Gregor8222b892013-01-21 16:52:34 +00006258 IdentifiersLoaded[ID]
6259 = &PP.getIdentifierTable().get(StringRef(Str, StrLen));
Guy Benyei7f92f2d2012-12-18 14:30:41 +00006260 if (DeserializationListener)
6261 DeserializationListener->IdentifierRead(ID + 1, IdentifiersLoaded[ID]);
6262 }
6263
6264 return IdentifiersLoaded[ID];
6265}
6266
Douglas Gregor8222b892013-01-21 16:52:34 +00006267IdentifierInfo *ASTReader::getLocalIdentifier(ModuleFile &M, unsigned LocalID) {
6268 return DecodeIdentifierInfo(getGlobalIdentifierID(M, LocalID));
Guy Benyei7f92f2d2012-12-18 14:30:41 +00006269}
6270
6271IdentifierID ASTReader::getGlobalIdentifierID(ModuleFile &M, unsigned LocalID) {
6272 if (LocalID < NUM_PREDEF_IDENT_IDS)
6273 return LocalID;
6274
6275 ContinuousRangeMap<uint32_t, int, 2>::iterator I
6276 = M.IdentifierRemap.find(LocalID - NUM_PREDEF_IDENT_IDS);
6277 assert(I != M.IdentifierRemap.end()
6278 && "Invalid index into identifier index remap");
6279
6280 return LocalID + I->second;
6281}
6282
Argyrios Kyrtzidis9818a1d2013-02-20 00:54:57 +00006283MacroDirective *ASTReader::getMacro(MacroID ID, MacroDirective *Hint) {
Guy Benyei7f92f2d2012-12-18 14:30:41 +00006284 if (ID == 0)
6285 return 0;
6286
6287 if (MacrosLoaded.empty()) {
6288 Error("no macro table in AST file");
6289 return 0;
6290 }
6291
6292 ID -= NUM_PREDEF_MACRO_IDS;
6293 if (!MacrosLoaded[ID]) {
6294 GlobalMacroMapType::iterator I
6295 = GlobalMacroMap.find(ID + NUM_PREDEF_MACRO_IDS);
6296 assert(I != GlobalMacroMap.end() && "Corrupted global macro map");
6297 ModuleFile *M = I->second;
6298 unsigned Index = ID - M->BaseMacroID;
Argyrios Kyrtzidisdc1088f2013-01-19 03:14:56 +00006299 ReadMacroRecord(*M, M->MacroOffsets[Index], Hint);
Guy Benyei7f92f2d2012-12-18 14:30:41 +00006300 }
6301
6302 return MacrosLoaded[ID];
6303}
6304
6305MacroID ASTReader::getGlobalMacroID(ModuleFile &M, unsigned LocalID) {
6306 if (LocalID < NUM_PREDEF_MACRO_IDS)
6307 return LocalID;
6308
6309 ContinuousRangeMap<uint32_t, int, 2>::iterator I
6310 = M.MacroRemap.find(LocalID - NUM_PREDEF_MACRO_IDS);
6311 assert(I != M.MacroRemap.end() && "Invalid index into macro index remap");
6312
6313 return LocalID + I->second;
6314}
6315
6316serialization::SubmoduleID
6317ASTReader::getGlobalSubmoduleID(ModuleFile &M, unsigned LocalID) {
6318 if (LocalID < NUM_PREDEF_SUBMODULE_IDS)
6319 return LocalID;
6320
6321 ContinuousRangeMap<uint32_t, int, 2>::iterator I
6322 = M.SubmoduleRemap.find(LocalID - NUM_PREDEF_SUBMODULE_IDS);
6323 assert(I != M.SubmoduleRemap.end()
6324 && "Invalid index into submodule index remap");
6325
6326 return LocalID + I->second;
6327}
6328
6329Module *ASTReader::getSubmodule(SubmoduleID GlobalID) {
6330 if (GlobalID < NUM_PREDEF_SUBMODULE_IDS) {
6331 assert(GlobalID == 0 && "Unhandled global submodule ID");
6332 return 0;
6333 }
6334
6335 if (GlobalID > SubmodulesLoaded.size()) {
6336 Error("submodule ID out of range in AST file");
6337 return 0;
6338 }
6339
6340 return SubmodulesLoaded[GlobalID - NUM_PREDEF_SUBMODULE_IDS];
6341}
Douglas Gregorca2ab452013-01-12 01:29:50 +00006342
6343Module *ASTReader::getModule(unsigned ID) {
6344 return getSubmodule(ID);
6345}
6346
Guy Benyei7f92f2d2012-12-18 14:30:41 +00006347Selector ASTReader::getLocalSelector(ModuleFile &M, unsigned LocalID) {
6348 return DecodeSelector(getGlobalSelectorID(M, LocalID));
6349}
6350
6351Selector ASTReader::DecodeSelector(serialization::SelectorID ID) {
6352 if (ID == 0)
6353 return Selector();
6354
6355 if (ID > SelectorsLoaded.size()) {
6356 Error("selector ID out of range in AST file");
6357 return Selector();
6358 }
6359
6360 if (SelectorsLoaded[ID - 1].getAsOpaquePtr() == 0) {
6361 // Load this selector from the selector table.
6362 GlobalSelectorMapType::iterator I = GlobalSelectorMap.find(ID);
6363 assert(I != GlobalSelectorMap.end() && "Corrupted global selector map");
6364 ModuleFile &M = *I->second;
6365 ASTSelectorLookupTrait Trait(*this, M);
6366 unsigned Idx = ID - M.BaseSelectorID - NUM_PREDEF_SELECTOR_IDS;
6367 SelectorsLoaded[ID - 1] =
6368 Trait.ReadKey(M.SelectorLookupTableData + M.SelectorOffsets[Idx], 0);
6369 if (DeserializationListener)
6370 DeserializationListener->SelectorRead(ID, SelectorsLoaded[ID - 1]);
6371 }
6372
6373 return SelectorsLoaded[ID - 1];
6374}
6375
6376Selector ASTReader::GetExternalSelector(serialization::SelectorID ID) {
6377 return DecodeSelector(ID);
6378}
6379
6380uint32_t ASTReader::GetNumExternalSelectors() {
6381 // ID 0 (the null selector) is considered an external selector.
6382 return getTotalNumSelectors() + 1;
6383}
6384
6385serialization::SelectorID
6386ASTReader::getGlobalSelectorID(ModuleFile &M, unsigned LocalID) const {
6387 if (LocalID < NUM_PREDEF_SELECTOR_IDS)
6388 return LocalID;
6389
6390 ContinuousRangeMap<uint32_t, int, 2>::iterator I
6391 = M.SelectorRemap.find(LocalID - NUM_PREDEF_SELECTOR_IDS);
6392 assert(I != M.SelectorRemap.end()
6393 && "Invalid index into selector index remap");
6394
6395 return LocalID + I->second;
6396}
6397
6398DeclarationName
6399ASTReader::ReadDeclarationName(ModuleFile &F,
6400 const RecordData &Record, unsigned &Idx) {
6401 DeclarationName::NameKind Kind = (DeclarationName::NameKind)Record[Idx++];
6402 switch (Kind) {
6403 case DeclarationName::Identifier:
Douglas Gregor8222b892013-01-21 16:52:34 +00006404 return DeclarationName(GetIdentifierInfo(F, Record, Idx));
Guy Benyei7f92f2d2012-12-18 14:30:41 +00006405
6406 case DeclarationName::ObjCZeroArgSelector:
6407 case DeclarationName::ObjCOneArgSelector:
6408 case DeclarationName::ObjCMultiArgSelector:
6409 return DeclarationName(ReadSelector(F, Record, Idx));
6410
6411 case DeclarationName::CXXConstructorName:
6412 return Context.DeclarationNames.getCXXConstructorName(
6413 Context.getCanonicalType(readType(F, Record, Idx)));
6414
6415 case DeclarationName::CXXDestructorName:
6416 return Context.DeclarationNames.getCXXDestructorName(
6417 Context.getCanonicalType(readType(F, Record, Idx)));
6418
6419 case DeclarationName::CXXConversionFunctionName:
6420 return Context.DeclarationNames.getCXXConversionFunctionName(
6421 Context.getCanonicalType(readType(F, Record, Idx)));
6422
6423 case DeclarationName::CXXOperatorName:
6424 return Context.DeclarationNames.getCXXOperatorName(
6425 (OverloadedOperatorKind)Record[Idx++]);
6426
6427 case DeclarationName::CXXLiteralOperatorName:
6428 return Context.DeclarationNames.getCXXLiteralOperatorName(
6429 GetIdentifierInfo(F, Record, Idx));
6430
6431 case DeclarationName::CXXUsingDirective:
6432 return DeclarationName::getUsingDirectiveName();
6433 }
6434
6435 llvm_unreachable("Invalid NameKind!");
6436}
6437
6438void ASTReader::ReadDeclarationNameLoc(ModuleFile &F,
6439 DeclarationNameLoc &DNLoc,
6440 DeclarationName Name,
6441 const RecordData &Record, unsigned &Idx) {
6442 switch (Name.getNameKind()) {
6443 case DeclarationName::CXXConstructorName:
6444 case DeclarationName::CXXDestructorName:
6445 case DeclarationName::CXXConversionFunctionName:
6446 DNLoc.NamedType.TInfo = GetTypeSourceInfo(F, Record, Idx);
6447 break;
6448
6449 case DeclarationName::CXXOperatorName:
6450 DNLoc.CXXOperatorName.BeginOpNameLoc
6451 = ReadSourceLocation(F, Record, Idx).getRawEncoding();
6452 DNLoc.CXXOperatorName.EndOpNameLoc
6453 = ReadSourceLocation(F, Record, Idx).getRawEncoding();
6454 break;
6455
6456 case DeclarationName::CXXLiteralOperatorName:
6457 DNLoc.CXXLiteralOperatorName.OpNameLoc
6458 = ReadSourceLocation(F, Record, Idx).getRawEncoding();
6459 break;
6460
6461 case DeclarationName::Identifier:
6462 case DeclarationName::ObjCZeroArgSelector:
6463 case DeclarationName::ObjCOneArgSelector:
6464 case DeclarationName::ObjCMultiArgSelector:
6465 case DeclarationName::CXXUsingDirective:
6466 break;
6467 }
6468}
6469
6470void ASTReader::ReadDeclarationNameInfo(ModuleFile &F,
6471 DeclarationNameInfo &NameInfo,
6472 const RecordData &Record, unsigned &Idx) {
6473 NameInfo.setName(ReadDeclarationName(F, Record, Idx));
6474 NameInfo.setLoc(ReadSourceLocation(F, Record, Idx));
6475 DeclarationNameLoc DNLoc;
6476 ReadDeclarationNameLoc(F, DNLoc, NameInfo.getName(), Record, Idx);
6477 NameInfo.setInfo(DNLoc);
6478}
6479
6480void ASTReader::ReadQualifierInfo(ModuleFile &F, QualifierInfo &Info,
6481 const RecordData &Record, unsigned &Idx) {
6482 Info.QualifierLoc = ReadNestedNameSpecifierLoc(F, Record, Idx);
6483 unsigned NumTPLists = Record[Idx++];
6484 Info.NumTemplParamLists = NumTPLists;
6485 if (NumTPLists) {
6486 Info.TemplParamLists = new (Context) TemplateParameterList*[NumTPLists];
6487 for (unsigned i=0; i != NumTPLists; ++i)
6488 Info.TemplParamLists[i] = ReadTemplateParameterList(F, Record, Idx);
6489 }
6490}
6491
6492TemplateName
6493ASTReader::ReadTemplateName(ModuleFile &F, const RecordData &Record,
6494 unsigned &Idx) {
6495 TemplateName::NameKind Kind = (TemplateName::NameKind)Record[Idx++];
6496 switch (Kind) {
6497 case TemplateName::Template:
6498 return TemplateName(ReadDeclAs<TemplateDecl>(F, Record, Idx));
6499
6500 case TemplateName::OverloadedTemplate: {
6501 unsigned size = Record[Idx++];
6502 UnresolvedSet<8> Decls;
6503 while (size--)
6504 Decls.addDecl(ReadDeclAs<NamedDecl>(F, Record, Idx));
6505
6506 return Context.getOverloadedTemplateName(Decls.begin(), Decls.end());
6507 }
6508
6509 case TemplateName::QualifiedTemplate: {
6510 NestedNameSpecifier *NNS = ReadNestedNameSpecifier(F, Record, Idx);
6511 bool hasTemplKeyword = Record[Idx++];
6512 TemplateDecl *Template = ReadDeclAs<TemplateDecl>(F, Record, Idx);
6513 return Context.getQualifiedTemplateName(NNS, hasTemplKeyword, Template);
6514 }
6515
6516 case TemplateName::DependentTemplate: {
6517 NestedNameSpecifier *NNS = ReadNestedNameSpecifier(F, Record, Idx);
6518 if (Record[Idx++]) // isIdentifier
6519 return Context.getDependentTemplateName(NNS,
6520 GetIdentifierInfo(F, Record,
6521 Idx));
6522 return Context.getDependentTemplateName(NNS,
6523 (OverloadedOperatorKind)Record[Idx++]);
6524 }
6525
6526 case TemplateName::SubstTemplateTemplateParm: {
6527 TemplateTemplateParmDecl *param
6528 = ReadDeclAs<TemplateTemplateParmDecl>(F, Record, Idx);
6529 if (!param) return TemplateName();
6530 TemplateName replacement = ReadTemplateName(F, Record, Idx);
6531 return Context.getSubstTemplateTemplateParm(param, replacement);
6532 }
6533
6534 case TemplateName::SubstTemplateTemplateParmPack: {
6535 TemplateTemplateParmDecl *Param
6536 = ReadDeclAs<TemplateTemplateParmDecl>(F, Record, Idx);
6537 if (!Param)
6538 return TemplateName();
6539
6540 TemplateArgument ArgPack = ReadTemplateArgument(F, Record, Idx);
6541 if (ArgPack.getKind() != TemplateArgument::Pack)
6542 return TemplateName();
6543
6544 return Context.getSubstTemplateTemplateParmPack(Param, ArgPack);
6545 }
6546 }
6547
6548 llvm_unreachable("Unhandled template name kind!");
6549}
6550
6551TemplateArgument
6552ASTReader::ReadTemplateArgument(ModuleFile &F,
6553 const RecordData &Record, unsigned &Idx) {
6554 TemplateArgument::ArgKind Kind = (TemplateArgument::ArgKind)Record[Idx++];
6555 switch (Kind) {
6556 case TemplateArgument::Null:
6557 return TemplateArgument();
6558 case TemplateArgument::Type:
6559 return TemplateArgument(readType(F, Record, Idx));
6560 case TemplateArgument::Declaration: {
6561 ValueDecl *D = ReadDeclAs<ValueDecl>(F, Record, Idx);
6562 bool ForReferenceParam = Record[Idx++];
6563 return TemplateArgument(D, ForReferenceParam);
6564 }
6565 case TemplateArgument::NullPtr:
6566 return TemplateArgument(readType(F, Record, Idx), /*isNullPtr*/true);
6567 case TemplateArgument::Integral: {
6568 llvm::APSInt Value = ReadAPSInt(Record, Idx);
6569 QualType T = readType(F, Record, Idx);
6570 return TemplateArgument(Context, Value, T);
6571 }
6572 case TemplateArgument::Template:
6573 return TemplateArgument(ReadTemplateName(F, Record, Idx));
6574 case TemplateArgument::TemplateExpansion: {
6575 TemplateName Name = ReadTemplateName(F, Record, Idx);
David Blaikiedc84cd52013-02-20 22:23:23 +00006576 Optional<unsigned> NumTemplateExpansions;
Guy Benyei7f92f2d2012-12-18 14:30:41 +00006577 if (unsigned NumExpansions = Record[Idx++])
6578 NumTemplateExpansions = NumExpansions - 1;
6579 return TemplateArgument(Name, NumTemplateExpansions);
6580 }
6581 case TemplateArgument::Expression:
6582 return TemplateArgument(ReadExpr(F));
6583 case TemplateArgument::Pack: {
6584 unsigned NumArgs = Record[Idx++];
6585 TemplateArgument *Args = new (Context) TemplateArgument[NumArgs];
6586 for (unsigned I = 0; I != NumArgs; ++I)
6587 Args[I] = ReadTemplateArgument(F, Record, Idx);
6588 return TemplateArgument(Args, NumArgs);
6589 }
6590 }
6591
6592 llvm_unreachable("Unhandled template argument kind!");
6593}
6594
6595TemplateParameterList *
6596ASTReader::ReadTemplateParameterList(ModuleFile &F,
6597 const RecordData &Record, unsigned &Idx) {
6598 SourceLocation TemplateLoc = ReadSourceLocation(F, Record, Idx);
6599 SourceLocation LAngleLoc = ReadSourceLocation(F, Record, Idx);
6600 SourceLocation RAngleLoc = ReadSourceLocation(F, Record, Idx);
6601
6602 unsigned NumParams = Record[Idx++];
6603 SmallVector<NamedDecl *, 16> Params;
6604 Params.reserve(NumParams);
6605 while (NumParams--)
6606 Params.push_back(ReadDeclAs<NamedDecl>(F, Record, Idx));
6607
6608 TemplateParameterList* TemplateParams =
6609 TemplateParameterList::Create(Context, TemplateLoc, LAngleLoc,
6610 Params.data(), Params.size(), RAngleLoc);
6611 return TemplateParams;
6612}
6613
6614void
6615ASTReader::
6616ReadTemplateArgumentList(SmallVector<TemplateArgument, 8> &TemplArgs,
6617 ModuleFile &F, const RecordData &Record,
6618 unsigned &Idx) {
6619 unsigned NumTemplateArgs = Record[Idx++];
6620 TemplArgs.reserve(NumTemplateArgs);
6621 while (NumTemplateArgs--)
6622 TemplArgs.push_back(ReadTemplateArgument(F, Record, Idx));
6623}
6624
6625/// \brief Read a UnresolvedSet structure.
6626void ASTReader::ReadUnresolvedSet(ModuleFile &F, ASTUnresolvedSet &Set,
6627 const RecordData &Record, unsigned &Idx) {
6628 unsigned NumDecls = Record[Idx++];
6629 Set.reserve(Context, NumDecls);
6630 while (NumDecls--) {
6631 NamedDecl *D = ReadDeclAs<NamedDecl>(F, Record, Idx);
6632 AccessSpecifier AS = (AccessSpecifier)Record[Idx++];
6633 Set.addDecl(Context, D, AS);
6634 }
6635}
6636
6637CXXBaseSpecifier
6638ASTReader::ReadCXXBaseSpecifier(ModuleFile &F,
6639 const RecordData &Record, unsigned &Idx) {
6640 bool isVirtual = static_cast<bool>(Record[Idx++]);
6641 bool isBaseOfClass = static_cast<bool>(Record[Idx++]);
6642 AccessSpecifier AS = static_cast<AccessSpecifier>(Record[Idx++]);
6643 bool inheritConstructors = static_cast<bool>(Record[Idx++]);
6644 TypeSourceInfo *TInfo = GetTypeSourceInfo(F, Record, Idx);
6645 SourceRange Range = ReadSourceRange(F, Record, Idx);
6646 SourceLocation EllipsisLoc = ReadSourceLocation(F, Record, Idx);
6647 CXXBaseSpecifier Result(Range, isVirtual, isBaseOfClass, AS, TInfo,
6648 EllipsisLoc);
6649 Result.setInheritConstructors(inheritConstructors);
6650 return Result;
6651}
6652
6653std::pair<CXXCtorInitializer **, unsigned>
6654ASTReader::ReadCXXCtorInitializers(ModuleFile &F, const RecordData &Record,
6655 unsigned &Idx) {
6656 CXXCtorInitializer **CtorInitializers = 0;
6657 unsigned NumInitializers = Record[Idx++];
6658 if (NumInitializers) {
6659 CtorInitializers
6660 = new (Context) CXXCtorInitializer*[NumInitializers];
6661 for (unsigned i=0; i != NumInitializers; ++i) {
6662 TypeSourceInfo *TInfo = 0;
6663 bool IsBaseVirtual = false;
6664 FieldDecl *Member = 0;
6665 IndirectFieldDecl *IndirectMember = 0;
6666
6667 CtorInitializerType Type = (CtorInitializerType)Record[Idx++];
6668 switch (Type) {
6669 case CTOR_INITIALIZER_BASE:
6670 TInfo = GetTypeSourceInfo(F, Record, Idx);
6671 IsBaseVirtual = Record[Idx++];
6672 break;
6673
6674 case CTOR_INITIALIZER_DELEGATING:
6675 TInfo = GetTypeSourceInfo(F, Record, Idx);
6676 break;
6677
6678 case CTOR_INITIALIZER_MEMBER:
6679 Member = ReadDeclAs<FieldDecl>(F, Record, Idx);
6680 break;
6681
6682 case CTOR_INITIALIZER_INDIRECT_MEMBER:
6683 IndirectMember = ReadDeclAs<IndirectFieldDecl>(F, Record, Idx);
6684 break;
6685 }
6686
6687 SourceLocation MemberOrEllipsisLoc = ReadSourceLocation(F, Record, Idx);
6688 Expr *Init = ReadExpr(F);
6689 SourceLocation LParenLoc = ReadSourceLocation(F, Record, Idx);
6690 SourceLocation RParenLoc = ReadSourceLocation(F, Record, Idx);
6691 bool IsWritten = Record[Idx++];
6692 unsigned SourceOrderOrNumArrayIndices;
6693 SmallVector<VarDecl *, 8> Indices;
6694 if (IsWritten) {
6695 SourceOrderOrNumArrayIndices = Record[Idx++];
6696 } else {
6697 SourceOrderOrNumArrayIndices = Record[Idx++];
6698 Indices.reserve(SourceOrderOrNumArrayIndices);
6699 for (unsigned i=0; i != SourceOrderOrNumArrayIndices; ++i)
6700 Indices.push_back(ReadDeclAs<VarDecl>(F, Record, Idx));
6701 }
6702
6703 CXXCtorInitializer *BOMInit;
6704 if (Type == CTOR_INITIALIZER_BASE) {
6705 BOMInit = new (Context) CXXCtorInitializer(Context, TInfo, IsBaseVirtual,
6706 LParenLoc, Init, RParenLoc,
6707 MemberOrEllipsisLoc);
6708 } else if (Type == CTOR_INITIALIZER_DELEGATING) {
6709 BOMInit = new (Context) CXXCtorInitializer(Context, TInfo, LParenLoc,
6710 Init, RParenLoc);
6711 } else if (IsWritten) {
6712 if (Member)
6713 BOMInit = new (Context) CXXCtorInitializer(Context, Member, MemberOrEllipsisLoc,
6714 LParenLoc, Init, RParenLoc);
6715 else
6716 BOMInit = new (Context) CXXCtorInitializer(Context, IndirectMember,
6717 MemberOrEllipsisLoc, LParenLoc,
6718 Init, RParenLoc);
6719 } else {
6720 BOMInit = CXXCtorInitializer::Create(Context, Member, MemberOrEllipsisLoc,
6721 LParenLoc, Init, RParenLoc,
6722 Indices.data(), Indices.size());
6723 }
6724
6725 if (IsWritten)
6726 BOMInit->setSourceOrder(SourceOrderOrNumArrayIndices);
6727 CtorInitializers[i] = BOMInit;
6728 }
6729 }
6730
6731 return std::make_pair(CtorInitializers, NumInitializers);
6732}
6733
6734NestedNameSpecifier *
6735ASTReader::ReadNestedNameSpecifier(ModuleFile &F,
6736 const RecordData &Record, unsigned &Idx) {
6737 unsigned N = Record[Idx++];
6738 NestedNameSpecifier *NNS = 0, *Prev = 0;
6739 for (unsigned I = 0; I != N; ++I) {
6740 NestedNameSpecifier::SpecifierKind Kind
6741 = (NestedNameSpecifier::SpecifierKind)Record[Idx++];
6742 switch (Kind) {
6743 case NestedNameSpecifier::Identifier: {
6744 IdentifierInfo *II = GetIdentifierInfo(F, Record, Idx);
6745 NNS = NestedNameSpecifier::Create(Context, Prev, II);
6746 break;
6747 }
6748
6749 case NestedNameSpecifier::Namespace: {
6750 NamespaceDecl *NS = ReadDeclAs<NamespaceDecl>(F, Record, Idx);
6751 NNS = NestedNameSpecifier::Create(Context, Prev, NS);
6752 break;
6753 }
6754
6755 case NestedNameSpecifier::NamespaceAlias: {
6756 NamespaceAliasDecl *Alias =ReadDeclAs<NamespaceAliasDecl>(F, Record, Idx);
6757 NNS = NestedNameSpecifier::Create(Context, Prev, Alias);
6758 break;
6759 }
6760
6761 case NestedNameSpecifier::TypeSpec:
6762 case NestedNameSpecifier::TypeSpecWithTemplate: {
6763 const Type *T = readType(F, Record, Idx).getTypePtrOrNull();
6764 if (!T)
6765 return 0;
6766
6767 bool Template = Record[Idx++];
6768 NNS = NestedNameSpecifier::Create(Context, Prev, Template, T);
6769 break;
6770 }
6771
6772 case NestedNameSpecifier::Global: {
6773 NNS = NestedNameSpecifier::GlobalSpecifier(Context);
6774 // No associated value, and there can't be a prefix.
6775 break;
6776 }
6777 }
6778 Prev = NNS;
6779 }
6780 return NNS;
6781}
6782
6783NestedNameSpecifierLoc
6784ASTReader::ReadNestedNameSpecifierLoc(ModuleFile &F, const RecordData &Record,
6785 unsigned &Idx) {
6786 unsigned N = Record[Idx++];
6787 NestedNameSpecifierLocBuilder Builder;
6788 for (unsigned I = 0; I != N; ++I) {
6789 NestedNameSpecifier::SpecifierKind Kind
6790 = (NestedNameSpecifier::SpecifierKind)Record[Idx++];
6791 switch (Kind) {
6792 case NestedNameSpecifier::Identifier: {
6793 IdentifierInfo *II = GetIdentifierInfo(F, Record, Idx);
6794 SourceRange Range = ReadSourceRange(F, Record, Idx);
6795 Builder.Extend(Context, II, Range.getBegin(), Range.getEnd());
6796 break;
6797 }
6798
6799 case NestedNameSpecifier::Namespace: {
6800 NamespaceDecl *NS = ReadDeclAs<NamespaceDecl>(F, Record, Idx);
6801 SourceRange Range = ReadSourceRange(F, Record, Idx);
6802 Builder.Extend(Context, NS, Range.getBegin(), Range.getEnd());
6803 break;
6804 }
6805
6806 case NestedNameSpecifier::NamespaceAlias: {
6807 NamespaceAliasDecl *Alias =ReadDeclAs<NamespaceAliasDecl>(F, Record, Idx);
6808 SourceRange Range = ReadSourceRange(F, Record, Idx);
6809 Builder.Extend(Context, Alias, Range.getBegin(), Range.getEnd());
6810 break;
6811 }
6812
6813 case NestedNameSpecifier::TypeSpec:
6814 case NestedNameSpecifier::TypeSpecWithTemplate: {
6815 bool Template = Record[Idx++];
6816 TypeSourceInfo *T = GetTypeSourceInfo(F, Record, Idx);
6817 if (!T)
6818 return NestedNameSpecifierLoc();
6819 SourceLocation ColonColonLoc = ReadSourceLocation(F, Record, Idx);
6820
6821 // FIXME: 'template' keyword location not saved anywhere, so we fake it.
6822 Builder.Extend(Context,
6823 Template? T->getTypeLoc().getBeginLoc() : SourceLocation(),
6824 T->getTypeLoc(), ColonColonLoc);
6825 break;
6826 }
6827
6828 case NestedNameSpecifier::Global: {
6829 SourceLocation ColonColonLoc = ReadSourceLocation(F, Record, Idx);
6830 Builder.MakeGlobal(Context, ColonColonLoc);
6831 break;
6832 }
6833 }
6834 }
6835
6836 return Builder.getWithLocInContext(Context);
6837}
6838
6839SourceRange
6840ASTReader::ReadSourceRange(ModuleFile &F, const RecordData &Record,
6841 unsigned &Idx) {
6842 SourceLocation beg = ReadSourceLocation(F, Record, Idx);
6843 SourceLocation end = ReadSourceLocation(F, Record, Idx);
6844 return SourceRange(beg, end);
6845}
6846
6847/// \brief Read an integral value
6848llvm::APInt ASTReader::ReadAPInt(const RecordData &Record, unsigned &Idx) {
6849 unsigned BitWidth = Record[Idx++];
6850 unsigned NumWords = llvm::APInt::getNumWords(BitWidth);
6851 llvm::APInt Result(BitWidth, NumWords, &Record[Idx]);
6852 Idx += NumWords;
6853 return Result;
6854}
6855
6856/// \brief Read a signed integral value
6857llvm::APSInt ASTReader::ReadAPSInt(const RecordData &Record, unsigned &Idx) {
6858 bool isUnsigned = Record[Idx++];
6859 return llvm::APSInt(ReadAPInt(Record, Idx), isUnsigned);
6860}
6861
6862/// \brief Read a floating-point value
Tim Northover9ec55f22013-01-22 09:46:51 +00006863llvm::APFloat ASTReader::ReadAPFloat(const RecordData &Record,
6864 const llvm::fltSemantics &Sem,
6865 unsigned &Idx) {
6866 return llvm::APFloat(Sem, ReadAPInt(Record, Idx));
Guy Benyei7f92f2d2012-12-18 14:30:41 +00006867}
6868
6869// \brief Read a string
6870std::string ASTReader::ReadString(const RecordData &Record, unsigned &Idx) {
6871 unsigned Len = Record[Idx++];
6872 std::string Result(Record.data() + Idx, Record.data() + Idx + Len);
6873 Idx += Len;
6874 return Result;
6875}
6876
6877VersionTuple ASTReader::ReadVersionTuple(const RecordData &Record,
6878 unsigned &Idx) {
6879 unsigned Major = Record[Idx++];
6880 unsigned Minor = Record[Idx++];
6881 unsigned Subminor = Record[Idx++];
6882 if (Minor == 0)
6883 return VersionTuple(Major);
6884 if (Subminor == 0)
6885 return VersionTuple(Major, Minor - 1);
6886 return VersionTuple(Major, Minor - 1, Subminor - 1);
6887}
6888
6889CXXTemporary *ASTReader::ReadCXXTemporary(ModuleFile &F,
6890 const RecordData &Record,
6891 unsigned &Idx) {
6892 CXXDestructorDecl *Decl = ReadDeclAs<CXXDestructorDecl>(F, Record, Idx);
6893 return CXXTemporary::Create(Context, Decl);
6894}
6895
6896DiagnosticBuilder ASTReader::Diag(unsigned DiagID) {
6897 return Diag(SourceLocation(), DiagID);
6898}
6899
6900DiagnosticBuilder ASTReader::Diag(SourceLocation Loc, unsigned DiagID) {
6901 return Diags.Report(Loc, DiagID);
6902}
6903
6904/// \brief Retrieve the identifier table associated with the
6905/// preprocessor.
6906IdentifierTable &ASTReader::getIdentifierTable() {
6907 return PP.getIdentifierTable();
6908}
6909
6910/// \brief Record that the given ID maps to the given switch-case
6911/// statement.
6912void ASTReader::RecordSwitchCaseID(SwitchCase *SC, unsigned ID) {
6913 assert((*CurrSwitchCaseStmts)[ID] == 0 &&
6914 "Already have a SwitchCase with this ID");
6915 (*CurrSwitchCaseStmts)[ID] = SC;
6916}
6917
6918/// \brief Retrieve the switch-case statement with the given ID.
6919SwitchCase *ASTReader::getSwitchCaseWithID(unsigned ID) {
6920 assert((*CurrSwitchCaseStmts)[ID] != 0 && "No SwitchCase with this ID");
6921 return (*CurrSwitchCaseStmts)[ID];
6922}
6923
6924void ASTReader::ClearSwitchCaseIDs() {
6925 CurrSwitchCaseStmts->clear();
6926}
6927
6928void ASTReader::ReadComments() {
6929 std::vector<RawComment *> Comments;
Chris Lattner8f9a1eb2013-01-20 00:56:42 +00006930 for (SmallVectorImpl<std::pair<BitstreamCursor,
Guy Benyei7f92f2d2012-12-18 14:30:41 +00006931 serialization::ModuleFile *> >::iterator
6932 I = CommentsCursors.begin(),
6933 E = CommentsCursors.end();
6934 I != E; ++I) {
Chris Lattner8f9a1eb2013-01-20 00:56:42 +00006935 BitstreamCursor &Cursor = I->first;
Guy Benyei7f92f2d2012-12-18 14:30:41 +00006936 serialization::ModuleFile &F = *I->second;
6937 SavedStreamPosition SavedPosition(Cursor);
6938
6939 RecordData Record;
6940 while (true) {
Chris Lattner8f9a1eb2013-01-20 00:56:42 +00006941 llvm::BitstreamEntry Entry =
6942 Cursor.advanceSkippingSubblocks(BitstreamCursor::AF_DontPopBlockAtEnd);
6943
6944 switch (Entry.Kind) {
6945 case llvm::BitstreamEntry::SubBlock: // Handled for us already.
6946 case llvm::BitstreamEntry::Error:
6947 Error("malformed block record in AST file");
6948 return;
6949 case llvm::BitstreamEntry::EndBlock:
6950 goto NextCursor;
6951 case llvm::BitstreamEntry::Record:
6952 // The interesting case.
Guy Benyei7f92f2d2012-12-18 14:30:41 +00006953 break;
Guy Benyei7f92f2d2012-12-18 14:30:41 +00006954 }
6955
6956 // Read a record.
6957 Record.clear();
Chris Lattnerb3ce3572013-01-20 02:38:54 +00006958 switch ((CommentRecordTypes)Cursor.readRecord(Entry.ID, Record)) {
Guy Benyei7f92f2d2012-12-18 14:30:41 +00006959 case COMMENTS_RAW_COMMENT: {
6960 unsigned Idx = 0;
6961 SourceRange SR = ReadSourceRange(F, Record, Idx);
6962 RawComment::CommentKind Kind =
6963 (RawComment::CommentKind) Record[Idx++];
6964 bool IsTrailingComment = Record[Idx++];
6965 bool IsAlmostTrailingComment = Record[Idx++];
6966 Comments.push_back(new (Context) RawComment(SR, Kind,
6967 IsTrailingComment,
6968 IsAlmostTrailingComment));
6969 break;
6970 }
6971 }
6972 }
Chris Lattner8f9a1eb2013-01-20 00:56:42 +00006973 NextCursor:;
Guy Benyei7f92f2d2012-12-18 14:30:41 +00006974 }
6975 Context.Comments.addCommentsToFront(Comments);
6976}
6977
6978void ASTReader::finishPendingActions() {
6979 while (!PendingIdentifierInfos.empty() || !PendingDeclChains.empty() ||
Argyrios Kyrtzidis7640b022013-02-16 00:48:59 +00006980 !PendingMacroIDs.empty() || !PendingDeclContextInfos.empty()) {
Guy Benyei7f92f2d2012-12-18 14:30:41 +00006981 // If any identifiers with corresponding top-level declarations have
6982 // been loaded, load those declarations now.
Douglas Gregoraa945902013-02-18 15:53:43 +00006983 llvm::DenseMap<IdentifierInfo *, SmallVector<Decl *, 2> > TopLevelDecls;
Guy Benyei7f92f2d2012-12-18 14:30:41 +00006984 while (!PendingIdentifierInfos.empty()) {
Douglas Gregoraa945902013-02-18 15:53:43 +00006985 // FIXME: std::move
6986 IdentifierInfo *II = PendingIdentifierInfos.back().first;
6987 SmallVector<uint32_t, 4> DeclIDs = PendingIdentifierInfos.back().second;
Douglas Gregorcc9bdcb2013-02-19 18:26:28 +00006988 PendingIdentifierInfos.pop_back();
Douglas Gregoraa945902013-02-18 15:53:43 +00006989
6990 SetGloballyVisibleDecls(II, DeclIDs, &TopLevelDecls[II]);
Guy Benyei7f92f2d2012-12-18 14:30:41 +00006991 }
6992
6993 // Load pending declaration chains.
6994 for (unsigned I = 0; I != PendingDeclChains.size(); ++I) {
6995 loadPendingDeclChain(PendingDeclChains[I]);
6996 PendingDeclChainsKnown.erase(PendingDeclChains[I]);
6997 }
6998 PendingDeclChains.clear();
6999
Douglas Gregoraa945902013-02-18 15:53:43 +00007000 // Make the most recent of the top-level declarations visible.
7001 for (llvm::DenseMap<IdentifierInfo *, SmallVector<Decl *, 2> >::iterator
7002 TLD = TopLevelDecls.begin(), TLDEnd = TopLevelDecls.end();
7003 TLD != TLDEnd; ++TLD) {
7004 IdentifierInfo *II = TLD->first;
7005 for (unsigned I = 0, N = TLD->second.size(); I != N; ++I) {
7006 NamedDecl *ND = cast<NamedDecl>(TLD->second[I]->getMostRecentDecl());
7007 SemaObj->pushExternalDeclIntoScope(ND, II);
7008 }
7009 }
7010
Guy Benyei7f92f2d2012-12-18 14:30:41 +00007011 // Load any pending macro definitions.
7012 for (unsigned I = 0; I != PendingMacroIDs.size(); ++I) {
Argyrios Kyrtzidisdc1088f2013-01-19 03:14:56 +00007013 // FIXME: std::move here
7014 SmallVector<MacroID, 2> GlobalIDs = PendingMacroIDs.begin()[I].second;
Argyrios Kyrtzidis9818a1d2013-02-20 00:54:57 +00007015 MacroDirective *Hint = 0;
Argyrios Kyrtzidisdc1088f2013-01-19 03:14:56 +00007016 for (unsigned IDIdx = 0, NumIDs = GlobalIDs.size(); IDIdx != NumIDs;
7017 ++IDIdx) {
7018 Hint = getMacro(GlobalIDs[IDIdx], Hint);
Guy Benyei7f92f2d2012-12-18 14:30:41 +00007019 }
7020 }
7021 PendingMacroIDs.clear();
Argyrios Kyrtzidis7640b022013-02-16 00:48:59 +00007022
7023 // Wire up the DeclContexts for Decls that we delayed setting until
7024 // recursive loading is completed.
7025 while (!PendingDeclContextInfos.empty()) {
7026 PendingDeclContextInfo Info = PendingDeclContextInfos.front();
7027 PendingDeclContextInfos.pop_front();
7028 DeclContext *SemaDC = cast<DeclContext>(GetDecl(Info.SemaDC));
7029 DeclContext *LexicalDC = cast<DeclContext>(GetDecl(Info.LexicalDC));
7030 Info.D->setDeclContextsImpl(SemaDC, LexicalDC, getContext());
7031 }
Guy Benyei7f92f2d2012-12-18 14:30:41 +00007032 }
7033
7034 // If we deserialized any C++ or Objective-C class definitions, any
7035 // Objective-C protocol definitions, or any redeclarable templates, make sure
7036 // that all redeclarations point to the definitions. Note that this can only
7037 // happen now, after the redeclaration chains have been fully wired.
7038 for (llvm::SmallPtrSet<Decl *, 4>::iterator D = PendingDefinitions.begin(),
7039 DEnd = PendingDefinitions.end();
7040 D != DEnd; ++D) {
7041 if (TagDecl *TD = dyn_cast<TagDecl>(*D)) {
7042 if (const TagType *TagT = dyn_cast<TagType>(TD->TypeForDecl)) {
7043 // Make sure that the TagType points at the definition.
7044 const_cast<TagType*>(TagT)->decl = TD;
7045 }
7046
7047 if (CXXRecordDecl *RD = dyn_cast<CXXRecordDecl>(*D)) {
7048 for (CXXRecordDecl::redecl_iterator R = RD->redecls_begin(),
7049 REnd = RD->redecls_end();
7050 R != REnd; ++R)
7051 cast<CXXRecordDecl>(*R)->DefinitionData = RD->DefinitionData;
7052
7053 }
7054
7055 continue;
7056 }
7057
7058 if (ObjCInterfaceDecl *ID = dyn_cast<ObjCInterfaceDecl>(*D)) {
7059 // Make sure that the ObjCInterfaceType points at the definition.
7060 const_cast<ObjCInterfaceType *>(cast<ObjCInterfaceType>(ID->TypeForDecl))
7061 ->Decl = ID;
7062
7063 for (ObjCInterfaceDecl::redecl_iterator R = ID->redecls_begin(),
7064 REnd = ID->redecls_end();
7065 R != REnd; ++R)
7066 R->Data = ID->Data;
7067
7068 continue;
7069 }
7070
7071 if (ObjCProtocolDecl *PD = dyn_cast<ObjCProtocolDecl>(*D)) {
7072 for (ObjCProtocolDecl::redecl_iterator R = PD->redecls_begin(),
7073 REnd = PD->redecls_end();
7074 R != REnd; ++R)
7075 R->Data = PD->Data;
7076
7077 continue;
7078 }
7079
7080 RedeclarableTemplateDecl *RTD
7081 = cast<RedeclarableTemplateDecl>(*D)->getCanonicalDecl();
7082 for (RedeclarableTemplateDecl::redecl_iterator R = RTD->redecls_begin(),
7083 REnd = RTD->redecls_end();
7084 R != REnd; ++R)
7085 R->Common = RTD->Common;
7086 }
7087 PendingDefinitions.clear();
7088
7089 // Load the bodies of any functions or methods we've encountered. We do
7090 // this now (delayed) so that we can be sure that the declaration chains
7091 // have been fully wired up.
7092 for (PendingBodiesMap::iterator PB = PendingBodies.begin(),
7093 PBEnd = PendingBodies.end();
7094 PB != PBEnd; ++PB) {
7095 if (FunctionDecl *FD = dyn_cast<FunctionDecl>(PB->first)) {
7096 // FIXME: Check for =delete/=default?
7097 // FIXME: Complain about ODR violations here?
7098 if (!getContext().getLangOpts().Modules || !FD->hasBody())
7099 FD->setLazyBody(PB->second);
7100 continue;
7101 }
7102
7103 ObjCMethodDecl *MD = cast<ObjCMethodDecl>(PB->first);
7104 if (!getContext().getLangOpts().Modules || !MD->hasBody())
7105 MD->setLazyBody(PB->second);
7106 }
7107 PendingBodies.clear();
7108}
7109
7110void ASTReader::FinishedDeserializing() {
7111 assert(NumCurrentElementsDeserializing &&
7112 "FinishedDeserializing not paired with StartedDeserializing");
7113 if (NumCurrentElementsDeserializing == 1) {
7114 // We decrease NumCurrentElementsDeserializing only after pending actions
7115 // are finished, to avoid recursively re-calling finishPendingActions().
7116 finishPendingActions();
7117 }
7118 --NumCurrentElementsDeserializing;
7119
7120 if (NumCurrentElementsDeserializing == 0 &&
7121 Consumer && !PassingDeclsToConsumer) {
7122 // Guard variable to avoid recursively redoing the process of passing
7123 // decls to consumer.
7124 SaveAndRestore<bool> GuardPassingDeclsToConsumer(PassingDeclsToConsumer,
7125 true);
7126
7127 while (!InterestingDecls.empty()) {
7128 // We are not in recursive loading, so it's safe to pass the "interesting"
7129 // decls to the consumer.
7130 Decl *D = InterestingDecls.front();
7131 InterestingDecls.pop_front();
7132 PassInterestingDeclToConsumer(D);
7133 }
7134 }
7135}
7136
7137ASTReader::ASTReader(Preprocessor &PP, ASTContext &Context,
7138 StringRef isysroot, bool DisableValidation,
Douglas Gregorf575d6e2013-01-25 00:45:27 +00007139 bool AllowASTWithCompilerErrors, bool UseGlobalIndex)
Guy Benyei7f92f2d2012-12-18 14:30:41 +00007140 : Listener(new PCHValidator(PP, *this)), DeserializationListener(0),
7141 SourceMgr(PP.getSourceManager()), FileMgr(PP.getFileManager()),
7142 Diags(PP.getDiagnostics()), SemaObj(0), PP(PP), Context(Context),
7143 Consumer(0), ModuleMgr(PP.getFileManager()),
7144 isysroot(isysroot), DisableValidation(DisableValidation),
Douglas Gregore1698072013-01-25 00:38:33 +00007145 AllowASTWithCompilerErrors(AllowASTWithCompilerErrors),
Douglas Gregorf575d6e2013-01-25 00:45:27 +00007146 UseGlobalIndex(UseGlobalIndex), TriedLoadingGlobalIndex(false),
Guy Benyei7f92f2d2012-12-18 14:30:41 +00007147 CurrentGeneration(0), CurrSwitchCaseStmts(&SwitchCaseStmts),
7148 NumSLocEntriesRead(0), TotalNumSLocEntries(0),
Douglas Gregore1698072013-01-25 00:38:33 +00007149 NumStatementsRead(0), TotalNumStatements(0), NumMacrosRead(0),
7150 TotalNumMacros(0), NumIdentifierLookups(0), NumIdentifierLookupHits(0),
7151 NumSelectorsRead(0), NumMethodPoolEntriesRead(0),
Douglas Gregor95fb36e2013-01-28 17:54:36 +00007152 NumMethodPoolLookups(0), NumMethodPoolHits(0),
7153 NumMethodPoolTableLookups(0), NumMethodPoolTableHits(0),
7154 TotalNumMethodPoolEntries(0),
Guy Benyei7f92f2d2012-12-18 14:30:41 +00007155 NumLexicalDeclContextsRead(0), TotalLexicalDeclContexts(0),
7156 NumVisibleDeclContextsRead(0), TotalVisibleDeclContexts(0),
7157 TotalModulesSizeInBits(0), NumCurrentElementsDeserializing(0),
7158 PassingDeclsToConsumer(false),
7159 NumCXXBaseSpecifiersLoaded(0)
7160{
7161 SourceMgr.setExternalSLocEntrySource(this);
7162}
7163
7164ASTReader::~ASTReader() {
7165 for (DeclContextVisibleUpdatesPending::iterator
7166 I = PendingVisibleUpdates.begin(),
7167 E = PendingVisibleUpdates.end();
7168 I != E; ++I) {
7169 for (DeclContextVisibleUpdates::iterator J = I->second.begin(),
7170 F = I->second.end();
7171 J != F; ++J)
7172 delete J->first;
7173 }
7174}