blob: e6ef9f64413cfc8b53cbae86fd739a4488c15ad0 [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"
44#include "llvm/ADT/StringExtras.h"
45#include "llvm/Bitcode/BitstreamReader.h"
46#include "llvm/Support/ErrorHandling.h"
47#include "llvm/Support/FileSystem.h"
48#include "llvm/Support/MemoryBuffer.h"
49#include "llvm/Support/Path.h"
50#include "llvm/Support/SaveAndRestore.h"
51#include "llvm/Support/system_error.h"
52#include <algorithm>
Chris Lattnere4e4a882013-01-20 00:57:52 +000053#include <cstdio>
Guy Benyei7f92f2d2012-12-18 14:30:41 +000054#include <iterator>
55
56using namespace clang;
57using namespace clang::serialization;
58using namespace clang::serialization::reader;
Chris Lattner8f9a1eb2013-01-20 00:56:42 +000059using llvm::BitstreamCursor;
Guy Benyei7f92f2d2012-12-18 14:30:41 +000060
61//===----------------------------------------------------------------------===//
62// PCH validator implementation
63//===----------------------------------------------------------------------===//
64
65ASTReaderListener::~ASTReaderListener() {}
66
67/// \brief Compare the given set of language options against an existing set of
68/// language options.
69///
70/// \param Diags If non-NULL, diagnostics will be emitted via this engine.
71///
72/// \returns true if the languagae options mis-match, false otherwise.
73static bool checkLanguageOptions(const LangOptions &LangOpts,
74 const LangOptions &ExistingLangOpts,
75 DiagnosticsEngine *Diags) {
76#define LANGOPT(Name, Bits, Default, Description) \
77 if (ExistingLangOpts.Name != LangOpts.Name) { \
78 if (Diags) \
79 Diags->Report(diag::err_pch_langopt_mismatch) \
80 << Description << LangOpts.Name << ExistingLangOpts.Name; \
81 return true; \
82 }
83
84#define VALUE_LANGOPT(Name, Bits, Default, Description) \
85 if (ExistingLangOpts.Name != LangOpts.Name) { \
86 if (Diags) \
87 Diags->Report(diag::err_pch_langopt_value_mismatch) \
88 << Description; \
89 return true; \
90 }
91
92#define ENUM_LANGOPT(Name, Type, Bits, Default, Description) \
93 if (ExistingLangOpts.get##Name() != LangOpts.get##Name()) { \
94 if (Diags) \
95 Diags->Report(diag::err_pch_langopt_value_mismatch) \
96 << Description; \
97 return true; \
98 }
99
100#define BENIGN_LANGOPT(Name, Bits, Default, Description)
101#define BENIGN_ENUM_LANGOPT(Name, Type, Bits, Default, Description)
102#include "clang/Basic/LangOptions.def"
103
104 if (ExistingLangOpts.ObjCRuntime != LangOpts.ObjCRuntime) {
105 if (Diags)
106 Diags->Report(diag::err_pch_langopt_value_mismatch)
107 << "target Objective-C runtime";
108 return true;
109 }
110
Dmitri Gribenko6ebf0912013-02-22 14:21:27 +0000111 if (ExistingLangOpts.CommentOpts.BlockCommandNames !=
112 LangOpts.CommentOpts.BlockCommandNames) {
113 if (Diags)
114 Diags->Report(diag::err_pch_langopt_value_mismatch)
115 << "block command names";
116 return true;
117 }
118
Guy Benyei7f92f2d2012-12-18 14:30:41 +0000119 return false;
120}
121
122/// \brief Compare the given set of target options against an existing set of
123/// target options.
124///
125/// \param Diags If non-NULL, diagnostics will be emitted via this engine.
126///
127/// \returns true if the target options mis-match, false otherwise.
128static bool checkTargetOptions(const TargetOptions &TargetOpts,
129 const TargetOptions &ExistingTargetOpts,
130 DiagnosticsEngine *Diags) {
131#define CHECK_TARGET_OPT(Field, Name) \
132 if (TargetOpts.Field != ExistingTargetOpts.Field) { \
133 if (Diags) \
134 Diags->Report(diag::err_pch_targetopt_mismatch) \
135 << Name << TargetOpts.Field << ExistingTargetOpts.Field; \
136 return true; \
137 }
138
139 CHECK_TARGET_OPT(Triple, "target");
140 CHECK_TARGET_OPT(CPU, "target CPU");
141 CHECK_TARGET_OPT(ABI, "target ABI");
142 CHECK_TARGET_OPT(CXXABI, "target C++ ABI");
143 CHECK_TARGET_OPT(LinkerVersion, "target linker version");
144#undef CHECK_TARGET_OPT
145
146 // Compare feature sets.
147 SmallVector<StringRef, 4> ExistingFeatures(
148 ExistingTargetOpts.FeaturesAsWritten.begin(),
149 ExistingTargetOpts.FeaturesAsWritten.end());
150 SmallVector<StringRef, 4> ReadFeatures(TargetOpts.FeaturesAsWritten.begin(),
151 TargetOpts.FeaturesAsWritten.end());
152 std::sort(ExistingFeatures.begin(), ExistingFeatures.end());
153 std::sort(ReadFeatures.begin(), ReadFeatures.end());
154
155 unsigned ExistingIdx = 0, ExistingN = ExistingFeatures.size();
156 unsigned ReadIdx = 0, ReadN = ReadFeatures.size();
157 while (ExistingIdx < ExistingN && ReadIdx < ReadN) {
158 if (ExistingFeatures[ExistingIdx] == ReadFeatures[ReadIdx]) {
159 ++ExistingIdx;
160 ++ReadIdx;
161 continue;
162 }
163
164 if (ReadFeatures[ReadIdx] < ExistingFeatures[ExistingIdx]) {
165 if (Diags)
166 Diags->Report(diag::err_pch_targetopt_feature_mismatch)
167 << false << ReadFeatures[ReadIdx];
168 return true;
169 }
170
171 if (Diags)
172 Diags->Report(diag::err_pch_targetopt_feature_mismatch)
173 << true << ExistingFeatures[ExistingIdx];
174 return true;
175 }
176
177 if (ExistingIdx < ExistingN) {
178 if (Diags)
179 Diags->Report(diag::err_pch_targetopt_feature_mismatch)
180 << true << ExistingFeatures[ExistingIdx];
181 return true;
182 }
183
184 if (ReadIdx < ReadN) {
185 if (Diags)
186 Diags->Report(diag::err_pch_targetopt_feature_mismatch)
187 << false << ReadFeatures[ReadIdx];
188 return true;
189 }
190
191 return false;
192}
193
194bool
195PCHValidator::ReadLanguageOptions(const LangOptions &LangOpts,
196 bool Complain) {
197 const LangOptions &ExistingLangOpts = PP.getLangOpts();
198 return checkLanguageOptions(LangOpts, ExistingLangOpts,
199 Complain? &Reader.Diags : 0);
200}
201
202bool PCHValidator::ReadTargetOptions(const TargetOptions &TargetOpts,
203 bool Complain) {
204 const TargetOptions &ExistingTargetOpts = PP.getTargetInfo().getTargetOpts();
205 return checkTargetOptions(TargetOpts, ExistingTargetOpts,
206 Complain? &Reader.Diags : 0);
207}
208
209namespace {
210 typedef llvm::StringMap<std::pair<StringRef, bool /*IsUndef*/> >
211 MacroDefinitionsMap;
212}
213
214/// \brief Collect the macro definitions provided by the given preprocessor
215/// options.
216static void collectMacroDefinitions(const PreprocessorOptions &PPOpts,
217 MacroDefinitionsMap &Macros,
218 SmallVectorImpl<StringRef> *MacroNames = 0){
219 for (unsigned I = 0, N = PPOpts.Macros.size(); I != N; ++I) {
220 StringRef Macro = PPOpts.Macros[I].first;
221 bool IsUndef = PPOpts.Macros[I].second;
222
223 std::pair<StringRef, StringRef> MacroPair = Macro.split('=');
224 StringRef MacroName = MacroPair.first;
225 StringRef MacroBody = MacroPair.second;
226
227 // For an #undef'd macro, we only care about the name.
228 if (IsUndef) {
229 if (MacroNames && !Macros.count(MacroName))
230 MacroNames->push_back(MacroName);
231
232 Macros[MacroName] = std::make_pair("", true);
233 continue;
234 }
235
236 // For a #define'd macro, figure out the actual definition.
237 if (MacroName.size() == Macro.size())
238 MacroBody = "1";
239 else {
240 // Note: GCC drops anything following an end-of-line character.
241 StringRef::size_type End = MacroBody.find_first_of("\n\r");
242 MacroBody = MacroBody.substr(0, End);
243 }
244
245 if (MacroNames && !Macros.count(MacroName))
246 MacroNames->push_back(MacroName);
247 Macros[MacroName] = std::make_pair(MacroBody, false);
248 }
249}
250
251/// \brief Check the preprocessor options deserialized from the control block
252/// against the preprocessor options in an existing preprocessor.
253///
254/// \param Diags If non-null, produce diagnostics for any mismatches incurred.
255static bool checkPreprocessorOptions(const PreprocessorOptions &PPOpts,
256 const PreprocessorOptions &ExistingPPOpts,
257 DiagnosticsEngine *Diags,
258 FileManager &FileMgr,
259 std::string &SuggestedPredefines) {
260 // Check macro definitions.
261 MacroDefinitionsMap ASTFileMacros;
262 collectMacroDefinitions(PPOpts, ASTFileMacros);
263 MacroDefinitionsMap ExistingMacros;
264 SmallVector<StringRef, 4> ExistingMacroNames;
265 collectMacroDefinitions(ExistingPPOpts, ExistingMacros, &ExistingMacroNames);
266
267 for (unsigned I = 0, N = ExistingMacroNames.size(); I != N; ++I) {
268 // Dig out the macro definition in the existing preprocessor options.
269 StringRef MacroName = ExistingMacroNames[I];
270 std::pair<StringRef, bool> Existing = ExistingMacros[MacroName];
271
272 // Check whether we know anything about this macro name or not.
273 llvm::StringMap<std::pair<StringRef, bool /*IsUndef*/> >::iterator Known
274 = ASTFileMacros.find(MacroName);
275 if (Known == ASTFileMacros.end()) {
276 // FIXME: Check whether this identifier was referenced anywhere in the
277 // AST file. If so, we should reject the AST file. Unfortunately, this
278 // information isn't in the control block. What shall we do about it?
279
280 if (Existing.second) {
281 SuggestedPredefines += "#undef ";
282 SuggestedPredefines += MacroName.str();
283 SuggestedPredefines += '\n';
284 } else {
285 SuggestedPredefines += "#define ";
286 SuggestedPredefines += MacroName.str();
287 SuggestedPredefines += ' ';
288 SuggestedPredefines += Existing.first.str();
289 SuggestedPredefines += '\n';
290 }
291 continue;
292 }
293
294 // If the macro was defined in one but undef'd in the other, we have a
295 // conflict.
296 if (Existing.second != Known->second.second) {
297 if (Diags) {
298 Diags->Report(diag::err_pch_macro_def_undef)
299 << MacroName << Known->second.second;
300 }
301 return true;
302 }
303
304 // If the macro was #undef'd in both, or if the macro bodies are identical,
305 // it's fine.
306 if (Existing.second || Existing.first == Known->second.first)
307 continue;
308
309 // The macro bodies differ; complain.
310 if (Diags) {
311 Diags->Report(diag::err_pch_macro_def_conflict)
312 << MacroName << Known->second.first << Existing.first;
313 }
314 return true;
315 }
316
317 // Check whether we're using predefines.
318 if (PPOpts.UsePredefines != ExistingPPOpts.UsePredefines) {
319 if (Diags) {
320 Diags->Report(diag::err_pch_undef) << ExistingPPOpts.UsePredefines;
321 }
322 return true;
323 }
324
325 // Compute the #include and #include_macros lines we need.
326 for (unsigned I = 0, N = ExistingPPOpts.Includes.size(); I != N; ++I) {
327 StringRef File = ExistingPPOpts.Includes[I];
328 if (File == ExistingPPOpts.ImplicitPCHInclude)
329 continue;
330
331 if (std::find(PPOpts.Includes.begin(), PPOpts.Includes.end(), File)
332 != PPOpts.Includes.end())
333 continue;
334
335 SuggestedPredefines += "#include \"";
336 SuggestedPredefines +=
337 HeaderSearch::NormalizeDashIncludePath(File, FileMgr);
338 SuggestedPredefines += "\"\n";
339 }
340
341 for (unsigned I = 0, N = ExistingPPOpts.MacroIncludes.size(); I != N; ++I) {
342 StringRef File = ExistingPPOpts.MacroIncludes[I];
343 if (std::find(PPOpts.MacroIncludes.begin(), PPOpts.MacroIncludes.end(),
344 File)
345 != PPOpts.MacroIncludes.end())
346 continue;
347
348 SuggestedPredefines += "#__include_macros \"";
349 SuggestedPredefines +=
350 HeaderSearch::NormalizeDashIncludePath(File, FileMgr);
351 SuggestedPredefines += "\"\n##\n";
352 }
353
354 return false;
355}
356
357bool PCHValidator::ReadPreprocessorOptions(const PreprocessorOptions &PPOpts,
358 bool Complain,
359 std::string &SuggestedPredefines) {
360 const PreprocessorOptions &ExistingPPOpts = PP.getPreprocessorOpts();
361
362 return checkPreprocessorOptions(PPOpts, ExistingPPOpts,
363 Complain? &Reader.Diags : 0,
364 PP.getFileManager(),
365 SuggestedPredefines);
366}
367
368void PCHValidator::ReadHeaderFileInfo(const HeaderFileInfo &HFI,
369 unsigned ID) {
370 PP.getHeaderSearchInfo().setHeaderFileInfoForUID(HFI, ID);
371 ++NumHeaderInfos;
372}
373
374void PCHValidator::ReadCounter(const ModuleFile &M, unsigned Value) {
375 PP.setCounterValue(Value);
376}
377
378//===----------------------------------------------------------------------===//
379// AST reader implementation
380//===----------------------------------------------------------------------===//
381
382void
383ASTReader::setDeserializationListener(ASTDeserializationListener *Listener) {
384 DeserializationListener = Listener;
385}
386
387
388
389unsigned ASTSelectorLookupTrait::ComputeHash(Selector Sel) {
390 return serialization::ComputeHash(Sel);
391}
392
393
394std::pair<unsigned, unsigned>
395ASTSelectorLookupTrait::ReadKeyDataLength(const unsigned char*& d) {
396 using namespace clang::io;
397 unsigned KeyLen = ReadUnalignedLE16(d);
398 unsigned DataLen = ReadUnalignedLE16(d);
399 return std::make_pair(KeyLen, DataLen);
400}
401
402ASTSelectorLookupTrait::internal_key_type
403ASTSelectorLookupTrait::ReadKey(const unsigned char* d, unsigned) {
404 using namespace clang::io;
405 SelectorTable &SelTable = Reader.getContext().Selectors;
406 unsigned N = ReadUnalignedLE16(d);
407 IdentifierInfo *FirstII
Douglas Gregor8222b892013-01-21 16:52:34 +0000408 = Reader.getLocalIdentifier(F, ReadUnalignedLE32(d));
Guy Benyei7f92f2d2012-12-18 14:30:41 +0000409 if (N == 0)
410 return SelTable.getNullarySelector(FirstII);
411 else if (N == 1)
412 return SelTable.getUnarySelector(FirstII);
413
414 SmallVector<IdentifierInfo *, 16> Args;
415 Args.push_back(FirstII);
416 for (unsigned I = 1; I != N; ++I)
Douglas Gregor8222b892013-01-21 16:52:34 +0000417 Args.push_back(Reader.getLocalIdentifier(F, ReadUnalignedLE32(d)));
Guy Benyei7f92f2d2012-12-18 14:30:41 +0000418
419 return SelTable.getSelector(N, Args.data());
420}
421
422ASTSelectorLookupTrait::data_type
423ASTSelectorLookupTrait::ReadData(Selector, const unsigned char* d,
424 unsigned DataLen) {
425 using namespace clang::io;
426
427 data_type Result;
428
429 Result.ID = Reader.getGlobalSelectorID(F, ReadUnalignedLE32(d));
430 unsigned NumInstanceMethods = ReadUnalignedLE16(d);
431 unsigned NumFactoryMethods = ReadUnalignedLE16(d);
432
433 // Load instance methods
434 for (unsigned I = 0; I != NumInstanceMethods; ++I) {
435 if (ObjCMethodDecl *Method
436 = Reader.GetLocalDeclAs<ObjCMethodDecl>(F, ReadUnalignedLE32(d)))
437 Result.Instance.push_back(Method);
438 }
439
440 // Load factory methods
441 for (unsigned I = 0; I != NumFactoryMethods; ++I) {
442 if (ObjCMethodDecl *Method
443 = Reader.GetLocalDeclAs<ObjCMethodDecl>(F, ReadUnalignedLE32(d)))
444 Result.Factory.push_back(Method);
445 }
446
447 return Result;
448}
449
Douglas Gregor479633c2013-01-23 18:53:14 +0000450unsigned ASTIdentifierLookupTraitBase::ComputeHash(const internal_key_type& a) {
451 return llvm::HashString(a);
Guy Benyei7f92f2d2012-12-18 14:30:41 +0000452}
453
454std::pair<unsigned, unsigned>
Douglas Gregor479633c2013-01-23 18:53:14 +0000455ASTIdentifierLookupTraitBase::ReadKeyDataLength(const unsigned char*& d) {
Guy Benyei7f92f2d2012-12-18 14:30:41 +0000456 using namespace clang::io;
457 unsigned DataLen = ReadUnalignedLE16(d);
458 unsigned KeyLen = ReadUnalignedLE16(d);
459 return std::make_pair(KeyLen, DataLen);
460}
461
Douglas Gregor479633c2013-01-23 18:53:14 +0000462ASTIdentifierLookupTraitBase::internal_key_type
463ASTIdentifierLookupTraitBase::ReadKey(const unsigned char* d, unsigned n) {
Guy Benyei7f92f2d2012-12-18 14:30:41 +0000464 assert(n >= 2 && d[n-1] == '\0');
Douglas Gregor479633c2013-01-23 18:53:14 +0000465 return StringRef((const char*) d, n-1);
Guy Benyei7f92f2d2012-12-18 14:30:41 +0000466}
467
Douglas Gregorf4e955b2013-02-11 18:16:18 +0000468/// \brief Whether the given identifier is "interesting".
469static bool isInterestingIdentifier(IdentifierInfo &II) {
470 return II.isPoisoned() ||
471 II.isExtensionToken() ||
472 II.getObjCOrBuiltinID() ||
473 II.hasRevertedTokenIDToIdentifier() ||
474 II.hadMacroDefinition() ||
475 II.getFETokenInfo<void>();
476}
477
Guy Benyei7f92f2d2012-12-18 14:30:41 +0000478IdentifierInfo *ASTIdentifierLookupTrait::ReadData(const internal_key_type& k,
479 const unsigned char* d,
480 unsigned DataLen) {
481 using namespace clang::io;
482 unsigned RawID = ReadUnalignedLE32(d);
483 bool IsInteresting = RawID & 0x01;
484
485 // Wipe out the "is interesting" bit.
486 RawID = RawID >> 1;
487
488 IdentID ID = Reader.getGlobalIdentifierID(F, RawID);
489 if (!IsInteresting) {
490 // For uninteresting identifiers, just build the IdentifierInfo
491 // and associate it with the persistent ID.
492 IdentifierInfo *II = KnownII;
493 if (!II) {
Douglas Gregor479633c2013-01-23 18:53:14 +0000494 II = &Reader.getIdentifierTable().getOwn(k);
Guy Benyei7f92f2d2012-12-18 14:30:41 +0000495 KnownII = II;
496 }
497 Reader.SetIdentifierInfo(ID, II);
Douglas Gregorf4e955b2013-02-11 18:16:18 +0000498 if (!II->isFromAST()) {
499 bool WasInteresting = isInterestingIdentifier(*II);
500 II->setIsFromAST();
501 if (WasInteresting)
502 II->setChangedSinceDeserialization();
503 }
504 Reader.markIdentifierUpToDate(II);
Guy Benyei7f92f2d2012-12-18 14:30:41 +0000505 return II;
506 }
507
508 unsigned ObjCOrBuiltinID = ReadUnalignedLE16(d);
509 unsigned Bits = ReadUnalignedLE16(d);
510 bool CPlusPlusOperatorKeyword = Bits & 0x01;
511 Bits >>= 1;
512 bool HasRevertedTokenIDToIdentifier = Bits & 0x01;
513 Bits >>= 1;
514 bool Poisoned = Bits & 0x01;
515 Bits >>= 1;
516 bool ExtensionToken = Bits & 0x01;
517 Bits >>= 1;
518 bool hadMacroDefinition = Bits & 0x01;
519 Bits >>= 1;
520
521 assert(Bits == 0 && "Extra bits in the identifier?");
522 DataLen -= 8;
523
524 // Build the IdentifierInfo itself and link the identifier ID with
525 // the new IdentifierInfo.
526 IdentifierInfo *II = KnownII;
527 if (!II) {
Douglas Gregor479633c2013-01-23 18:53:14 +0000528 II = &Reader.getIdentifierTable().getOwn(StringRef(k));
Guy Benyei7f92f2d2012-12-18 14:30:41 +0000529 KnownII = II;
530 }
531 Reader.markIdentifierUpToDate(II);
Douglas Gregorf4e955b2013-02-11 18:16:18 +0000532 if (!II->isFromAST()) {
533 bool WasInteresting = isInterestingIdentifier(*II);
534 II->setIsFromAST();
535 if (WasInteresting)
536 II->setChangedSinceDeserialization();
537 }
Guy Benyei7f92f2d2012-12-18 14:30:41 +0000538
539 // Set or check the various bits in the IdentifierInfo structure.
540 // Token IDs are read-only.
Argyrios Kyrtzidis1ebefc72013-02-27 01:13:51 +0000541 if (HasRevertedTokenIDToIdentifier && II->getTokenID() != tok::identifier)
Guy Benyei7f92f2d2012-12-18 14:30:41 +0000542 II->RevertTokenIDToIdentifier();
543 II->setObjCOrBuiltinID(ObjCOrBuiltinID);
544 assert(II->isExtensionToken() == ExtensionToken &&
545 "Incorrect extension token flag");
546 (void)ExtensionToken;
547 if (Poisoned)
548 II->setIsPoisoned(true);
549 assert(II->isCPlusPlusOperatorKeyword() == CPlusPlusOperatorKeyword &&
550 "Incorrect C++ operator keyword flag");
551 (void)CPlusPlusOperatorKeyword;
552
553 // If this identifier is a macro, deserialize the macro
554 // definition.
555 if (hadMacroDefinition) {
Argyrios Kyrtzidisdc1088f2013-01-19 03:14:56 +0000556 SmallVector<MacroID, 4> MacroIDs;
557 while (uint32_t LocalID = ReadUnalignedLE32(d)) {
558 MacroIDs.push_back(Reader.getGlobalMacroID(F, LocalID));
559 DataLen -= 4;
560 }
Guy Benyei7f92f2d2012-12-18 14:30:41 +0000561 DataLen -= 4;
Argyrios Kyrtzidisdc1088f2013-01-19 03:14:56 +0000562 Reader.setIdentifierIsMacro(II, MacroIDs);
Guy Benyei7f92f2d2012-12-18 14:30:41 +0000563 }
564
565 Reader.SetIdentifierInfo(ID, II);
566
567 // Read all of the declarations visible at global scope with this
568 // name.
569 if (DataLen > 0) {
570 SmallVector<uint32_t, 4> DeclIDs;
571 for (; DataLen > 0; DataLen -= 4)
572 DeclIDs.push_back(Reader.getGlobalDeclID(F, ReadUnalignedLE32(d)));
573 Reader.SetGloballyVisibleDecls(II, DeclIDs);
574 }
575
576 return II;
577}
578
579unsigned
580ASTDeclContextNameLookupTrait::ComputeHash(const DeclNameKey &Key) const {
581 llvm::FoldingSetNodeID ID;
582 ID.AddInteger(Key.Kind);
583
584 switch (Key.Kind) {
585 case DeclarationName::Identifier:
586 case DeclarationName::CXXLiteralOperatorName:
587 ID.AddString(((IdentifierInfo*)Key.Data)->getName());
588 break;
589 case DeclarationName::ObjCZeroArgSelector:
590 case DeclarationName::ObjCOneArgSelector:
591 case DeclarationName::ObjCMultiArgSelector:
592 ID.AddInteger(serialization::ComputeHash(Selector(Key.Data)));
593 break;
594 case DeclarationName::CXXOperatorName:
595 ID.AddInteger((OverloadedOperatorKind)Key.Data);
596 break;
597 case DeclarationName::CXXConstructorName:
598 case DeclarationName::CXXDestructorName:
599 case DeclarationName::CXXConversionFunctionName:
600 case DeclarationName::CXXUsingDirective:
601 break;
602 }
603
604 return ID.ComputeHash();
605}
606
607ASTDeclContextNameLookupTrait::internal_key_type
608ASTDeclContextNameLookupTrait::GetInternalKey(
609 const external_key_type& Name) const {
610 DeclNameKey Key;
611 Key.Kind = Name.getNameKind();
612 switch (Name.getNameKind()) {
613 case DeclarationName::Identifier:
614 Key.Data = (uint64_t)Name.getAsIdentifierInfo();
615 break;
616 case DeclarationName::ObjCZeroArgSelector:
617 case DeclarationName::ObjCOneArgSelector:
618 case DeclarationName::ObjCMultiArgSelector:
619 Key.Data = (uint64_t)Name.getObjCSelector().getAsOpaquePtr();
620 break;
621 case DeclarationName::CXXOperatorName:
622 Key.Data = Name.getCXXOverloadedOperator();
623 break;
624 case DeclarationName::CXXLiteralOperatorName:
625 Key.Data = (uint64_t)Name.getCXXLiteralIdentifier();
626 break;
627 case DeclarationName::CXXConstructorName:
628 case DeclarationName::CXXDestructorName:
629 case DeclarationName::CXXConversionFunctionName:
630 case DeclarationName::CXXUsingDirective:
631 Key.Data = 0;
632 break;
633 }
634
635 return Key;
636}
637
638std::pair<unsigned, unsigned>
639ASTDeclContextNameLookupTrait::ReadKeyDataLength(const unsigned char*& d) {
640 using namespace clang::io;
641 unsigned KeyLen = ReadUnalignedLE16(d);
642 unsigned DataLen = ReadUnalignedLE16(d);
643 return std::make_pair(KeyLen, DataLen);
644}
645
646ASTDeclContextNameLookupTrait::internal_key_type
647ASTDeclContextNameLookupTrait::ReadKey(const unsigned char* d, unsigned) {
648 using namespace clang::io;
649
650 DeclNameKey Key;
651 Key.Kind = (DeclarationName::NameKind)*d++;
652 switch (Key.Kind) {
653 case DeclarationName::Identifier:
654 Key.Data = (uint64_t)Reader.getLocalIdentifier(F, ReadUnalignedLE32(d));
655 break;
656 case DeclarationName::ObjCZeroArgSelector:
657 case DeclarationName::ObjCOneArgSelector:
658 case DeclarationName::ObjCMultiArgSelector:
659 Key.Data =
660 (uint64_t)Reader.getLocalSelector(F, ReadUnalignedLE32(d))
661 .getAsOpaquePtr();
662 break;
663 case DeclarationName::CXXOperatorName:
664 Key.Data = *d++; // OverloadedOperatorKind
665 break;
666 case DeclarationName::CXXLiteralOperatorName:
667 Key.Data = (uint64_t)Reader.getLocalIdentifier(F, ReadUnalignedLE32(d));
668 break;
669 case DeclarationName::CXXConstructorName:
670 case DeclarationName::CXXDestructorName:
671 case DeclarationName::CXXConversionFunctionName:
672 case DeclarationName::CXXUsingDirective:
673 Key.Data = 0;
674 break;
675 }
676
677 return Key;
678}
679
680ASTDeclContextNameLookupTrait::data_type
681ASTDeclContextNameLookupTrait::ReadData(internal_key_type,
682 const unsigned char* d,
683 unsigned DataLen) {
684 using namespace clang::io;
685 unsigned NumDecls = ReadUnalignedLE16(d);
Argyrios Kyrtzidise8b61cf2013-01-11 22:29:49 +0000686 LE32DeclID *Start = reinterpret_cast<LE32DeclID *>(
687 const_cast<unsigned char *>(d));
Guy Benyei7f92f2d2012-12-18 14:30:41 +0000688 return std::make_pair(Start, Start + NumDecls);
689}
690
691bool ASTReader::ReadDeclContextStorage(ModuleFile &M,
Chris Lattner8f9a1eb2013-01-20 00:56:42 +0000692 BitstreamCursor &Cursor,
Guy Benyei7f92f2d2012-12-18 14:30:41 +0000693 const std::pair<uint64_t, uint64_t> &Offsets,
694 DeclContextInfo &Info) {
695 SavedStreamPosition SavedPosition(Cursor);
696 // First the lexical decls.
697 if (Offsets.first != 0) {
698 Cursor.JumpToBit(Offsets.first);
699
700 RecordData Record;
Chris Lattnerb3ce3572013-01-20 02:38:54 +0000701 StringRef Blob;
Guy Benyei7f92f2d2012-12-18 14:30:41 +0000702 unsigned Code = Cursor.ReadCode();
Chris Lattnerb3ce3572013-01-20 02:38:54 +0000703 unsigned RecCode = Cursor.readRecord(Code, Record, &Blob);
Guy Benyei7f92f2d2012-12-18 14:30:41 +0000704 if (RecCode != DECL_CONTEXT_LEXICAL) {
705 Error("Expected lexical block");
706 return true;
707 }
708
Chris Lattnerb3ce3572013-01-20 02:38:54 +0000709 Info.LexicalDecls = reinterpret_cast<const KindDeclIDPair*>(Blob.data());
710 Info.NumLexicalDecls = Blob.size() / sizeof(KindDeclIDPair);
Guy Benyei7f92f2d2012-12-18 14:30:41 +0000711 }
712
713 // Now the lookup table.
714 if (Offsets.second != 0) {
715 Cursor.JumpToBit(Offsets.second);
716
717 RecordData Record;
Chris Lattnerb3ce3572013-01-20 02:38:54 +0000718 StringRef Blob;
Guy Benyei7f92f2d2012-12-18 14:30:41 +0000719 unsigned Code = Cursor.ReadCode();
Chris Lattnerb3ce3572013-01-20 02:38:54 +0000720 unsigned RecCode = Cursor.readRecord(Code, Record, &Blob);
Guy Benyei7f92f2d2012-12-18 14:30:41 +0000721 if (RecCode != DECL_CONTEXT_VISIBLE) {
722 Error("Expected visible lookup table block");
723 return true;
724 }
725 Info.NameLookupTableData
726 = ASTDeclContextNameLookupTable::Create(
Chris Lattnerb3ce3572013-01-20 02:38:54 +0000727 (const unsigned char *)Blob.data() + Record[0],
728 (const unsigned char *)Blob.data(),
Guy Benyei7f92f2d2012-12-18 14:30:41 +0000729 ASTDeclContextNameLookupTrait(*this, M));
730 }
731
732 return false;
733}
734
735void ASTReader::Error(StringRef Msg) {
736 Error(diag::err_fe_pch_malformed, Msg);
737}
738
739void ASTReader::Error(unsigned DiagID,
740 StringRef Arg1, StringRef Arg2) {
741 if (Diags.isDiagnosticInFlight())
742 Diags.SetDelayedDiagnostic(DiagID, Arg1, Arg2);
743 else
744 Diag(DiagID) << Arg1 << Arg2;
745}
746
747//===----------------------------------------------------------------------===//
748// Source Manager Deserialization
749//===----------------------------------------------------------------------===//
750
751/// \brief Read the line table in the source manager block.
752/// \returns true if there was an error.
753bool ASTReader::ParseLineTable(ModuleFile &F,
754 SmallVectorImpl<uint64_t> &Record) {
755 unsigned Idx = 0;
756 LineTableInfo &LineTable = SourceMgr.getLineTable();
757
758 // Parse the file names
759 std::map<int, int> FileIDs;
760 for (int I = 0, N = Record[Idx++]; I != N; ++I) {
761 // Extract the file name
762 unsigned FilenameLen = Record[Idx++];
763 std::string Filename(&Record[Idx], &Record[Idx] + FilenameLen);
764 Idx += FilenameLen;
765 MaybeAddSystemRootToFilename(F, Filename);
766 FileIDs[I] = LineTable.getLineTableFilenameID(Filename);
767 }
768
769 // Parse the line entries
770 std::vector<LineEntry> Entries;
771 while (Idx < Record.size()) {
772 int FID = Record[Idx++];
773 assert(FID >= 0 && "Serialized line entries for non-local file.");
774 // Remap FileID from 1-based old view.
775 FID += F.SLocEntryBaseID - 1;
776
777 // Extract the line entries
778 unsigned NumEntries = Record[Idx++];
779 assert(NumEntries && "Numentries is 00000");
780 Entries.clear();
781 Entries.reserve(NumEntries);
782 for (unsigned I = 0; I != NumEntries; ++I) {
783 unsigned FileOffset = Record[Idx++];
784 unsigned LineNo = Record[Idx++];
785 int FilenameID = FileIDs[Record[Idx++]];
786 SrcMgr::CharacteristicKind FileKind
787 = (SrcMgr::CharacteristicKind)Record[Idx++];
788 unsigned IncludeOffset = Record[Idx++];
789 Entries.push_back(LineEntry::get(FileOffset, LineNo, FilenameID,
790 FileKind, IncludeOffset));
791 }
792 LineTable.AddEntry(FileID::get(FID), Entries);
793 }
794
795 return false;
796}
797
798/// \brief Read a source manager block
799bool ASTReader::ReadSourceManagerBlock(ModuleFile &F) {
800 using namespace SrcMgr;
801
Chris Lattner8f9a1eb2013-01-20 00:56:42 +0000802 BitstreamCursor &SLocEntryCursor = F.SLocEntryCursor;
Guy Benyei7f92f2d2012-12-18 14:30:41 +0000803
804 // Set the source-location entry cursor to the current position in
805 // the stream. This cursor will be used to read the contents of the
806 // source manager block initially, and then lazily read
807 // source-location entries as needed.
808 SLocEntryCursor = F.Stream;
809
810 // The stream itself is going to skip over the source manager block.
811 if (F.Stream.SkipBlock()) {
812 Error("malformed block record in AST file");
813 return true;
814 }
815
816 // Enter the source manager block.
817 if (SLocEntryCursor.EnterSubBlock(SOURCE_MANAGER_BLOCK_ID)) {
818 Error("malformed source manager block record in AST file");
819 return true;
820 }
821
822 RecordData Record;
823 while (true) {
Chris Lattner88bde502013-01-19 21:39:22 +0000824 llvm::BitstreamEntry E = SLocEntryCursor.advanceSkippingSubblocks();
825
826 switch (E.Kind) {
827 case llvm::BitstreamEntry::SubBlock: // Handled for us already.
828 case llvm::BitstreamEntry::Error:
829 Error("malformed block record in AST file");
830 return true;
831 case llvm::BitstreamEntry::EndBlock:
Guy Benyei7f92f2d2012-12-18 14:30:41 +0000832 return false;
Chris Lattner88bde502013-01-19 21:39:22 +0000833 case llvm::BitstreamEntry::Record:
834 // The interesting case.
835 break;
Guy Benyei7f92f2d2012-12-18 14:30:41 +0000836 }
Chris Lattner88bde502013-01-19 21:39:22 +0000837
Guy Benyei7f92f2d2012-12-18 14:30:41 +0000838 // Read a record.
Guy Benyei7f92f2d2012-12-18 14:30:41 +0000839 Record.clear();
Chris Lattner125eb3e2013-01-21 18:28:26 +0000840 StringRef Blob;
841 switch (SLocEntryCursor.readRecord(E.ID, Record, &Blob)) {
Guy Benyei7f92f2d2012-12-18 14:30:41 +0000842 default: // Default behavior: ignore.
843 break;
844
845 case SM_SLOC_FILE_ENTRY:
846 case SM_SLOC_BUFFER_ENTRY:
847 case SM_SLOC_EXPANSION_ENTRY:
848 // Once we hit one of the source location entries, we're done.
849 return false;
850 }
851 }
852}
853
854/// \brief If a header file is not found at the path that we expect it to be
855/// and the PCH file was moved from its original location, try to resolve the
856/// file by assuming that header+PCH were moved together and the header is in
857/// the same place relative to the PCH.
858static std::string
859resolveFileRelativeToOriginalDir(const std::string &Filename,
860 const std::string &OriginalDir,
861 const std::string &CurrDir) {
862 assert(OriginalDir != CurrDir &&
863 "No point trying to resolve the file if the PCH dir didn't change");
864 using namespace llvm::sys;
865 SmallString<128> filePath(Filename);
866 fs::make_absolute(filePath);
867 assert(path::is_absolute(OriginalDir));
868 SmallString<128> currPCHPath(CurrDir);
869
870 path::const_iterator fileDirI = path::begin(path::parent_path(filePath)),
871 fileDirE = path::end(path::parent_path(filePath));
872 path::const_iterator origDirI = path::begin(OriginalDir),
873 origDirE = path::end(OriginalDir);
874 // Skip the common path components from filePath and OriginalDir.
875 while (fileDirI != fileDirE && origDirI != origDirE &&
876 *fileDirI == *origDirI) {
877 ++fileDirI;
878 ++origDirI;
879 }
880 for (; origDirI != origDirE; ++origDirI)
881 path::append(currPCHPath, "..");
882 path::append(currPCHPath, fileDirI, fileDirE);
883 path::append(currPCHPath, path::filename(Filename));
884 return currPCHPath.str();
885}
886
887bool ASTReader::ReadSLocEntry(int ID) {
888 if (ID == 0)
889 return false;
890
891 if (unsigned(-ID) - 2 >= getTotalNumSLocs() || ID > 0) {
892 Error("source location entry ID out-of-range for AST file");
893 return true;
894 }
895
896 ModuleFile *F = GlobalSLocEntryMap.find(-ID)->second;
897 F->SLocEntryCursor.JumpToBit(F->SLocEntryOffsets[ID - F->SLocEntryBaseID]);
Chris Lattner8f9a1eb2013-01-20 00:56:42 +0000898 BitstreamCursor &SLocEntryCursor = F->SLocEntryCursor;
Guy Benyei7f92f2d2012-12-18 14:30:41 +0000899 unsigned BaseOffset = F->SLocEntryBaseOffset;
900
901 ++NumSLocEntriesRead;
Chris Lattner88bde502013-01-19 21:39:22 +0000902 llvm::BitstreamEntry Entry = SLocEntryCursor.advance();
903 if (Entry.Kind != llvm::BitstreamEntry::Record) {
Guy Benyei7f92f2d2012-12-18 14:30:41 +0000904 Error("incorrectly-formatted source location entry in AST file");
905 return true;
906 }
Chris Lattner88bde502013-01-19 21:39:22 +0000907
Guy Benyei7f92f2d2012-12-18 14:30:41 +0000908 RecordData Record;
Chris Lattnerb3ce3572013-01-20 02:38:54 +0000909 StringRef Blob;
910 switch (SLocEntryCursor.readRecord(Entry.ID, Record, &Blob)) {
Guy Benyei7f92f2d2012-12-18 14:30:41 +0000911 default:
912 Error("incorrectly-formatted source location entry in AST file");
913 return true;
914
915 case SM_SLOC_FILE_ENTRY: {
916 // We will detect whether a file changed and return 'Failure' for it, but
917 // we will also try to fail gracefully by setting up the SLocEntry.
918 unsigned InputID = Record[4];
919 InputFile IF = getInputFile(*F, InputID);
Argyrios Kyrtzidis8504b7b2013-03-01 03:26:04 +0000920 const FileEntry *File = IF.getFile();
921 bool OverriddenBuffer = IF.isOverridden();
Guy Benyei7f92f2d2012-12-18 14:30:41 +0000922
Argyrios Kyrtzidis8504b7b2013-03-01 03:26:04 +0000923 // Note that we only check if a File was returned. If it was out-of-date
924 // we have complained but we will continue creating a FileID to recover
925 // gracefully.
926 if (!File)
Guy Benyei7f92f2d2012-12-18 14:30:41 +0000927 return true;
928
929 SourceLocation IncludeLoc = ReadSourceLocation(*F, Record[1]);
930 if (IncludeLoc.isInvalid() && F->Kind != MK_MainFile) {
931 // This is the module's main file.
932 IncludeLoc = getImportLocation(F);
933 }
934 SrcMgr::CharacteristicKind
935 FileCharacter = (SrcMgr::CharacteristicKind)Record[2];
936 FileID FID = SourceMgr.createFileID(File, IncludeLoc, FileCharacter,
937 ID, BaseOffset + Record[0]);
938 SrcMgr::FileInfo &FileInfo =
939 const_cast<SrcMgr::FileInfo&>(SourceMgr.getSLocEntry(FID).getFile());
940 FileInfo.NumCreatedFIDs = Record[5];
941 if (Record[3])
942 FileInfo.setHasLineDirectives();
943
944 const DeclID *FirstDecl = F->FileSortedDecls + Record[6];
945 unsigned NumFileDecls = Record[7];
946 if (NumFileDecls) {
947 assert(F->FileSortedDecls && "FILE_SORTED_DECLS not encountered yet ?");
948 FileDeclIDs[FID] = FileDeclsInfo(F, llvm::makeArrayRef(FirstDecl,
949 NumFileDecls));
950 }
951
952 const SrcMgr::ContentCache *ContentCache
953 = SourceMgr.getOrCreateContentCache(File,
954 /*isSystemFile=*/FileCharacter != SrcMgr::C_User);
955 if (OverriddenBuffer && !ContentCache->BufferOverridden &&
956 ContentCache->ContentsEntry == ContentCache->OrigEntry) {
957 unsigned Code = SLocEntryCursor.ReadCode();
958 Record.clear();
Chris Lattnerb3ce3572013-01-20 02:38:54 +0000959 unsigned RecCode = SLocEntryCursor.readRecord(Code, Record, &Blob);
Guy Benyei7f92f2d2012-12-18 14:30:41 +0000960
961 if (RecCode != SM_SLOC_BUFFER_BLOB) {
962 Error("AST record has invalid code");
963 return true;
964 }
965
966 llvm::MemoryBuffer *Buffer
Chris Lattnerb3ce3572013-01-20 02:38:54 +0000967 = llvm::MemoryBuffer::getMemBuffer(Blob.drop_back(1), File->getName());
Guy Benyei7f92f2d2012-12-18 14:30:41 +0000968 SourceMgr.overrideFileContents(File, Buffer);
969 }
970
971 break;
972 }
973
974 case SM_SLOC_BUFFER_ENTRY: {
Chris Lattnerb3ce3572013-01-20 02:38:54 +0000975 const char *Name = Blob.data();
Guy Benyei7f92f2d2012-12-18 14:30:41 +0000976 unsigned Offset = Record[0];
977 SrcMgr::CharacteristicKind
978 FileCharacter = (SrcMgr::CharacteristicKind)Record[2];
979 SourceLocation IncludeLoc = ReadSourceLocation(*F, Record[1]);
980 if (IncludeLoc.isInvalid() && F->Kind == MK_Module) {
981 IncludeLoc = getImportLocation(F);
982 }
983 unsigned Code = SLocEntryCursor.ReadCode();
984 Record.clear();
985 unsigned RecCode
Chris Lattnerb3ce3572013-01-20 02:38:54 +0000986 = SLocEntryCursor.readRecord(Code, Record, &Blob);
Guy Benyei7f92f2d2012-12-18 14:30:41 +0000987
988 if (RecCode != SM_SLOC_BUFFER_BLOB) {
989 Error("AST record has invalid code");
990 return true;
991 }
992
993 llvm::MemoryBuffer *Buffer
Chris Lattnerb3ce3572013-01-20 02:38:54 +0000994 = llvm::MemoryBuffer::getMemBuffer(Blob.drop_back(1), Name);
Guy Benyei7f92f2d2012-12-18 14:30:41 +0000995 SourceMgr.createFileIDForMemBuffer(Buffer, FileCharacter, ID,
996 BaseOffset + Offset, IncludeLoc);
997 break;
998 }
999
1000 case SM_SLOC_EXPANSION_ENTRY: {
1001 SourceLocation SpellingLoc = ReadSourceLocation(*F, Record[1]);
1002 SourceMgr.createExpansionLoc(SpellingLoc,
1003 ReadSourceLocation(*F, Record[2]),
1004 ReadSourceLocation(*F, Record[3]),
1005 Record[4],
1006 ID,
1007 BaseOffset + Record[0]);
1008 break;
1009 }
1010 }
1011
1012 return false;
1013}
1014
1015std::pair<SourceLocation, StringRef> ASTReader::getModuleImportLoc(int ID) {
1016 if (ID == 0)
1017 return std::make_pair(SourceLocation(), "");
1018
1019 if (unsigned(-ID) - 2 >= getTotalNumSLocs() || ID > 0) {
1020 Error("source location entry ID out-of-range for AST file");
1021 return std::make_pair(SourceLocation(), "");
1022 }
1023
1024 // Find which module file this entry lands in.
1025 ModuleFile *M = GlobalSLocEntryMap.find(-ID)->second;
1026 if (M->Kind != MK_Module)
1027 return std::make_pair(SourceLocation(), "");
1028
1029 // FIXME: Can we map this down to a particular submodule? That would be
1030 // ideal.
1031 return std::make_pair(M->ImportLoc, llvm::sys::path::stem(M->FileName));
1032}
1033
1034/// \brief Find the location where the module F is imported.
1035SourceLocation ASTReader::getImportLocation(ModuleFile *F) {
1036 if (F->ImportLoc.isValid())
1037 return F->ImportLoc;
1038
1039 // Otherwise we have a PCH. It's considered to be "imported" at the first
1040 // location of its includer.
1041 if (F->ImportedBy.empty() || !F->ImportedBy[0]) {
1042 // Main file is the importer. We assume that it is the first entry in the
1043 // entry table. We can't ask the manager, because at the time of PCH loading
1044 // the main file entry doesn't exist yet.
1045 // The very first entry is the invalid instantiation loc, which takes up
1046 // offsets 0 and 1.
1047 return SourceLocation::getFromRawEncoding(2U);
1048 }
1049 //return F->Loaders[0]->FirstLoc;
1050 return F->ImportedBy[0]->FirstLoc;
1051}
1052
1053/// ReadBlockAbbrevs - Enter a subblock of the specified BlockID with the
1054/// specified cursor. Read the abbreviations that are at the top of the block
1055/// and then leave the cursor pointing into the block.
Chris Lattner8f9a1eb2013-01-20 00:56:42 +00001056bool ASTReader::ReadBlockAbbrevs(BitstreamCursor &Cursor, unsigned BlockID) {
Guy Benyei7f92f2d2012-12-18 14:30:41 +00001057 if (Cursor.EnterSubBlock(BlockID)) {
1058 Error("malformed block record in AST file");
1059 return Failure;
1060 }
1061
1062 while (true) {
1063 uint64_t Offset = Cursor.GetCurrentBitNo();
1064 unsigned Code = Cursor.ReadCode();
1065
1066 // We expect all abbrevs to be at the start of the block.
1067 if (Code != llvm::bitc::DEFINE_ABBREV) {
1068 Cursor.JumpToBit(Offset);
1069 return false;
1070 }
1071 Cursor.ReadAbbrevRecord();
1072 }
1073}
1074
Argyrios Kyrtzidisdc1088f2013-01-19 03:14:56 +00001075void ASTReader::ReadMacroRecord(ModuleFile &F, uint64_t Offset,
Argyrios Kyrtzidis9818a1d2013-02-20 00:54:57 +00001076 MacroDirective *Hint) {
Chris Lattner8f9a1eb2013-01-20 00:56:42 +00001077 BitstreamCursor &Stream = F.MacroCursor;
Guy Benyei7f92f2d2012-12-18 14:30:41 +00001078
1079 // Keep track of where we are in the stream, then jump back there
1080 // after reading this macro.
1081 SavedStreamPosition SavedPosition(Stream);
1082
1083 Stream.JumpToBit(Offset);
1084 RecordData Record;
1085 SmallVector<IdentifierInfo*, 16> MacroArgs;
1086 MacroInfo *Macro = 0;
1087
Douglas Gregord3b036e2013-01-18 04:34:14 +00001088 // RAII object to add the loaded macro information once we're done
1089 // adding tokens.
1090 struct AddLoadedMacroInfoRAII {
1091 Preprocessor &PP;
Argyrios Kyrtzidis9818a1d2013-02-20 00:54:57 +00001092 MacroDirective *Hint;
1093 MacroDirective *MD;
Douglas Gregord3b036e2013-01-18 04:34:14 +00001094 IdentifierInfo *II;
1095
Argyrios Kyrtzidis9818a1d2013-02-20 00:54:57 +00001096 AddLoadedMacroInfoRAII(Preprocessor &PP, MacroDirective *Hint)
1097 : PP(PP), Hint(Hint), MD(), II() { }
Douglas Gregord3b036e2013-01-18 04:34:14 +00001098 ~AddLoadedMacroInfoRAII( ) {
Argyrios Kyrtzidis9818a1d2013-02-20 00:54:57 +00001099 if (MD) {
Douglas Gregord3b036e2013-01-18 04:34:14 +00001100 // Finally, install the macro.
Argyrios Kyrtzidis9818a1d2013-02-20 00:54:57 +00001101 PP.addLoadedMacroInfo(II, MD, Hint);
Douglas Gregord3b036e2013-01-18 04:34:14 +00001102 }
1103 }
Argyrios Kyrtzidisdc1088f2013-01-19 03:14:56 +00001104 } AddLoadedMacroInfo(PP, Hint);
Douglas Gregord3b036e2013-01-18 04:34:14 +00001105
Guy Benyei7f92f2d2012-12-18 14:30:41 +00001106 while (true) {
Chris Lattner99a5af02013-01-20 00:00:22 +00001107 // Advance to the next record, but if we get to the end of the block, don't
1108 // pop it (removing all the abbreviations from the cursor) since we want to
1109 // be able to reseek within the block and read entries.
Chris Lattner8f9a1eb2013-01-20 00:56:42 +00001110 unsigned Flags = BitstreamCursor::AF_DontPopBlockAtEnd;
Chris Lattner99a5af02013-01-20 00:00:22 +00001111 llvm::BitstreamEntry Entry = Stream.advanceSkippingSubblocks(Flags);
1112
1113 switch (Entry.Kind) {
1114 case llvm::BitstreamEntry::SubBlock: // Handled for us already.
1115 case llvm::BitstreamEntry::Error:
1116 Error("malformed block record in AST file");
Guy Benyei7f92f2d2012-12-18 14:30:41 +00001117 return;
Chris Lattner99a5af02013-01-20 00:00:22 +00001118 case llvm::BitstreamEntry::EndBlock:
1119 return;
1120 case llvm::BitstreamEntry::Record:
1121 // The interesting case.
1122 break;
Guy Benyei7f92f2d2012-12-18 14:30:41 +00001123 }
1124
1125 // Read a record.
Guy Benyei7f92f2d2012-12-18 14:30:41 +00001126 Record.clear();
1127 PreprocessorRecordTypes RecType =
Chris Lattnerb3ce3572013-01-20 02:38:54 +00001128 (PreprocessorRecordTypes)Stream.readRecord(Entry.ID, Record);
Guy Benyei7f92f2d2012-12-18 14:30:41 +00001129 switch (RecType) {
1130 case PP_MACRO_OBJECT_LIKE:
1131 case PP_MACRO_FUNCTION_LIKE: {
1132 // If we already have a macro, that means that we've hit the end
1133 // of the definition of the macro we were looking for. We're
1134 // done.
1135 if (Macro)
1136 return;
1137
1138 IdentifierInfo *II = getLocalIdentifier(F, Record[0]);
1139 if (II == 0) {
1140 Error("macro must have a name in AST file");
1141 return;
1142 }
1143
1144 unsigned GlobalID = getGlobalMacroID(F, Record[1]);
1145
1146 // If this macro has already been loaded, don't do so again.
1147 if (MacrosLoaded[GlobalID - NUM_PREDEF_MACRO_IDS])
1148 return;
1149
1150 SubmoduleID GlobalSubmoduleID = getGlobalSubmoduleID(F, Record[2]);
1151 unsigned NextIndex = 3;
1152 SourceLocation Loc = ReadSourceLocation(F, Record, NextIndex);
1153 MacroInfo *MI = PP.AllocateMacroInfo(Loc);
Argyrios Kyrtzidis9818a1d2013-02-20 00:54:57 +00001154 // FIXME: Location should be import location in case of module.
1155 MacroDirective *MD = PP.AllocateMacroDirective(MI, Loc,
1156 /*isImported=*/true);
Argyrios Kyrtzidis8169b672013-01-07 19:16:23 +00001157 MI->setDefinitionEndLoc(ReadSourceLocation(F, Record, NextIndex));
Guy Benyei7f92f2d2012-12-18 14:30:41 +00001158
1159 // Record this macro.
Argyrios Kyrtzidis9818a1d2013-02-20 00:54:57 +00001160 MacrosLoaded[GlobalID - NUM_PREDEF_MACRO_IDS] = MD;
Guy Benyei7f92f2d2012-12-18 14:30:41 +00001161
1162 SourceLocation UndefLoc = ReadSourceLocation(F, Record, NextIndex);
1163 if (UndefLoc.isValid())
Argyrios Kyrtzidis9818a1d2013-02-20 00:54:57 +00001164 MD->setUndefLoc(UndefLoc);
Guy Benyei7f92f2d2012-12-18 14:30:41 +00001165
1166 MI->setIsUsed(Record[NextIndex++]);
Guy Benyei7f92f2d2012-12-18 14:30:41 +00001167
1168 bool IsPublic = Record[NextIndex++];
Argyrios Kyrtzidis9818a1d2013-02-20 00:54:57 +00001169 MD->setVisibility(IsPublic, ReadSourceLocation(F, Record, NextIndex));
Guy Benyei7f92f2d2012-12-18 14:30:41 +00001170
1171 if (RecType == PP_MACRO_FUNCTION_LIKE) {
1172 // Decode function-like macro info.
1173 bool isC99VarArgs = Record[NextIndex++];
1174 bool isGNUVarArgs = Record[NextIndex++];
1175 bool hasCommaPasting = Record[NextIndex++];
1176 MacroArgs.clear();
1177 unsigned NumArgs = Record[NextIndex++];
1178 for (unsigned i = 0; i != NumArgs; ++i)
1179 MacroArgs.push_back(getLocalIdentifier(F, Record[NextIndex++]));
1180
1181 // Install function-like macro info.
1182 MI->setIsFunctionLike();
1183 if (isC99VarArgs) MI->setIsC99Varargs();
1184 if (isGNUVarArgs) MI->setIsGNUVarargs();
1185 if (hasCommaPasting) MI->setHasCommaPasting();
1186 MI->setArgumentList(MacroArgs.data(), MacroArgs.size(),
1187 PP.getPreprocessorAllocator());
1188 }
1189
1190 if (DeserializationListener)
Argyrios Kyrtzidis9818a1d2013-02-20 00:54:57 +00001191 DeserializationListener->MacroRead(GlobalID, MD);
Guy Benyei7f92f2d2012-12-18 14:30:41 +00001192
1193 // If an update record marked this as undefined, do so now.
1194 // FIXME: Only if the submodule this update came from is visible?
1195 MacroUpdatesMap::iterator Update = MacroUpdates.find(GlobalID);
1196 if (Update != MacroUpdates.end()) {
Argyrios Kyrtzidis9818a1d2013-02-20 00:54:57 +00001197 if (MD->getUndefLoc().isInvalid()) {
Guy Benyei7f92f2d2012-12-18 14:30:41 +00001198 for (unsigned I = 0, N = Update->second.size(); I != N; ++I) {
1199 bool Hidden = false;
1200 if (unsigned SubmoduleID = Update->second[I].first) {
1201 if (Module *Owner = getSubmodule(SubmoduleID)) {
1202 if (Owner->NameVisibility == Module::Hidden) {
1203 // Note that this #undef is hidden.
1204 Hidden = true;
1205
1206 // Record this hiding for later.
1207 HiddenNamesMap[Owner].push_back(
Argyrios Kyrtzidis9818a1d2013-02-20 00:54:57 +00001208 HiddenName(II, MD, Update->second[I].second.UndefLoc));
Guy Benyei7f92f2d2012-12-18 14:30:41 +00001209 }
1210 }
1211 }
1212
1213 if (!Hidden) {
Argyrios Kyrtzidis9818a1d2013-02-20 00:54:57 +00001214 MD->setUndefLoc(Update->second[I].second.UndefLoc);
Guy Benyei7f92f2d2012-12-18 14:30:41 +00001215 if (PPMutationListener *Listener = PP.getPPMutationListener())
Argyrios Kyrtzidis9818a1d2013-02-20 00:54:57 +00001216 Listener->UndefinedMacro(MD);
Guy Benyei7f92f2d2012-12-18 14:30:41 +00001217 break;
1218 }
1219 }
1220 }
1221 MacroUpdates.erase(Update);
1222 }
1223
1224 // Determine whether this macro definition is visible.
Argyrios Kyrtzidis9818a1d2013-02-20 00:54:57 +00001225 bool Hidden = !MD->isPublic();
Guy Benyei7f92f2d2012-12-18 14:30:41 +00001226 if (!Hidden && GlobalSubmoduleID) {
1227 if (Module *Owner = getSubmodule(GlobalSubmoduleID)) {
1228 if (Owner->NameVisibility == Module::Hidden) {
1229 // The owning module is not visible, and this macro definition
1230 // should not be, either.
1231 Hidden = true;
1232
1233 // Note that this macro definition was hidden because its owning
1234 // module is not yet visible.
Argyrios Kyrtzidis9818a1d2013-02-20 00:54:57 +00001235 HiddenNamesMap[Owner].push_back(HiddenName(II, MD));
Guy Benyei7f92f2d2012-12-18 14:30:41 +00001236 }
1237 }
1238 }
Argyrios Kyrtzidis9818a1d2013-02-20 00:54:57 +00001239 MD->setHidden(Hidden);
Guy Benyei7f92f2d2012-12-18 14:30:41 +00001240
Argyrios Kyrtzidisdc1088f2013-01-19 03:14:56 +00001241 // Make sure we install the macro once we're done.
Argyrios Kyrtzidis9818a1d2013-02-20 00:54:57 +00001242 AddLoadedMacroInfo.MD = MD;
Argyrios Kyrtzidisdc1088f2013-01-19 03:14:56 +00001243 AddLoadedMacroInfo.II = II;
Douglas Gregord3b036e2013-01-18 04:34:14 +00001244
Guy Benyei7f92f2d2012-12-18 14:30:41 +00001245 // Remember that we saw this macro last so that we add the tokens that
1246 // form its body to it.
1247 Macro = MI;
1248
1249 if (NextIndex + 1 == Record.size() && PP.getPreprocessingRecord() &&
1250 Record[NextIndex]) {
1251 // We have a macro definition. Register the association
1252 PreprocessedEntityID
1253 GlobalID = getGlobalPreprocessedEntityID(F, Record[NextIndex]);
1254 PreprocessingRecord &PPRec = *PP.getPreprocessingRecord();
Argyrios Kyrtzidis0b849d32013-02-22 18:35:59 +00001255 PreprocessingRecord::PPEntityID
1256 PPID = PPRec.getPPEntityID(GlobalID-1, /*isLoaded=*/true);
1257 MacroDefinition *PPDef =
1258 cast_or_null<MacroDefinition>(PPRec.getPreprocessedEntity(PPID));
1259 if (PPDef)
1260 PPRec.RegisterMacroDefinition(Macro, PPDef);
Guy Benyei7f92f2d2012-12-18 14:30:41 +00001261 }
1262
1263 ++NumMacrosRead;
1264 break;
1265 }
1266
1267 case PP_TOKEN: {
1268 // If we see a TOKEN before a PP_MACRO_*, then the file is
1269 // erroneous, just pretend we didn't see this.
1270 if (Macro == 0) break;
1271
1272 Token Tok;
1273 Tok.startToken();
1274 Tok.setLocation(ReadSourceLocation(F, Record[0]));
1275 Tok.setLength(Record[1]);
1276 if (IdentifierInfo *II = getLocalIdentifier(F, Record[2]))
1277 Tok.setIdentifierInfo(II);
1278 Tok.setKind((tok::TokenKind)Record[3]);
1279 Tok.setFlag((Token::TokenFlags)Record[4]);
1280 Macro->AddTokenToBody(Tok);
1281 break;
1282 }
1283 }
1284 }
1285}
1286
1287PreprocessedEntityID
1288ASTReader::getGlobalPreprocessedEntityID(ModuleFile &M, unsigned LocalID) const {
1289 ContinuousRangeMap<uint32_t, int, 2>::const_iterator
1290 I = M.PreprocessedEntityRemap.find(LocalID - NUM_PREDEF_PP_ENTITY_IDS);
1291 assert(I != M.PreprocessedEntityRemap.end()
1292 && "Invalid index into preprocessed entity index remap");
1293
1294 return LocalID + I->second;
1295}
1296
1297unsigned HeaderFileInfoTrait::ComputeHash(const char *path) {
1298 return llvm::HashString(llvm::sys::path::filename(path));
1299}
1300
1301HeaderFileInfoTrait::internal_key_type
1302HeaderFileInfoTrait::GetInternalKey(const char *path) { return path; }
1303
1304bool HeaderFileInfoTrait::EqualKey(internal_key_type a, internal_key_type b) {
1305 if (strcmp(a, b) == 0)
1306 return true;
1307
1308 if (llvm::sys::path::filename(a) != llvm::sys::path::filename(b))
1309 return false;
1310
1311 // Determine whether the actual files are equivalent.
1312 bool Result = false;
1313 if (llvm::sys::fs::equivalent(a, b, Result))
1314 return false;
1315
1316 return Result;
1317}
1318
1319std::pair<unsigned, unsigned>
1320HeaderFileInfoTrait::ReadKeyDataLength(const unsigned char*& d) {
1321 unsigned KeyLen = (unsigned) clang::io::ReadUnalignedLE16(d);
1322 unsigned DataLen = (unsigned) *d++;
1323 return std::make_pair(KeyLen + 1, DataLen);
1324}
1325
1326HeaderFileInfoTrait::data_type
1327HeaderFileInfoTrait::ReadData(const internal_key_type, const unsigned char *d,
1328 unsigned DataLen) {
1329 const unsigned char *End = d + DataLen;
1330 using namespace clang::io;
1331 HeaderFileInfo HFI;
1332 unsigned Flags = *d++;
1333 HFI.isImport = (Flags >> 5) & 0x01;
1334 HFI.isPragmaOnce = (Flags >> 4) & 0x01;
1335 HFI.DirInfo = (Flags >> 2) & 0x03;
1336 HFI.Resolved = (Flags >> 1) & 0x01;
1337 HFI.IndexHeaderMapHeader = Flags & 0x01;
1338 HFI.NumIncludes = ReadUnalignedLE16(d);
1339 HFI.ControllingMacroID = Reader.getGlobalIdentifierID(M,
1340 ReadUnalignedLE32(d));
1341 if (unsigned FrameworkOffset = ReadUnalignedLE32(d)) {
1342 // The framework offset is 1 greater than the actual offset,
1343 // since 0 is used as an indicator for "no framework name".
1344 StringRef FrameworkName(FrameworkStrings + FrameworkOffset - 1);
1345 HFI.Framework = HS->getUniqueFrameworkName(FrameworkName);
1346 }
1347
1348 assert(End == d && "Wrong data length in HeaderFileInfo deserialization");
1349 (void)End;
1350
1351 // This HeaderFileInfo was externally loaded.
1352 HFI.External = true;
1353 return HFI;
1354}
1355
Argyrios Kyrtzidisdc1088f2013-01-19 03:14:56 +00001356void ASTReader::setIdentifierIsMacro(IdentifierInfo *II, ArrayRef<MacroID> IDs){
Guy Benyei7f92f2d2012-12-18 14:30:41 +00001357 II->setHadMacroDefinition(true);
1358 assert(NumCurrentElementsDeserializing > 0 &&"Missing deserialization guard");
Argyrios Kyrtzidisdc1088f2013-01-19 03:14:56 +00001359 PendingMacroIDs[II].append(IDs.begin(), IDs.end());
Guy Benyei7f92f2d2012-12-18 14:30:41 +00001360}
1361
1362void ASTReader::ReadDefinedMacros() {
1363 // Note that we are loading defined macros.
1364 Deserializing Macros(this);
1365
1366 for (ModuleReverseIterator I = ModuleMgr.rbegin(),
1367 E = ModuleMgr.rend(); I != E; ++I) {
Chris Lattner8f9a1eb2013-01-20 00:56:42 +00001368 BitstreamCursor &MacroCursor = (*I)->MacroCursor;
Guy Benyei7f92f2d2012-12-18 14:30:41 +00001369
1370 // If there was no preprocessor block, skip this file.
1371 if (!MacroCursor.getBitStreamReader())
1372 continue;
1373
Chris Lattner8f9a1eb2013-01-20 00:56:42 +00001374 BitstreamCursor Cursor = MacroCursor;
Guy Benyei7f92f2d2012-12-18 14:30:41 +00001375 Cursor.JumpToBit((*I)->MacroStartOffset);
1376
1377 RecordData Record;
1378 while (true) {
Chris Lattner88bde502013-01-19 21:39:22 +00001379 llvm::BitstreamEntry E = Cursor.advanceSkippingSubblocks();
1380
1381 switch (E.Kind) {
1382 case llvm::BitstreamEntry::SubBlock: // Handled for us already.
1383 case llvm::BitstreamEntry::Error:
1384 Error("malformed block record in AST file");
1385 return;
1386 case llvm::BitstreamEntry::EndBlock:
1387 goto NextCursor;
1388
1389 case llvm::BitstreamEntry::Record:
Chris Lattner88bde502013-01-19 21:39:22 +00001390 Record.clear();
Chris Lattnerb3ce3572013-01-20 02:38:54 +00001391 switch (Cursor.readRecord(E.ID, Record)) {
Chris Lattner88bde502013-01-19 21:39:22 +00001392 default: // Default behavior: ignore.
1393 break;
1394
1395 case PP_MACRO_OBJECT_LIKE:
1396 case PP_MACRO_FUNCTION_LIKE:
1397 getLocalIdentifier(**I, Record[0]);
1398 break;
1399
1400 case PP_TOKEN:
1401 // Ignore tokens.
1402 break;
Guy Benyei7f92f2d2012-12-18 14:30:41 +00001403 }
Guy Benyei7f92f2d2012-12-18 14:30:41 +00001404 break;
1405 }
1406 }
Chris Lattner88bde502013-01-19 21:39:22 +00001407 NextCursor: ;
Guy Benyei7f92f2d2012-12-18 14:30:41 +00001408 }
1409}
1410
1411namespace {
1412 /// \brief Visitor class used to look up identifirs in an AST file.
1413 class IdentifierLookupVisitor {
1414 StringRef Name;
1415 unsigned PriorGeneration;
Douglas Gregore1698072013-01-25 00:38:33 +00001416 unsigned &NumIdentifierLookups;
1417 unsigned &NumIdentifierLookupHits;
Guy Benyei7f92f2d2012-12-18 14:30:41 +00001418 IdentifierInfo *Found;
Douglas Gregore1698072013-01-25 00:38:33 +00001419
Guy Benyei7f92f2d2012-12-18 14:30:41 +00001420 public:
Douglas Gregore1698072013-01-25 00:38:33 +00001421 IdentifierLookupVisitor(StringRef Name, unsigned PriorGeneration,
1422 unsigned &NumIdentifierLookups,
1423 unsigned &NumIdentifierLookupHits)
Douglas Gregor188bdcd2013-01-25 23:32:03 +00001424 : Name(Name), PriorGeneration(PriorGeneration),
Douglas Gregore1698072013-01-25 00:38:33 +00001425 NumIdentifierLookups(NumIdentifierLookups),
1426 NumIdentifierLookupHits(NumIdentifierLookupHits),
1427 Found()
1428 {
1429 }
Guy Benyei7f92f2d2012-12-18 14:30:41 +00001430
1431 static bool visit(ModuleFile &M, void *UserData) {
1432 IdentifierLookupVisitor *This
1433 = static_cast<IdentifierLookupVisitor *>(UserData);
1434
1435 // If we've already searched this module file, skip it now.
1436 if (M.Generation <= This->PriorGeneration)
1437 return true;
Douglas Gregor1a49d972013-01-25 01:03:03 +00001438
Guy Benyei7f92f2d2012-12-18 14:30:41 +00001439 ASTIdentifierLookupTable *IdTable
1440 = (ASTIdentifierLookupTable *)M.IdentifierLookupTable;
1441 if (!IdTable)
1442 return false;
1443
1444 ASTIdentifierLookupTrait Trait(IdTable->getInfoObj().getReader(),
1445 M, This->Found);
Douglas Gregore1698072013-01-25 00:38:33 +00001446 ++This->NumIdentifierLookups;
1447 ASTIdentifierLookupTable::iterator Pos = IdTable->find(This->Name,&Trait);
Guy Benyei7f92f2d2012-12-18 14:30:41 +00001448 if (Pos == IdTable->end())
1449 return false;
1450
1451 // Dereferencing the iterator has the effect of building the
1452 // IdentifierInfo node and populating it with the various
1453 // declarations it needs.
Douglas Gregore1698072013-01-25 00:38:33 +00001454 ++This->NumIdentifierLookupHits;
Guy Benyei7f92f2d2012-12-18 14:30:41 +00001455 This->Found = *Pos;
1456 return true;
1457 }
1458
1459 // \brief Retrieve the identifier info found within the module
1460 // files.
1461 IdentifierInfo *getIdentifierInfo() const { return Found; }
1462 };
1463}
1464
1465void ASTReader::updateOutOfDateIdentifier(IdentifierInfo &II) {
1466 // Note that we are loading an identifier.
1467 Deserializing AnIdentifier(this);
1468
1469 unsigned PriorGeneration = 0;
1470 if (getContext().getLangOpts().Modules)
1471 PriorGeneration = IdentifierGeneration[&II];
Douglas Gregor1a49d972013-01-25 01:03:03 +00001472
1473 // If there is a global index, look there first to determine which modules
1474 // provably do not have any results for this identifier.
Douglas Gregor188bdcd2013-01-25 23:32:03 +00001475 GlobalModuleIndex::HitSet Hits;
1476 GlobalModuleIndex::HitSet *HitsPtr = 0;
Douglas Gregor1a49d972013-01-25 01:03:03 +00001477 if (!loadGlobalIndex()) {
Douglas Gregor188bdcd2013-01-25 23:32:03 +00001478 if (GlobalIndex->lookupIdentifier(II.getName(), Hits)) {
1479 HitsPtr = &Hits;
Douglas Gregor1a49d972013-01-25 01:03:03 +00001480 }
1481 }
1482
Douglas Gregor188bdcd2013-01-25 23:32:03 +00001483 IdentifierLookupVisitor Visitor(II.getName(), PriorGeneration,
Douglas Gregore1698072013-01-25 00:38:33 +00001484 NumIdentifierLookups,
1485 NumIdentifierLookupHits);
Douglas Gregor188bdcd2013-01-25 23:32:03 +00001486 ModuleMgr.visit(IdentifierLookupVisitor::visit, &Visitor, HitsPtr);
Guy Benyei7f92f2d2012-12-18 14:30:41 +00001487 markIdentifierUpToDate(&II);
1488}
1489
1490void ASTReader::markIdentifierUpToDate(IdentifierInfo *II) {
1491 if (!II)
1492 return;
1493
1494 II->setOutOfDate(false);
1495
1496 // Update the generation for this identifier.
1497 if (getContext().getLangOpts().Modules)
1498 IdentifierGeneration[II] = CurrentGeneration;
1499}
1500
Argyrios Kyrtzidis8504b7b2013-03-01 03:26:04 +00001501InputFile ASTReader::getInputFile(ModuleFile &F, unsigned ID, bool Complain) {
Guy Benyei7f92f2d2012-12-18 14:30:41 +00001502 // If this ID is bogus, just return an empty input file.
1503 if (ID == 0 || ID > F.InputFilesLoaded.size())
1504 return InputFile();
1505
1506 // If we've already loaded this input file, return it.
Argyrios Kyrtzidis8504b7b2013-03-01 03:26:04 +00001507 if (F.InputFilesLoaded[ID-1].getFile())
Guy Benyei7f92f2d2012-12-18 14:30:41 +00001508 return F.InputFilesLoaded[ID-1];
1509
1510 // Go find this input file.
Chris Lattner8f9a1eb2013-01-20 00:56:42 +00001511 BitstreamCursor &Cursor = F.InputFilesCursor;
Guy Benyei7f92f2d2012-12-18 14:30:41 +00001512 SavedStreamPosition SavedPosition(Cursor);
1513 Cursor.JumpToBit(F.InputFileOffsets[ID-1]);
1514
1515 unsigned Code = Cursor.ReadCode();
1516 RecordData Record;
Chris Lattnerb3ce3572013-01-20 02:38:54 +00001517 StringRef Blob;
1518 switch ((InputFileRecordTypes)Cursor.readRecord(Code, Record, &Blob)) {
Guy Benyei7f92f2d2012-12-18 14:30:41 +00001519 case INPUT_FILE: {
1520 unsigned StoredID = Record[0];
1521 assert(ID == StoredID && "Bogus stored ID or offset");
1522 (void)StoredID;
1523 off_t StoredSize = (off_t)Record[1];
1524 time_t StoredTime = (time_t)Record[2];
1525 bool Overridden = (bool)Record[3];
1526
1527 // Get the file entry for this input file.
Chris Lattnerb3ce3572013-01-20 02:38:54 +00001528 StringRef OrigFilename = Blob;
Guy Benyei7f92f2d2012-12-18 14:30:41 +00001529 std::string Filename = OrigFilename;
1530 MaybeAddSystemRootToFilename(F, Filename);
1531 const FileEntry *File
1532 = Overridden? FileMgr.getVirtualFile(Filename, StoredSize, StoredTime)
1533 : FileMgr.getFile(Filename, /*OpenFile=*/false);
1534
1535 // If we didn't find the file, resolve it relative to the
1536 // original directory from which this AST file was created.
1537 if (File == 0 && !F.OriginalDir.empty() && !CurrentDir.empty() &&
1538 F.OriginalDir != CurrentDir) {
1539 std::string Resolved = resolveFileRelativeToOriginalDir(Filename,
1540 F.OriginalDir,
1541 CurrentDir);
1542 if (!Resolved.empty())
1543 File = FileMgr.getFile(Resolved);
1544 }
1545
1546 // For an overridden file, create a virtual file with the stored
1547 // size/timestamp.
1548 if (Overridden && File == 0) {
1549 File = FileMgr.getVirtualFile(Filename, StoredSize, StoredTime);
1550 }
1551
1552 if (File == 0) {
1553 if (Complain) {
1554 std::string ErrorStr = "could not find file '";
1555 ErrorStr += Filename;
1556 ErrorStr += "' referenced by AST file";
1557 Error(ErrorStr.c_str());
1558 }
1559 return InputFile();
1560 }
Argyrios Kyrtzidis8504b7b2013-03-01 03:26:04 +00001561
Guy Benyei7f92f2d2012-12-18 14:30:41 +00001562 // Check if there was a request to override the contents of the file
1563 // that was part of the precompiled header. Overridding such a file
1564 // can lead to problems when lexing using the source locations from the
1565 // PCH.
1566 SourceManager &SM = getSourceManager();
1567 if (!Overridden && SM.isFileOverridden(File)) {
Argyrios Kyrtzidis8504b7b2013-03-01 03:26:04 +00001568 if (Complain)
1569 Error(diag::err_fe_pch_file_overridden, Filename);
Guy Benyei7f92f2d2012-12-18 14:30:41 +00001570 // After emitting the diagnostic, recover by disabling the override so
1571 // that the original file will be used.
1572 SM.disableFileContentsOverride(File);
1573 // The FileEntry is a virtual file entry with the size of the contents
1574 // that would override the original contents. Set it to the original's
1575 // size/time.
1576 FileMgr.modifyFileEntry(const_cast<FileEntry*>(File),
1577 StoredSize, StoredTime);
1578 }
1579
Argyrios Kyrtzidis8504b7b2013-03-01 03:26:04 +00001580 bool IsOutOfDate = false;
Guy Benyei7f92f2d2012-12-18 14:30:41 +00001581
Argyrios Kyrtzidis8504b7b2013-03-01 03:26:04 +00001582 // For an overridden file, there is nothing to validate.
1583 if (!Overridden && (StoredSize != File->getSize()
Guy Benyei7f92f2d2012-12-18 14:30:41 +00001584#if !defined(LLVM_ON_WIN32)
1585 // In our regression testing, the Windows file system seems to
1586 // have inconsistent modification times that sometimes
1587 // erroneously trigger this error-handling path.
1588 || StoredTime != File->getModificationTime()
1589#endif
1590 )) {
1591 if (Complain)
1592 Error(diag::err_fe_pch_file_modified, Filename);
Argyrios Kyrtzidis8504b7b2013-03-01 03:26:04 +00001593 IsOutOfDate = true;
Guy Benyei7f92f2d2012-12-18 14:30:41 +00001594 }
1595
Argyrios Kyrtzidis8504b7b2013-03-01 03:26:04 +00001596 InputFile IF = InputFile(File, Overridden, IsOutOfDate);
1597
1598 // Note that we've loaded this input file.
1599 F.InputFilesLoaded[ID-1] = IF;
1600 return IF;
Guy Benyei7f92f2d2012-12-18 14:30:41 +00001601 }
1602 }
1603
1604 return InputFile();
1605}
1606
1607const FileEntry *ASTReader::getFileEntry(StringRef filenameStrRef) {
1608 ModuleFile &M = ModuleMgr.getPrimaryModule();
1609 std::string Filename = filenameStrRef;
1610 MaybeAddSystemRootToFilename(M, Filename);
1611 const FileEntry *File = FileMgr.getFile(Filename);
1612 if (File == 0 && !M.OriginalDir.empty() && !CurrentDir.empty() &&
1613 M.OriginalDir != CurrentDir) {
1614 std::string resolved = resolveFileRelativeToOriginalDir(Filename,
1615 M.OriginalDir,
1616 CurrentDir);
1617 if (!resolved.empty())
1618 File = FileMgr.getFile(resolved);
1619 }
1620
1621 return File;
1622}
1623
1624/// \brief If we are loading a relocatable PCH file, and the filename is
1625/// not an absolute path, add the system root to the beginning of the file
1626/// name.
1627void ASTReader::MaybeAddSystemRootToFilename(ModuleFile &M,
1628 std::string &Filename) {
1629 // If this is not a relocatable PCH file, there's nothing to do.
1630 if (!M.RelocatablePCH)
1631 return;
1632
1633 if (Filename.empty() || llvm::sys::path::is_absolute(Filename))
1634 return;
1635
1636 if (isysroot.empty()) {
1637 // If no system root was given, default to '/'
1638 Filename.insert(Filename.begin(), '/');
1639 return;
1640 }
1641
1642 unsigned Length = isysroot.size();
1643 if (isysroot[Length - 1] != '/')
1644 Filename.insert(Filename.begin(), '/');
1645
1646 Filename.insert(Filename.begin(), isysroot.begin(), isysroot.end());
1647}
1648
1649ASTReader::ASTReadResult
1650ASTReader::ReadControlBlock(ModuleFile &F,
Dmitri Gribenkocfa88f82013-01-12 19:30:44 +00001651 SmallVectorImpl<ImportedModule> &Loaded,
Guy Benyei7f92f2d2012-12-18 14:30:41 +00001652 unsigned ClientLoadCapabilities) {
Chris Lattner8f9a1eb2013-01-20 00:56:42 +00001653 BitstreamCursor &Stream = F.Stream;
Guy Benyei7f92f2d2012-12-18 14:30:41 +00001654
1655 if (Stream.EnterSubBlock(CONTROL_BLOCK_ID)) {
1656 Error("malformed block record in AST file");
1657 return Failure;
1658 }
1659
1660 // Read all of the records and blocks in the control block.
1661 RecordData Record;
Chris Lattner88bde502013-01-19 21:39:22 +00001662 while (1) {
1663 llvm::BitstreamEntry Entry = Stream.advance();
1664
1665 switch (Entry.Kind) {
1666 case llvm::BitstreamEntry::Error:
1667 Error("malformed block record in AST file");
1668 return Failure;
1669 case llvm::BitstreamEntry::EndBlock:
Guy Benyei7f92f2d2012-12-18 14:30:41 +00001670 // Validate all of the input files.
1671 if (!DisableValidation) {
1672 bool Complain = (ClientLoadCapabilities & ARR_OutOfDate) == 0;
Argyrios Kyrtzidis8504b7b2013-03-01 03:26:04 +00001673 for (unsigned I = 0, N = Record[0]; I < N; ++I) {
1674 InputFile IF = getInputFile(F, I+1, Complain);
1675 if (!IF.getFile() || IF.isOutOfDate())
Guy Benyei7f92f2d2012-12-18 14:30:41 +00001676 return OutOfDate;
Argyrios Kyrtzidis8504b7b2013-03-01 03:26:04 +00001677 }
Guy Benyei7f92f2d2012-12-18 14:30:41 +00001678 }
Guy Benyei7f92f2d2012-12-18 14:30:41 +00001679 return Success;
Chris Lattner88bde502013-01-19 21:39:22 +00001680
1681 case llvm::BitstreamEntry::SubBlock:
1682 switch (Entry.ID) {
Guy Benyei7f92f2d2012-12-18 14:30:41 +00001683 case INPUT_FILES_BLOCK_ID:
1684 F.InputFilesCursor = Stream;
1685 if (Stream.SkipBlock() || // Skip with the main cursor
1686 // Read the abbreviations
1687 ReadBlockAbbrevs(F.InputFilesCursor, INPUT_FILES_BLOCK_ID)) {
1688 Error("malformed block record in AST file");
1689 return Failure;
1690 }
1691 continue;
Chris Lattner88bde502013-01-19 21:39:22 +00001692
Guy Benyei7f92f2d2012-12-18 14:30:41 +00001693 default:
Chris Lattner88bde502013-01-19 21:39:22 +00001694 if (Stream.SkipBlock()) {
1695 Error("malformed block record in AST file");
1696 return Failure;
1697 }
1698 continue;
Guy Benyei7f92f2d2012-12-18 14:30:41 +00001699 }
Chris Lattner88bde502013-01-19 21:39:22 +00001700
1701 case llvm::BitstreamEntry::Record:
1702 // The interesting case.
1703 break;
Guy Benyei7f92f2d2012-12-18 14:30:41 +00001704 }
1705
1706 // Read and process a record.
1707 Record.clear();
Chris Lattnerb3ce3572013-01-20 02:38:54 +00001708 StringRef Blob;
1709 switch ((ControlRecordTypes)Stream.readRecord(Entry.ID, Record, &Blob)) {
Guy Benyei7f92f2d2012-12-18 14:30:41 +00001710 case METADATA: {
1711 if (Record[0] != VERSION_MAJOR && !DisableValidation) {
1712 if ((ClientLoadCapabilities & ARR_VersionMismatch) == 0)
1713 Diag(Record[0] < VERSION_MAJOR? diag::warn_pch_version_too_old
1714 : diag::warn_pch_version_too_new);
1715 return VersionMismatch;
1716 }
1717
1718 bool hasErrors = Record[5];
1719 if (hasErrors && !DisableValidation && !AllowASTWithCompilerErrors) {
1720 Diag(diag::err_pch_with_compiler_errors);
1721 return HadErrors;
1722 }
1723
1724 F.RelocatablePCH = Record[4];
1725
1726 const std::string &CurBranch = getClangFullRepositoryVersion();
Chris Lattnerb3ce3572013-01-20 02:38:54 +00001727 StringRef ASTBranch = Blob;
Guy Benyei7f92f2d2012-12-18 14:30:41 +00001728 if (StringRef(CurBranch) != ASTBranch && !DisableValidation) {
1729 if ((ClientLoadCapabilities & ARR_VersionMismatch) == 0)
1730 Diag(diag::warn_pch_different_branch) << ASTBranch << CurBranch;
1731 return VersionMismatch;
1732 }
1733 break;
1734 }
1735
1736 case IMPORTS: {
1737 // Load each of the imported PCH files.
1738 unsigned Idx = 0, N = Record.size();
1739 while (Idx < N) {
1740 // Read information about the AST file.
1741 ModuleKind ImportedKind = (ModuleKind)Record[Idx++];
1742 // The import location will be the local one for now; we will adjust
1743 // all import locations of module imports after the global source
1744 // location info are setup.
1745 SourceLocation ImportLoc =
1746 SourceLocation::getFromRawEncoding(Record[Idx++]);
1747 unsigned Length = Record[Idx++];
1748 SmallString<128> ImportedFile(Record.begin() + Idx,
1749 Record.begin() + Idx + Length);
1750 Idx += Length;
1751
1752 // Load the AST file.
1753 switch(ReadASTCore(ImportedFile, ImportedKind, ImportLoc, &F, Loaded,
1754 ClientLoadCapabilities)) {
1755 case Failure: return Failure;
1756 // If we have to ignore the dependency, we'll have to ignore this too.
1757 case OutOfDate: return OutOfDate;
1758 case VersionMismatch: return VersionMismatch;
1759 case ConfigurationMismatch: return ConfigurationMismatch;
1760 case HadErrors: return HadErrors;
1761 case Success: break;
1762 }
1763 }
1764 break;
1765 }
1766
1767 case LANGUAGE_OPTIONS: {
1768 bool Complain = (ClientLoadCapabilities & ARR_ConfigurationMismatch) == 0;
1769 if (Listener && &F == *ModuleMgr.begin() &&
1770 ParseLanguageOptions(Record, Complain, *Listener) &&
1771 !DisableValidation)
1772 return ConfigurationMismatch;
1773 break;
1774 }
1775
1776 case TARGET_OPTIONS: {
1777 bool Complain = (ClientLoadCapabilities & ARR_ConfigurationMismatch)==0;
1778 if (Listener && &F == *ModuleMgr.begin() &&
1779 ParseTargetOptions(Record, Complain, *Listener) &&
1780 !DisableValidation)
1781 return ConfigurationMismatch;
1782 break;
1783 }
1784
1785 case DIAGNOSTIC_OPTIONS: {
1786 bool Complain = (ClientLoadCapabilities & ARR_ConfigurationMismatch)==0;
1787 if (Listener && &F == *ModuleMgr.begin() &&
1788 ParseDiagnosticOptions(Record, Complain, *Listener) &&
1789 !DisableValidation)
1790 return ConfigurationMismatch;
1791 break;
1792 }
1793
1794 case FILE_SYSTEM_OPTIONS: {
1795 bool Complain = (ClientLoadCapabilities & ARR_ConfigurationMismatch)==0;
1796 if (Listener && &F == *ModuleMgr.begin() &&
1797 ParseFileSystemOptions(Record, Complain, *Listener) &&
1798 !DisableValidation)
1799 return ConfigurationMismatch;
1800 break;
1801 }
1802
1803 case HEADER_SEARCH_OPTIONS: {
1804 bool Complain = (ClientLoadCapabilities & ARR_ConfigurationMismatch)==0;
1805 if (Listener && &F == *ModuleMgr.begin() &&
1806 ParseHeaderSearchOptions(Record, Complain, *Listener) &&
1807 !DisableValidation)
1808 return ConfigurationMismatch;
1809 break;
1810 }
1811
1812 case PREPROCESSOR_OPTIONS: {
1813 bool Complain = (ClientLoadCapabilities & ARR_ConfigurationMismatch)==0;
1814 if (Listener && &F == *ModuleMgr.begin() &&
1815 ParsePreprocessorOptions(Record, Complain, *Listener,
1816 SuggestedPredefines) &&
1817 !DisableValidation)
1818 return ConfigurationMismatch;
1819 break;
1820 }
1821
1822 case ORIGINAL_FILE:
1823 F.OriginalSourceFileID = FileID::get(Record[0]);
Chris Lattnerb3ce3572013-01-20 02:38:54 +00001824 F.ActualOriginalSourceFileName = Blob;
Guy Benyei7f92f2d2012-12-18 14:30:41 +00001825 F.OriginalSourceFileName = F.ActualOriginalSourceFileName;
1826 MaybeAddSystemRootToFilename(F, F.OriginalSourceFileName);
1827 break;
1828
1829 case ORIGINAL_FILE_ID:
1830 F.OriginalSourceFileID = FileID::get(Record[0]);
1831 break;
1832
1833 case ORIGINAL_PCH_DIR:
Chris Lattnerb3ce3572013-01-20 02:38:54 +00001834 F.OriginalDir = Blob;
Guy Benyei7f92f2d2012-12-18 14:30:41 +00001835 break;
1836
1837 case INPUT_FILE_OFFSETS:
Chris Lattnerb3ce3572013-01-20 02:38:54 +00001838 F.InputFileOffsets = (const uint32_t *)Blob.data();
Guy Benyei7f92f2d2012-12-18 14:30:41 +00001839 F.InputFilesLoaded.resize(Record[0]);
1840 break;
1841 }
1842 }
Guy Benyei7f92f2d2012-12-18 14:30:41 +00001843}
1844
1845bool ASTReader::ReadASTBlock(ModuleFile &F) {
Chris Lattner8f9a1eb2013-01-20 00:56:42 +00001846 BitstreamCursor &Stream = F.Stream;
Guy Benyei7f92f2d2012-12-18 14:30:41 +00001847
1848 if (Stream.EnterSubBlock(AST_BLOCK_ID)) {
1849 Error("malformed block record in AST file");
1850 return true;
1851 }
1852
1853 // Read all of the records and blocks for the AST file.
1854 RecordData Record;
Chris Lattner88bde502013-01-19 21:39:22 +00001855 while (1) {
1856 llvm::BitstreamEntry Entry = Stream.advance();
1857
1858 switch (Entry.Kind) {
1859 case llvm::BitstreamEntry::Error:
1860 Error("error at end of module block in AST file");
1861 return true;
1862 case llvm::BitstreamEntry::EndBlock: {
Guy Benyei7f92f2d2012-12-18 14:30:41 +00001863 DeclContext *DC = Context.getTranslationUnitDecl();
1864 if (!DC->hasExternalVisibleStorage() && DC->hasExternalLexicalStorage())
1865 DC->setMustBuildLookupTable();
Chris Lattner88bde502013-01-19 21:39:22 +00001866
Guy Benyei7f92f2d2012-12-18 14:30:41 +00001867 return false;
1868 }
Chris Lattner88bde502013-01-19 21:39:22 +00001869 case llvm::BitstreamEntry::SubBlock:
1870 switch (Entry.ID) {
Guy Benyei7f92f2d2012-12-18 14:30:41 +00001871 case DECLTYPES_BLOCK_ID:
1872 // We lazily load the decls block, but we want to set up the
1873 // DeclsCursor cursor to point into it. Clone our current bitcode
1874 // cursor to it, enter the block and read the abbrevs in that block.
1875 // With the main cursor, we just skip over it.
1876 F.DeclsCursor = Stream;
1877 if (Stream.SkipBlock() || // Skip with the main cursor.
1878 // Read the abbrevs.
1879 ReadBlockAbbrevs(F.DeclsCursor, DECLTYPES_BLOCK_ID)) {
1880 Error("malformed block record in AST file");
1881 return true;
1882 }
1883 break;
Chris Lattner88bde502013-01-19 21:39:22 +00001884
Guy Benyei7f92f2d2012-12-18 14:30:41 +00001885 case DECL_UPDATES_BLOCK_ID:
1886 if (Stream.SkipBlock()) {
1887 Error("malformed block record in AST file");
1888 return true;
1889 }
1890 break;
Chris Lattner88bde502013-01-19 21:39:22 +00001891
Guy Benyei7f92f2d2012-12-18 14:30:41 +00001892 case PREPROCESSOR_BLOCK_ID:
1893 F.MacroCursor = Stream;
1894 if (!PP.getExternalSource())
1895 PP.setExternalSource(this);
Chris Lattner88bde502013-01-19 21:39:22 +00001896
Guy Benyei7f92f2d2012-12-18 14:30:41 +00001897 if (Stream.SkipBlock() ||
1898 ReadBlockAbbrevs(F.MacroCursor, PREPROCESSOR_BLOCK_ID)) {
1899 Error("malformed block record in AST file");
1900 return true;
1901 }
1902 F.MacroStartOffset = F.MacroCursor.GetCurrentBitNo();
1903 break;
Chris Lattner88bde502013-01-19 21:39:22 +00001904
Guy Benyei7f92f2d2012-12-18 14:30:41 +00001905 case PREPROCESSOR_DETAIL_BLOCK_ID:
1906 F.PreprocessorDetailCursor = Stream;
1907 if (Stream.SkipBlock() ||
Chris Lattner88bde502013-01-19 21:39:22 +00001908 ReadBlockAbbrevs(F.PreprocessorDetailCursor,
Guy Benyei7f92f2d2012-12-18 14:30:41 +00001909 PREPROCESSOR_DETAIL_BLOCK_ID)) {
Chris Lattner88bde502013-01-19 21:39:22 +00001910 Error("malformed preprocessor detail record in AST file");
1911 return true;
1912 }
Guy Benyei7f92f2d2012-12-18 14:30:41 +00001913 F.PreprocessorDetailStartOffset
Chris Lattner88bde502013-01-19 21:39:22 +00001914 = F.PreprocessorDetailCursor.GetCurrentBitNo();
1915
Guy Benyei7f92f2d2012-12-18 14:30:41 +00001916 if (!PP.getPreprocessingRecord())
1917 PP.createPreprocessingRecord();
1918 if (!PP.getPreprocessingRecord()->getExternalSource())
1919 PP.getPreprocessingRecord()->SetExternalSource(*this);
1920 break;
1921
1922 case SOURCE_MANAGER_BLOCK_ID:
1923 if (ReadSourceManagerBlock(F))
1924 return true;
1925 break;
Chris Lattner88bde502013-01-19 21:39:22 +00001926
Guy Benyei7f92f2d2012-12-18 14:30:41 +00001927 case SUBMODULE_BLOCK_ID:
1928 if (ReadSubmoduleBlock(F))
1929 return true;
1930 break;
Chris Lattner88bde502013-01-19 21:39:22 +00001931
Guy Benyei7f92f2d2012-12-18 14:30:41 +00001932 case COMMENTS_BLOCK_ID: {
Chris Lattner8f9a1eb2013-01-20 00:56:42 +00001933 BitstreamCursor C = Stream;
Guy Benyei7f92f2d2012-12-18 14:30:41 +00001934 if (Stream.SkipBlock() ||
1935 ReadBlockAbbrevs(C, COMMENTS_BLOCK_ID)) {
1936 Error("malformed comments block in AST file");
1937 return true;
1938 }
1939 CommentsCursors.push_back(std::make_pair(C, &F));
1940 break;
1941 }
Chris Lattner88bde502013-01-19 21:39:22 +00001942
Guy Benyei7f92f2d2012-12-18 14:30:41 +00001943 default:
Chris Lattner88bde502013-01-19 21:39:22 +00001944 if (Stream.SkipBlock()) {
1945 Error("malformed block record in AST file");
1946 return true;
1947 }
1948 break;
Guy Benyei7f92f2d2012-12-18 14:30:41 +00001949 }
1950 continue;
Chris Lattner88bde502013-01-19 21:39:22 +00001951
1952 case llvm::BitstreamEntry::Record:
1953 // The interesting case.
1954 break;
Guy Benyei7f92f2d2012-12-18 14:30:41 +00001955 }
1956
1957 // Read and process a record.
1958 Record.clear();
Chris Lattnerb3ce3572013-01-20 02:38:54 +00001959 StringRef Blob;
1960 switch ((ASTRecordTypes)Stream.readRecord(Entry.ID, Record, &Blob)) {
Guy Benyei7f92f2d2012-12-18 14:30:41 +00001961 default: // Default behavior: ignore.
1962 break;
1963
1964 case TYPE_OFFSET: {
1965 if (F.LocalNumTypes != 0) {
1966 Error("duplicate TYPE_OFFSET record in AST file");
1967 return true;
1968 }
Chris Lattnerb3ce3572013-01-20 02:38:54 +00001969 F.TypeOffsets = (const uint32_t *)Blob.data();
Guy Benyei7f92f2d2012-12-18 14:30:41 +00001970 F.LocalNumTypes = Record[0];
1971 unsigned LocalBaseTypeIndex = Record[1];
1972 F.BaseTypeIndex = getTotalNumTypes();
1973
1974 if (F.LocalNumTypes > 0) {
1975 // Introduce the global -> local mapping for types within this module.
1976 GlobalTypeMap.insert(std::make_pair(getTotalNumTypes(), &F));
1977
1978 // Introduce the local -> global mapping for types within this module.
1979 F.TypeRemap.insertOrReplace(
1980 std::make_pair(LocalBaseTypeIndex,
1981 F.BaseTypeIndex - LocalBaseTypeIndex));
1982
1983 TypesLoaded.resize(TypesLoaded.size() + F.LocalNumTypes);
1984 }
1985 break;
1986 }
1987
1988 case DECL_OFFSET: {
1989 if (F.LocalNumDecls != 0) {
1990 Error("duplicate DECL_OFFSET record in AST file");
1991 return true;
1992 }
Chris Lattnerb3ce3572013-01-20 02:38:54 +00001993 F.DeclOffsets = (const DeclOffset *)Blob.data();
Guy Benyei7f92f2d2012-12-18 14:30:41 +00001994 F.LocalNumDecls = Record[0];
1995 unsigned LocalBaseDeclID = Record[1];
1996 F.BaseDeclID = getTotalNumDecls();
1997
1998 if (F.LocalNumDecls > 0) {
1999 // Introduce the global -> local mapping for declarations within this
2000 // module.
2001 GlobalDeclMap.insert(
2002 std::make_pair(getTotalNumDecls() + NUM_PREDEF_DECL_IDS, &F));
2003
2004 // Introduce the local -> global mapping for declarations within this
2005 // module.
2006 F.DeclRemap.insertOrReplace(
2007 std::make_pair(LocalBaseDeclID, F.BaseDeclID - LocalBaseDeclID));
2008
2009 // Introduce the global -> local mapping for declarations within this
2010 // module.
2011 F.GlobalToLocalDeclIDs[&F] = LocalBaseDeclID;
2012
2013 DeclsLoaded.resize(DeclsLoaded.size() + F.LocalNumDecls);
2014 }
2015 break;
2016 }
2017
2018 case TU_UPDATE_LEXICAL: {
2019 DeclContext *TU = Context.getTranslationUnitDecl();
2020 DeclContextInfo &Info = F.DeclContextInfos[TU];
Chris Lattnerb3ce3572013-01-20 02:38:54 +00002021 Info.LexicalDecls = reinterpret_cast<const KindDeclIDPair *>(Blob.data());
Guy Benyei7f92f2d2012-12-18 14:30:41 +00002022 Info.NumLexicalDecls
Chris Lattnerb3ce3572013-01-20 02:38:54 +00002023 = static_cast<unsigned int>(Blob.size() / sizeof(KindDeclIDPair));
Guy Benyei7f92f2d2012-12-18 14:30:41 +00002024 TU->setHasExternalLexicalStorage(true);
2025 break;
2026 }
2027
2028 case UPDATE_VISIBLE: {
2029 unsigned Idx = 0;
2030 serialization::DeclID ID = ReadDeclID(F, Record, Idx);
2031 ASTDeclContextNameLookupTable *Table =
2032 ASTDeclContextNameLookupTable::Create(
Chris Lattnerb3ce3572013-01-20 02:38:54 +00002033 (const unsigned char *)Blob.data() + Record[Idx++],
2034 (const unsigned char *)Blob.data(),
Guy Benyei7f92f2d2012-12-18 14:30:41 +00002035 ASTDeclContextNameLookupTrait(*this, F));
2036 if (ID == PREDEF_DECL_TRANSLATION_UNIT_ID) { // Is it the TU?
2037 DeclContext *TU = Context.getTranslationUnitDecl();
2038 F.DeclContextInfos[TU].NameLookupTableData = Table;
2039 TU->setHasExternalVisibleStorage(true);
2040 } else
2041 PendingVisibleUpdates[ID].push_back(std::make_pair(Table, &F));
2042 break;
2043 }
2044
2045 case IDENTIFIER_TABLE:
Chris Lattnerb3ce3572013-01-20 02:38:54 +00002046 F.IdentifierTableData = Blob.data();
Guy Benyei7f92f2d2012-12-18 14:30:41 +00002047 if (Record[0]) {
2048 F.IdentifierLookupTable
2049 = ASTIdentifierLookupTable::Create(
2050 (const unsigned char *)F.IdentifierTableData + Record[0],
2051 (const unsigned char *)F.IdentifierTableData,
2052 ASTIdentifierLookupTrait(*this, F));
2053
2054 PP.getIdentifierTable().setExternalIdentifierLookup(this);
2055 }
2056 break;
2057
2058 case IDENTIFIER_OFFSET: {
2059 if (F.LocalNumIdentifiers != 0) {
2060 Error("duplicate IDENTIFIER_OFFSET record in AST file");
2061 return true;
2062 }
Chris Lattnerb3ce3572013-01-20 02:38:54 +00002063 F.IdentifierOffsets = (const uint32_t *)Blob.data();
Guy Benyei7f92f2d2012-12-18 14:30:41 +00002064 F.LocalNumIdentifiers = Record[0];
2065 unsigned LocalBaseIdentifierID = Record[1];
2066 F.BaseIdentifierID = getTotalNumIdentifiers();
2067
2068 if (F.LocalNumIdentifiers > 0) {
2069 // Introduce the global -> local mapping for identifiers within this
2070 // module.
2071 GlobalIdentifierMap.insert(std::make_pair(getTotalNumIdentifiers() + 1,
2072 &F));
2073
2074 // Introduce the local -> global mapping for identifiers within this
2075 // module.
2076 F.IdentifierRemap.insertOrReplace(
2077 std::make_pair(LocalBaseIdentifierID,
2078 F.BaseIdentifierID - LocalBaseIdentifierID));
2079
2080 IdentifiersLoaded.resize(IdentifiersLoaded.size()
2081 + F.LocalNumIdentifiers);
2082 }
2083 break;
2084 }
2085
2086 case EXTERNAL_DEFINITIONS:
2087 for (unsigned I = 0, N = Record.size(); I != N; ++I)
2088 ExternalDefinitions.push_back(getGlobalDeclID(F, Record[I]));
2089 break;
2090
2091 case SPECIAL_TYPES:
Douglas Gregorf5cfc892013-02-01 23:45:03 +00002092 if (SpecialTypes.empty()) {
2093 for (unsigned I = 0, N = Record.size(); I != N; ++I)
2094 SpecialTypes.push_back(getGlobalTypeID(F, Record[I]));
2095 break;
2096 }
2097
2098 if (SpecialTypes.size() != Record.size()) {
2099 Error("invalid special-types record");
2100 return true;
2101 }
2102
2103 for (unsigned I = 0, N = Record.size(); I != N; ++I) {
2104 serialization::TypeID ID = getGlobalTypeID(F, Record[I]);
2105 if (!SpecialTypes[I])
2106 SpecialTypes[I] = ID;
2107 // FIXME: If ID && SpecialTypes[I] != ID, do we need a separate
2108 // merge step?
2109 }
Guy Benyei7f92f2d2012-12-18 14:30:41 +00002110 break;
2111
2112 case STATISTICS:
2113 TotalNumStatements += Record[0];
2114 TotalNumMacros += Record[1];
2115 TotalLexicalDeclContexts += Record[2];
2116 TotalVisibleDeclContexts += Record[3];
2117 break;
2118
2119 case UNUSED_FILESCOPED_DECLS:
2120 for (unsigned I = 0, N = Record.size(); I != N; ++I)
2121 UnusedFileScopedDecls.push_back(getGlobalDeclID(F, Record[I]));
2122 break;
2123
2124 case DELEGATING_CTORS:
2125 for (unsigned I = 0, N = Record.size(); I != N; ++I)
2126 DelegatingCtorDecls.push_back(getGlobalDeclID(F, Record[I]));
2127 break;
2128
2129 case WEAK_UNDECLARED_IDENTIFIERS:
2130 if (Record.size() % 4 != 0) {
2131 Error("invalid weak identifiers record");
2132 return true;
2133 }
2134
2135 // FIXME: Ignore weak undeclared identifiers from non-original PCH
2136 // files. This isn't the way to do it :)
2137 WeakUndeclaredIdentifiers.clear();
2138
2139 // Translate the weak, undeclared identifiers into global IDs.
2140 for (unsigned I = 0, N = Record.size(); I < N; /* in loop */) {
2141 WeakUndeclaredIdentifiers.push_back(
2142 getGlobalIdentifierID(F, Record[I++]));
2143 WeakUndeclaredIdentifiers.push_back(
2144 getGlobalIdentifierID(F, Record[I++]));
2145 WeakUndeclaredIdentifiers.push_back(
2146 ReadSourceLocation(F, Record, I).getRawEncoding());
2147 WeakUndeclaredIdentifiers.push_back(Record[I++]);
2148 }
2149 break;
2150
Richard Smith5ea6ef42013-01-10 23:43:47 +00002151 case LOCALLY_SCOPED_EXTERN_C_DECLS:
Guy Benyei7f92f2d2012-12-18 14:30:41 +00002152 for (unsigned I = 0, N = Record.size(); I != N; ++I)
Richard Smith5ea6ef42013-01-10 23:43:47 +00002153 LocallyScopedExternCDecls.push_back(getGlobalDeclID(F, Record[I]));
Guy Benyei7f92f2d2012-12-18 14:30:41 +00002154 break;
2155
2156 case SELECTOR_OFFSETS: {
Chris Lattnerb3ce3572013-01-20 02:38:54 +00002157 F.SelectorOffsets = (const uint32_t *)Blob.data();
Guy Benyei7f92f2d2012-12-18 14:30:41 +00002158 F.LocalNumSelectors = Record[0];
2159 unsigned LocalBaseSelectorID = Record[1];
2160 F.BaseSelectorID = getTotalNumSelectors();
2161
2162 if (F.LocalNumSelectors > 0) {
2163 // Introduce the global -> local mapping for selectors within this
2164 // module.
2165 GlobalSelectorMap.insert(std::make_pair(getTotalNumSelectors()+1, &F));
2166
2167 // Introduce the local -> global mapping for selectors within this
2168 // module.
2169 F.SelectorRemap.insertOrReplace(
2170 std::make_pair(LocalBaseSelectorID,
2171 F.BaseSelectorID - LocalBaseSelectorID));
2172
2173 SelectorsLoaded.resize(SelectorsLoaded.size() + F.LocalNumSelectors);
2174 }
2175 break;
2176 }
2177
2178 case METHOD_POOL:
Chris Lattnerb3ce3572013-01-20 02:38:54 +00002179 F.SelectorLookupTableData = (const unsigned char *)Blob.data();
Guy Benyei7f92f2d2012-12-18 14:30:41 +00002180 if (Record[0])
2181 F.SelectorLookupTable
2182 = ASTSelectorLookupTable::Create(
2183 F.SelectorLookupTableData + Record[0],
2184 F.SelectorLookupTableData,
2185 ASTSelectorLookupTrait(*this, F));
2186 TotalNumMethodPoolEntries += Record[1];
2187 break;
2188
2189 case REFERENCED_SELECTOR_POOL:
2190 if (!Record.empty()) {
2191 for (unsigned Idx = 0, N = Record.size() - 1; Idx < N; /* in loop */) {
2192 ReferencedSelectorsData.push_back(getGlobalSelectorID(F,
2193 Record[Idx++]));
2194 ReferencedSelectorsData.push_back(ReadSourceLocation(F, Record, Idx).
2195 getRawEncoding());
2196 }
2197 }
2198 break;
2199
2200 case PP_COUNTER_VALUE:
2201 if (!Record.empty() && Listener)
2202 Listener->ReadCounter(F, Record[0]);
2203 break;
2204
2205 case FILE_SORTED_DECLS:
Chris Lattnerb3ce3572013-01-20 02:38:54 +00002206 F.FileSortedDecls = (const DeclID *)Blob.data();
Guy Benyei7f92f2d2012-12-18 14:30:41 +00002207 F.NumFileSortedDecls = Record[0];
2208 break;
2209
2210 case SOURCE_LOCATION_OFFSETS: {
Chris Lattnerb3ce3572013-01-20 02:38:54 +00002211 F.SLocEntryOffsets = (const uint32_t *)Blob.data();
Guy Benyei7f92f2d2012-12-18 14:30:41 +00002212 F.LocalNumSLocEntries = Record[0];
2213 unsigned SLocSpaceSize = Record[1];
2214 llvm::tie(F.SLocEntryBaseID, F.SLocEntryBaseOffset) =
2215 SourceMgr.AllocateLoadedSLocEntries(F.LocalNumSLocEntries,
2216 SLocSpaceSize);
2217 // Make our entry in the range map. BaseID is negative and growing, so
2218 // we invert it. Because we invert it, though, we need the other end of
2219 // the range.
2220 unsigned RangeStart =
2221 unsigned(-F.SLocEntryBaseID) - F.LocalNumSLocEntries + 1;
2222 GlobalSLocEntryMap.insert(std::make_pair(RangeStart, &F));
2223 F.FirstLoc = SourceLocation::getFromRawEncoding(F.SLocEntryBaseOffset);
2224
2225 // SLocEntryBaseOffset is lower than MaxLoadedOffset and decreasing.
2226 assert((F.SLocEntryBaseOffset & (1U << 31U)) == 0);
2227 GlobalSLocOffsetMap.insert(
2228 std::make_pair(SourceManager::MaxLoadedOffset - F.SLocEntryBaseOffset
2229 - SLocSpaceSize,&F));
2230
2231 // Initialize the remapping table.
2232 // Invalid stays invalid.
2233 F.SLocRemap.insert(std::make_pair(0U, 0));
2234 // This module. Base was 2 when being compiled.
2235 F.SLocRemap.insert(std::make_pair(2U,
2236 static_cast<int>(F.SLocEntryBaseOffset - 2)));
2237
2238 TotalNumSLocEntries += F.LocalNumSLocEntries;
2239 break;
2240 }
2241
2242 case MODULE_OFFSET_MAP: {
2243 // Additional remapping information.
Chris Lattnerb3ce3572013-01-20 02:38:54 +00002244 const unsigned char *Data = (const unsigned char*)Blob.data();
2245 const unsigned char *DataEnd = Data + Blob.size();
Guy Benyei7f92f2d2012-12-18 14:30:41 +00002246
2247 // Continuous range maps we may be updating in our module.
2248 ContinuousRangeMap<uint32_t, int, 2>::Builder SLocRemap(F.SLocRemap);
2249 ContinuousRangeMap<uint32_t, int, 2>::Builder
2250 IdentifierRemap(F.IdentifierRemap);
2251 ContinuousRangeMap<uint32_t, int, 2>::Builder
2252 MacroRemap(F.MacroRemap);
2253 ContinuousRangeMap<uint32_t, int, 2>::Builder
2254 PreprocessedEntityRemap(F.PreprocessedEntityRemap);
2255 ContinuousRangeMap<uint32_t, int, 2>::Builder
2256 SubmoduleRemap(F.SubmoduleRemap);
2257 ContinuousRangeMap<uint32_t, int, 2>::Builder
2258 SelectorRemap(F.SelectorRemap);
2259 ContinuousRangeMap<uint32_t, int, 2>::Builder DeclRemap(F.DeclRemap);
2260 ContinuousRangeMap<uint32_t, int, 2>::Builder TypeRemap(F.TypeRemap);
2261
2262 while(Data < DataEnd) {
2263 uint16_t Len = io::ReadUnalignedLE16(Data);
2264 StringRef Name = StringRef((const char*)Data, Len);
2265 Data += Len;
2266 ModuleFile *OM = ModuleMgr.lookup(Name);
2267 if (!OM) {
2268 Error("SourceLocation remap refers to unknown module");
2269 return true;
2270 }
2271
2272 uint32_t SLocOffset = io::ReadUnalignedLE32(Data);
2273 uint32_t IdentifierIDOffset = io::ReadUnalignedLE32(Data);
2274 uint32_t MacroIDOffset = io::ReadUnalignedLE32(Data);
2275 uint32_t PreprocessedEntityIDOffset = io::ReadUnalignedLE32(Data);
2276 uint32_t SubmoduleIDOffset = io::ReadUnalignedLE32(Data);
2277 uint32_t SelectorIDOffset = io::ReadUnalignedLE32(Data);
2278 uint32_t DeclIDOffset = io::ReadUnalignedLE32(Data);
2279 uint32_t TypeIndexOffset = io::ReadUnalignedLE32(Data);
2280
2281 // Source location offset is mapped to OM->SLocEntryBaseOffset.
2282 SLocRemap.insert(std::make_pair(SLocOffset,
2283 static_cast<int>(OM->SLocEntryBaseOffset - SLocOffset)));
2284 IdentifierRemap.insert(
2285 std::make_pair(IdentifierIDOffset,
2286 OM->BaseIdentifierID - IdentifierIDOffset));
2287 MacroRemap.insert(std::make_pair(MacroIDOffset,
2288 OM->BaseMacroID - MacroIDOffset));
2289 PreprocessedEntityRemap.insert(
2290 std::make_pair(PreprocessedEntityIDOffset,
2291 OM->BasePreprocessedEntityID - PreprocessedEntityIDOffset));
2292 SubmoduleRemap.insert(std::make_pair(SubmoduleIDOffset,
2293 OM->BaseSubmoduleID - SubmoduleIDOffset));
2294 SelectorRemap.insert(std::make_pair(SelectorIDOffset,
2295 OM->BaseSelectorID - SelectorIDOffset));
2296 DeclRemap.insert(std::make_pair(DeclIDOffset,
2297 OM->BaseDeclID - DeclIDOffset));
2298
2299 TypeRemap.insert(std::make_pair(TypeIndexOffset,
2300 OM->BaseTypeIndex - TypeIndexOffset));
2301
2302 // Global -> local mappings.
2303 F.GlobalToLocalDeclIDs[OM] = DeclIDOffset;
2304 }
2305 break;
2306 }
2307
2308 case SOURCE_MANAGER_LINE_TABLE:
2309 if (ParseLineTable(F, Record))
2310 return true;
2311 break;
2312
2313 case SOURCE_LOCATION_PRELOADS: {
2314 // Need to transform from the local view (1-based IDs) to the global view,
2315 // which is based off F.SLocEntryBaseID.
2316 if (!F.PreloadSLocEntries.empty()) {
2317 Error("Multiple SOURCE_LOCATION_PRELOADS records in AST file");
2318 return true;
2319 }
2320
2321 F.PreloadSLocEntries.swap(Record);
2322 break;
2323 }
2324
2325 case EXT_VECTOR_DECLS:
2326 for (unsigned I = 0, N = Record.size(); I != N; ++I)
2327 ExtVectorDecls.push_back(getGlobalDeclID(F, Record[I]));
2328 break;
2329
2330 case VTABLE_USES:
2331 if (Record.size() % 3 != 0) {
2332 Error("Invalid VTABLE_USES record");
2333 return true;
2334 }
2335
2336 // Later tables overwrite earlier ones.
2337 // FIXME: Modules will have some trouble with this. This is clearly not
2338 // the right way to do this.
2339 VTableUses.clear();
2340
2341 for (unsigned Idx = 0, N = Record.size(); Idx != N; /* In loop */) {
2342 VTableUses.push_back(getGlobalDeclID(F, Record[Idx++]));
2343 VTableUses.push_back(
2344 ReadSourceLocation(F, Record, Idx).getRawEncoding());
2345 VTableUses.push_back(Record[Idx++]);
2346 }
2347 break;
2348
2349 case DYNAMIC_CLASSES:
2350 for (unsigned I = 0, N = Record.size(); I != N; ++I)
2351 DynamicClasses.push_back(getGlobalDeclID(F, Record[I]));
2352 break;
2353
2354 case PENDING_IMPLICIT_INSTANTIATIONS:
2355 if (PendingInstantiations.size() % 2 != 0) {
2356 Error("Invalid existing PendingInstantiations");
2357 return true;
2358 }
2359
2360 if (Record.size() % 2 != 0) {
2361 Error("Invalid PENDING_IMPLICIT_INSTANTIATIONS block");
2362 return true;
2363 }
2364
2365 for (unsigned I = 0, N = Record.size(); I != N; /* in loop */) {
2366 PendingInstantiations.push_back(getGlobalDeclID(F, Record[I++]));
2367 PendingInstantiations.push_back(
2368 ReadSourceLocation(F, Record, I).getRawEncoding());
2369 }
2370 break;
2371
2372 case SEMA_DECL_REFS:
2373 // Later tables overwrite earlier ones.
2374 // FIXME: Modules will have some trouble with this.
2375 SemaDeclRefs.clear();
2376 for (unsigned I = 0, N = Record.size(); I != N; ++I)
2377 SemaDeclRefs.push_back(getGlobalDeclID(F, Record[I]));
2378 break;
2379
2380 case PPD_ENTITIES_OFFSETS: {
Chris Lattnerb3ce3572013-01-20 02:38:54 +00002381 F.PreprocessedEntityOffsets = (const PPEntityOffset *)Blob.data();
2382 assert(Blob.size() % sizeof(PPEntityOffset) == 0);
2383 F.NumPreprocessedEntities = Blob.size() / sizeof(PPEntityOffset);
Guy Benyei7f92f2d2012-12-18 14:30:41 +00002384
2385 unsigned LocalBasePreprocessedEntityID = Record[0];
2386
2387 unsigned StartingID;
2388 if (!PP.getPreprocessingRecord())
2389 PP.createPreprocessingRecord();
2390 if (!PP.getPreprocessingRecord()->getExternalSource())
2391 PP.getPreprocessingRecord()->SetExternalSource(*this);
2392 StartingID
2393 = PP.getPreprocessingRecord()
2394 ->allocateLoadedEntities(F.NumPreprocessedEntities);
2395 F.BasePreprocessedEntityID = StartingID;
2396
2397 if (F.NumPreprocessedEntities > 0) {
2398 // Introduce the global -> local mapping for preprocessed entities in
2399 // this module.
2400 GlobalPreprocessedEntityMap.insert(std::make_pair(StartingID, &F));
2401
2402 // Introduce the local -> global mapping for preprocessed entities in
2403 // this module.
2404 F.PreprocessedEntityRemap.insertOrReplace(
2405 std::make_pair(LocalBasePreprocessedEntityID,
2406 F.BasePreprocessedEntityID - LocalBasePreprocessedEntityID));
2407 }
2408
2409 break;
2410 }
2411
2412 case DECL_UPDATE_OFFSETS: {
2413 if (Record.size() % 2 != 0) {
2414 Error("invalid DECL_UPDATE_OFFSETS block in AST file");
2415 return true;
2416 }
2417 for (unsigned I = 0, N = Record.size(); I != N; I += 2)
2418 DeclUpdateOffsets[getGlobalDeclID(F, Record[I])]
2419 .push_back(std::make_pair(&F, Record[I+1]));
2420 break;
2421 }
2422
2423 case DECL_REPLACEMENTS: {
2424 if (Record.size() % 3 != 0) {
2425 Error("invalid DECL_REPLACEMENTS block in AST file");
2426 return true;
2427 }
2428 for (unsigned I = 0, N = Record.size(); I != N; I += 3)
2429 ReplacedDecls[getGlobalDeclID(F, Record[I])]
2430 = ReplacedDeclInfo(&F, Record[I+1], Record[I+2]);
2431 break;
2432 }
2433
2434 case OBJC_CATEGORIES_MAP: {
2435 if (F.LocalNumObjCCategoriesInMap != 0) {
2436 Error("duplicate OBJC_CATEGORIES_MAP record in AST file");
2437 return true;
2438 }
2439
2440 F.LocalNumObjCCategoriesInMap = Record[0];
Chris Lattnerb3ce3572013-01-20 02:38:54 +00002441 F.ObjCCategoriesMap = (const ObjCCategoriesInfo *)Blob.data();
Guy Benyei7f92f2d2012-12-18 14:30:41 +00002442 break;
2443 }
2444
2445 case OBJC_CATEGORIES:
2446 F.ObjCCategories.swap(Record);
2447 break;
2448
2449 case CXX_BASE_SPECIFIER_OFFSETS: {
2450 if (F.LocalNumCXXBaseSpecifiers != 0) {
2451 Error("duplicate CXX_BASE_SPECIFIER_OFFSETS record in AST file");
2452 return true;
2453 }
2454
2455 F.LocalNumCXXBaseSpecifiers = Record[0];
Chris Lattnerb3ce3572013-01-20 02:38:54 +00002456 F.CXXBaseSpecifiersOffsets = (const uint32_t *)Blob.data();
Guy Benyei7f92f2d2012-12-18 14:30:41 +00002457 NumCXXBaseSpecifiersLoaded += F.LocalNumCXXBaseSpecifiers;
2458 break;
2459 }
2460
2461 case DIAG_PRAGMA_MAPPINGS:
2462 if (F.PragmaDiagMappings.empty())
2463 F.PragmaDiagMappings.swap(Record);
2464 else
2465 F.PragmaDiagMappings.insert(F.PragmaDiagMappings.end(),
2466 Record.begin(), Record.end());
2467 break;
2468
2469 case CUDA_SPECIAL_DECL_REFS:
2470 // Later tables overwrite earlier ones.
2471 // FIXME: Modules will have trouble with this.
2472 CUDASpecialDeclRefs.clear();
2473 for (unsigned I = 0, N = Record.size(); I != N; ++I)
2474 CUDASpecialDeclRefs.push_back(getGlobalDeclID(F, Record[I]));
2475 break;
2476
2477 case HEADER_SEARCH_TABLE: {
Chris Lattnerb3ce3572013-01-20 02:38:54 +00002478 F.HeaderFileInfoTableData = Blob.data();
Guy Benyei7f92f2d2012-12-18 14:30:41 +00002479 F.LocalNumHeaderFileInfos = Record[1];
Chris Lattnerb3ce3572013-01-20 02:38:54 +00002480 F.HeaderFileFrameworkStrings = Blob.data() + Record[2];
Guy Benyei7f92f2d2012-12-18 14:30:41 +00002481 if (Record[0]) {
2482 F.HeaderFileInfoTable
2483 = HeaderFileInfoLookupTable::Create(
2484 (const unsigned char *)F.HeaderFileInfoTableData + Record[0],
2485 (const unsigned char *)F.HeaderFileInfoTableData,
2486 HeaderFileInfoTrait(*this, F,
2487 &PP.getHeaderSearchInfo(),
Chris Lattnerb3ce3572013-01-20 02:38:54 +00002488 Blob.data() + Record[2]));
Guy Benyei7f92f2d2012-12-18 14:30:41 +00002489
2490 PP.getHeaderSearchInfo().SetExternalSource(this);
2491 if (!PP.getHeaderSearchInfo().getExternalLookup())
2492 PP.getHeaderSearchInfo().SetExternalLookup(this);
2493 }
2494 break;
2495 }
2496
2497 case FP_PRAGMA_OPTIONS:
2498 // Later tables overwrite earlier ones.
2499 FPPragmaOptions.swap(Record);
2500 break;
2501
2502 case OPENCL_EXTENSIONS:
2503 // Later tables overwrite earlier ones.
2504 OpenCLExtensions.swap(Record);
2505 break;
2506
2507 case TENTATIVE_DEFINITIONS:
2508 for (unsigned I = 0, N = Record.size(); I != N; ++I)
2509 TentativeDefinitions.push_back(getGlobalDeclID(F, Record[I]));
2510 break;
2511
2512 case KNOWN_NAMESPACES:
2513 for (unsigned I = 0, N = Record.size(); I != N; ++I)
2514 KnownNamespaces.push_back(getGlobalDeclID(F, Record[I]));
2515 break;
Nick Lewycky01a41142013-01-26 00:35:08 +00002516
Nick Lewyckycd0655b2013-02-01 08:13:20 +00002517 case UNDEFINED_BUT_USED:
2518 if (UndefinedButUsed.size() % 2 != 0) {
2519 Error("Invalid existing UndefinedButUsed");
Nick Lewycky01a41142013-01-26 00:35:08 +00002520 return true;
2521 }
2522
2523 if (Record.size() % 2 != 0) {
Nick Lewyckycd0655b2013-02-01 08:13:20 +00002524 Error("invalid undefined-but-used record");
Nick Lewycky01a41142013-01-26 00:35:08 +00002525 return true;
2526 }
2527 for (unsigned I = 0, N = Record.size(); I != N; /* in loop */) {
Nick Lewyckycd0655b2013-02-01 08:13:20 +00002528 UndefinedButUsed.push_back(getGlobalDeclID(F, Record[I++]));
2529 UndefinedButUsed.push_back(
Nick Lewycky01a41142013-01-26 00:35:08 +00002530 ReadSourceLocation(F, Record, I).getRawEncoding());
2531 }
2532 break;
2533
Guy Benyei7f92f2d2012-12-18 14:30:41 +00002534 case IMPORTED_MODULES: {
2535 if (F.Kind != MK_Module) {
2536 // If we aren't loading a module (which has its own exports), make
2537 // all of the imported modules visible.
2538 // FIXME: Deal with macros-only imports.
2539 for (unsigned I = 0, N = Record.size(); I != N; ++I) {
2540 if (unsigned GlobalID = getGlobalSubmoduleID(F, Record[I]))
2541 ImportedModules.push_back(GlobalID);
2542 }
2543 }
2544 break;
2545 }
2546
2547 case LOCAL_REDECLARATIONS: {
2548 F.RedeclarationChains.swap(Record);
2549 break;
2550 }
2551
2552 case LOCAL_REDECLARATIONS_MAP: {
2553 if (F.LocalNumRedeclarationsInMap != 0) {
2554 Error("duplicate LOCAL_REDECLARATIONS_MAP record in AST file");
2555 return true;
2556 }
2557
2558 F.LocalNumRedeclarationsInMap = Record[0];
Chris Lattnerb3ce3572013-01-20 02:38:54 +00002559 F.RedeclarationsMap = (const LocalRedeclarationsInfo *)Blob.data();
Guy Benyei7f92f2d2012-12-18 14:30:41 +00002560 break;
2561 }
2562
2563 case MERGED_DECLARATIONS: {
2564 for (unsigned Idx = 0; Idx < Record.size(); /* increment in loop */) {
2565 GlobalDeclID CanonID = getGlobalDeclID(F, Record[Idx++]);
2566 SmallVectorImpl<GlobalDeclID> &Decls = StoredMergedDecls[CanonID];
2567 for (unsigned N = Record[Idx++]; N > 0; --N)
2568 Decls.push_back(getGlobalDeclID(F, Record[Idx++]));
2569 }
2570 break;
2571 }
2572
2573 case MACRO_OFFSET: {
2574 if (F.LocalNumMacros != 0) {
2575 Error("duplicate MACRO_OFFSET record in AST file");
2576 return true;
2577 }
Chris Lattnerb3ce3572013-01-20 02:38:54 +00002578 F.MacroOffsets = (const uint32_t *)Blob.data();
Guy Benyei7f92f2d2012-12-18 14:30:41 +00002579 F.LocalNumMacros = Record[0];
2580 unsigned LocalBaseMacroID = Record[1];
2581 F.BaseMacroID = getTotalNumMacros();
2582
2583 if (F.LocalNumMacros > 0) {
2584 // Introduce the global -> local mapping for macros within this module.
2585 GlobalMacroMap.insert(std::make_pair(getTotalNumMacros() + 1, &F));
2586
2587 // Introduce the local -> global mapping for macros within this module.
2588 F.MacroRemap.insertOrReplace(
2589 std::make_pair(LocalBaseMacroID,
2590 F.BaseMacroID - LocalBaseMacroID));
2591
2592 MacrosLoaded.resize(MacrosLoaded.size() + F.LocalNumMacros);
2593 }
2594 break;
2595 }
2596
2597 case MACRO_UPDATES: {
2598 for (unsigned I = 0, N = Record.size(); I != N; /* in loop */) {
2599 MacroID ID = getGlobalMacroID(F, Record[I++]);
2600 if (I == N)
2601 break;
2602
2603 SourceLocation UndefLoc = ReadSourceLocation(F, Record, I);
2604 SubmoduleID SubmoduleID = getGlobalSubmoduleID(F, Record[I++]);;
2605 MacroUpdate Update;
2606 Update.UndefLoc = UndefLoc;
2607 MacroUpdates[ID].push_back(std::make_pair(SubmoduleID, Update));
2608 }
2609 break;
2610 }
2611 }
2612 }
Guy Benyei7f92f2d2012-12-18 14:30:41 +00002613}
2614
Douglas Gregor2cbd4272013-02-12 23:36:21 +00002615/// \brief Move the given method to the back of the global list of methods.
2616static void moveMethodToBackOfGlobalList(Sema &S, ObjCMethodDecl *Method) {
2617 // Find the entry for this selector in the method pool.
2618 Sema::GlobalMethodPool::iterator Known
2619 = S.MethodPool.find(Method->getSelector());
2620 if (Known == S.MethodPool.end())
2621 return;
2622
2623 // Retrieve the appropriate method list.
2624 ObjCMethodList &Start = Method->isInstanceMethod()? Known->second.first
2625 : Known->second.second;
2626 bool Found = false;
2627 for (ObjCMethodList *List = &Start; List; List = List->Next) {
2628 if (!Found) {
2629 if (List->Method == Method) {
2630 Found = true;
2631 } else {
2632 // Keep searching.
2633 continue;
2634 }
2635 }
2636
2637 if (List->Next)
2638 List->Method = List->Next->Method;
2639 else
2640 List->Method = Method;
2641 }
2642}
2643
Guy Benyei7f92f2d2012-12-18 14:30:41 +00002644void ASTReader::makeNamesVisible(const HiddenNames &Names) {
2645 for (unsigned I = 0, N = Names.size(); I != N; ++I) {
2646 switch (Names[I].getKind()) {
Douglas Gregor2cbd4272013-02-12 23:36:21 +00002647 case HiddenName::Declaration: {
2648 Decl *D = Names[I].getDecl();
2649 bool wasHidden = D->Hidden;
2650 D->Hidden = false;
Guy Benyei7f92f2d2012-12-18 14:30:41 +00002651
Douglas Gregor2cbd4272013-02-12 23:36:21 +00002652 if (wasHidden && SemaObj) {
2653 if (ObjCMethodDecl *Method = dyn_cast<ObjCMethodDecl>(D)) {
2654 moveMethodToBackOfGlobalList(*SemaObj, Method);
2655 }
2656 }
2657 break;
2658 }
Guy Benyei7f92f2d2012-12-18 14:30:41 +00002659 case HiddenName::MacroVisibility: {
Argyrios Kyrtzidis9818a1d2013-02-20 00:54:57 +00002660 std::pair<IdentifierInfo *, MacroDirective *> Macro = Names[I].getMacro();
Guy Benyei7f92f2d2012-12-18 14:30:41 +00002661 Macro.second->setHidden(!Macro.second->isPublic());
2662 if (Macro.second->isDefined()) {
2663 PP.makeLoadedMacroInfoVisible(Macro.first, Macro.second);
2664 }
2665 break;
2666 }
2667
2668 case HiddenName::MacroUndef: {
Argyrios Kyrtzidis9818a1d2013-02-20 00:54:57 +00002669 std::pair<IdentifierInfo *, MacroDirective *> Macro = Names[I].getMacro();
Guy Benyei7f92f2d2012-12-18 14:30:41 +00002670 if (Macro.second->isDefined()) {
2671 Macro.second->setUndefLoc(Names[I].getMacroUndefLoc());
2672 if (PPMutationListener *Listener = PP.getPPMutationListener())
2673 Listener->UndefinedMacro(Macro.second);
2674 PP.makeLoadedMacroInfoVisible(Macro.first, Macro.second);
2675 }
2676 break;
2677 }
2678 }
2679 }
2680}
2681
2682void ASTReader::makeModuleVisible(Module *Mod,
Argyrios Kyrtzidis5ebcb202013-02-01 16:36:12 +00002683 Module::NameVisibilityKind NameVisibility,
2684 SourceLocation ImportLoc) {
Guy Benyei7f92f2d2012-12-18 14:30:41 +00002685 llvm::SmallPtrSet<Module *, 4> Visited;
Dmitri Gribenkocfa88f82013-01-12 19:30:44 +00002686 SmallVector<Module *, 4> Stack;
Guy Benyei7f92f2d2012-12-18 14:30:41 +00002687 Stack.push_back(Mod);
2688 while (!Stack.empty()) {
2689 Mod = Stack.back();
2690 Stack.pop_back();
2691
2692 if (NameVisibility <= Mod->NameVisibility) {
2693 // This module already has this level of visibility (or greater), so
2694 // there is nothing more to do.
2695 continue;
2696 }
2697
2698 if (!Mod->isAvailable()) {
2699 // Modules that aren't available cannot be made visible.
2700 continue;
2701 }
2702
2703 // Update the module's name visibility.
2704 Mod->NameVisibility = NameVisibility;
2705
2706 // If we've already deserialized any names from this module,
2707 // mark them as visible.
2708 HiddenNamesMapType::iterator Hidden = HiddenNamesMap.find(Mod);
2709 if (Hidden != HiddenNamesMap.end()) {
2710 makeNamesVisible(Hidden->second);
2711 HiddenNamesMap.erase(Hidden);
2712 }
2713
2714 // Push any non-explicit submodules onto the stack to be marked as
2715 // visible.
2716 for (Module::submodule_iterator Sub = Mod->submodule_begin(),
2717 SubEnd = Mod->submodule_end();
2718 Sub != SubEnd; ++Sub) {
2719 if (!(*Sub)->IsExplicit && Visited.insert(*Sub))
2720 Stack.push_back(*Sub);
2721 }
2722
2723 // Push any exported modules onto the stack to be marked as visible.
Argyrios Kyrtzidis21a00042013-02-19 19:34:40 +00002724 SmallVector<Module *, 16> Exports;
2725 Mod->getExportedModules(Exports);
2726 for (SmallVectorImpl<Module *>::iterator
2727 I = Exports.begin(), E = Exports.end(); I != E; ++I) {
2728 Module *Exported = *I;
2729 if (Visited.insert(Exported))
2730 Stack.push_back(Exported);
Guy Benyei7f92f2d2012-12-18 14:30:41 +00002731 }
2732 }
2733}
2734
Douglas Gregor1a49d972013-01-25 01:03:03 +00002735bool ASTReader::loadGlobalIndex() {
2736 if (GlobalIndex)
2737 return false;
2738
2739 if (TriedLoadingGlobalIndex || !UseGlobalIndex ||
2740 !Context.getLangOpts().Modules)
2741 return true;
2742
2743 // Try to load the global index.
2744 TriedLoadingGlobalIndex = true;
2745 StringRef ModuleCachePath
2746 = getPreprocessor().getHeaderSearchInfo().getModuleCachePath();
2747 std::pair<GlobalModuleIndex *, GlobalModuleIndex::ErrorCode> Result
2748 = GlobalModuleIndex::readIndex(FileMgr, ModuleCachePath);
2749 if (!Result.first)
2750 return true;
2751
2752 GlobalIndex.reset(Result.first);
Douglas Gregor188bdcd2013-01-25 23:32:03 +00002753 ModuleMgr.setGlobalIndex(GlobalIndex.get());
Douglas Gregor1a49d972013-01-25 01:03:03 +00002754 return false;
2755}
2756
2757bool ASTReader::isGlobalIndexUnavailable() const {
2758 return Context.getLangOpts().Modules && UseGlobalIndex &&
2759 !hasGlobalIndex() && TriedLoadingGlobalIndex;
2760}
2761
Guy Benyei7f92f2d2012-12-18 14:30:41 +00002762ASTReader::ASTReadResult ASTReader::ReadAST(const std::string &FileName,
2763 ModuleKind Type,
2764 SourceLocation ImportLoc,
2765 unsigned ClientLoadCapabilities) {
2766 // Bump the generation number.
2767 unsigned PreviousGeneration = CurrentGeneration++;
2768
2769 unsigned NumModules = ModuleMgr.size();
Dmitri Gribenkocfa88f82013-01-12 19:30:44 +00002770 SmallVector<ImportedModule, 4> Loaded;
Guy Benyei7f92f2d2012-12-18 14:30:41 +00002771 switch(ASTReadResult ReadResult = ReadASTCore(FileName, Type, ImportLoc,
2772 /*ImportedBy=*/0, Loaded,
2773 ClientLoadCapabilities)) {
2774 case Failure:
2775 case OutOfDate:
2776 case VersionMismatch:
2777 case ConfigurationMismatch:
2778 case HadErrors:
2779 ModuleMgr.removeModules(ModuleMgr.begin() + NumModules, ModuleMgr.end());
Douglas Gregor1a49d972013-01-25 01:03:03 +00002780
2781 // If we find that any modules are unusable, the global index is going
2782 // to be out-of-date. Just remove it.
2783 GlobalIndex.reset();
Douglas Gregor188bdcd2013-01-25 23:32:03 +00002784 ModuleMgr.setGlobalIndex(0);
Guy Benyei7f92f2d2012-12-18 14:30:41 +00002785 return ReadResult;
2786
2787 case Success:
2788 break;
2789 }
2790
2791 // Here comes stuff that we only do once the entire chain is loaded.
2792
2793 // Load the AST blocks of all of the modules that we loaded.
Dmitri Gribenkocfa88f82013-01-12 19:30:44 +00002794 for (SmallVectorImpl<ImportedModule>::iterator M = Loaded.begin(),
2795 MEnd = Loaded.end();
Guy Benyei7f92f2d2012-12-18 14:30:41 +00002796 M != MEnd; ++M) {
2797 ModuleFile &F = *M->Mod;
2798
2799 // Read the AST block.
2800 if (ReadASTBlock(F))
2801 return Failure;
2802
2803 // Once read, set the ModuleFile bit base offset and update the size in
2804 // bits of all files we've seen.
2805 F.GlobalBitOffset = TotalModulesSizeInBits;
2806 TotalModulesSizeInBits += F.SizeInBits;
2807 GlobalBitOffsetsMap.insert(std::make_pair(F.GlobalBitOffset, &F));
2808
2809 // Preload SLocEntries.
2810 for (unsigned I = 0, N = F.PreloadSLocEntries.size(); I != N; ++I) {
2811 int Index = int(F.PreloadSLocEntries[I] - 1) + F.SLocEntryBaseID;
2812 // Load it through the SourceManager and don't call ReadSLocEntry()
2813 // directly because the entry may have already been loaded in which case
2814 // calling ReadSLocEntry() directly would trigger an assertion in
2815 // SourceManager.
2816 SourceMgr.getLoadedSLocEntryByID(Index);
2817 }
2818 }
2819
2820 // Setup the import locations.
Dmitri Gribenkocfa88f82013-01-12 19:30:44 +00002821 for (SmallVectorImpl<ImportedModule>::iterator M = Loaded.begin(),
2822 MEnd = Loaded.end();
Guy Benyei7f92f2d2012-12-18 14:30:41 +00002823 M != MEnd; ++M) {
2824 ModuleFile &F = *M->Mod;
Argyrios Kyrtzidis8b136d82013-02-01 16:36:14 +00002825 F.DirectImportLoc = ImportLoc;
Guy Benyei7f92f2d2012-12-18 14:30:41 +00002826 if (!M->ImportedBy)
2827 F.ImportLoc = M->ImportLoc;
2828 else
2829 F.ImportLoc = ReadSourceLocation(*M->ImportedBy,
2830 M->ImportLoc.getRawEncoding());
2831 }
2832
2833 // Mark all of the identifiers in the identifier table as being out of date,
2834 // so that various accessors know to check the loaded modules when the
2835 // identifier is used.
2836 for (IdentifierTable::iterator Id = PP.getIdentifierTable().begin(),
2837 IdEnd = PP.getIdentifierTable().end();
2838 Id != IdEnd; ++Id)
2839 Id->second->setOutOfDate(true);
2840
2841 // Resolve any unresolved module exports.
2842 for (unsigned I = 0, N = UnresolvedModuleImportExports.size(); I != N; ++I) {
2843 UnresolvedModuleImportExport &Unresolved = UnresolvedModuleImportExports[I];
2844 SubmoduleID GlobalID = getGlobalSubmoduleID(*Unresolved.File,Unresolved.ID);
2845 Module *ResolvedMod = getSubmodule(GlobalID);
2846
2847 if (Unresolved.IsImport) {
2848 if (ResolvedMod)
2849 Unresolved.Mod->Imports.push_back(ResolvedMod);
2850 continue;
2851 }
2852
2853 if (ResolvedMod || Unresolved.IsWildcard)
2854 Unresolved.Mod->Exports.push_back(
2855 Module::ExportDecl(ResolvedMod, Unresolved.IsWildcard));
2856 }
2857 UnresolvedModuleImportExports.clear();
2858
2859 InitializeContext();
2860
2861 if (DeserializationListener)
2862 DeserializationListener->ReaderInitialized(this);
2863
2864 ModuleFile &PrimaryModule = ModuleMgr.getPrimaryModule();
2865 if (!PrimaryModule.OriginalSourceFileID.isInvalid()) {
2866 PrimaryModule.OriginalSourceFileID
2867 = FileID::get(PrimaryModule.SLocEntryBaseID
2868 + PrimaryModule.OriginalSourceFileID.getOpaqueValue() - 1);
2869
2870 // If this AST file is a precompiled preamble, then set the
2871 // preamble file ID of the source manager to the file source file
2872 // from which the preamble was built.
2873 if (Type == MK_Preamble) {
2874 SourceMgr.setPreambleFileID(PrimaryModule.OriginalSourceFileID);
2875 } else if (Type == MK_MainFile) {
2876 SourceMgr.setMainFileID(PrimaryModule.OriginalSourceFileID);
2877 }
2878 }
2879
2880 // For any Objective-C class definitions we have already loaded, make sure
2881 // that we load any additional categories.
2882 for (unsigned I = 0, N = ObjCClassesLoaded.size(); I != N; ++I) {
2883 loadObjCCategories(ObjCClassesLoaded[I]->getGlobalID(),
2884 ObjCClassesLoaded[I],
2885 PreviousGeneration);
2886 }
Douglas Gregor1a49d972013-01-25 01:03:03 +00002887
Guy Benyei7f92f2d2012-12-18 14:30:41 +00002888 return Success;
2889}
2890
2891ASTReader::ASTReadResult
2892ASTReader::ReadASTCore(StringRef FileName,
2893 ModuleKind Type,
2894 SourceLocation ImportLoc,
2895 ModuleFile *ImportedBy,
Dmitri Gribenkocfa88f82013-01-12 19:30:44 +00002896 SmallVectorImpl<ImportedModule> &Loaded,
Guy Benyei7f92f2d2012-12-18 14:30:41 +00002897 unsigned ClientLoadCapabilities) {
2898 ModuleFile *M;
2899 bool NewModule;
2900 std::string ErrorStr;
2901 llvm::tie(M, NewModule) = ModuleMgr.addModule(FileName, Type, ImportLoc,
2902 ImportedBy, CurrentGeneration,
2903 ErrorStr);
2904
2905 if (!M) {
2906 // We couldn't load the module.
2907 std::string Msg = "Unable to load module \"" + FileName.str() + "\": "
2908 + ErrorStr;
2909 Error(Msg);
2910 return Failure;
2911 }
2912
2913 if (!NewModule) {
2914 // We've already loaded this module.
2915 return Success;
2916 }
2917
2918 // FIXME: This seems rather a hack. Should CurrentDir be part of the
2919 // module?
2920 if (FileName != "-") {
2921 CurrentDir = llvm::sys::path::parent_path(FileName);
2922 if (CurrentDir.empty()) CurrentDir = ".";
2923 }
2924
2925 ModuleFile &F = *M;
Chris Lattner8f9a1eb2013-01-20 00:56:42 +00002926 BitstreamCursor &Stream = F.Stream;
Guy Benyei7f92f2d2012-12-18 14:30:41 +00002927 Stream.init(F.StreamFile);
2928 F.SizeInBits = F.Buffer->getBufferSize() * 8;
2929
2930 // Sniff for the signature.
2931 if (Stream.Read(8) != 'C' ||
2932 Stream.Read(8) != 'P' ||
2933 Stream.Read(8) != 'C' ||
2934 Stream.Read(8) != 'H') {
2935 Diag(diag::err_not_a_pch_file) << FileName;
2936 return Failure;
2937 }
2938
2939 // This is used for compatibility with older PCH formats.
2940 bool HaveReadControlBlock = false;
2941
Chris Lattner99a5af02013-01-20 00:00:22 +00002942 while (1) {
2943 llvm::BitstreamEntry Entry = Stream.advance();
2944
2945 switch (Entry.Kind) {
2946 case llvm::BitstreamEntry::Error:
2947 case llvm::BitstreamEntry::EndBlock:
2948 case llvm::BitstreamEntry::Record:
Guy Benyei7f92f2d2012-12-18 14:30:41 +00002949 Error("invalid record at top-level of AST file");
2950 return Failure;
Chris Lattner99a5af02013-01-20 00:00:22 +00002951
2952 case llvm::BitstreamEntry::SubBlock:
2953 break;
Guy Benyei7f92f2d2012-12-18 14:30:41 +00002954 }
2955
Guy Benyei7f92f2d2012-12-18 14:30:41 +00002956 // We only know the control subblock ID.
Chris Lattner99a5af02013-01-20 00:00:22 +00002957 switch (Entry.ID) {
Guy Benyei7f92f2d2012-12-18 14:30:41 +00002958 case llvm::bitc::BLOCKINFO_BLOCK_ID:
2959 if (Stream.ReadBlockInfoBlock()) {
2960 Error("malformed BlockInfoBlock in AST file");
2961 return Failure;
2962 }
2963 break;
2964 case CONTROL_BLOCK_ID:
2965 HaveReadControlBlock = true;
2966 switch (ReadControlBlock(F, Loaded, ClientLoadCapabilities)) {
2967 case Success:
2968 break;
2969
2970 case Failure: return Failure;
2971 case OutOfDate: return OutOfDate;
2972 case VersionMismatch: return VersionMismatch;
2973 case ConfigurationMismatch: return ConfigurationMismatch;
2974 case HadErrors: return HadErrors;
2975 }
2976 break;
2977 case AST_BLOCK_ID:
2978 if (!HaveReadControlBlock) {
2979 if ((ClientLoadCapabilities & ARR_VersionMismatch) == 0)
2980 Diag(diag::warn_pch_version_too_old);
2981 return VersionMismatch;
2982 }
2983
2984 // Record that we've loaded this module.
2985 Loaded.push_back(ImportedModule(M, ImportedBy, ImportLoc));
2986 return Success;
2987
2988 default:
2989 if (Stream.SkipBlock()) {
2990 Error("malformed block record in AST file");
2991 return Failure;
2992 }
2993 break;
2994 }
2995 }
2996
2997 return Success;
2998}
2999
3000void ASTReader::InitializeContext() {
3001 // If there's a listener, notify them that we "read" the translation unit.
3002 if (DeserializationListener)
3003 DeserializationListener->DeclRead(PREDEF_DECL_TRANSLATION_UNIT_ID,
3004 Context.getTranslationUnitDecl());
3005
3006 // Make sure we load the declaration update records for the translation unit,
3007 // if there are any.
3008 loadDeclUpdateRecords(PREDEF_DECL_TRANSLATION_UNIT_ID,
3009 Context.getTranslationUnitDecl());
3010
3011 // FIXME: Find a better way to deal with collisions between these
3012 // built-in types. Right now, we just ignore the problem.
3013
3014 // Load the special types.
3015 if (SpecialTypes.size() >= NumSpecialTypeIDs) {
3016 if (unsigned String = SpecialTypes[SPECIAL_TYPE_CF_CONSTANT_STRING]) {
3017 if (!Context.CFConstantStringTypeDecl)
3018 Context.setCFConstantStringType(GetType(String));
3019 }
3020
3021 if (unsigned File = SpecialTypes[SPECIAL_TYPE_FILE]) {
3022 QualType FileType = GetType(File);
3023 if (FileType.isNull()) {
3024 Error("FILE type is NULL");
3025 return;
3026 }
3027
3028 if (!Context.FILEDecl) {
3029 if (const TypedefType *Typedef = FileType->getAs<TypedefType>())
3030 Context.setFILEDecl(Typedef->getDecl());
3031 else {
3032 const TagType *Tag = FileType->getAs<TagType>();
3033 if (!Tag) {
3034 Error("Invalid FILE type in AST file");
3035 return;
3036 }
3037 Context.setFILEDecl(Tag->getDecl());
3038 }
3039 }
3040 }
3041
3042 if (unsigned Jmp_buf = SpecialTypes[SPECIAL_TYPE_JMP_BUF]) {
3043 QualType Jmp_bufType = GetType(Jmp_buf);
3044 if (Jmp_bufType.isNull()) {
3045 Error("jmp_buf type is NULL");
3046 return;
3047 }
3048
3049 if (!Context.jmp_bufDecl) {
3050 if (const TypedefType *Typedef = Jmp_bufType->getAs<TypedefType>())
3051 Context.setjmp_bufDecl(Typedef->getDecl());
3052 else {
3053 const TagType *Tag = Jmp_bufType->getAs<TagType>();
3054 if (!Tag) {
3055 Error("Invalid jmp_buf type in AST file");
3056 return;
3057 }
3058 Context.setjmp_bufDecl(Tag->getDecl());
3059 }
3060 }
3061 }
3062
3063 if (unsigned Sigjmp_buf = SpecialTypes[SPECIAL_TYPE_SIGJMP_BUF]) {
3064 QualType Sigjmp_bufType = GetType(Sigjmp_buf);
3065 if (Sigjmp_bufType.isNull()) {
3066 Error("sigjmp_buf type is NULL");
3067 return;
3068 }
3069
3070 if (!Context.sigjmp_bufDecl) {
3071 if (const TypedefType *Typedef = Sigjmp_bufType->getAs<TypedefType>())
3072 Context.setsigjmp_bufDecl(Typedef->getDecl());
3073 else {
3074 const TagType *Tag = Sigjmp_bufType->getAs<TagType>();
3075 assert(Tag && "Invalid sigjmp_buf type in AST file");
3076 Context.setsigjmp_bufDecl(Tag->getDecl());
3077 }
3078 }
3079 }
3080
3081 if (unsigned ObjCIdRedef
3082 = SpecialTypes[SPECIAL_TYPE_OBJC_ID_REDEFINITION]) {
3083 if (Context.ObjCIdRedefinitionType.isNull())
3084 Context.ObjCIdRedefinitionType = GetType(ObjCIdRedef);
3085 }
3086
3087 if (unsigned ObjCClassRedef
3088 = SpecialTypes[SPECIAL_TYPE_OBJC_CLASS_REDEFINITION]) {
3089 if (Context.ObjCClassRedefinitionType.isNull())
3090 Context.ObjCClassRedefinitionType = GetType(ObjCClassRedef);
3091 }
3092
3093 if (unsigned ObjCSelRedef
3094 = SpecialTypes[SPECIAL_TYPE_OBJC_SEL_REDEFINITION]) {
3095 if (Context.ObjCSelRedefinitionType.isNull())
3096 Context.ObjCSelRedefinitionType = GetType(ObjCSelRedef);
3097 }
3098
3099 if (unsigned Ucontext_t = SpecialTypes[SPECIAL_TYPE_UCONTEXT_T]) {
3100 QualType Ucontext_tType = GetType(Ucontext_t);
3101 if (Ucontext_tType.isNull()) {
3102 Error("ucontext_t type is NULL");
3103 return;
3104 }
3105
3106 if (!Context.ucontext_tDecl) {
3107 if (const TypedefType *Typedef = Ucontext_tType->getAs<TypedefType>())
3108 Context.setucontext_tDecl(Typedef->getDecl());
3109 else {
3110 const TagType *Tag = Ucontext_tType->getAs<TagType>();
3111 assert(Tag && "Invalid ucontext_t type in AST file");
3112 Context.setucontext_tDecl(Tag->getDecl());
3113 }
3114 }
3115 }
3116 }
3117
3118 ReadPragmaDiagnosticMappings(Context.getDiagnostics());
3119
3120 // If there were any CUDA special declarations, deserialize them.
3121 if (!CUDASpecialDeclRefs.empty()) {
3122 assert(CUDASpecialDeclRefs.size() == 1 && "More decl refs than expected!");
3123 Context.setcudaConfigureCallDecl(
3124 cast<FunctionDecl>(GetDecl(CUDASpecialDeclRefs[0])));
3125 }
3126
3127 // Re-export any modules that were imported by a non-module AST file.
3128 for (unsigned I = 0, N = ImportedModules.size(); I != N; ++I) {
3129 if (Module *Imported = getSubmodule(ImportedModules[I]))
Argyrios Kyrtzidis5ebcb202013-02-01 16:36:12 +00003130 makeModuleVisible(Imported, Module::AllVisible,
3131 /*ImportLoc=*/SourceLocation());
Guy Benyei7f92f2d2012-12-18 14:30:41 +00003132 }
3133 ImportedModules.clear();
3134}
3135
3136void ASTReader::finalizeForWriting() {
3137 for (HiddenNamesMapType::iterator Hidden = HiddenNamesMap.begin(),
3138 HiddenEnd = HiddenNamesMap.end();
3139 Hidden != HiddenEnd; ++Hidden) {
3140 makeNamesVisible(Hidden->second);
3141 }
3142 HiddenNamesMap.clear();
3143}
3144
Chris Lattner8f9a1eb2013-01-20 00:56:42 +00003145/// SkipCursorToControlBlock - Given a cursor at the start of an AST file, scan
3146/// ahead and drop the cursor into the start of the CONTROL_BLOCK, returning
3147/// false on success and true on failure.
3148static bool SkipCursorToControlBlock(BitstreamCursor &Cursor) {
3149 while (1) {
3150 llvm::BitstreamEntry Entry = Cursor.advance();
3151 switch (Entry.Kind) {
3152 case llvm::BitstreamEntry::Error:
3153 case llvm::BitstreamEntry::EndBlock:
3154 return true;
3155
3156 case llvm::BitstreamEntry::Record:
3157 // Ignore top-level records.
3158 Cursor.skipRecord(Entry.ID);
3159 break;
3160
3161 case llvm::BitstreamEntry::SubBlock:
3162 if (Entry.ID == CONTROL_BLOCK_ID) {
3163 if (Cursor.EnterSubBlock(CONTROL_BLOCK_ID))
3164 return true;
3165 // Found it!
3166 return false;
3167 }
3168
3169 if (Cursor.SkipBlock())
3170 return true;
3171 }
3172 }
3173}
3174
Guy Benyei7f92f2d2012-12-18 14:30:41 +00003175/// \brief Retrieve the name of the original source file name
3176/// directly from the AST file, without actually loading the AST
3177/// file.
3178std::string ASTReader::getOriginalSourceFile(const std::string &ASTFileName,
3179 FileManager &FileMgr,
3180 DiagnosticsEngine &Diags) {
3181 // Open the AST file.
3182 std::string ErrStr;
3183 OwningPtr<llvm::MemoryBuffer> Buffer;
3184 Buffer.reset(FileMgr.getBufferForFile(ASTFileName, &ErrStr));
3185 if (!Buffer) {
3186 Diags.Report(diag::err_fe_unable_to_read_pch_file) << ASTFileName << ErrStr;
3187 return std::string();
3188 }
3189
3190 // Initialize the stream
3191 llvm::BitstreamReader StreamFile;
Chris Lattner8f9a1eb2013-01-20 00:56:42 +00003192 BitstreamCursor Stream;
Guy Benyei7f92f2d2012-12-18 14:30:41 +00003193 StreamFile.init((const unsigned char *)Buffer->getBufferStart(),
3194 (const unsigned char *)Buffer->getBufferEnd());
3195 Stream.init(StreamFile);
3196
3197 // Sniff for the signature.
3198 if (Stream.Read(8) != 'C' ||
3199 Stream.Read(8) != 'P' ||
3200 Stream.Read(8) != 'C' ||
3201 Stream.Read(8) != 'H') {
3202 Diags.Report(diag::err_fe_not_a_pch_file) << ASTFileName;
3203 return std::string();
3204 }
Chris Lattner8f9a1eb2013-01-20 00:56:42 +00003205
Chris Lattner88bde502013-01-19 21:39:22 +00003206 // Scan for the CONTROL_BLOCK_ID block.
Chris Lattner8f9a1eb2013-01-20 00:56:42 +00003207 if (SkipCursorToControlBlock(Stream)) {
3208 Diags.Report(diag::err_fe_pch_malformed_block) << ASTFileName;
3209 return std::string();
Chris Lattner88bde502013-01-19 21:39:22 +00003210 }
Guy Benyei7f92f2d2012-12-18 14:30:41 +00003211
Chris Lattner8f9a1eb2013-01-20 00:56:42 +00003212 // Scan for ORIGINAL_FILE inside the control block.
3213 RecordData Record;
Chris Lattner88bde502013-01-19 21:39:22 +00003214 while (1) {
Chris Lattner8f9a1eb2013-01-20 00:56:42 +00003215 llvm::BitstreamEntry Entry = Stream.advanceSkippingSubblocks();
Chris Lattner88bde502013-01-19 21:39:22 +00003216 if (Entry.Kind == llvm::BitstreamEntry::EndBlock)
3217 return std::string();
3218
3219 if (Entry.Kind != llvm::BitstreamEntry::Record) {
3220 Diags.Report(diag::err_fe_pch_malformed_block) << ASTFileName;
3221 return std::string();
Guy Benyei7f92f2d2012-12-18 14:30:41 +00003222 }
Chris Lattner88bde502013-01-19 21:39:22 +00003223
Guy Benyei7f92f2d2012-12-18 14:30:41 +00003224 Record.clear();
Chris Lattnerb3ce3572013-01-20 02:38:54 +00003225 StringRef Blob;
3226 if (Stream.readRecord(Entry.ID, Record, &Blob) == ORIGINAL_FILE)
3227 return Blob.str();
Guy Benyei7f92f2d2012-12-18 14:30:41 +00003228 }
Guy Benyei7f92f2d2012-12-18 14:30:41 +00003229}
3230
3231namespace {
3232 class SimplePCHValidator : public ASTReaderListener {
3233 const LangOptions &ExistingLangOpts;
3234 const TargetOptions &ExistingTargetOpts;
3235 const PreprocessorOptions &ExistingPPOpts;
3236 FileManager &FileMgr;
3237
3238 public:
3239 SimplePCHValidator(const LangOptions &ExistingLangOpts,
3240 const TargetOptions &ExistingTargetOpts,
3241 const PreprocessorOptions &ExistingPPOpts,
3242 FileManager &FileMgr)
3243 : ExistingLangOpts(ExistingLangOpts),
3244 ExistingTargetOpts(ExistingTargetOpts),
3245 ExistingPPOpts(ExistingPPOpts),
3246 FileMgr(FileMgr)
3247 {
3248 }
3249
3250 virtual bool ReadLanguageOptions(const LangOptions &LangOpts,
3251 bool Complain) {
3252 return checkLanguageOptions(ExistingLangOpts, LangOpts, 0);
3253 }
3254 virtual bool ReadTargetOptions(const TargetOptions &TargetOpts,
3255 bool Complain) {
3256 return checkTargetOptions(ExistingTargetOpts, TargetOpts, 0);
3257 }
3258 virtual bool ReadPreprocessorOptions(const PreprocessorOptions &PPOpts,
3259 bool Complain,
3260 std::string &SuggestedPredefines) {
3261 return checkPreprocessorOptions(ExistingPPOpts, PPOpts, 0, FileMgr,
3262 SuggestedPredefines);
3263 }
3264 };
3265}
3266
3267bool ASTReader::readASTFileControlBlock(StringRef Filename,
3268 FileManager &FileMgr,
3269 ASTReaderListener &Listener) {
3270 // Open the AST file.
3271 std::string ErrStr;
3272 OwningPtr<llvm::MemoryBuffer> Buffer;
3273 Buffer.reset(FileMgr.getBufferForFile(Filename, &ErrStr));
3274 if (!Buffer) {
3275 return true;
3276 }
3277
3278 // Initialize the stream
3279 llvm::BitstreamReader StreamFile;
Chris Lattner8f9a1eb2013-01-20 00:56:42 +00003280 BitstreamCursor Stream;
Guy Benyei7f92f2d2012-12-18 14:30:41 +00003281 StreamFile.init((const unsigned char *)Buffer->getBufferStart(),
3282 (const unsigned char *)Buffer->getBufferEnd());
3283 Stream.init(StreamFile);
3284
3285 // Sniff for the signature.
3286 if (Stream.Read(8) != 'C' ||
3287 Stream.Read(8) != 'P' ||
3288 Stream.Read(8) != 'C' ||
3289 Stream.Read(8) != 'H') {
3290 return true;
3291 }
3292
Chris Lattner8f9a1eb2013-01-20 00:56:42 +00003293 // Scan for the CONTROL_BLOCK_ID block.
3294 if (SkipCursorToControlBlock(Stream))
3295 return true;
3296
3297 // Scan for ORIGINAL_FILE inside the control block.
Guy Benyei7f92f2d2012-12-18 14:30:41 +00003298 RecordData Record;
Chris Lattner8f9a1eb2013-01-20 00:56:42 +00003299 while (1) {
3300 llvm::BitstreamEntry Entry = Stream.advanceSkippingSubblocks();
3301 if (Entry.Kind == llvm::BitstreamEntry::EndBlock)
3302 return false;
3303
3304 if (Entry.Kind != llvm::BitstreamEntry::Record)
3305 return true;
3306
Guy Benyei7f92f2d2012-12-18 14:30:41 +00003307 Record.clear();
Chris Lattnerb3ce3572013-01-20 02:38:54 +00003308 StringRef Blob;
3309 unsigned RecCode = Stream.readRecord(Entry.ID, Record, &Blob);
Chris Lattner8f9a1eb2013-01-20 00:56:42 +00003310 switch ((ControlRecordTypes)RecCode) {
3311 case METADATA: {
3312 if (Record[0] != VERSION_MAJOR)
3313 return true;
Guy Benyei7f92f2d2012-12-18 14:30:41 +00003314
Chris Lattner8f9a1eb2013-01-20 00:56:42 +00003315 const std::string &CurBranch = getClangFullRepositoryVersion();
Chris Lattnerb3ce3572013-01-20 02:38:54 +00003316 if (StringRef(CurBranch) != Blob)
Chris Lattner8f9a1eb2013-01-20 00:56:42 +00003317 return true;
Guy Benyei7f92f2d2012-12-18 14:30:41 +00003318
Chris Lattner8f9a1eb2013-01-20 00:56:42 +00003319 break;
3320 }
3321 case LANGUAGE_OPTIONS:
3322 if (ParseLanguageOptions(Record, false, Listener))
3323 return true;
3324 break;
Guy Benyei7f92f2d2012-12-18 14:30:41 +00003325
Chris Lattner8f9a1eb2013-01-20 00:56:42 +00003326 case TARGET_OPTIONS:
3327 if (ParseTargetOptions(Record, false, Listener))
3328 return true;
3329 break;
Guy Benyei7f92f2d2012-12-18 14:30:41 +00003330
Chris Lattner8f9a1eb2013-01-20 00:56:42 +00003331 case DIAGNOSTIC_OPTIONS:
3332 if (ParseDiagnosticOptions(Record, false, Listener))
3333 return true;
3334 break;
Guy Benyei7f92f2d2012-12-18 14:30:41 +00003335
Chris Lattner8f9a1eb2013-01-20 00:56:42 +00003336 case FILE_SYSTEM_OPTIONS:
3337 if (ParseFileSystemOptions(Record, false, Listener))
3338 return true;
3339 break;
Guy Benyei7f92f2d2012-12-18 14:30:41 +00003340
Chris Lattner8f9a1eb2013-01-20 00:56:42 +00003341 case HEADER_SEARCH_OPTIONS:
3342 if (ParseHeaderSearchOptions(Record, false, Listener))
3343 return true;
3344 break;
Guy Benyei7f92f2d2012-12-18 14:30:41 +00003345
Chris Lattner8f9a1eb2013-01-20 00:56:42 +00003346 case PREPROCESSOR_OPTIONS: {
3347 std::string IgnoredSuggestedPredefines;
3348 if (ParsePreprocessorOptions(Record, false, Listener,
3349 IgnoredSuggestedPredefines))
3350 return true;
3351 break;
3352 }
Guy Benyei7f92f2d2012-12-18 14:30:41 +00003353
Chris Lattner8f9a1eb2013-01-20 00:56:42 +00003354 default:
3355 // No other validation to perform.
3356 break;
Guy Benyei7f92f2d2012-12-18 14:30:41 +00003357 }
3358 }
Guy Benyei7f92f2d2012-12-18 14:30:41 +00003359}
3360
3361
3362bool ASTReader::isAcceptableASTFile(StringRef Filename,
3363 FileManager &FileMgr,
3364 const LangOptions &LangOpts,
3365 const TargetOptions &TargetOpts,
3366 const PreprocessorOptions &PPOpts) {
3367 SimplePCHValidator validator(LangOpts, TargetOpts, PPOpts, FileMgr);
3368 return !readASTFileControlBlock(Filename, FileMgr, validator);
3369}
3370
3371bool ASTReader::ReadSubmoduleBlock(ModuleFile &F) {
3372 // Enter the submodule block.
3373 if (F.Stream.EnterSubBlock(SUBMODULE_BLOCK_ID)) {
3374 Error("malformed submodule block record in AST file");
3375 return true;
3376 }
3377
3378 ModuleMap &ModMap = PP.getHeaderSearchInfo().getModuleMap();
3379 bool First = true;
3380 Module *CurrentModule = 0;
3381 RecordData Record;
3382 while (true) {
Chris Lattner8f9a1eb2013-01-20 00:56:42 +00003383 llvm::BitstreamEntry Entry = F.Stream.advanceSkippingSubblocks();
3384
3385 switch (Entry.Kind) {
3386 case llvm::BitstreamEntry::SubBlock: // Handled for us already.
3387 case llvm::BitstreamEntry::Error:
3388 Error("malformed block record in AST file");
3389 return true;
3390 case llvm::BitstreamEntry::EndBlock:
Guy Benyei7f92f2d2012-12-18 14:30:41 +00003391 return false;
Chris Lattner8f9a1eb2013-01-20 00:56:42 +00003392 case llvm::BitstreamEntry::Record:
3393 // The interesting case.
3394 break;
Guy Benyei7f92f2d2012-12-18 14:30:41 +00003395 }
Chris Lattner8f9a1eb2013-01-20 00:56:42 +00003396
Guy Benyei7f92f2d2012-12-18 14:30:41 +00003397 // Read a record.
Chris Lattnerb3ce3572013-01-20 02:38:54 +00003398 StringRef Blob;
Guy Benyei7f92f2d2012-12-18 14:30:41 +00003399 Record.clear();
Chris Lattnerb3ce3572013-01-20 02:38:54 +00003400 switch (F.Stream.readRecord(Entry.ID, Record, &Blob)) {
Guy Benyei7f92f2d2012-12-18 14:30:41 +00003401 default: // Default behavior: ignore.
3402 break;
3403
3404 case SUBMODULE_DEFINITION: {
3405 if (First) {
3406 Error("missing submodule metadata record at beginning of block");
3407 return true;
3408 }
3409
3410 if (Record.size() < 7) {
3411 Error("malformed module definition");
3412 return true;
3413 }
3414
Chris Lattnerb3ce3572013-01-20 02:38:54 +00003415 StringRef Name = Blob;
Guy Benyei7f92f2d2012-12-18 14:30:41 +00003416 SubmoduleID GlobalID = getGlobalSubmoduleID(F, Record[0]);
3417 SubmoduleID Parent = getGlobalSubmoduleID(F, Record[1]);
3418 bool IsFramework = Record[2];
3419 bool IsExplicit = Record[3];
3420 bool IsSystem = Record[4];
3421 bool InferSubmodules = Record[5];
3422 bool InferExplicitSubmodules = Record[6];
3423 bool InferExportWildcard = Record[7];
3424
3425 Module *ParentModule = 0;
3426 if (Parent)
3427 ParentModule = getSubmodule(Parent);
3428
3429 // Retrieve this (sub)module from the module map, creating it if
3430 // necessary.
3431 CurrentModule = ModMap.findOrCreateModule(Name, ParentModule,
3432 IsFramework,
3433 IsExplicit).first;
3434 SubmoduleID GlobalIndex = GlobalID - NUM_PREDEF_SUBMODULE_IDS;
3435 if (GlobalIndex >= SubmodulesLoaded.size() ||
3436 SubmodulesLoaded[GlobalIndex]) {
3437 Error("too many submodules");
3438 return true;
3439 }
Douglas Gregor8bf778e2013-02-06 22:40:31 +00003440
3441 if (const FileEntry *CurFile = CurrentModule->getASTFile()) {
3442 if (CurFile != F.File) {
3443 if (!Diags.isDiagnosticInFlight()) {
3444 Diag(diag::err_module_file_conflict)
3445 << CurrentModule->getTopLevelModuleName()
3446 << CurFile->getName()
3447 << F.File->getName();
3448 }
3449 return true;
3450 }
3451 }
Guy Benyei7f92f2d2012-12-18 14:30:41 +00003452 CurrentModule->setASTFile(F.File);
3453 CurrentModule->IsFromModuleFile = true;
3454 CurrentModule->IsSystem = IsSystem || CurrentModule->IsSystem;
3455 CurrentModule->InferSubmodules = InferSubmodules;
3456 CurrentModule->InferExplicitSubmodules = InferExplicitSubmodules;
3457 CurrentModule->InferExportWildcard = InferExportWildcard;
3458 if (DeserializationListener)
3459 DeserializationListener->ModuleRead(GlobalID, CurrentModule);
3460
3461 SubmodulesLoaded[GlobalIndex] = CurrentModule;
Douglas Gregorb6cbe512013-01-14 17:21:00 +00003462
3463 // Clear out link libraries; the module file has them.
3464 CurrentModule->LinkLibraries.clear();
Guy Benyei7f92f2d2012-12-18 14:30:41 +00003465 break;
3466 }
3467
3468 case SUBMODULE_UMBRELLA_HEADER: {
3469 if (First) {
3470 Error("missing submodule metadata record at beginning of block");
3471 return true;
3472 }
3473
3474 if (!CurrentModule)
3475 break;
3476
Chris Lattnerb3ce3572013-01-20 02:38:54 +00003477 if (const FileEntry *Umbrella = PP.getFileManager().getFile(Blob)) {
Guy Benyei7f92f2d2012-12-18 14:30:41 +00003478 if (!CurrentModule->getUmbrellaHeader())
3479 ModMap.setUmbrellaHeader(CurrentModule, Umbrella);
3480 else if (CurrentModule->getUmbrellaHeader() != Umbrella) {
3481 Error("mismatched umbrella headers in submodule");
3482 return true;
3483 }
3484 }
3485 break;
3486 }
3487
3488 case SUBMODULE_HEADER: {
3489 if (First) {
3490 Error("missing submodule metadata record at beginning of block");
3491 return true;
3492 }
3493
3494 if (!CurrentModule)
3495 break;
3496
3497 // FIXME: Be more lazy about this!
Chris Lattnerb3ce3572013-01-20 02:38:54 +00003498 if (const FileEntry *File = PP.getFileManager().getFile(Blob)) {
Guy Benyei7f92f2d2012-12-18 14:30:41 +00003499 if (std::find(CurrentModule->Headers.begin(),
3500 CurrentModule->Headers.end(),
3501 File) == CurrentModule->Headers.end())
3502 ModMap.addHeader(CurrentModule, File, false);
3503 }
3504 break;
3505 }
3506
3507 case SUBMODULE_EXCLUDED_HEADER: {
3508 if (First) {
3509 Error("missing submodule metadata record at beginning of block");
3510 return true;
3511 }
3512
3513 if (!CurrentModule)
3514 break;
3515
3516 // FIXME: Be more lazy about this!
Chris Lattnerb3ce3572013-01-20 02:38:54 +00003517 if (const FileEntry *File = PP.getFileManager().getFile(Blob)) {
Guy Benyei7f92f2d2012-12-18 14:30:41 +00003518 if (std::find(CurrentModule->Headers.begin(),
3519 CurrentModule->Headers.end(),
3520 File) == CurrentModule->Headers.end())
3521 ModMap.addHeader(CurrentModule, File, true);
3522 }
3523 break;
3524 }
3525
3526 case SUBMODULE_TOPHEADER: {
3527 if (First) {
3528 Error("missing submodule metadata record at beginning of block");
3529 return true;
3530 }
3531
3532 if (!CurrentModule)
3533 break;
3534
3535 // FIXME: Be more lazy about this!
Chris Lattnerb3ce3572013-01-20 02:38:54 +00003536 if (const FileEntry *File = PP.getFileManager().getFile(Blob))
Guy Benyei7f92f2d2012-12-18 14:30:41 +00003537 CurrentModule->TopHeaders.insert(File);
3538 break;
3539 }
3540
3541 case SUBMODULE_UMBRELLA_DIR: {
3542 if (First) {
3543 Error("missing submodule metadata record at beginning of block");
3544 return true;
3545 }
3546
3547 if (!CurrentModule)
3548 break;
3549
Guy Benyei7f92f2d2012-12-18 14:30:41 +00003550 if (const DirectoryEntry *Umbrella
Chris Lattnerb3ce3572013-01-20 02:38:54 +00003551 = PP.getFileManager().getDirectory(Blob)) {
Guy Benyei7f92f2d2012-12-18 14:30:41 +00003552 if (!CurrentModule->getUmbrellaDir())
3553 ModMap.setUmbrellaDir(CurrentModule, Umbrella);
3554 else if (CurrentModule->getUmbrellaDir() != Umbrella) {
3555 Error("mismatched umbrella directories in submodule");
3556 return true;
3557 }
3558 }
3559 break;
3560 }
3561
3562 case SUBMODULE_METADATA: {
3563 if (!First) {
3564 Error("submodule metadata record not at beginning of block");
3565 return true;
3566 }
3567 First = false;
3568
3569 F.BaseSubmoduleID = getTotalNumSubmodules();
3570 F.LocalNumSubmodules = Record[0];
3571 unsigned LocalBaseSubmoduleID = Record[1];
3572 if (F.LocalNumSubmodules > 0) {
3573 // Introduce the global -> local mapping for submodules within this
3574 // module.
3575 GlobalSubmoduleMap.insert(std::make_pair(getTotalNumSubmodules()+1,&F));
3576
3577 // Introduce the local -> global mapping for submodules within this
3578 // module.
3579 F.SubmoduleRemap.insertOrReplace(
3580 std::make_pair(LocalBaseSubmoduleID,
3581 F.BaseSubmoduleID - LocalBaseSubmoduleID));
3582
3583 SubmodulesLoaded.resize(SubmodulesLoaded.size() + F.LocalNumSubmodules);
3584 }
3585 break;
3586 }
3587
3588 case SUBMODULE_IMPORTS: {
3589 if (First) {
3590 Error("missing submodule metadata record at beginning of block");
3591 return true;
3592 }
3593
3594 if (!CurrentModule)
3595 break;
3596
3597 for (unsigned Idx = 0; Idx != Record.size(); ++Idx) {
3598 UnresolvedModuleImportExport Unresolved;
3599 Unresolved.File = &F;
3600 Unresolved.Mod = CurrentModule;
3601 Unresolved.ID = Record[Idx];
3602 Unresolved.IsImport = true;
3603 Unresolved.IsWildcard = false;
3604 UnresolvedModuleImportExports.push_back(Unresolved);
3605 }
3606 break;
3607 }
3608
3609 case SUBMODULE_EXPORTS: {
3610 if (First) {
3611 Error("missing submodule metadata record at beginning of block");
3612 return true;
3613 }
3614
3615 if (!CurrentModule)
3616 break;
3617
3618 for (unsigned Idx = 0; Idx + 1 < Record.size(); Idx += 2) {
3619 UnresolvedModuleImportExport Unresolved;
3620 Unresolved.File = &F;
3621 Unresolved.Mod = CurrentModule;
3622 Unresolved.ID = Record[Idx];
3623 Unresolved.IsImport = false;
3624 Unresolved.IsWildcard = Record[Idx + 1];
3625 UnresolvedModuleImportExports.push_back(Unresolved);
3626 }
3627
3628 // Once we've loaded the set of exports, there's no reason to keep
3629 // the parsed, unresolved exports around.
3630 CurrentModule->UnresolvedExports.clear();
3631 break;
3632 }
3633 case SUBMODULE_REQUIRES: {
3634 if (First) {
3635 Error("missing submodule metadata record at beginning of block");
3636 return true;
3637 }
3638
3639 if (!CurrentModule)
3640 break;
3641
Chris Lattnerb3ce3572013-01-20 02:38:54 +00003642 CurrentModule->addRequirement(Blob, Context.getLangOpts(),
Guy Benyei7f92f2d2012-12-18 14:30:41 +00003643 Context.getTargetInfo());
3644 break;
3645 }
Douglas Gregorb6cbe512013-01-14 17:21:00 +00003646
3647 case SUBMODULE_LINK_LIBRARY:
3648 if (First) {
3649 Error("missing submodule metadata record at beginning of block");
3650 return true;
3651 }
3652
3653 if (!CurrentModule)
3654 break;
3655
3656 CurrentModule->LinkLibraries.push_back(
Chris Lattnerb3ce3572013-01-20 02:38:54 +00003657 Module::LinkLibrary(Blob, Record[0]));
Douglas Gregorb6cbe512013-01-14 17:21:00 +00003658 break;
Guy Benyei7f92f2d2012-12-18 14:30:41 +00003659 }
3660 }
3661}
3662
3663/// \brief Parse the record that corresponds to a LangOptions data
3664/// structure.
3665///
3666/// This routine parses the language options from the AST file and then gives
3667/// them to the AST listener if one is set.
3668///
3669/// \returns true if the listener deems the file unacceptable, false otherwise.
3670bool ASTReader::ParseLanguageOptions(const RecordData &Record,
3671 bool Complain,
3672 ASTReaderListener &Listener) {
3673 LangOptions LangOpts;
3674 unsigned Idx = 0;
3675#define LANGOPT(Name, Bits, Default, Description) \
3676 LangOpts.Name = Record[Idx++];
3677#define ENUM_LANGOPT(Name, Type, Bits, Default, Description) \
3678 LangOpts.set##Name(static_cast<LangOptions::Type>(Record[Idx++]));
3679#include "clang/Basic/LangOptions.def"
Will Dietz4f45bc02013-01-18 11:30:38 +00003680#define SANITIZER(NAME, ID) LangOpts.Sanitize.ID = Record[Idx++];
3681#include "clang/Basic/Sanitizers.def"
Guy Benyei7f92f2d2012-12-18 14:30:41 +00003682
3683 ObjCRuntime::Kind runtimeKind = (ObjCRuntime::Kind) Record[Idx++];
3684 VersionTuple runtimeVersion = ReadVersionTuple(Record, Idx);
3685 LangOpts.ObjCRuntime = ObjCRuntime(runtimeKind, runtimeVersion);
3686
3687 unsigned Length = Record[Idx++];
3688 LangOpts.CurrentModule.assign(Record.begin() + Idx,
3689 Record.begin() + Idx + Length);
Dmitri Gribenko6ebf0912013-02-22 14:21:27 +00003690
3691 Idx += Length;
3692
3693 // Comment options.
3694 for (unsigned N = Record[Idx++]; N; --N) {
3695 LangOpts.CommentOpts.BlockCommandNames.push_back(
3696 ReadString(Record, Idx));
3697 }
3698
Guy Benyei7f92f2d2012-12-18 14:30:41 +00003699 return Listener.ReadLanguageOptions(LangOpts, Complain);
3700}
3701
3702bool ASTReader::ParseTargetOptions(const RecordData &Record,
3703 bool Complain,
3704 ASTReaderListener &Listener) {
3705 unsigned Idx = 0;
3706 TargetOptions TargetOpts;
3707 TargetOpts.Triple = ReadString(Record, Idx);
3708 TargetOpts.CPU = ReadString(Record, Idx);
3709 TargetOpts.ABI = ReadString(Record, Idx);
3710 TargetOpts.CXXABI = ReadString(Record, Idx);
3711 TargetOpts.LinkerVersion = ReadString(Record, Idx);
3712 for (unsigned N = Record[Idx++]; N; --N) {
3713 TargetOpts.FeaturesAsWritten.push_back(ReadString(Record, Idx));
3714 }
3715 for (unsigned N = Record[Idx++]; N; --N) {
3716 TargetOpts.Features.push_back(ReadString(Record, Idx));
3717 }
3718
3719 return Listener.ReadTargetOptions(TargetOpts, Complain);
3720}
3721
3722bool ASTReader::ParseDiagnosticOptions(const RecordData &Record, bool Complain,
3723 ASTReaderListener &Listener) {
3724 DiagnosticOptions DiagOpts;
3725 unsigned Idx = 0;
3726#define DIAGOPT(Name, Bits, Default) DiagOpts.Name = Record[Idx++];
3727#define ENUM_DIAGOPT(Name, Type, Bits, Default) \
3728 DiagOpts.set##Name(static_cast<Type>(Record[Idx++]));
3729#include "clang/Basic/DiagnosticOptions.def"
3730
3731 for (unsigned N = Record[Idx++]; N; --N) {
3732 DiagOpts.Warnings.push_back(ReadString(Record, Idx));
3733 }
3734
3735 return Listener.ReadDiagnosticOptions(DiagOpts, Complain);
3736}
3737
3738bool ASTReader::ParseFileSystemOptions(const RecordData &Record, bool Complain,
3739 ASTReaderListener &Listener) {
3740 FileSystemOptions FSOpts;
3741 unsigned Idx = 0;
3742 FSOpts.WorkingDir = ReadString(Record, Idx);
3743 return Listener.ReadFileSystemOptions(FSOpts, Complain);
3744}
3745
3746bool ASTReader::ParseHeaderSearchOptions(const RecordData &Record,
3747 bool Complain,
3748 ASTReaderListener &Listener) {
3749 HeaderSearchOptions HSOpts;
3750 unsigned Idx = 0;
3751 HSOpts.Sysroot = ReadString(Record, Idx);
3752
3753 // Include entries.
3754 for (unsigned N = Record[Idx++]; N; --N) {
3755 std::string Path = ReadString(Record, Idx);
3756 frontend::IncludeDirGroup Group
3757 = static_cast<frontend::IncludeDirGroup>(Record[Idx++]);
Guy Benyei7f92f2d2012-12-18 14:30:41 +00003758 bool IsFramework = Record[Idx++];
3759 bool IgnoreSysRoot = Record[Idx++];
Guy Benyei7f92f2d2012-12-18 14:30:41 +00003760 HSOpts.UserEntries.push_back(
Daniel Dunbar59fd6352013-01-30 00:34:26 +00003761 HeaderSearchOptions::Entry(Path, Group, IsFramework, IgnoreSysRoot));
Guy Benyei7f92f2d2012-12-18 14:30:41 +00003762 }
3763
3764 // System header prefixes.
3765 for (unsigned N = Record[Idx++]; N; --N) {
3766 std::string Prefix = ReadString(Record, Idx);
3767 bool IsSystemHeader = Record[Idx++];
3768 HSOpts.SystemHeaderPrefixes.push_back(
3769 HeaderSearchOptions::SystemHeaderPrefix(Prefix, IsSystemHeader));
3770 }
3771
3772 HSOpts.ResourceDir = ReadString(Record, Idx);
3773 HSOpts.ModuleCachePath = ReadString(Record, Idx);
3774 HSOpts.DisableModuleHash = Record[Idx++];
3775 HSOpts.UseBuiltinIncludes = Record[Idx++];
3776 HSOpts.UseStandardSystemIncludes = Record[Idx++];
3777 HSOpts.UseStandardCXXIncludes = Record[Idx++];
3778 HSOpts.UseLibcxx = Record[Idx++];
3779
3780 return Listener.ReadHeaderSearchOptions(HSOpts, Complain);
3781}
3782
3783bool ASTReader::ParsePreprocessorOptions(const RecordData &Record,
3784 bool Complain,
3785 ASTReaderListener &Listener,
3786 std::string &SuggestedPredefines) {
3787 PreprocessorOptions PPOpts;
3788 unsigned Idx = 0;
3789
3790 // Macro definitions/undefs
3791 for (unsigned N = Record[Idx++]; N; --N) {
3792 std::string Macro = ReadString(Record, Idx);
3793 bool IsUndef = Record[Idx++];
3794 PPOpts.Macros.push_back(std::make_pair(Macro, IsUndef));
3795 }
3796
3797 // Includes
3798 for (unsigned N = Record[Idx++]; N; --N) {
3799 PPOpts.Includes.push_back(ReadString(Record, Idx));
3800 }
3801
3802 // Macro Includes
3803 for (unsigned N = Record[Idx++]; N; --N) {
3804 PPOpts.MacroIncludes.push_back(ReadString(Record, Idx));
3805 }
3806
3807 PPOpts.UsePredefines = Record[Idx++];
3808 PPOpts.ImplicitPCHInclude = ReadString(Record, Idx);
3809 PPOpts.ImplicitPTHInclude = ReadString(Record, Idx);
3810 PPOpts.ObjCXXARCStandardLibrary =
3811 static_cast<ObjCXXARCStandardLibraryKind>(Record[Idx++]);
3812 SuggestedPredefines.clear();
3813 return Listener.ReadPreprocessorOptions(PPOpts, Complain,
3814 SuggestedPredefines);
3815}
3816
3817std::pair<ModuleFile *, unsigned>
3818ASTReader::getModulePreprocessedEntity(unsigned GlobalIndex) {
3819 GlobalPreprocessedEntityMapType::iterator
3820 I = GlobalPreprocessedEntityMap.find(GlobalIndex);
3821 assert(I != GlobalPreprocessedEntityMap.end() &&
3822 "Corrupted global preprocessed entity map");
3823 ModuleFile *M = I->second;
3824 unsigned LocalIndex = GlobalIndex - M->BasePreprocessedEntityID;
3825 return std::make_pair(M, LocalIndex);
3826}
3827
3828std::pair<PreprocessingRecord::iterator, PreprocessingRecord::iterator>
3829ASTReader::getModulePreprocessedEntities(ModuleFile &Mod) const {
3830 if (PreprocessingRecord *PPRec = PP.getPreprocessingRecord())
3831 return PPRec->getIteratorsForLoadedRange(Mod.BasePreprocessedEntityID,
3832 Mod.NumPreprocessedEntities);
3833
3834 return std::make_pair(PreprocessingRecord::iterator(),
3835 PreprocessingRecord::iterator());
3836}
3837
3838std::pair<ASTReader::ModuleDeclIterator, ASTReader::ModuleDeclIterator>
3839ASTReader::getModuleFileLevelDecls(ModuleFile &Mod) {
3840 return std::make_pair(ModuleDeclIterator(this, &Mod, Mod.FileSortedDecls),
3841 ModuleDeclIterator(this, &Mod,
3842 Mod.FileSortedDecls + Mod.NumFileSortedDecls));
3843}
3844
3845PreprocessedEntity *ASTReader::ReadPreprocessedEntity(unsigned Index) {
3846 PreprocessedEntityID PPID = Index+1;
3847 std::pair<ModuleFile *, unsigned> PPInfo = getModulePreprocessedEntity(Index);
3848 ModuleFile &M = *PPInfo.first;
3849 unsigned LocalIndex = PPInfo.second;
3850 const PPEntityOffset &PPOffs = M.PreprocessedEntityOffsets[LocalIndex];
3851
Guy Benyei7f92f2d2012-12-18 14:30:41 +00003852 if (!PP.getPreprocessingRecord()) {
3853 Error("no preprocessing record");
3854 return 0;
3855 }
3856
Chris Lattner8f9a1eb2013-01-20 00:56:42 +00003857 SavedStreamPosition SavedPosition(M.PreprocessorDetailCursor);
3858 M.PreprocessorDetailCursor.JumpToBit(PPOffs.BitOffset);
3859
3860 llvm::BitstreamEntry Entry =
3861 M.PreprocessorDetailCursor.advance(BitstreamCursor::AF_DontPopBlockAtEnd);
3862 if (Entry.Kind != llvm::BitstreamEntry::Record)
3863 return 0;
3864
Guy Benyei7f92f2d2012-12-18 14:30:41 +00003865 // Read the record.
3866 SourceRange Range(ReadSourceLocation(M, PPOffs.Begin),
3867 ReadSourceLocation(M, PPOffs.End));
3868 PreprocessingRecord &PPRec = *PP.getPreprocessingRecord();
Chris Lattnerb3ce3572013-01-20 02:38:54 +00003869 StringRef Blob;
Guy Benyei7f92f2d2012-12-18 14:30:41 +00003870 RecordData Record;
3871 PreprocessorDetailRecordTypes RecType =
Chris Lattnerb3ce3572013-01-20 02:38:54 +00003872 (PreprocessorDetailRecordTypes)M.PreprocessorDetailCursor.readRecord(
3873 Entry.ID, Record, &Blob);
Guy Benyei7f92f2d2012-12-18 14:30:41 +00003874 switch (RecType) {
3875 case PPD_MACRO_EXPANSION: {
3876 bool isBuiltin = Record[0];
3877 IdentifierInfo *Name = 0;
3878 MacroDefinition *Def = 0;
3879 if (isBuiltin)
3880 Name = getLocalIdentifier(M, Record[1]);
3881 else {
3882 PreprocessedEntityID
3883 GlobalID = getGlobalPreprocessedEntityID(M, Record[1]);
3884 Def =cast<MacroDefinition>(PPRec.getLoadedPreprocessedEntity(GlobalID-1));
3885 }
3886
3887 MacroExpansion *ME;
3888 if (isBuiltin)
3889 ME = new (PPRec) MacroExpansion(Name, Range);
3890 else
3891 ME = new (PPRec) MacroExpansion(Def, Range);
3892
3893 return ME;
3894 }
3895
3896 case PPD_MACRO_DEFINITION: {
3897 // Decode the identifier info and then check again; if the macro is
3898 // still defined and associated with the identifier,
3899 IdentifierInfo *II = getLocalIdentifier(M, Record[0]);
3900 MacroDefinition *MD
3901 = new (PPRec) MacroDefinition(II, Range);
3902
3903 if (DeserializationListener)
3904 DeserializationListener->MacroDefinitionRead(PPID, MD);
3905
3906 return MD;
3907 }
3908
3909 case PPD_INCLUSION_DIRECTIVE: {
Chris Lattnerb3ce3572013-01-20 02:38:54 +00003910 const char *FullFileNameStart = Blob.data() + Record[0];
3911 StringRef FullFileName(FullFileNameStart, Blob.size() - Record[0]);
Guy Benyei7f92f2d2012-12-18 14:30:41 +00003912 const FileEntry *File = 0;
3913 if (!FullFileName.empty())
3914 File = PP.getFileManager().getFile(FullFileName);
3915
3916 // FIXME: Stable encoding
3917 InclusionDirective::InclusionKind Kind
3918 = static_cast<InclusionDirective::InclusionKind>(Record[2]);
3919 InclusionDirective *ID
3920 = new (PPRec) InclusionDirective(PPRec, Kind,
Chris Lattnerb3ce3572013-01-20 02:38:54 +00003921 StringRef(Blob.data(), Record[0]),
Guy Benyei7f92f2d2012-12-18 14:30:41 +00003922 Record[1], Record[3],
3923 File,
3924 Range);
3925 return ID;
3926 }
3927 }
3928
3929 llvm_unreachable("Invalid PreprocessorDetailRecordTypes");
3930}
3931
3932/// \brief \arg SLocMapI points at a chunk of a module that contains no
3933/// preprocessed entities or the entities it contains are not the ones we are
3934/// looking for. Find the next module that contains entities and return the ID
3935/// of the first entry.
3936PreprocessedEntityID ASTReader::findNextPreprocessedEntity(
3937 GlobalSLocOffsetMapType::const_iterator SLocMapI) const {
3938 ++SLocMapI;
3939 for (GlobalSLocOffsetMapType::const_iterator
3940 EndI = GlobalSLocOffsetMap.end(); SLocMapI != EndI; ++SLocMapI) {
3941 ModuleFile &M = *SLocMapI->second;
3942 if (M.NumPreprocessedEntities)
3943 return M.BasePreprocessedEntityID;
3944 }
3945
3946 return getTotalNumPreprocessedEntities();
3947}
3948
3949namespace {
3950
3951template <unsigned PPEntityOffset::*PPLoc>
3952struct PPEntityComp {
3953 const ASTReader &Reader;
3954 ModuleFile &M;
3955
3956 PPEntityComp(const ASTReader &Reader, ModuleFile &M) : Reader(Reader), M(M) { }
3957
3958 bool operator()(const PPEntityOffset &L, const PPEntityOffset &R) const {
3959 SourceLocation LHS = getLoc(L);
3960 SourceLocation RHS = getLoc(R);
3961 return Reader.getSourceManager().isBeforeInTranslationUnit(LHS, RHS);
3962 }
3963
3964 bool operator()(const PPEntityOffset &L, SourceLocation RHS) const {
3965 SourceLocation LHS = getLoc(L);
3966 return Reader.getSourceManager().isBeforeInTranslationUnit(LHS, RHS);
3967 }
3968
3969 bool operator()(SourceLocation LHS, const PPEntityOffset &R) const {
3970 SourceLocation RHS = getLoc(R);
3971 return Reader.getSourceManager().isBeforeInTranslationUnit(LHS, RHS);
3972 }
3973
3974 SourceLocation getLoc(const PPEntityOffset &PPE) const {
3975 return Reader.ReadSourceLocation(M, PPE.*PPLoc);
3976 }
3977};
3978
3979}
3980
3981/// \brief Returns the first preprocessed entity ID that ends after \arg BLoc.
3982PreprocessedEntityID
3983ASTReader::findBeginPreprocessedEntity(SourceLocation BLoc) const {
3984 if (SourceMgr.isLocalSourceLocation(BLoc))
3985 return getTotalNumPreprocessedEntities();
3986
3987 GlobalSLocOffsetMapType::const_iterator
3988 SLocMapI = GlobalSLocOffsetMap.find(SourceManager::MaxLoadedOffset -
3989 BLoc.getOffset());
3990 assert(SLocMapI != GlobalSLocOffsetMap.end() &&
3991 "Corrupted global sloc offset map");
3992
3993 if (SLocMapI->second->NumPreprocessedEntities == 0)
3994 return findNextPreprocessedEntity(SLocMapI);
3995
3996 ModuleFile &M = *SLocMapI->second;
3997 typedef const PPEntityOffset *pp_iterator;
3998 pp_iterator pp_begin = M.PreprocessedEntityOffsets;
3999 pp_iterator pp_end = pp_begin + M.NumPreprocessedEntities;
4000
4001 size_t Count = M.NumPreprocessedEntities;
4002 size_t Half;
4003 pp_iterator First = pp_begin;
4004 pp_iterator PPI;
4005
4006 // Do a binary search manually instead of using std::lower_bound because
4007 // The end locations of entities may be unordered (when a macro expansion
4008 // is inside another macro argument), but for this case it is not important
4009 // whether we get the first macro expansion or its containing macro.
4010 while (Count > 0) {
4011 Half = Count/2;
4012 PPI = First;
4013 std::advance(PPI, Half);
4014 if (SourceMgr.isBeforeInTranslationUnit(ReadSourceLocation(M, PPI->End),
4015 BLoc)){
4016 First = PPI;
4017 ++First;
4018 Count = Count - Half - 1;
4019 } else
4020 Count = Half;
4021 }
4022
4023 if (PPI == pp_end)
4024 return findNextPreprocessedEntity(SLocMapI);
4025
4026 return M.BasePreprocessedEntityID + (PPI - pp_begin);
4027}
4028
4029/// \brief Returns the first preprocessed entity ID that begins after \arg ELoc.
4030PreprocessedEntityID
4031ASTReader::findEndPreprocessedEntity(SourceLocation ELoc) const {
4032 if (SourceMgr.isLocalSourceLocation(ELoc))
4033 return getTotalNumPreprocessedEntities();
4034
4035 GlobalSLocOffsetMapType::const_iterator
4036 SLocMapI = GlobalSLocOffsetMap.find(SourceManager::MaxLoadedOffset -
4037 ELoc.getOffset());
4038 assert(SLocMapI != GlobalSLocOffsetMap.end() &&
4039 "Corrupted global sloc offset map");
4040
4041 if (SLocMapI->second->NumPreprocessedEntities == 0)
4042 return findNextPreprocessedEntity(SLocMapI);
4043
4044 ModuleFile &M = *SLocMapI->second;
4045 typedef const PPEntityOffset *pp_iterator;
4046 pp_iterator pp_begin = M.PreprocessedEntityOffsets;
4047 pp_iterator pp_end = pp_begin + M.NumPreprocessedEntities;
4048 pp_iterator PPI =
4049 std::upper_bound(pp_begin, pp_end, ELoc,
4050 PPEntityComp<&PPEntityOffset::Begin>(*this, M));
4051
4052 if (PPI == pp_end)
4053 return findNextPreprocessedEntity(SLocMapI);
4054
4055 return M.BasePreprocessedEntityID + (PPI - pp_begin);
4056}
4057
4058/// \brief Returns a pair of [Begin, End) indices of preallocated
4059/// preprocessed entities that \arg Range encompasses.
4060std::pair<unsigned, unsigned>
4061 ASTReader::findPreprocessedEntitiesInRange(SourceRange Range) {
4062 if (Range.isInvalid())
4063 return std::make_pair(0,0);
4064 assert(!SourceMgr.isBeforeInTranslationUnit(Range.getEnd(),Range.getBegin()));
4065
4066 PreprocessedEntityID BeginID = findBeginPreprocessedEntity(Range.getBegin());
4067 PreprocessedEntityID EndID = findEndPreprocessedEntity(Range.getEnd());
4068 return std::make_pair(BeginID, EndID);
4069}
4070
4071/// \brief Optionally returns true or false if the preallocated preprocessed
4072/// entity with index \arg Index came from file \arg FID.
David Blaikiedc84cd52013-02-20 22:23:23 +00004073Optional<bool> ASTReader::isPreprocessedEntityInFileID(unsigned Index,
Guy Benyei7f92f2d2012-12-18 14:30:41 +00004074 FileID FID) {
4075 if (FID.isInvalid())
4076 return false;
4077
4078 std::pair<ModuleFile *, unsigned> PPInfo = getModulePreprocessedEntity(Index);
4079 ModuleFile &M = *PPInfo.first;
4080 unsigned LocalIndex = PPInfo.second;
4081 const PPEntityOffset &PPOffs = M.PreprocessedEntityOffsets[LocalIndex];
4082
4083 SourceLocation Loc = ReadSourceLocation(M, PPOffs.Begin);
4084 if (Loc.isInvalid())
4085 return false;
4086
4087 if (SourceMgr.isInFileID(SourceMgr.getFileLoc(Loc), FID))
4088 return true;
4089 else
4090 return false;
4091}
4092
4093namespace {
4094 /// \brief Visitor used to search for information about a header file.
4095 class HeaderFileInfoVisitor {
4096 ASTReader &Reader;
4097 const FileEntry *FE;
4098
David Blaikiedc84cd52013-02-20 22:23:23 +00004099 Optional<HeaderFileInfo> HFI;
Guy Benyei7f92f2d2012-12-18 14:30:41 +00004100
4101 public:
4102 HeaderFileInfoVisitor(ASTReader &Reader, const FileEntry *FE)
4103 : Reader(Reader), FE(FE) { }
4104
4105 static bool visit(ModuleFile &M, void *UserData) {
4106 HeaderFileInfoVisitor *This
4107 = static_cast<HeaderFileInfoVisitor *>(UserData);
4108
4109 HeaderFileInfoTrait Trait(This->Reader, M,
4110 &This->Reader.getPreprocessor().getHeaderSearchInfo(),
4111 M.HeaderFileFrameworkStrings,
4112 This->FE->getName());
4113
4114 HeaderFileInfoLookupTable *Table
4115 = static_cast<HeaderFileInfoLookupTable *>(M.HeaderFileInfoTable);
4116 if (!Table)
4117 return false;
4118
4119 // Look in the on-disk hash table for an entry for this file name.
4120 HeaderFileInfoLookupTable::iterator Pos = Table->find(This->FE->getName(),
4121 &Trait);
4122 if (Pos == Table->end())
4123 return false;
4124
4125 This->HFI = *Pos;
4126 return true;
4127 }
4128
David Blaikiedc84cd52013-02-20 22:23:23 +00004129 Optional<HeaderFileInfo> getHeaderFileInfo() const { return HFI; }
Guy Benyei7f92f2d2012-12-18 14:30:41 +00004130 };
4131}
4132
4133HeaderFileInfo ASTReader::GetHeaderFileInfo(const FileEntry *FE) {
4134 HeaderFileInfoVisitor Visitor(*this, FE);
4135 ModuleMgr.visit(&HeaderFileInfoVisitor::visit, &Visitor);
David Blaikiedc84cd52013-02-20 22:23:23 +00004136 if (Optional<HeaderFileInfo> HFI = Visitor.getHeaderFileInfo()) {
Guy Benyei7f92f2d2012-12-18 14:30:41 +00004137 if (Listener)
4138 Listener->ReadHeaderFileInfo(*HFI, FE->getUID());
4139 return *HFI;
4140 }
4141
4142 return HeaderFileInfo();
4143}
4144
4145void ASTReader::ReadPragmaDiagnosticMappings(DiagnosticsEngine &Diag) {
4146 // FIXME: Make it work properly with modules.
Dmitri Gribenkocfa88f82013-01-12 19:30:44 +00004147 SmallVector<DiagnosticsEngine::DiagState *, 32> DiagStates;
Guy Benyei7f92f2d2012-12-18 14:30:41 +00004148 for (ModuleIterator I = ModuleMgr.begin(), E = ModuleMgr.end(); I != E; ++I) {
4149 ModuleFile &F = *(*I);
4150 unsigned Idx = 0;
4151 DiagStates.clear();
4152 assert(!Diag.DiagStates.empty());
4153 DiagStates.push_back(&Diag.DiagStates.front()); // the command-line one.
4154 while (Idx < F.PragmaDiagMappings.size()) {
4155 SourceLocation Loc = ReadSourceLocation(F, F.PragmaDiagMappings[Idx++]);
4156 unsigned DiagStateID = F.PragmaDiagMappings[Idx++];
4157 if (DiagStateID != 0) {
4158 Diag.DiagStatePoints.push_back(
4159 DiagnosticsEngine::DiagStatePoint(DiagStates[DiagStateID-1],
4160 FullSourceLoc(Loc, SourceMgr)));
4161 continue;
4162 }
4163
4164 assert(DiagStateID == 0);
4165 // A new DiagState was created here.
4166 Diag.DiagStates.push_back(*Diag.GetCurDiagState());
4167 DiagnosticsEngine::DiagState *NewState = &Diag.DiagStates.back();
4168 DiagStates.push_back(NewState);
4169 Diag.DiagStatePoints.push_back(
4170 DiagnosticsEngine::DiagStatePoint(NewState,
4171 FullSourceLoc(Loc, SourceMgr)));
4172 while (1) {
4173 assert(Idx < F.PragmaDiagMappings.size() &&
4174 "Invalid data, didn't find '-1' marking end of diag/map pairs");
4175 if (Idx >= F.PragmaDiagMappings.size()) {
4176 break; // Something is messed up but at least avoid infinite loop in
4177 // release build.
4178 }
4179 unsigned DiagID = F.PragmaDiagMappings[Idx++];
4180 if (DiagID == (unsigned)-1) {
4181 break; // no more diag/map pairs for this location.
4182 }
4183 diag::Mapping Map = (diag::Mapping)F.PragmaDiagMappings[Idx++];
4184 DiagnosticMappingInfo MappingInfo = Diag.makeMappingInfo(Map, Loc);
4185 Diag.GetCurDiagState()->setMappingInfo(DiagID, MappingInfo);
4186 }
4187 }
4188 }
4189}
4190
4191/// \brief Get the correct cursor and offset for loading a type.
4192ASTReader::RecordLocation ASTReader::TypeCursorForIndex(unsigned Index) {
4193 GlobalTypeMapType::iterator I = GlobalTypeMap.find(Index);
4194 assert(I != GlobalTypeMap.end() && "Corrupted global type map");
4195 ModuleFile *M = I->second;
4196 return RecordLocation(M, M->TypeOffsets[Index - M->BaseTypeIndex]);
4197}
4198
4199/// \brief Read and return the type with the given index..
4200///
4201/// The index is the type ID, shifted and minus the number of predefs. This
4202/// routine actually reads the record corresponding to the type at the given
4203/// location. It is a helper routine for GetType, which deals with reading type
4204/// IDs.
4205QualType ASTReader::readTypeRecord(unsigned Index) {
4206 RecordLocation Loc = TypeCursorForIndex(Index);
Chris Lattner8f9a1eb2013-01-20 00:56:42 +00004207 BitstreamCursor &DeclsCursor = Loc.F->DeclsCursor;
Guy Benyei7f92f2d2012-12-18 14:30:41 +00004208
4209 // Keep track of where we are in the stream, then jump back there
4210 // after reading this type.
4211 SavedStreamPosition SavedPosition(DeclsCursor);
4212
4213 ReadingKindTracker ReadingKind(Read_Type, *this);
4214
4215 // Note that we are loading a type record.
4216 Deserializing AType(this);
4217
4218 unsigned Idx = 0;
4219 DeclsCursor.JumpToBit(Loc.Offset);
4220 RecordData Record;
4221 unsigned Code = DeclsCursor.ReadCode();
Chris Lattnerb3ce3572013-01-20 02:38:54 +00004222 switch ((TypeCode)DeclsCursor.readRecord(Code, Record)) {
Guy Benyei7f92f2d2012-12-18 14:30:41 +00004223 case TYPE_EXT_QUAL: {
4224 if (Record.size() != 2) {
4225 Error("Incorrect encoding of extended qualifier type");
4226 return QualType();
4227 }
4228 QualType Base = readType(*Loc.F, Record, Idx);
4229 Qualifiers Quals = Qualifiers::fromOpaqueValue(Record[Idx++]);
4230 return Context.getQualifiedType(Base, Quals);
4231 }
4232
4233 case TYPE_COMPLEX: {
4234 if (Record.size() != 1) {
4235 Error("Incorrect encoding of complex type");
4236 return QualType();
4237 }
4238 QualType ElemType = readType(*Loc.F, Record, Idx);
4239 return Context.getComplexType(ElemType);
4240 }
4241
4242 case TYPE_POINTER: {
4243 if (Record.size() != 1) {
4244 Error("Incorrect encoding of pointer type");
4245 return QualType();
4246 }
4247 QualType PointeeType = readType(*Loc.F, Record, Idx);
4248 return Context.getPointerType(PointeeType);
4249 }
4250
4251 case TYPE_BLOCK_POINTER: {
4252 if (Record.size() != 1) {
4253 Error("Incorrect encoding of block pointer type");
4254 return QualType();
4255 }
4256 QualType PointeeType = readType(*Loc.F, Record, Idx);
4257 return Context.getBlockPointerType(PointeeType);
4258 }
4259
4260 case TYPE_LVALUE_REFERENCE: {
4261 if (Record.size() != 2) {
4262 Error("Incorrect encoding of lvalue reference type");
4263 return QualType();
4264 }
4265 QualType PointeeType = readType(*Loc.F, Record, Idx);
4266 return Context.getLValueReferenceType(PointeeType, Record[1]);
4267 }
4268
4269 case TYPE_RVALUE_REFERENCE: {
4270 if (Record.size() != 1) {
4271 Error("Incorrect encoding of rvalue reference type");
4272 return QualType();
4273 }
4274 QualType PointeeType = readType(*Loc.F, Record, Idx);
4275 return Context.getRValueReferenceType(PointeeType);
4276 }
4277
4278 case TYPE_MEMBER_POINTER: {
4279 if (Record.size() != 2) {
4280 Error("Incorrect encoding of member pointer type");
4281 return QualType();
4282 }
4283 QualType PointeeType = readType(*Loc.F, Record, Idx);
4284 QualType ClassType = readType(*Loc.F, Record, Idx);
4285 if (PointeeType.isNull() || ClassType.isNull())
4286 return QualType();
4287
4288 return Context.getMemberPointerType(PointeeType, ClassType.getTypePtr());
4289 }
4290
4291 case TYPE_CONSTANT_ARRAY: {
4292 QualType ElementType = readType(*Loc.F, Record, Idx);
4293 ArrayType::ArraySizeModifier ASM = (ArrayType::ArraySizeModifier)Record[1];
4294 unsigned IndexTypeQuals = Record[2];
4295 unsigned Idx = 3;
4296 llvm::APInt Size = ReadAPInt(Record, Idx);
4297 return Context.getConstantArrayType(ElementType, Size,
4298 ASM, IndexTypeQuals);
4299 }
4300
4301 case TYPE_INCOMPLETE_ARRAY: {
4302 QualType ElementType = readType(*Loc.F, Record, Idx);
4303 ArrayType::ArraySizeModifier ASM = (ArrayType::ArraySizeModifier)Record[1];
4304 unsigned IndexTypeQuals = Record[2];
4305 return Context.getIncompleteArrayType(ElementType, ASM, IndexTypeQuals);
4306 }
4307
4308 case TYPE_VARIABLE_ARRAY: {
4309 QualType ElementType = readType(*Loc.F, Record, Idx);
4310 ArrayType::ArraySizeModifier ASM = (ArrayType::ArraySizeModifier)Record[1];
4311 unsigned IndexTypeQuals = Record[2];
4312 SourceLocation LBLoc = ReadSourceLocation(*Loc.F, Record[3]);
4313 SourceLocation RBLoc = ReadSourceLocation(*Loc.F, Record[4]);
4314 return Context.getVariableArrayType(ElementType, ReadExpr(*Loc.F),
4315 ASM, IndexTypeQuals,
4316 SourceRange(LBLoc, RBLoc));
4317 }
4318
4319 case TYPE_VECTOR: {
4320 if (Record.size() != 3) {
4321 Error("incorrect encoding of vector type in AST file");
4322 return QualType();
4323 }
4324
4325 QualType ElementType = readType(*Loc.F, Record, Idx);
4326 unsigned NumElements = Record[1];
4327 unsigned VecKind = Record[2];
4328 return Context.getVectorType(ElementType, NumElements,
4329 (VectorType::VectorKind)VecKind);
4330 }
4331
4332 case TYPE_EXT_VECTOR: {
4333 if (Record.size() != 3) {
4334 Error("incorrect encoding of extended vector type in AST file");
4335 return QualType();
4336 }
4337
4338 QualType ElementType = readType(*Loc.F, Record, Idx);
4339 unsigned NumElements = Record[1];
4340 return Context.getExtVectorType(ElementType, NumElements);
4341 }
4342
4343 case TYPE_FUNCTION_NO_PROTO: {
4344 if (Record.size() != 6) {
4345 Error("incorrect encoding of no-proto function type");
4346 return QualType();
4347 }
4348 QualType ResultType = readType(*Loc.F, Record, Idx);
4349 FunctionType::ExtInfo Info(Record[1], Record[2], Record[3],
4350 (CallingConv)Record[4], Record[5]);
4351 return Context.getFunctionNoProtoType(ResultType, Info);
4352 }
4353
4354 case TYPE_FUNCTION_PROTO: {
4355 QualType ResultType = readType(*Loc.F, Record, Idx);
4356
4357 FunctionProtoType::ExtProtoInfo EPI;
4358 EPI.ExtInfo = FunctionType::ExtInfo(/*noreturn*/ Record[1],
4359 /*hasregparm*/ Record[2],
4360 /*regparm*/ Record[3],
4361 static_cast<CallingConv>(Record[4]),
4362 /*produces*/ Record[5]);
4363
4364 unsigned Idx = 6;
4365 unsigned NumParams = Record[Idx++];
4366 SmallVector<QualType, 16> ParamTypes;
4367 for (unsigned I = 0; I != NumParams; ++I)
4368 ParamTypes.push_back(readType(*Loc.F, Record, Idx));
4369
4370 EPI.Variadic = Record[Idx++];
4371 EPI.HasTrailingReturn = Record[Idx++];
4372 EPI.TypeQuals = Record[Idx++];
4373 EPI.RefQualifier = static_cast<RefQualifierKind>(Record[Idx++]);
4374 ExceptionSpecificationType EST =
4375 static_cast<ExceptionSpecificationType>(Record[Idx++]);
4376 EPI.ExceptionSpecType = EST;
4377 SmallVector<QualType, 2> Exceptions;
4378 if (EST == EST_Dynamic) {
4379 EPI.NumExceptions = Record[Idx++];
4380 for (unsigned I = 0; I != EPI.NumExceptions; ++I)
4381 Exceptions.push_back(readType(*Loc.F, Record, Idx));
4382 EPI.Exceptions = Exceptions.data();
4383 } else if (EST == EST_ComputedNoexcept) {
4384 EPI.NoexceptExpr = ReadExpr(*Loc.F);
4385 } else if (EST == EST_Uninstantiated) {
4386 EPI.ExceptionSpecDecl = ReadDeclAs<FunctionDecl>(*Loc.F, Record, Idx);
4387 EPI.ExceptionSpecTemplate = ReadDeclAs<FunctionDecl>(*Loc.F, Record, Idx);
4388 } else if (EST == EST_Unevaluated) {
4389 EPI.ExceptionSpecDecl = ReadDeclAs<FunctionDecl>(*Loc.F, Record, Idx);
4390 }
4391 return Context.getFunctionType(ResultType, ParamTypes.data(), NumParams,
4392 EPI);
4393 }
4394
4395 case TYPE_UNRESOLVED_USING: {
4396 unsigned Idx = 0;
4397 return Context.getTypeDeclType(
4398 ReadDeclAs<UnresolvedUsingTypenameDecl>(*Loc.F, Record, Idx));
4399 }
4400
4401 case TYPE_TYPEDEF: {
4402 if (Record.size() != 2) {
4403 Error("incorrect encoding of typedef type");
4404 return QualType();
4405 }
4406 unsigned Idx = 0;
4407 TypedefNameDecl *Decl = ReadDeclAs<TypedefNameDecl>(*Loc.F, Record, Idx);
4408 QualType Canonical = readType(*Loc.F, Record, Idx);
4409 if (!Canonical.isNull())
4410 Canonical = Context.getCanonicalType(Canonical);
4411 return Context.getTypedefType(Decl, Canonical);
4412 }
4413
4414 case TYPE_TYPEOF_EXPR:
4415 return Context.getTypeOfExprType(ReadExpr(*Loc.F));
4416
4417 case TYPE_TYPEOF: {
4418 if (Record.size() != 1) {
4419 Error("incorrect encoding of typeof(type) in AST file");
4420 return QualType();
4421 }
4422 QualType UnderlyingType = readType(*Loc.F, Record, Idx);
4423 return Context.getTypeOfType(UnderlyingType);
4424 }
4425
4426 case TYPE_DECLTYPE: {
4427 QualType UnderlyingType = readType(*Loc.F, Record, Idx);
4428 return Context.getDecltypeType(ReadExpr(*Loc.F), UnderlyingType);
4429 }
4430
4431 case TYPE_UNARY_TRANSFORM: {
4432 QualType BaseType = readType(*Loc.F, Record, Idx);
4433 QualType UnderlyingType = readType(*Loc.F, Record, Idx);
4434 UnaryTransformType::UTTKind UKind = (UnaryTransformType::UTTKind)Record[2];
4435 return Context.getUnaryTransformType(BaseType, UnderlyingType, UKind);
4436 }
4437
4438 case TYPE_AUTO:
4439 return Context.getAutoType(readType(*Loc.F, Record, Idx));
4440
4441 case TYPE_RECORD: {
4442 if (Record.size() != 2) {
4443 Error("incorrect encoding of record type");
4444 return QualType();
4445 }
4446 unsigned Idx = 0;
4447 bool IsDependent = Record[Idx++];
4448 RecordDecl *RD = ReadDeclAs<RecordDecl>(*Loc.F, Record, Idx);
4449 RD = cast_or_null<RecordDecl>(RD->getCanonicalDecl());
4450 QualType T = Context.getRecordType(RD);
4451 const_cast<Type*>(T.getTypePtr())->setDependent(IsDependent);
4452 return T;
4453 }
4454
4455 case TYPE_ENUM: {
4456 if (Record.size() != 2) {
4457 Error("incorrect encoding of enum type");
4458 return QualType();
4459 }
4460 unsigned Idx = 0;
4461 bool IsDependent = Record[Idx++];
4462 QualType T
4463 = Context.getEnumType(ReadDeclAs<EnumDecl>(*Loc.F, Record, Idx));
4464 const_cast<Type*>(T.getTypePtr())->setDependent(IsDependent);
4465 return T;
4466 }
4467
4468 case TYPE_ATTRIBUTED: {
4469 if (Record.size() != 3) {
4470 Error("incorrect encoding of attributed type");
4471 return QualType();
4472 }
4473 QualType modifiedType = readType(*Loc.F, Record, Idx);
4474 QualType equivalentType = readType(*Loc.F, Record, Idx);
4475 AttributedType::Kind kind = static_cast<AttributedType::Kind>(Record[2]);
4476 return Context.getAttributedType(kind, modifiedType, equivalentType);
4477 }
4478
4479 case TYPE_PAREN: {
4480 if (Record.size() != 1) {
4481 Error("incorrect encoding of paren type");
4482 return QualType();
4483 }
4484 QualType InnerType = readType(*Loc.F, Record, Idx);
4485 return Context.getParenType(InnerType);
4486 }
4487
4488 case TYPE_PACK_EXPANSION: {
4489 if (Record.size() != 2) {
4490 Error("incorrect encoding of pack expansion type");
4491 return QualType();
4492 }
4493 QualType Pattern = readType(*Loc.F, Record, Idx);
4494 if (Pattern.isNull())
4495 return QualType();
David Blaikiedc84cd52013-02-20 22:23:23 +00004496 Optional<unsigned> NumExpansions;
Guy Benyei7f92f2d2012-12-18 14:30:41 +00004497 if (Record[1])
4498 NumExpansions = Record[1] - 1;
4499 return Context.getPackExpansionType(Pattern, NumExpansions);
4500 }
4501
4502 case TYPE_ELABORATED: {
4503 unsigned Idx = 0;
4504 ElaboratedTypeKeyword Keyword = (ElaboratedTypeKeyword)Record[Idx++];
4505 NestedNameSpecifier *NNS = ReadNestedNameSpecifier(*Loc.F, Record, Idx);
4506 QualType NamedType = readType(*Loc.F, Record, Idx);
4507 return Context.getElaboratedType(Keyword, NNS, NamedType);
4508 }
4509
4510 case TYPE_OBJC_INTERFACE: {
4511 unsigned Idx = 0;
4512 ObjCInterfaceDecl *ItfD
4513 = ReadDeclAs<ObjCInterfaceDecl>(*Loc.F, Record, Idx);
4514 return Context.getObjCInterfaceType(ItfD->getCanonicalDecl());
4515 }
4516
4517 case TYPE_OBJC_OBJECT: {
4518 unsigned Idx = 0;
4519 QualType Base = readType(*Loc.F, Record, Idx);
4520 unsigned NumProtos = Record[Idx++];
4521 SmallVector<ObjCProtocolDecl*, 4> Protos;
4522 for (unsigned I = 0; I != NumProtos; ++I)
4523 Protos.push_back(ReadDeclAs<ObjCProtocolDecl>(*Loc.F, Record, Idx));
4524 return Context.getObjCObjectType(Base, Protos.data(), NumProtos);
4525 }
4526
4527 case TYPE_OBJC_OBJECT_POINTER: {
4528 unsigned Idx = 0;
4529 QualType Pointee = readType(*Loc.F, Record, Idx);
4530 return Context.getObjCObjectPointerType(Pointee);
4531 }
4532
4533 case TYPE_SUBST_TEMPLATE_TYPE_PARM: {
4534 unsigned Idx = 0;
4535 QualType Parm = readType(*Loc.F, Record, Idx);
4536 QualType Replacement = readType(*Loc.F, Record, Idx);
4537 return
4538 Context.getSubstTemplateTypeParmType(cast<TemplateTypeParmType>(Parm),
4539 Replacement);
4540 }
4541
4542 case TYPE_SUBST_TEMPLATE_TYPE_PARM_PACK: {
4543 unsigned Idx = 0;
4544 QualType Parm = readType(*Loc.F, Record, Idx);
4545 TemplateArgument ArgPack = ReadTemplateArgument(*Loc.F, Record, Idx);
4546 return Context.getSubstTemplateTypeParmPackType(
4547 cast<TemplateTypeParmType>(Parm),
4548 ArgPack);
4549 }
4550
4551 case TYPE_INJECTED_CLASS_NAME: {
4552 CXXRecordDecl *D = ReadDeclAs<CXXRecordDecl>(*Loc.F, Record, Idx);
4553 QualType TST = readType(*Loc.F, Record, Idx); // probably derivable
4554 // FIXME: ASTContext::getInjectedClassNameType is not currently suitable
4555 // for AST reading, too much interdependencies.
4556 return
4557 QualType(new (Context, TypeAlignment) InjectedClassNameType(D, TST), 0);
4558 }
4559
4560 case TYPE_TEMPLATE_TYPE_PARM: {
4561 unsigned Idx = 0;
4562 unsigned Depth = Record[Idx++];
4563 unsigned Index = Record[Idx++];
4564 bool Pack = Record[Idx++];
4565 TemplateTypeParmDecl *D
4566 = ReadDeclAs<TemplateTypeParmDecl>(*Loc.F, Record, Idx);
4567 return Context.getTemplateTypeParmType(Depth, Index, Pack, D);
4568 }
4569
4570 case TYPE_DEPENDENT_NAME: {
4571 unsigned Idx = 0;
4572 ElaboratedTypeKeyword Keyword = (ElaboratedTypeKeyword)Record[Idx++];
4573 NestedNameSpecifier *NNS = ReadNestedNameSpecifier(*Loc.F, Record, Idx);
4574 const IdentifierInfo *Name = this->GetIdentifierInfo(*Loc.F, Record, Idx);
4575 QualType Canon = readType(*Loc.F, Record, Idx);
4576 if (!Canon.isNull())
4577 Canon = Context.getCanonicalType(Canon);
4578 return Context.getDependentNameType(Keyword, NNS, Name, Canon);
4579 }
4580
4581 case TYPE_DEPENDENT_TEMPLATE_SPECIALIZATION: {
4582 unsigned Idx = 0;
4583 ElaboratedTypeKeyword Keyword = (ElaboratedTypeKeyword)Record[Idx++];
4584 NestedNameSpecifier *NNS = ReadNestedNameSpecifier(*Loc.F, Record, Idx);
4585 const IdentifierInfo *Name = this->GetIdentifierInfo(*Loc.F, Record, Idx);
4586 unsigned NumArgs = Record[Idx++];
4587 SmallVector<TemplateArgument, 8> Args;
4588 Args.reserve(NumArgs);
4589 while (NumArgs--)
4590 Args.push_back(ReadTemplateArgument(*Loc.F, Record, Idx));
4591 return Context.getDependentTemplateSpecializationType(Keyword, NNS, Name,
4592 Args.size(), Args.data());
4593 }
4594
4595 case TYPE_DEPENDENT_SIZED_ARRAY: {
4596 unsigned Idx = 0;
4597
4598 // ArrayType
4599 QualType ElementType = readType(*Loc.F, Record, Idx);
4600 ArrayType::ArraySizeModifier ASM
4601 = (ArrayType::ArraySizeModifier)Record[Idx++];
4602 unsigned IndexTypeQuals = Record[Idx++];
4603
4604 // DependentSizedArrayType
4605 Expr *NumElts = ReadExpr(*Loc.F);
4606 SourceRange Brackets = ReadSourceRange(*Loc.F, Record, Idx);
4607
4608 return Context.getDependentSizedArrayType(ElementType, NumElts, ASM,
4609 IndexTypeQuals, Brackets);
4610 }
4611
4612 case TYPE_TEMPLATE_SPECIALIZATION: {
4613 unsigned Idx = 0;
4614 bool IsDependent = Record[Idx++];
4615 TemplateName Name = ReadTemplateName(*Loc.F, Record, Idx);
4616 SmallVector<TemplateArgument, 8> Args;
4617 ReadTemplateArgumentList(Args, *Loc.F, Record, Idx);
4618 QualType Underlying = readType(*Loc.F, Record, Idx);
4619 QualType T;
4620 if (Underlying.isNull())
4621 T = Context.getCanonicalTemplateSpecializationType(Name, Args.data(),
4622 Args.size());
4623 else
4624 T = Context.getTemplateSpecializationType(Name, Args.data(),
4625 Args.size(), Underlying);
4626 const_cast<Type*>(T.getTypePtr())->setDependent(IsDependent);
4627 return T;
4628 }
4629
4630 case TYPE_ATOMIC: {
4631 if (Record.size() != 1) {
4632 Error("Incorrect encoding of atomic type");
4633 return QualType();
4634 }
4635 QualType ValueType = readType(*Loc.F, Record, Idx);
4636 return Context.getAtomicType(ValueType);
4637 }
4638 }
4639 llvm_unreachable("Invalid TypeCode!");
4640}
4641
4642class clang::TypeLocReader : public TypeLocVisitor<TypeLocReader> {
4643 ASTReader &Reader;
4644 ModuleFile &F;
4645 const ASTReader::RecordData &Record;
4646 unsigned &Idx;
4647
4648 SourceLocation ReadSourceLocation(const ASTReader::RecordData &R,
4649 unsigned &I) {
4650 return Reader.ReadSourceLocation(F, R, I);
4651 }
4652
4653 template<typename T>
4654 T *ReadDeclAs(const ASTReader::RecordData &Record, unsigned &Idx) {
4655 return Reader.ReadDeclAs<T>(F, Record, Idx);
4656 }
4657
4658public:
4659 TypeLocReader(ASTReader &Reader, ModuleFile &F,
4660 const ASTReader::RecordData &Record, unsigned &Idx)
4661 : Reader(Reader), F(F), Record(Record), Idx(Idx)
4662 { }
4663
4664 // We want compile-time assurance that we've enumerated all of
4665 // these, so unfortunately we have to declare them first, then
4666 // define them out-of-line.
4667#define ABSTRACT_TYPELOC(CLASS, PARENT)
4668#define TYPELOC(CLASS, PARENT) \
4669 void Visit##CLASS##TypeLoc(CLASS##TypeLoc TyLoc);
4670#include "clang/AST/TypeLocNodes.def"
4671
4672 void VisitFunctionTypeLoc(FunctionTypeLoc);
4673 void VisitArrayTypeLoc(ArrayTypeLoc);
4674};
4675
4676void TypeLocReader::VisitQualifiedTypeLoc(QualifiedTypeLoc TL) {
4677 // nothing to do
4678}
4679void TypeLocReader::VisitBuiltinTypeLoc(BuiltinTypeLoc TL) {
4680 TL.setBuiltinLoc(ReadSourceLocation(Record, Idx));
4681 if (TL.needsExtraLocalData()) {
4682 TL.setWrittenTypeSpec(static_cast<DeclSpec::TST>(Record[Idx++]));
4683 TL.setWrittenSignSpec(static_cast<DeclSpec::TSS>(Record[Idx++]));
4684 TL.setWrittenWidthSpec(static_cast<DeclSpec::TSW>(Record[Idx++]));
4685 TL.setModeAttr(Record[Idx++]);
4686 }
4687}
4688void TypeLocReader::VisitComplexTypeLoc(ComplexTypeLoc TL) {
4689 TL.setNameLoc(ReadSourceLocation(Record, Idx));
4690}
4691void TypeLocReader::VisitPointerTypeLoc(PointerTypeLoc TL) {
4692 TL.setStarLoc(ReadSourceLocation(Record, Idx));
4693}
4694void TypeLocReader::VisitBlockPointerTypeLoc(BlockPointerTypeLoc TL) {
4695 TL.setCaretLoc(ReadSourceLocation(Record, Idx));
4696}
4697void TypeLocReader::VisitLValueReferenceTypeLoc(LValueReferenceTypeLoc TL) {
4698 TL.setAmpLoc(ReadSourceLocation(Record, Idx));
4699}
4700void TypeLocReader::VisitRValueReferenceTypeLoc(RValueReferenceTypeLoc TL) {
4701 TL.setAmpAmpLoc(ReadSourceLocation(Record, Idx));
4702}
4703void TypeLocReader::VisitMemberPointerTypeLoc(MemberPointerTypeLoc TL) {
4704 TL.setStarLoc(ReadSourceLocation(Record, Idx));
4705 TL.setClassTInfo(Reader.GetTypeSourceInfo(F, Record, Idx));
4706}
4707void TypeLocReader::VisitArrayTypeLoc(ArrayTypeLoc TL) {
4708 TL.setLBracketLoc(ReadSourceLocation(Record, Idx));
4709 TL.setRBracketLoc(ReadSourceLocation(Record, Idx));
4710 if (Record[Idx++])
4711 TL.setSizeExpr(Reader.ReadExpr(F));
4712 else
4713 TL.setSizeExpr(0);
4714}
4715void TypeLocReader::VisitConstantArrayTypeLoc(ConstantArrayTypeLoc TL) {
4716 VisitArrayTypeLoc(TL);
4717}
4718void TypeLocReader::VisitIncompleteArrayTypeLoc(IncompleteArrayTypeLoc TL) {
4719 VisitArrayTypeLoc(TL);
4720}
4721void TypeLocReader::VisitVariableArrayTypeLoc(VariableArrayTypeLoc TL) {
4722 VisitArrayTypeLoc(TL);
4723}
4724void TypeLocReader::VisitDependentSizedArrayTypeLoc(
4725 DependentSizedArrayTypeLoc TL) {
4726 VisitArrayTypeLoc(TL);
4727}
4728void TypeLocReader::VisitDependentSizedExtVectorTypeLoc(
4729 DependentSizedExtVectorTypeLoc TL) {
4730 TL.setNameLoc(ReadSourceLocation(Record, Idx));
4731}
4732void TypeLocReader::VisitVectorTypeLoc(VectorTypeLoc TL) {
4733 TL.setNameLoc(ReadSourceLocation(Record, Idx));
4734}
4735void TypeLocReader::VisitExtVectorTypeLoc(ExtVectorTypeLoc TL) {
4736 TL.setNameLoc(ReadSourceLocation(Record, Idx));
4737}
4738void TypeLocReader::VisitFunctionTypeLoc(FunctionTypeLoc TL) {
4739 TL.setLocalRangeBegin(ReadSourceLocation(Record, Idx));
4740 TL.setLParenLoc(ReadSourceLocation(Record, Idx));
4741 TL.setRParenLoc(ReadSourceLocation(Record, Idx));
4742 TL.setLocalRangeEnd(ReadSourceLocation(Record, Idx));
4743 for (unsigned i = 0, e = TL.getNumArgs(); i != e; ++i) {
4744 TL.setArg(i, ReadDeclAs<ParmVarDecl>(Record, Idx));
4745 }
4746}
4747void TypeLocReader::VisitFunctionProtoTypeLoc(FunctionProtoTypeLoc TL) {
4748 VisitFunctionTypeLoc(TL);
4749}
4750void TypeLocReader::VisitFunctionNoProtoTypeLoc(FunctionNoProtoTypeLoc TL) {
4751 VisitFunctionTypeLoc(TL);
4752}
4753void TypeLocReader::VisitUnresolvedUsingTypeLoc(UnresolvedUsingTypeLoc TL) {
4754 TL.setNameLoc(ReadSourceLocation(Record, Idx));
4755}
4756void TypeLocReader::VisitTypedefTypeLoc(TypedefTypeLoc TL) {
4757 TL.setNameLoc(ReadSourceLocation(Record, Idx));
4758}
4759void TypeLocReader::VisitTypeOfExprTypeLoc(TypeOfExprTypeLoc TL) {
4760 TL.setTypeofLoc(ReadSourceLocation(Record, Idx));
4761 TL.setLParenLoc(ReadSourceLocation(Record, Idx));
4762 TL.setRParenLoc(ReadSourceLocation(Record, Idx));
4763}
4764void TypeLocReader::VisitTypeOfTypeLoc(TypeOfTypeLoc TL) {
4765 TL.setTypeofLoc(ReadSourceLocation(Record, Idx));
4766 TL.setLParenLoc(ReadSourceLocation(Record, Idx));
4767 TL.setRParenLoc(ReadSourceLocation(Record, Idx));
4768 TL.setUnderlyingTInfo(Reader.GetTypeSourceInfo(F, Record, Idx));
4769}
4770void TypeLocReader::VisitDecltypeTypeLoc(DecltypeTypeLoc TL) {
4771 TL.setNameLoc(ReadSourceLocation(Record, Idx));
4772}
4773void TypeLocReader::VisitUnaryTransformTypeLoc(UnaryTransformTypeLoc TL) {
4774 TL.setKWLoc(ReadSourceLocation(Record, Idx));
4775 TL.setLParenLoc(ReadSourceLocation(Record, Idx));
4776 TL.setRParenLoc(ReadSourceLocation(Record, Idx));
4777 TL.setUnderlyingTInfo(Reader.GetTypeSourceInfo(F, Record, Idx));
4778}
4779void TypeLocReader::VisitAutoTypeLoc(AutoTypeLoc TL) {
4780 TL.setNameLoc(ReadSourceLocation(Record, Idx));
4781}
4782void TypeLocReader::VisitRecordTypeLoc(RecordTypeLoc TL) {
4783 TL.setNameLoc(ReadSourceLocation(Record, Idx));
4784}
4785void TypeLocReader::VisitEnumTypeLoc(EnumTypeLoc TL) {
4786 TL.setNameLoc(ReadSourceLocation(Record, Idx));
4787}
4788void TypeLocReader::VisitAttributedTypeLoc(AttributedTypeLoc TL) {
4789 TL.setAttrNameLoc(ReadSourceLocation(Record, Idx));
4790 if (TL.hasAttrOperand()) {
4791 SourceRange range;
4792 range.setBegin(ReadSourceLocation(Record, Idx));
4793 range.setEnd(ReadSourceLocation(Record, Idx));
4794 TL.setAttrOperandParensRange(range);
4795 }
4796 if (TL.hasAttrExprOperand()) {
4797 if (Record[Idx++])
4798 TL.setAttrExprOperand(Reader.ReadExpr(F));
4799 else
4800 TL.setAttrExprOperand(0);
4801 } else if (TL.hasAttrEnumOperand())
4802 TL.setAttrEnumOperandLoc(ReadSourceLocation(Record, Idx));
4803}
4804void TypeLocReader::VisitTemplateTypeParmTypeLoc(TemplateTypeParmTypeLoc TL) {
4805 TL.setNameLoc(ReadSourceLocation(Record, Idx));
4806}
4807void TypeLocReader::VisitSubstTemplateTypeParmTypeLoc(
4808 SubstTemplateTypeParmTypeLoc TL) {
4809 TL.setNameLoc(ReadSourceLocation(Record, Idx));
4810}
4811void TypeLocReader::VisitSubstTemplateTypeParmPackTypeLoc(
4812 SubstTemplateTypeParmPackTypeLoc TL) {
4813 TL.setNameLoc(ReadSourceLocation(Record, Idx));
4814}
4815void TypeLocReader::VisitTemplateSpecializationTypeLoc(
4816 TemplateSpecializationTypeLoc TL) {
4817 TL.setTemplateKeywordLoc(ReadSourceLocation(Record, Idx));
4818 TL.setTemplateNameLoc(ReadSourceLocation(Record, Idx));
4819 TL.setLAngleLoc(ReadSourceLocation(Record, Idx));
4820 TL.setRAngleLoc(ReadSourceLocation(Record, Idx));
4821 for (unsigned i = 0, e = TL.getNumArgs(); i != e; ++i)
4822 TL.setArgLocInfo(i,
4823 Reader.GetTemplateArgumentLocInfo(F,
4824 TL.getTypePtr()->getArg(i).getKind(),
4825 Record, Idx));
4826}
4827void TypeLocReader::VisitParenTypeLoc(ParenTypeLoc TL) {
4828 TL.setLParenLoc(ReadSourceLocation(Record, Idx));
4829 TL.setRParenLoc(ReadSourceLocation(Record, Idx));
4830}
4831void TypeLocReader::VisitElaboratedTypeLoc(ElaboratedTypeLoc TL) {
4832 TL.setElaboratedKeywordLoc(ReadSourceLocation(Record, Idx));
4833 TL.setQualifierLoc(Reader.ReadNestedNameSpecifierLoc(F, Record, Idx));
4834}
4835void TypeLocReader::VisitInjectedClassNameTypeLoc(InjectedClassNameTypeLoc TL) {
4836 TL.setNameLoc(ReadSourceLocation(Record, Idx));
4837}
4838void TypeLocReader::VisitDependentNameTypeLoc(DependentNameTypeLoc TL) {
4839 TL.setElaboratedKeywordLoc(ReadSourceLocation(Record, Idx));
4840 TL.setQualifierLoc(Reader.ReadNestedNameSpecifierLoc(F, Record, Idx));
4841 TL.setNameLoc(ReadSourceLocation(Record, Idx));
4842}
4843void TypeLocReader::VisitDependentTemplateSpecializationTypeLoc(
4844 DependentTemplateSpecializationTypeLoc TL) {
4845 TL.setElaboratedKeywordLoc(ReadSourceLocation(Record, Idx));
4846 TL.setQualifierLoc(Reader.ReadNestedNameSpecifierLoc(F, Record, Idx));
4847 TL.setTemplateKeywordLoc(ReadSourceLocation(Record, Idx));
4848 TL.setTemplateNameLoc(ReadSourceLocation(Record, Idx));
4849 TL.setLAngleLoc(ReadSourceLocation(Record, Idx));
4850 TL.setRAngleLoc(ReadSourceLocation(Record, Idx));
4851 for (unsigned I = 0, E = TL.getNumArgs(); I != E; ++I)
4852 TL.setArgLocInfo(I,
4853 Reader.GetTemplateArgumentLocInfo(F,
4854 TL.getTypePtr()->getArg(I).getKind(),
4855 Record, Idx));
4856}
4857void TypeLocReader::VisitPackExpansionTypeLoc(PackExpansionTypeLoc TL) {
4858 TL.setEllipsisLoc(ReadSourceLocation(Record, Idx));
4859}
4860void TypeLocReader::VisitObjCInterfaceTypeLoc(ObjCInterfaceTypeLoc TL) {
4861 TL.setNameLoc(ReadSourceLocation(Record, Idx));
4862}
4863void TypeLocReader::VisitObjCObjectTypeLoc(ObjCObjectTypeLoc TL) {
4864 TL.setHasBaseTypeAsWritten(Record[Idx++]);
4865 TL.setLAngleLoc(ReadSourceLocation(Record, Idx));
4866 TL.setRAngleLoc(ReadSourceLocation(Record, Idx));
4867 for (unsigned i = 0, e = TL.getNumProtocols(); i != e; ++i)
4868 TL.setProtocolLoc(i, ReadSourceLocation(Record, Idx));
4869}
4870void TypeLocReader::VisitObjCObjectPointerTypeLoc(ObjCObjectPointerTypeLoc TL) {
4871 TL.setStarLoc(ReadSourceLocation(Record, Idx));
4872}
4873void TypeLocReader::VisitAtomicTypeLoc(AtomicTypeLoc TL) {
4874 TL.setKWLoc(ReadSourceLocation(Record, Idx));
4875 TL.setLParenLoc(ReadSourceLocation(Record, Idx));
4876 TL.setRParenLoc(ReadSourceLocation(Record, Idx));
4877}
4878
4879TypeSourceInfo *ASTReader::GetTypeSourceInfo(ModuleFile &F,
4880 const RecordData &Record,
4881 unsigned &Idx) {
4882 QualType InfoTy = readType(F, Record, Idx);
4883 if (InfoTy.isNull())
4884 return 0;
4885
4886 TypeSourceInfo *TInfo = getContext().CreateTypeSourceInfo(InfoTy);
4887 TypeLocReader TLR(*this, F, Record, Idx);
4888 for (TypeLoc TL = TInfo->getTypeLoc(); !TL.isNull(); TL = TL.getNextTypeLoc())
4889 TLR.Visit(TL);
4890 return TInfo;
4891}
4892
4893QualType ASTReader::GetType(TypeID ID) {
4894 unsigned FastQuals = ID & Qualifiers::FastMask;
4895 unsigned Index = ID >> Qualifiers::FastWidth;
4896
4897 if (Index < NUM_PREDEF_TYPE_IDS) {
4898 QualType T;
4899 switch ((PredefinedTypeIDs)Index) {
4900 case PREDEF_TYPE_NULL_ID: return QualType();
4901 case PREDEF_TYPE_VOID_ID: T = Context.VoidTy; break;
4902 case PREDEF_TYPE_BOOL_ID: T = Context.BoolTy; break;
4903
4904 case PREDEF_TYPE_CHAR_U_ID:
4905 case PREDEF_TYPE_CHAR_S_ID:
4906 // FIXME: Check that the signedness of CharTy is correct!
4907 T = Context.CharTy;
4908 break;
4909
4910 case PREDEF_TYPE_UCHAR_ID: T = Context.UnsignedCharTy; break;
4911 case PREDEF_TYPE_USHORT_ID: T = Context.UnsignedShortTy; break;
4912 case PREDEF_TYPE_UINT_ID: T = Context.UnsignedIntTy; break;
4913 case PREDEF_TYPE_ULONG_ID: T = Context.UnsignedLongTy; break;
4914 case PREDEF_TYPE_ULONGLONG_ID: T = Context.UnsignedLongLongTy; break;
4915 case PREDEF_TYPE_UINT128_ID: T = Context.UnsignedInt128Ty; break;
4916 case PREDEF_TYPE_SCHAR_ID: T = Context.SignedCharTy; break;
4917 case PREDEF_TYPE_WCHAR_ID: T = Context.WCharTy; break;
4918 case PREDEF_TYPE_SHORT_ID: T = Context.ShortTy; break;
4919 case PREDEF_TYPE_INT_ID: T = Context.IntTy; break;
4920 case PREDEF_TYPE_LONG_ID: T = Context.LongTy; break;
4921 case PREDEF_TYPE_LONGLONG_ID: T = Context.LongLongTy; break;
4922 case PREDEF_TYPE_INT128_ID: T = Context.Int128Ty; break;
4923 case PREDEF_TYPE_HALF_ID: T = Context.HalfTy; break;
4924 case PREDEF_TYPE_FLOAT_ID: T = Context.FloatTy; break;
4925 case PREDEF_TYPE_DOUBLE_ID: T = Context.DoubleTy; break;
4926 case PREDEF_TYPE_LONGDOUBLE_ID: T = Context.LongDoubleTy; break;
4927 case PREDEF_TYPE_OVERLOAD_ID: T = Context.OverloadTy; break;
4928 case PREDEF_TYPE_BOUND_MEMBER: T = Context.BoundMemberTy; break;
4929 case PREDEF_TYPE_PSEUDO_OBJECT: T = Context.PseudoObjectTy; break;
4930 case PREDEF_TYPE_DEPENDENT_ID: T = Context.DependentTy; break;
4931 case PREDEF_TYPE_UNKNOWN_ANY: T = Context.UnknownAnyTy; break;
4932 case PREDEF_TYPE_NULLPTR_ID: T = Context.NullPtrTy; break;
4933 case PREDEF_TYPE_CHAR16_ID: T = Context.Char16Ty; break;
4934 case PREDEF_TYPE_CHAR32_ID: T = Context.Char32Ty; break;
4935 case PREDEF_TYPE_OBJC_ID: T = Context.ObjCBuiltinIdTy; break;
4936 case PREDEF_TYPE_OBJC_CLASS: T = Context.ObjCBuiltinClassTy; break;
4937 case PREDEF_TYPE_OBJC_SEL: T = Context.ObjCBuiltinSelTy; break;
Guy Benyeib13621d2012-12-18 14:38:23 +00004938 case PREDEF_TYPE_IMAGE1D_ID: T = Context.OCLImage1dTy; break;
4939 case PREDEF_TYPE_IMAGE1D_ARR_ID: T = Context.OCLImage1dArrayTy; break;
4940 case PREDEF_TYPE_IMAGE1D_BUFF_ID: T = Context.OCLImage1dBufferTy; break;
4941 case PREDEF_TYPE_IMAGE2D_ID: T = Context.OCLImage2dTy; break;
4942 case PREDEF_TYPE_IMAGE2D_ARR_ID: T = Context.OCLImage2dArrayTy; break;
4943 case PREDEF_TYPE_IMAGE3D_ID: T = Context.OCLImage3dTy; break;
Guy Benyei21f18c42013-02-07 10:55:47 +00004944 case PREDEF_TYPE_SAMPLER_ID: T = Context.OCLSamplerTy; break;
Guy Benyeie6b9d802013-01-20 12:31:11 +00004945 case PREDEF_TYPE_EVENT_ID: T = Context.OCLEventTy; break;
Guy Benyei7f92f2d2012-12-18 14:30:41 +00004946 case PREDEF_TYPE_AUTO_DEDUCT: T = Context.getAutoDeductType(); break;
4947
4948 case PREDEF_TYPE_AUTO_RREF_DEDUCT:
4949 T = Context.getAutoRRefDeductType();
4950 break;
4951
4952 case PREDEF_TYPE_ARC_UNBRIDGED_CAST:
4953 T = Context.ARCUnbridgedCastTy;
4954 break;
4955
4956 case PREDEF_TYPE_VA_LIST_TAG:
4957 T = Context.getVaListTagType();
4958 break;
4959
4960 case PREDEF_TYPE_BUILTIN_FN:
4961 T = Context.BuiltinFnTy;
4962 break;
4963 }
4964
4965 assert(!T.isNull() && "Unknown predefined type");
4966 return T.withFastQualifiers(FastQuals);
4967 }
4968
4969 Index -= NUM_PREDEF_TYPE_IDS;
4970 assert(Index < TypesLoaded.size() && "Type index out-of-range");
4971 if (TypesLoaded[Index].isNull()) {
4972 TypesLoaded[Index] = readTypeRecord(Index);
4973 if (TypesLoaded[Index].isNull())
4974 return QualType();
4975
4976 TypesLoaded[Index]->setFromAST();
4977 if (DeserializationListener)
4978 DeserializationListener->TypeRead(TypeIdx::fromTypeID(ID),
4979 TypesLoaded[Index]);
4980 }
4981
4982 return TypesLoaded[Index].withFastQualifiers(FastQuals);
4983}
4984
4985QualType ASTReader::getLocalType(ModuleFile &F, unsigned LocalID) {
4986 return GetType(getGlobalTypeID(F, LocalID));
4987}
4988
4989serialization::TypeID
4990ASTReader::getGlobalTypeID(ModuleFile &F, unsigned LocalID) const {
4991 unsigned FastQuals = LocalID & Qualifiers::FastMask;
4992 unsigned LocalIndex = LocalID >> Qualifiers::FastWidth;
4993
4994 if (LocalIndex < NUM_PREDEF_TYPE_IDS)
4995 return LocalID;
4996
4997 ContinuousRangeMap<uint32_t, int, 2>::iterator I
4998 = F.TypeRemap.find(LocalIndex - NUM_PREDEF_TYPE_IDS);
4999 assert(I != F.TypeRemap.end() && "Invalid index into type index remap");
5000
5001 unsigned GlobalIndex = LocalIndex + I->second;
5002 return (GlobalIndex << Qualifiers::FastWidth) | FastQuals;
5003}
5004
5005TemplateArgumentLocInfo
5006ASTReader::GetTemplateArgumentLocInfo(ModuleFile &F,
5007 TemplateArgument::ArgKind Kind,
5008 const RecordData &Record,
5009 unsigned &Index) {
5010 switch (Kind) {
5011 case TemplateArgument::Expression:
5012 return ReadExpr(F);
5013 case TemplateArgument::Type:
5014 return GetTypeSourceInfo(F, Record, Index);
5015 case TemplateArgument::Template: {
5016 NestedNameSpecifierLoc QualifierLoc = ReadNestedNameSpecifierLoc(F, Record,
5017 Index);
5018 SourceLocation TemplateNameLoc = ReadSourceLocation(F, Record, Index);
5019 return TemplateArgumentLocInfo(QualifierLoc, TemplateNameLoc,
5020 SourceLocation());
5021 }
5022 case TemplateArgument::TemplateExpansion: {
5023 NestedNameSpecifierLoc QualifierLoc = ReadNestedNameSpecifierLoc(F, Record,
5024 Index);
5025 SourceLocation TemplateNameLoc = ReadSourceLocation(F, Record, Index);
5026 SourceLocation EllipsisLoc = ReadSourceLocation(F, Record, Index);
5027 return TemplateArgumentLocInfo(QualifierLoc, TemplateNameLoc,
5028 EllipsisLoc);
5029 }
5030 case TemplateArgument::Null:
5031 case TemplateArgument::Integral:
5032 case TemplateArgument::Declaration:
5033 case TemplateArgument::NullPtr:
5034 case TemplateArgument::Pack:
5035 // FIXME: Is this right?
5036 return TemplateArgumentLocInfo();
5037 }
5038 llvm_unreachable("unexpected template argument loc");
5039}
5040
5041TemplateArgumentLoc
5042ASTReader::ReadTemplateArgumentLoc(ModuleFile &F,
5043 const RecordData &Record, unsigned &Index) {
5044 TemplateArgument Arg = ReadTemplateArgument(F, Record, Index);
5045
5046 if (Arg.getKind() == TemplateArgument::Expression) {
5047 if (Record[Index++]) // bool InfoHasSameExpr.
5048 return TemplateArgumentLoc(Arg, TemplateArgumentLocInfo(Arg.getAsExpr()));
5049 }
5050 return TemplateArgumentLoc(Arg, GetTemplateArgumentLocInfo(F, Arg.getKind(),
5051 Record, Index));
5052}
5053
5054Decl *ASTReader::GetExternalDecl(uint32_t ID) {
5055 return GetDecl(ID);
5056}
5057
5058uint64_t ASTReader::readCXXBaseSpecifiers(ModuleFile &M, const RecordData &Record,
5059 unsigned &Idx){
5060 if (Idx >= Record.size())
5061 return 0;
5062
5063 unsigned LocalID = Record[Idx++];
5064 return getGlobalBitOffset(M, M.CXXBaseSpecifiersOffsets[LocalID - 1]);
5065}
5066
5067CXXBaseSpecifier *ASTReader::GetExternalCXXBaseSpecifiers(uint64_t Offset) {
5068 RecordLocation Loc = getLocalBitOffset(Offset);
Chris Lattner8f9a1eb2013-01-20 00:56:42 +00005069 BitstreamCursor &Cursor = Loc.F->DeclsCursor;
Guy Benyei7f92f2d2012-12-18 14:30:41 +00005070 SavedStreamPosition SavedPosition(Cursor);
5071 Cursor.JumpToBit(Loc.Offset);
5072 ReadingKindTracker ReadingKind(Read_Decl, *this);
5073 RecordData Record;
5074 unsigned Code = Cursor.ReadCode();
Chris Lattnerb3ce3572013-01-20 02:38:54 +00005075 unsigned RecCode = Cursor.readRecord(Code, Record);
Guy Benyei7f92f2d2012-12-18 14:30:41 +00005076 if (RecCode != DECL_CXX_BASE_SPECIFIERS) {
5077 Error("Malformed AST file: missing C++ base specifiers");
5078 return 0;
5079 }
5080
5081 unsigned Idx = 0;
5082 unsigned NumBases = Record[Idx++];
5083 void *Mem = Context.Allocate(sizeof(CXXBaseSpecifier) * NumBases);
5084 CXXBaseSpecifier *Bases = new (Mem) CXXBaseSpecifier [NumBases];
5085 for (unsigned I = 0; I != NumBases; ++I)
5086 Bases[I] = ReadCXXBaseSpecifier(*Loc.F, Record, Idx);
5087 return Bases;
5088}
5089
5090serialization::DeclID
5091ASTReader::getGlobalDeclID(ModuleFile &F, LocalDeclID LocalID) const {
5092 if (LocalID < NUM_PREDEF_DECL_IDS)
5093 return LocalID;
5094
5095 ContinuousRangeMap<uint32_t, int, 2>::iterator I
5096 = F.DeclRemap.find(LocalID - NUM_PREDEF_DECL_IDS);
5097 assert(I != F.DeclRemap.end() && "Invalid index into decl index remap");
5098
5099 return LocalID + I->second;
5100}
5101
5102bool ASTReader::isDeclIDFromModule(serialization::GlobalDeclID ID,
5103 ModuleFile &M) const {
5104 GlobalDeclMapType::const_iterator I = GlobalDeclMap.find(ID);
5105 assert(I != GlobalDeclMap.end() && "Corrupted global declaration map");
5106 return &M == I->second;
5107}
5108
Douglas Gregor5a04f9f2013-01-21 15:25:38 +00005109ModuleFile *ASTReader::getOwningModuleFile(const Decl *D) {
Guy Benyei7f92f2d2012-12-18 14:30:41 +00005110 if (!D->isFromASTFile())
5111 return 0;
5112 GlobalDeclMapType::const_iterator I = GlobalDeclMap.find(D->getGlobalID());
5113 assert(I != GlobalDeclMap.end() && "Corrupted global declaration map");
5114 return I->second;
5115}
5116
5117SourceLocation ASTReader::getSourceLocationForDeclID(GlobalDeclID ID) {
5118 if (ID < NUM_PREDEF_DECL_IDS)
5119 return SourceLocation();
5120
5121 unsigned Index = ID - NUM_PREDEF_DECL_IDS;
5122
5123 if (Index > DeclsLoaded.size()) {
5124 Error("declaration ID out-of-range for AST file");
5125 return SourceLocation();
5126 }
5127
5128 if (Decl *D = DeclsLoaded[Index])
5129 return D->getLocation();
5130
5131 unsigned RawLocation = 0;
5132 RecordLocation Rec = DeclCursorForID(ID, RawLocation);
5133 return ReadSourceLocation(*Rec.F, RawLocation);
5134}
5135
5136Decl *ASTReader::GetDecl(DeclID ID) {
5137 if (ID < NUM_PREDEF_DECL_IDS) {
5138 switch ((PredefinedDeclIDs)ID) {
5139 case PREDEF_DECL_NULL_ID:
5140 return 0;
5141
5142 case PREDEF_DECL_TRANSLATION_UNIT_ID:
5143 return Context.getTranslationUnitDecl();
5144
5145 case PREDEF_DECL_OBJC_ID_ID:
5146 return Context.getObjCIdDecl();
5147
5148 case PREDEF_DECL_OBJC_SEL_ID:
5149 return Context.getObjCSelDecl();
5150
5151 case PREDEF_DECL_OBJC_CLASS_ID:
5152 return Context.getObjCClassDecl();
5153
5154 case PREDEF_DECL_OBJC_PROTOCOL_ID:
5155 return Context.getObjCProtocolDecl();
5156
5157 case PREDEF_DECL_INT_128_ID:
5158 return Context.getInt128Decl();
5159
5160 case PREDEF_DECL_UNSIGNED_INT_128_ID:
5161 return Context.getUInt128Decl();
5162
5163 case PREDEF_DECL_OBJC_INSTANCETYPE_ID:
5164 return Context.getObjCInstanceTypeDecl();
5165
5166 case PREDEF_DECL_BUILTIN_VA_LIST_ID:
5167 return Context.getBuiltinVaListDecl();
5168 }
5169 }
5170
5171 unsigned Index = ID - NUM_PREDEF_DECL_IDS;
5172
5173 if (Index >= DeclsLoaded.size()) {
5174 assert(0 && "declaration ID out-of-range for AST file");
5175 Error("declaration ID out-of-range for AST file");
5176 return 0;
5177 }
5178
5179 if (!DeclsLoaded[Index]) {
5180 ReadDeclRecord(ID);
5181 if (DeserializationListener)
5182 DeserializationListener->DeclRead(ID, DeclsLoaded[Index]);
5183 }
5184
5185 return DeclsLoaded[Index];
5186}
5187
5188DeclID ASTReader::mapGlobalIDToModuleFileGlobalID(ModuleFile &M,
5189 DeclID GlobalID) {
5190 if (GlobalID < NUM_PREDEF_DECL_IDS)
5191 return GlobalID;
5192
5193 GlobalDeclMapType::const_iterator I = GlobalDeclMap.find(GlobalID);
5194 assert(I != GlobalDeclMap.end() && "Corrupted global declaration map");
5195 ModuleFile *Owner = I->second;
5196
5197 llvm::DenseMap<ModuleFile *, serialization::DeclID>::iterator Pos
5198 = M.GlobalToLocalDeclIDs.find(Owner);
5199 if (Pos == M.GlobalToLocalDeclIDs.end())
5200 return 0;
5201
5202 return GlobalID - Owner->BaseDeclID + Pos->second;
5203}
5204
5205serialization::DeclID ASTReader::ReadDeclID(ModuleFile &F,
5206 const RecordData &Record,
5207 unsigned &Idx) {
5208 if (Idx >= Record.size()) {
5209 Error("Corrupted AST file");
5210 return 0;
5211 }
5212
5213 return getGlobalDeclID(F, Record[Idx++]);
5214}
5215
5216/// \brief Resolve the offset of a statement into a statement.
5217///
5218/// This operation will read a new statement from the external
5219/// source each time it is called, and is meant to be used via a
5220/// LazyOffsetPtr (which is used by Decls for the body of functions, etc).
5221Stmt *ASTReader::GetExternalDeclStmt(uint64_t Offset) {
5222 // Switch case IDs are per Decl.
5223 ClearSwitchCaseIDs();
5224
5225 // Offset here is a global offset across the entire chain.
5226 RecordLocation Loc = getLocalBitOffset(Offset);
5227 Loc.F->DeclsCursor.JumpToBit(Loc.Offset);
5228 return ReadStmtFromStream(*Loc.F);
5229}
5230
5231namespace {
5232 class FindExternalLexicalDeclsVisitor {
5233 ASTReader &Reader;
5234 const DeclContext *DC;
5235 bool (*isKindWeWant)(Decl::Kind);
5236
5237 SmallVectorImpl<Decl*> &Decls;
5238 bool PredefsVisited[NUM_PREDEF_DECL_IDS];
5239
5240 public:
5241 FindExternalLexicalDeclsVisitor(ASTReader &Reader, const DeclContext *DC,
5242 bool (*isKindWeWant)(Decl::Kind),
5243 SmallVectorImpl<Decl*> &Decls)
5244 : Reader(Reader), DC(DC), isKindWeWant(isKindWeWant), Decls(Decls)
5245 {
5246 for (unsigned I = 0; I != NUM_PREDEF_DECL_IDS; ++I)
5247 PredefsVisited[I] = false;
5248 }
5249
5250 static bool visit(ModuleFile &M, bool Preorder, void *UserData) {
5251 if (Preorder)
5252 return false;
5253
5254 FindExternalLexicalDeclsVisitor *This
5255 = static_cast<FindExternalLexicalDeclsVisitor *>(UserData);
5256
5257 ModuleFile::DeclContextInfosMap::iterator Info
5258 = M.DeclContextInfos.find(This->DC);
5259 if (Info == M.DeclContextInfos.end() || !Info->second.LexicalDecls)
5260 return false;
5261
5262 // Load all of the declaration IDs
5263 for (const KindDeclIDPair *ID = Info->second.LexicalDecls,
5264 *IDE = ID + Info->second.NumLexicalDecls;
5265 ID != IDE; ++ID) {
5266 if (This->isKindWeWant && !This->isKindWeWant((Decl::Kind)ID->first))
5267 continue;
5268
5269 // Don't add predefined declarations to the lexical context more
5270 // than once.
5271 if (ID->second < NUM_PREDEF_DECL_IDS) {
5272 if (This->PredefsVisited[ID->second])
5273 continue;
5274
5275 This->PredefsVisited[ID->second] = true;
5276 }
5277
5278 if (Decl *D = This->Reader.GetLocalDecl(M, ID->second)) {
5279 if (!This->DC->isDeclInLexicalTraversal(D))
5280 This->Decls.push_back(D);
5281 }
5282 }
5283
5284 return false;
5285 }
5286 };
5287}
5288
5289ExternalLoadResult ASTReader::FindExternalLexicalDecls(const DeclContext *DC,
5290 bool (*isKindWeWant)(Decl::Kind),
5291 SmallVectorImpl<Decl*> &Decls) {
5292 // There might be lexical decls in multiple modules, for the TU at
5293 // least. Walk all of the modules in the order they were loaded.
5294 FindExternalLexicalDeclsVisitor Visitor(*this, DC, isKindWeWant, Decls);
5295 ModuleMgr.visitDepthFirst(&FindExternalLexicalDeclsVisitor::visit, &Visitor);
5296 ++NumLexicalDeclContextsRead;
5297 return ELR_Success;
5298}
5299
5300namespace {
5301
5302class DeclIDComp {
5303 ASTReader &Reader;
5304 ModuleFile &Mod;
5305
5306public:
5307 DeclIDComp(ASTReader &Reader, ModuleFile &M) : Reader(Reader), Mod(M) {}
5308
5309 bool operator()(LocalDeclID L, LocalDeclID R) const {
5310 SourceLocation LHS = getLocation(L);
5311 SourceLocation RHS = getLocation(R);
5312 return Reader.getSourceManager().isBeforeInTranslationUnit(LHS, RHS);
5313 }
5314
5315 bool operator()(SourceLocation LHS, LocalDeclID R) const {
5316 SourceLocation RHS = getLocation(R);
5317 return Reader.getSourceManager().isBeforeInTranslationUnit(LHS, RHS);
5318 }
5319
5320 bool operator()(LocalDeclID L, SourceLocation RHS) const {
5321 SourceLocation LHS = getLocation(L);
5322 return Reader.getSourceManager().isBeforeInTranslationUnit(LHS, RHS);
5323 }
5324
5325 SourceLocation getLocation(LocalDeclID ID) const {
5326 return Reader.getSourceManager().getFileLoc(
5327 Reader.getSourceLocationForDeclID(Reader.getGlobalDeclID(Mod, ID)));
5328 }
5329};
5330
5331}
5332
5333void ASTReader::FindFileRegionDecls(FileID File,
5334 unsigned Offset, unsigned Length,
5335 SmallVectorImpl<Decl *> &Decls) {
5336 SourceManager &SM = getSourceManager();
5337
5338 llvm::DenseMap<FileID, FileDeclsInfo>::iterator I = FileDeclIDs.find(File);
5339 if (I == FileDeclIDs.end())
5340 return;
5341
5342 FileDeclsInfo &DInfo = I->second;
5343 if (DInfo.Decls.empty())
5344 return;
5345
5346 SourceLocation
5347 BeginLoc = SM.getLocForStartOfFile(File).getLocWithOffset(Offset);
5348 SourceLocation EndLoc = BeginLoc.getLocWithOffset(Length);
5349
5350 DeclIDComp DIDComp(*this, *DInfo.Mod);
5351 ArrayRef<serialization::LocalDeclID>::iterator
5352 BeginIt = std::lower_bound(DInfo.Decls.begin(), DInfo.Decls.end(),
5353 BeginLoc, DIDComp);
5354 if (BeginIt != DInfo.Decls.begin())
5355 --BeginIt;
5356
5357 // If we are pointing at a top-level decl inside an objc container, we need
5358 // to backtrack until we find it otherwise we will fail to report that the
5359 // region overlaps with an objc container.
5360 while (BeginIt != DInfo.Decls.begin() &&
5361 GetDecl(getGlobalDeclID(*DInfo.Mod, *BeginIt))
5362 ->isTopLevelDeclInObjCContainer())
5363 --BeginIt;
5364
5365 ArrayRef<serialization::LocalDeclID>::iterator
5366 EndIt = std::upper_bound(DInfo.Decls.begin(), DInfo.Decls.end(),
5367 EndLoc, DIDComp);
5368 if (EndIt != DInfo.Decls.end())
5369 ++EndIt;
5370
5371 for (ArrayRef<serialization::LocalDeclID>::iterator
5372 DIt = BeginIt; DIt != EndIt; ++DIt)
5373 Decls.push_back(GetDecl(getGlobalDeclID(*DInfo.Mod, *DIt)));
5374}
5375
5376namespace {
5377 /// \brief ModuleFile visitor used to perform name lookup into a
5378 /// declaration context.
5379 class DeclContextNameLookupVisitor {
5380 ASTReader &Reader;
Dmitri Gribenkocfa88f82013-01-12 19:30:44 +00005381 SmallVectorImpl<const DeclContext *> &Contexts;
Guy Benyei7f92f2d2012-12-18 14:30:41 +00005382 DeclarationName Name;
5383 SmallVectorImpl<NamedDecl *> &Decls;
5384
5385 public:
5386 DeclContextNameLookupVisitor(ASTReader &Reader,
5387 SmallVectorImpl<const DeclContext *> &Contexts,
5388 DeclarationName Name,
5389 SmallVectorImpl<NamedDecl *> &Decls)
5390 : Reader(Reader), Contexts(Contexts), Name(Name), Decls(Decls) { }
5391
5392 static bool visit(ModuleFile &M, void *UserData) {
5393 DeclContextNameLookupVisitor *This
5394 = static_cast<DeclContextNameLookupVisitor *>(UserData);
5395
5396 // Check whether we have any visible declaration information for
5397 // this context in this module.
5398 ModuleFile::DeclContextInfosMap::iterator Info;
5399 bool FoundInfo = false;
5400 for (unsigned I = 0, N = This->Contexts.size(); I != N; ++I) {
5401 Info = M.DeclContextInfos.find(This->Contexts[I]);
5402 if (Info != M.DeclContextInfos.end() &&
5403 Info->second.NameLookupTableData) {
5404 FoundInfo = true;
5405 break;
5406 }
5407 }
5408
5409 if (!FoundInfo)
5410 return false;
5411
5412 // Look for this name within this module.
5413 ASTDeclContextNameLookupTable *LookupTable =
5414 Info->second.NameLookupTableData;
5415 ASTDeclContextNameLookupTable::iterator Pos
5416 = LookupTable->find(This->Name);
5417 if (Pos == LookupTable->end())
5418 return false;
5419
5420 bool FoundAnything = false;
5421 ASTDeclContextNameLookupTrait::data_type Data = *Pos;
5422 for (; Data.first != Data.second; ++Data.first) {
5423 NamedDecl *ND = This->Reader.GetLocalDeclAs<NamedDecl>(M, *Data.first);
5424 if (!ND)
5425 continue;
5426
5427 if (ND->getDeclName() != This->Name) {
5428 // A name might be null because the decl's redeclarable part is
5429 // currently read before reading its name. The lookup is triggered by
5430 // building that decl (likely indirectly), and so it is later in the
5431 // sense of "already existing" and can be ignored here.
5432 continue;
5433 }
5434
5435 // Record this declaration.
5436 FoundAnything = true;
5437 This->Decls.push_back(ND);
5438 }
5439
5440 return FoundAnything;
5441 }
5442 };
5443}
5444
Douglas Gregor5a04f9f2013-01-21 15:25:38 +00005445/// \brief Retrieve the "definitive" module file for the definition of the
5446/// given declaration context, if there is one.
5447///
5448/// The "definitive" module file is the only place where we need to look to
5449/// find information about the declarations within the given declaration
5450/// context. For example, C++ and Objective-C classes, C structs/unions, and
5451/// Objective-C protocols, categories, and extensions are all defined in a
5452/// single place in the source code, so they have definitive module files
5453/// associated with them. C++ namespaces, on the other hand, can have
5454/// definitions in multiple different module files.
5455///
5456/// Note: this needs to be kept in sync with ASTWriter::AddedVisibleDecl's
5457/// NDEBUG checking.
5458static ModuleFile *getDefinitiveModuleFileFor(const DeclContext *DC,
5459 ASTReader &Reader) {
Douglas Gregore0d20662013-01-22 17:08:30 +00005460 if (const DeclContext *DefDC = getDefinitiveDeclContext(DC))
5461 return Reader.getOwningModuleFile(cast<Decl>(DefDC));
Douglas Gregor5a04f9f2013-01-21 15:25:38 +00005462
5463 return 0;
5464}
5465
Richard Smith3646c682013-02-07 03:30:24 +00005466bool
Guy Benyei7f92f2d2012-12-18 14:30:41 +00005467ASTReader::FindExternalVisibleDeclsByName(const DeclContext *DC,
5468 DeclarationName Name) {
5469 assert(DC->hasExternalVisibleStorage() &&
5470 "DeclContext has no visible decls in storage");
5471 if (!Name)
Richard Smith3646c682013-02-07 03:30:24 +00005472 return false;
Guy Benyei7f92f2d2012-12-18 14:30:41 +00005473
5474 SmallVector<NamedDecl *, 64> Decls;
5475
5476 // Compute the declaration contexts we need to look into. Multiple such
5477 // declaration contexts occur when two declaration contexts from disjoint
5478 // modules get merged, e.g., when two namespaces with the same name are
5479 // independently defined in separate modules.
5480 SmallVector<const DeclContext *, 2> Contexts;
5481 Contexts.push_back(DC);
5482
5483 if (DC->isNamespace()) {
5484 MergedDeclsMap::iterator Merged
5485 = MergedDecls.find(const_cast<Decl *>(cast<Decl>(DC)));
5486 if (Merged != MergedDecls.end()) {
5487 for (unsigned I = 0, N = Merged->second.size(); I != N; ++I)
5488 Contexts.push_back(cast<DeclContext>(GetDecl(Merged->second[I])));
5489 }
5490 }
5491
5492 DeclContextNameLookupVisitor Visitor(*this, Contexts, Name, Decls);
Douglas Gregor5a04f9f2013-01-21 15:25:38 +00005493
5494 // If we can definitively determine which module file to look into,
5495 // only look there. Otherwise, look in all module files.
5496 ModuleFile *Definitive;
5497 if (Contexts.size() == 1 &&
5498 (Definitive = getDefinitiveModuleFileFor(DC, *this))) {
5499 DeclContextNameLookupVisitor::visit(*Definitive, &Visitor);
5500 } else {
5501 ModuleMgr.visit(&DeclContextNameLookupVisitor::visit, &Visitor);
5502 }
Guy Benyei7f92f2d2012-12-18 14:30:41 +00005503 ++NumVisibleDeclContextsRead;
5504 SetExternalVisibleDeclsForName(DC, Name, Decls);
Richard Smith3646c682013-02-07 03:30:24 +00005505 return !Decls.empty();
Guy Benyei7f92f2d2012-12-18 14:30:41 +00005506}
5507
5508namespace {
5509 /// \brief ModuleFile visitor used to retrieve all visible names in a
5510 /// declaration context.
5511 class DeclContextAllNamesVisitor {
5512 ASTReader &Reader;
Dmitri Gribenkocfa88f82013-01-12 19:30:44 +00005513 SmallVectorImpl<const DeclContext *> &Contexts;
Guy Benyei7f92f2d2012-12-18 14:30:41 +00005514 llvm::DenseMap<DeclarationName, SmallVector<NamedDecl *, 8> > &Decls;
Argyrios Kyrtzidisca40f302012-12-19 22:21:18 +00005515 bool VisitAll;
Guy Benyei7f92f2d2012-12-18 14:30:41 +00005516
5517 public:
5518 DeclContextAllNamesVisitor(ASTReader &Reader,
5519 SmallVectorImpl<const DeclContext *> &Contexts,
5520 llvm::DenseMap<DeclarationName,
Argyrios Kyrtzidisca40f302012-12-19 22:21:18 +00005521 SmallVector<NamedDecl *, 8> > &Decls,
5522 bool VisitAll)
5523 : Reader(Reader), Contexts(Contexts), Decls(Decls), VisitAll(VisitAll) { }
Guy Benyei7f92f2d2012-12-18 14:30:41 +00005524
5525 static bool visit(ModuleFile &M, void *UserData) {
5526 DeclContextAllNamesVisitor *This
5527 = static_cast<DeclContextAllNamesVisitor *>(UserData);
5528
5529 // Check whether we have any visible declaration information for
5530 // this context in this module.
5531 ModuleFile::DeclContextInfosMap::iterator Info;
5532 bool FoundInfo = false;
5533 for (unsigned I = 0, N = This->Contexts.size(); I != N; ++I) {
5534 Info = M.DeclContextInfos.find(This->Contexts[I]);
5535 if (Info != M.DeclContextInfos.end() &&
5536 Info->second.NameLookupTableData) {
5537 FoundInfo = true;
5538 break;
5539 }
5540 }
5541
5542 if (!FoundInfo)
5543 return false;
5544
5545 ASTDeclContextNameLookupTable *LookupTable =
5546 Info->second.NameLookupTableData;
5547 bool FoundAnything = false;
5548 for (ASTDeclContextNameLookupTable::data_iterator
Douglas Gregora6b00fc2013-01-23 22:38:11 +00005549 I = LookupTable->data_begin(), E = LookupTable->data_end();
5550 I != E;
5551 ++I) {
Guy Benyei7f92f2d2012-12-18 14:30:41 +00005552 ASTDeclContextNameLookupTrait::data_type Data = *I;
5553 for (; Data.first != Data.second; ++Data.first) {
5554 NamedDecl *ND = This->Reader.GetLocalDeclAs<NamedDecl>(M,
5555 *Data.first);
5556 if (!ND)
5557 continue;
5558
5559 // Record this declaration.
5560 FoundAnything = true;
5561 This->Decls[ND->getDeclName()].push_back(ND);
5562 }
5563 }
5564
Argyrios Kyrtzidisca40f302012-12-19 22:21:18 +00005565 return FoundAnything && !This->VisitAll;
Guy Benyei7f92f2d2012-12-18 14:30:41 +00005566 }
5567 };
5568}
5569
5570void ASTReader::completeVisibleDeclsMap(const DeclContext *DC) {
5571 if (!DC->hasExternalVisibleStorage())
5572 return;
Dmitri Gribenkocfa88f82013-01-12 19:30:44 +00005573 llvm::DenseMap<DeclarationName, SmallVector<NamedDecl *, 8> > Decls;
Guy Benyei7f92f2d2012-12-18 14:30:41 +00005574
5575 // Compute the declaration contexts we need to look into. Multiple such
5576 // declaration contexts occur when two declaration contexts from disjoint
5577 // modules get merged, e.g., when two namespaces with the same name are
5578 // independently defined in separate modules.
5579 SmallVector<const DeclContext *, 2> Contexts;
5580 Contexts.push_back(DC);
5581
5582 if (DC->isNamespace()) {
5583 MergedDeclsMap::iterator Merged
5584 = MergedDecls.find(const_cast<Decl *>(cast<Decl>(DC)));
5585 if (Merged != MergedDecls.end()) {
5586 for (unsigned I = 0, N = Merged->second.size(); I != N; ++I)
5587 Contexts.push_back(cast<DeclContext>(GetDecl(Merged->second[I])));
5588 }
5589 }
5590
Argyrios Kyrtzidisca40f302012-12-19 22:21:18 +00005591 DeclContextAllNamesVisitor Visitor(*this, Contexts, Decls,
5592 /*VisitAll=*/DC->isFileContext());
Guy Benyei7f92f2d2012-12-18 14:30:41 +00005593 ModuleMgr.visit(&DeclContextAllNamesVisitor::visit, &Visitor);
5594 ++NumVisibleDeclContextsRead;
5595
5596 for (llvm::DenseMap<DeclarationName,
Dmitri Gribenkocfa88f82013-01-12 19:30:44 +00005597 SmallVector<NamedDecl *, 8> >::iterator
Guy Benyei7f92f2d2012-12-18 14:30:41 +00005598 I = Decls.begin(), E = Decls.end(); I != E; ++I) {
5599 SetExternalVisibleDeclsForName(DC, I->first, I->second);
5600 }
5601 const_cast<DeclContext *>(DC)->setHasExternalVisibleStorage(false);
5602}
5603
5604/// \brief Under non-PCH compilation the consumer receives the objc methods
5605/// before receiving the implementation, and codegen depends on this.
5606/// We simulate this by deserializing and passing to consumer the methods of the
5607/// implementation before passing the deserialized implementation decl.
5608static void PassObjCImplDeclToConsumer(ObjCImplDecl *ImplD,
5609 ASTConsumer *Consumer) {
5610 assert(ImplD && Consumer);
5611
5612 for (ObjCImplDecl::method_iterator
5613 I = ImplD->meth_begin(), E = ImplD->meth_end(); I != E; ++I)
5614 Consumer->HandleInterestingDecl(DeclGroupRef(*I));
5615
5616 Consumer->HandleInterestingDecl(DeclGroupRef(ImplD));
5617}
5618
5619void ASTReader::PassInterestingDeclsToConsumer() {
5620 assert(Consumer);
5621 while (!InterestingDecls.empty()) {
5622 Decl *D = InterestingDecls.front();
5623 InterestingDecls.pop_front();
5624
5625 PassInterestingDeclToConsumer(D);
5626 }
5627}
5628
5629void ASTReader::PassInterestingDeclToConsumer(Decl *D) {
5630 if (ObjCImplDecl *ImplD = dyn_cast<ObjCImplDecl>(D))
5631 PassObjCImplDeclToConsumer(ImplD, Consumer);
5632 else
5633 Consumer->HandleInterestingDecl(DeclGroupRef(D));
5634}
5635
5636void ASTReader::StartTranslationUnit(ASTConsumer *Consumer) {
5637 this->Consumer = Consumer;
5638
5639 if (!Consumer)
5640 return;
5641
5642 for (unsigned I = 0, N = ExternalDefinitions.size(); I != N; ++I) {
5643 // Force deserialization of this decl, which will cause it to be queued for
5644 // passing to the consumer.
5645 GetDecl(ExternalDefinitions[I]);
5646 }
5647 ExternalDefinitions.clear();
5648
5649 PassInterestingDeclsToConsumer();
5650}
5651
5652void ASTReader::PrintStats() {
5653 std::fprintf(stderr, "*** AST File Statistics:\n");
5654
5655 unsigned NumTypesLoaded
5656 = TypesLoaded.size() - std::count(TypesLoaded.begin(), TypesLoaded.end(),
5657 QualType());
5658 unsigned NumDeclsLoaded
5659 = DeclsLoaded.size() - std::count(DeclsLoaded.begin(), DeclsLoaded.end(),
5660 (Decl *)0);
5661 unsigned NumIdentifiersLoaded
5662 = IdentifiersLoaded.size() - std::count(IdentifiersLoaded.begin(),
5663 IdentifiersLoaded.end(),
5664 (IdentifierInfo *)0);
5665 unsigned NumMacrosLoaded
5666 = MacrosLoaded.size() - std::count(MacrosLoaded.begin(),
5667 MacrosLoaded.end(),
Argyrios Kyrtzidis9818a1d2013-02-20 00:54:57 +00005668 (MacroDirective *)0);
Guy Benyei7f92f2d2012-12-18 14:30:41 +00005669 unsigned NumSelectorsLoaded
5670 = SelectorsLoaded.size() - std::count(SelectorsLoaded.begin(),
5671 SelectorsLoaded.end(),
5672 Selector());
5673
5674 if (unsigned TotalNumSLocEntries = getTotalNumSLocs())
5675 std::fprintf(stderr, " %u/%u source location entries read (%f%%)\n",
5676 NumSLocEntriesRead, TotalNumSLocEntries,
5677 ((float)NumSLocEntriesRead/TotalNumSLocEntries * 100));
5678 if (!TypesLoaded.empty())
5679 std::fprintf(stderr, " %u/%u types read (%f%%)\n",
5680 NumTypesLoaded, (unsigned)TypesLoaded.size(),
5681 ((float)NumTypesLoaded/TypesLoaded.size() * 100));
5682 if (!DeclsLoaded.empty())
5683 std::fprintf(stderr, " %u/%u declarations read (%f%%)\n",
5684 NumDeclsLoaded, (unsigned)DeclsLoaded.size(),
5685 ((float)NumDeclsLoaded/DeclsLoaded.size() * 100));
5686 if (!IdentifiersLoaded.empty())
5687 std::fprintf(stderr, " %u/%u identifiers read (%f%%)\n",
5688 NumIdentifiersLoaded, (unsigned)IdentifiersLoaded.size(),
5689 ((float)NumIdentifiersLoaded/IdentifiersLoaded.size() * 100));
5690 if (!MacrosLoaded.empty())
5691 std::fprintf(stderr, " %u/%u macros read (%f%%)\n",
5692 NumMacrosLoaded, (unsigned)MacrosLoaded.size(),
5693 ((float)NumMacrosLoaded/MacrosLoaded.size() * 100));
5694 if (!SelectorsLoaded.empty())
5695 std::fprintf(stderr, " %u/%u selectors read (%f%%)\n",
5696 NumSelectorsLoaded, (unsigned)SelectorsLoaded.size(),
5697 ((float)NumSelectorsLoaded/SelectorsLoaded.size() * 100));
5698 if (TotalNumStatements)
5699 std::fprintf(stderr, " %u/%u statements read (%f%%)\n",
5700 NumStatementsRead, TotalNumStatements,
5701 ((float)NumStatementsRead/TotalNumStatements * 100));
5702 if (TotalNumMacros)
5703 std::fprintf(stderr, " %u/%u macros read (%f%%)\n",
5704 NumMacrosRead, TotalNumMacros,
5705 ((float)NumMacrosRead/TotalNumMacros * 100));
5706 if (TotalLexicalDeclContexts)
5707 std::fprintf(stderr, " %u/%u lexical declcontexts read (%f%%)\n",
5708 NumLexicalDeclContextsRead, TotalLexicalDeclContexts,
5709 ((float)NumLexicalDeclContextsRead/TotalLexicalDeclContexts
5710 * 100));
5711 if (TotalVisibleDeclContexts)
5712 std::fprintf(stderr, " %u/%u visible declcontexts read (%f%%)\n",
5713 NumVisibleDeclContextsRead, TotalVisibleDeclContexts,
5714 ((float)NumVisibleDeclContextsRead/TotalVisibleDeclContexts
5715 * 100));
5716 if (TotalNumMethodPoolEntries) {
5717 std::fprintf(stderr, " %u/%u method pool entries read (%f%%)\n",
5718 NumMethodPoolEntriesRead, TotalNumMethodPoolEntries,
5719 ((float)NumMethodPoolEntriesRead/TotalNumMethodPoolEntries
5720 * 100));
Guy Benyei7f92f2d2012-12-18 14:30:41 +00005721 }
Douglas Gregor95fb36e2013-01-28 17:54:36 +00005722 if (NumMethodPoolLookups) {
5723 std::fprintf(stderr, " %u/%u method pool lookups succeeded (%f%%)\n",
5724 NumMethodPoolHits, NumMethodPoolLookups,
5725 ((float)NumMethodPoolHits/NumMethodPoolLookups * 100.0));
5726 }
5727 if (NumMethodPoolTableLookups) {
5728 std::fprintf(stderr, " %u/%u method pool table lookups succeeded (%f%%)\n",
5729 NumMethodPoolTableHits, NumMethodPoolTableLookups,
5730 ((float)NumMethodPoolTableHits/NumMethodPoolTableLookups
5731 * 100.0));
5732 }
5733
Douglas Gregore1698072013-01-25 00:38:33 +00005734 if (NumIdentifierLookupHits) {
5735 std::fprintf(stderr,
5736 " %u / %u identifier table lookups succeeded (%f%%)\n",
5737 NumIdentifierLookupHits, NumIdentifierLookups,
5738 (double)NumIdentifierLookupHits*100.0/NumIdentifierLookups);
5739 }
5740
Douglas Gregor1a49d972013-01-25 01:03:03 +00005741 if (GlobalIndex) {
5742 std::fprintf(stderr, "\n");
5743 GlobalIndex->printStats();
5744 }
5745
Guy Benyei7f92f2d2012-12-18 14:30:41 +00005746 std::fprintf(stderr, "\n");
5747 dump();
5748 std::fprintf(stderr, "\n");
5749}
5750
5751template<typename Key, typename ModuleFile, unsigned InitialCapacity>
5752static void
5753dumpModuleIDMap(StringRef Name,
5754 const ContinuousRangeMap<Key, ModuleFile *,
5755 InitialCapacity> &Map) {
5756 if (Map.begin() == Map.end())
5757 return;
5758
5759 typedef ContinuousRangeMap<Key, ModuleFile *, InitialCapacity> MapType;
5760 llvm::errs() << Name << ":\n";
5761 for (typename MapType::const_iterator I = Map.begin(), IEnd = Map.end();
5762 I != IEnd; ++I) {
5763 llvm::errs() << " " << I->first << " -> " << I->second->FileName
5764 << "\n";
5765 }
5766}
5767
5768void ASTReader::dump() {
5769 llvm::errs() << "*** PCH/ModuleFile Remappings:\n";
5770 dumpModuleIDMap("Global bit offset map", GlobalBitOffsetsMap);
5771 dumpModuleIDMap("Global source location entry map", GlobalSLocEntryMap);
5772 dumpModuleIDMap("Global type map", GlobalTypeMap);
5773 dumpModuleIDMap("Global declaration map", GlobalDeclMap);
5774 dumpModuleIDMap("Global identifier map", GlobalIdentifierMap);
5775 dumpModuleIDMap("Global macro map", GlobalMacroMap);
5776 dumpModuleIDMap("Global submodule map", GlobalSubmoduleMap);
5777 dumpModuleIDMap("Global selector map", GlobalSelectorMap);
5778 dumpModuleIDMap("Global preprocessed entity map",
5779 GlobalPreprocessedEntityMap);
5780
5781 llvm::errs() << "\n*** PCH/Modules Loaded:";
5782 for (ModuleManager::ModuleConstIterator M = ModuleMgr.begin(),
5783 MEnd = ModuleMgr.end();
5784 M != MEnd; ++M)
5785 (*M)->dump();
5786}
5787
5788/// Return the amount of memory used by memory buffers, breaking down
5789/// by heap-backed versus mmap'ed memory.
5790void ASTReader::getMemoryBufferSizes(MemoryBufferSizes &sizes) const {
5791 for (ModuleConstIterator I = ModuleMgr.begin(),
5792 E = ModuleMgr.end(); I != E; ++I) {
5793 if (llvm::MemoryBuffer *buf = (*I)->Buffer.get()) {
5794 size_t bytes = buf->getBufferSize();
5795 switch (buf->getBufferKind()) {
5796 case llvm::MemoryBuffer::MemoryBuffer_Malloc:
5797 sizes.malloc_bytes += bytes;
5798 break;
5799 case llvm::MemoryBuffer::MemoryBuffer_MMap:
5800 sizes.mmap_bytes += bytes;
5801 break;
5802 }
5803 }
5804 }
5805}
5806
5807void ASTReader::InitializeSema(Sema &S) {
5808 SemaObj = &S;
5809 S.addExternalSource(this);
5810
5811 // Makes sure any declarations that were deserialized "too early"
5812 // still get added to the identifier's declaration chains.
5813 for (unsigned I = 0, N = PreloadedDecls.size(); I != N; ++I) {
Douglas Gregoraa945902013-02-18 15:53:43 +00005814 NamedDecl *ND = cast<NamedDecl>(PreloadedDecls[I]->getMostRecentDecl());
5815 SemaObj->pushExternalDeclIntoScope(ND, PreloadedDecls[I]->getDeclName());
Guy Benyei7f92f2d2012-12-18 14:30:41 +00005816 }
5817 PreloadedDecls.clear();
5818
5819 // Load the offsets of the declarations that Sema references.
5820 // They will be lazily deserialized when needed.
5821 if (!SemaDeclRefs.empty()) {
5822 assert(SemaDeclRefs.size() == 2 && "More decl refs than expected!");
5823 if (!SemaObj->StdNamespace)
5824 SemaObj->StdNamespace = SemaDeclRefs[0];
5825 if (!SemaObj->StdBadAlloc)
5826 SemaObj->StdBadAlloc = SemaDeclRefs[1];
5827 }
5828
5829 if (!FPPragmaOptions.empty()) {
5830 assert(FPPragmaOptions.size() == 1 && "Wrong number of FP_PRAGMA_OPTIONS");
5831 SemaObj->FPFeatures.fp_contract = FPPragmaOptions[0];
5832 }
5833
5834 if (!OpenCLExtensions.empty()) {
5835 unsigned I = 0;
5836#define OPENCLEXT(nm) SemaObj->OpenCLFeatures.nm = OpenCLExtensions[I++];
5837#include "clang/Basic/OpenCLExtensions.def"
5838
5839 assert(OpenCLExtensions.size() == I && "Wrong number of OPENCL_EXTENSIONS");
5840 }
5841}
5842
5843IdentifierInfo* ASTReader::get(const char *NameStart, const char *NameEnd) {
5844 // Note that we are loading an identifier.
5845 Deserializing AnIdentifier(this);
Douglas Gregor1a49d972013-01-25 01:03:03 +00005846 StringRef Name(NameStart, NameEnd - NameStart);
5847
5848 // If there is a global index, look there first to determine which modules
5849 // provably do not have any results for this identifier.
Douglas Gregor188bdcd2013-01-25 23:32:03 +00005850 GlobalModuleIndex::HitSet Hits;
5851 GlobalModuleIndex::HitSet *HitsPtr = 0;
Douglas Gregor1a49d972013-01-25 01:03:03 +00005852 if (!loadGlobalIndex()) {
Douglas Gregor188bdcd2013-01-25 23:32:03 +00005853 if (GlobalIndex->lookupIdentifier(Name, Hits)) {
5854 HitsPtr = &Hits;
Douglas Gregor1a49d972013-01-25 01:03:03 +00005855 }
5856 }
Douglas Gregor188bdcd2013-01-25 23:32:03 +00005857 IdentifierLookupVisitor Visitor(Name, /*PriorGeneration=*/0,
Douglas Gregore1698072013-01-25 00:38:33 +00005858 NumIdentifierLookups,
5859 NumIdentifierLookupHits);
Douglas Gregor188bdcd2013-01-25 23:32:03 +00005860 ModuleMgr.visit(IdentifierLookupVisitor::visit, &Visitor, HitsPtr);
Guy Benyei7f92f2d2012-12-18 14:30:41 +00005861 IdentifierInfo *II = Visitor.getIdentifierInfo();
5862 markIdentifierUpToDate(II);
5863 return II;
5864}
5865
5866namespace clang {
5867 /// \brief An identifier-lookup iterator that enumerates all of the
5868 /// identifiers stored within a set of AST files.
5869 class ASTIdentifierIterator : public IdentifierIterator {
5870 /// \brief The AST reader whose identifiers are being enumerated.
5871 const ASTReader &Reader;
5872
5873 /// \brief The current index into the chain of AST files stored in
5874 /// the AST reader.
5875 unsigned Index;
5876
5877 /// \brief The current position within the identifier lookup table
5878 /// of the current AST file.
5879 ASTIdentifierLookupTable::key_iterator Current;
5880
5881 /// \brief The end position within the identifier lookup table of
5882 /// the current AST file.
5883 ASTIdentifierLookupTable::key_iterator End;
5884
5885 public:
5886 explicit ASTIdentifierIterator(const ASTReader &Reader);
5887
5888 virtual StringRef Next();
5889 };
5890}
5891
5892ASTIdentifierIterator::ASTIdentifierIterator(const ASTReader &Reader)
5893 : Reader(Reader), Index(Reader.ModuleMgr.size() - 1) {
5894 ASTIdentifierLookupTable *IdTable
5895 = (ASTIdentifierLookupTable *)Reader.ModuleMgr[Index].IdentifierLookupTable;
5896 Current = IdTable->key_begin();
5897 End = IdTable->key_end();
5898}
5899
5900StringRef ASTIdentifierIterator::Next() {
5901 while (Current == End) {
5902 // If we have exhausted all of our AST files, we're done.
5903 if (Index == 0)
5904 return StringRef();
5905
5906 --Index;
5907 ASTIdentifierLookupTable *IdTable
5908 = (ASTIdentifierLookupTable *)Reader.ModuleMgr[Index].
5909 IdentifierLookupTable;
5910 Current = IdTable->key_begin();
5911 End = IdTable->key_end();
5912 }
5913
5914 // We have any identifiers remaining in the current AST file; return
5915 // the next one.
Douglas Gregor479633c2013-01-23 18:53:14 +00005916 StringRef Result = *Current;
Guy Benyei7f92f2d2012-12-18 14:30:41 +00005917 ++Current;
Douglas Gregor479633c2013-01-23 18:53:14 +00005918 return Result;
Guy Benyei7f92f2d2012-12-18 14:30:41 +00005919}
5920
5921IdentifierIterator *ASTReader::getIdentifiers() const {
5922 return new ASTIdentifierIterator(*this);
5923}
5924
5925namespace clang { namespace serialization {
5926 class ReadMethodPoolVisitor {
5927 ASTReader &Reader;
5928 Selector Sel;
5929 unsigned PriorGeneration;
Dmitri Gribenkocfa88f82013-01-12 19:30:44 +00005930 SmallVector<ObjCMethodDecl *, 4> InstanceMethods;
5931 SmallVector<ObjCMethodDecl *, 4> FactoryMethods;
Guy Benyei7f92f2d2012-12-18 14:30:41 +00005932
5933 public:
5934 ReadMethodPoolVisitor(ASTReader &Reader, Selector Sel,
5935 unsigned PriorGeneration)
5936 : Reader(Reader), Sel(Sel), PriorGeneration(PriorGeneration) { }
5937
5938 static bool visit(ModuleFile &M, void *UserData) {
5939 ReadMethodPoolVisitor *This
5940 = static_cast<ReadMethodPoolVisitor *>(UserData);
5941
5942 if (!M.SelectorLookupTable)
5943 return false;
5944
5945 // If we've already searched this module file, skip it now.
5946 if (M.Generation <= This->PriorGeneration)
5947 return true;
5948
Douglas Gregor95fb36e2013-01-28 17:54:36 +00005949 ++This->Reader.NumMethodPoolTableLookups;
Guy Benyei7f92f2d2012-12-18 14:30:41 +00005950 ASTSelectorLookupTable *PoolTable
5951 = (ASTSelectorLookupTable*)M.SelectorLookupTable;
5952 ASTSelectorLookupTable::iterator Pos = PoolTable->find(This->Sel);
5953 if (Pos == PoolTable->end())
5954 return false;
Douglas Gregor95fb36e2013-01-28 17:54:36 +00005955
5956 ++This->Reader.NumMethodPoolTableHits;
Guy Benyei7f92f2d2012-12-18 14:30:41 +00005957 ++This->Reader.NumSelectorsRead;
5958 // FIXME: Not quite happy with the statistics here. We probably should
5959 // disable this tracking when called via LoadSelector.
5960 // Also, should entries without methods count as misses?
5961 ++This->Reader.NumMethodPoolEntriesRead;
5962 ASTSelectorLookupTrait::data_type Data = *Pos;
5963 if (This->Reader.DeserializationListener)
5964 This->Reader.DeserializationListener->SelectorRead(Data.ID,
5965 This->Sel);
5966
5967 This->InstanceMethods.append(Data.Instance.begin(), Data.Instance.end());
5968 This->FactoryMethods.append(Data.Factory.begin(), Data.Factory.end());
5969 return true;
5970 }
5971
5972 /// \brief Retrieve the instance methods found by this visitor.
5973 ArrayRef<ObjCMethodDecl *> getInstanceMethods() const {
5974 return InstanceMethods;
5975 }
5976
5977 /// \brief Retrieve the instance methods found by this visitor.
5978 ArrayRef<ObjCMethodDecl *> getFactoryMethods() const {
5979 return FactoryMethods;
5980 }
5981 };
5982} } // end namespace clang::serialization
5983
5984/// \brief Add the given set of methods to the method list.
5985static void addMethodsToPool(Sema &S, ArrayRef<ObjCMethodDecl *> Methods,
5986 ObjCMethodList &List) {
5987 for (unsigned I = 0, N = Methods.size(); I != N; ++I) {
5988 S.addMethodToGlobalList(&List, Methods[I]);
5989 }
5990}
5991
5992void ASTReader::ReadMethodPool(Selector Sel) {
5993 // Get the selector generation and update it to the current generation.
5994 unsigned &Generation = SelectorGeneration[Sel];
5995 unsigned PriorGeneration = Generation;
5996 Generation = CurrentGeneration;
5997
5998 // Search for methods defined with this selector.
Douglas Gregor95fb36e2013-01-28 17:54:36 +00005999 ++NumMethodPoolLookups;
Guy Benyei7f92f2d2012-12-18 14:30:41 +00006000 ReadMethodPoolVisitor Visitor(*this, Sel, PriorGeneration);
6001 ModuleMgr.visit(&ReadMethodPoolVisitor::visit, &Visitor);
6002
6003 if (Visitor.getInstanceMethods().empty() &&
Douglas Gregor95fb36e2013-01-28 17:54:36 +00006004 Visitor.getFactoryMethods().empty())
Guy Benyei7f92f2d2012-12-18 14:30:41 +00006005 return;
Douglas Gregor95fb36e2013-01-28 17:54:36 +00006006
6007 ++NumMethodPoolHits;
6008
Guy Benyei7f92f2d2012-12-18 14:30:41 +00006009 if (!getSema())
6010 return;
6011
6012 Sema &S = *getSema();
6013 Sema::GlobalMethodPool::iterator Pos
6014 = S.MethodPool.insert(std::make_pair(Sel, Sema::GlobalMethods())).first;
6015
6016 addMethodsToPool(S, Visitor.getInstanceMethods(), Pos->second.first);
6017 addMethodsToPool(S, Visitor.getFactoryMethods(), Pos->second.second);
6018}
6019
6020void ASTReader::ReadKnownNamespaces(
6021 SmallVectorImpl<NamespaceDecl *> &Namespaces) {
6022 Namespaces.clear();
6023
6024 for (unsigned I = 0, N = KnownNamespaces.size(); I != N; ++I) {
6025 if (NamespaceDecl *Namespace
6026 = dyn_cast_or_null<NamespaceDecl>(GetDecl(KnownNamespaces[I])))
6027 Namespaces.push_back(Namespace);
6028 }
6029}
6030
Nick Lewyckycd0655b2013-02-01 08:13:20 +00006031void ASTReader::ReadUndefinedButUsed(
Nick Lewycky995e26b2013-01-31 03:23:57 +00006032 llvm::DenseMap<NamedDecl*, SourceLocation> &Undefined) {
Nick Lewyckycd0655b2013-02-01 08:13:20 +00006033 for (unsigned Idx = 0, N = UndefinedButUsed.size(); Idx != N;) {
6034 NamedDecl *D = cast<NamedDecl>(GetDecl(UndefinedButUsed[Idx++]));
Nick Lewycky01a41142013-01-26 00:35:08 +00006035 SourceLocation Loc =
Nick Lewyckycd0655b2013-02-01 08:13:20 +00006036 SourceLocation::getFromRawEncoding(UndefinedButUsed[Idx++]);
Nick Lewycky01a41142013-01-26 00:35:08 +00006037 Undefined.insert(std::make_pair(D, Loc));
6038 }
6039}
Nick Lewycky01a41142013-01-26 00:35:08 +00006040
Guy Benyei7f92f2d2012-12-18 14:30:41 +00006041void ASTReader::ReadTentativeDefinitions(
6042 SmallVectorImpl<VarDecl *> &TentativeDefs) {
6043 for (unsigned I = 0, N = TentativeDefinitions.size(); I != N; ++I) {
6044 VarDecl *Var = dyn_cast_or_null<VarDecl>(GetDecl(TentativeDefinitions[I]));
6045 if (Var)
6046 TentativeDefs.push_back(Var);
6047 }
6048 TentativeDefinitions.clear();
6049}
6050
6051void ASTReader::ReadUnusedFileScopedDecls(
6052 SmallVectorImpl<const DeclaratorDecl *> &Decls) {
6053 for (unsigned I = 0, N = UnusedFileScopedDecls.size(); I != N; ++I) {
6054 DeclaratorDecl *D
6055 = dyn_cast_or_null<DeclaratorDecl>(GetDecl(UnusedFileScopedDecls[I]));
6056 if (D)
6057 Decls.push_back(D);
6058 }
6059 UnusedFileScopedDecls.clear();
6060}
6061
6062void ASTReader::ReadDelegatingConstructors(
6063 SmallVectorImpl<CXXConstructorDecl *> &Decls) {
6064 for (unsigned I = 0, N = DelegatingCtorDecls.size(); I != N; ++I) {
6065 CXXConstructorDecl *D
6066 = dyn_cast_or_null<CXXConstructorDecl>(GetDecl(DelegatingCtorDecls[I]));
6067 if (D)
6068 Decls.push_back(D);
6069 }
6070 DelegatingCtorDecls.clear();
6071}
6072
6073void ASTReader::ReadExtVectorDecls(SmallVectorImpl<TypedefNameDecl *> &Decls) {
6074 for (unsigned I = 0, N = ExtVectorDecls.size(); I != N; ++I) {
6075 TypedefNameDecl *D
6076 = dyn_cast_or_null<TypedefNameDecl>(GetDecl(ExtVectorDecls[I]));
6077 if (D)
6078 Decls.push_back(D);
6079 }
6080 ExtVectorDecls.clear();
6081}
6082
6083void ASTReader::ReadDynamicClasses(SmallVectorImpl<CXXRecordDecl *> &Decls) {
6084 for (unsigned I = 0, N = DynamicClasses.size(); I != N; ++I) {
6085 CXXRecordDecl *D
6086 = dyn_cast_or_null<CXXRecordDecl>(GetDecl(DynamicClasses[I]));
6087 if (D)
6088 Decls.push_back(D);
6089 }
6090 DynamicClasses.clear();
6091}
6092
6093void
Richard Smith5ea6ef42013-01-10 23:43:47 +00006094ASTReader::ReadLocallyScopedExternCDecls(SmallVectorImpl<NamedDecl *> &Decls) {
6095 for (unsigned I = 0, N = LocallyScopedExternCDecls.size(); I != N; ++I) {
6096 NamedDecl *D
6097 = dyn_cast_or_null<NamedDecl>(GetDecl(LocallyScopedExternCDecls[I]));
Guy Benyei7f92f2d2012-12-18 14:30:41 +00006098 if (D)
6099 Decls.push_back(D);
6100 }
Richard Smith5ea6ef42013-01-10 23:43:47 +00006101 LocallyScopedExternCDecls.clear();
Guy Benyei7f92f2d2012-12-18 14:30:41 +00006102}
6103
6104void ASTReader::ReadReferencedSelectors(
6105 SmallVectorImpl<std::pair<Selector, SourceLocation> > &Sels) {
6106 if (ReferencedSelectorsData.empty())
6107 return;
6108
6109 // If there are @selector references added them to its pool. This is for
6110 // implementation of -Wselector.
6111 unsigned int DataSize = ReferencedSelectorsData.size()-1;
6112 unsigned I = 0;
6113 while (I < DataSize) {
6114 Selector Sel = DecodeSelector(ReferencedSelectorsData[I++]);
6115 SourceLocation SelLoc
6116 = SourceLocation::getFromRawEncoding(ReferencedSelectorsData[I++]);
6117 Sels.push_back(std::make_pair(Sel, SelLoc));
6118 }
6119 ReferencedSelectorsData.clear();
6120}
6121
6122void ASTReader::ReadWeakUndeclaredIdentifiers(
6123 SmallVectorImpl<std::pair<IdentifierInfo *, WeakInfo> > &WeakIDs) {
6124 if (WeakUndeclaredIdentifiers.empty())
6125 return;
6126
6127 for (unsigned I = 0, N = WeakUndeclaredIdentifiers.size(); I < N; /*none*/) {
6128 IdentifierInfo *WeakId
6129 = DecodeIdentifierInfo(WeakUndeclaredIdentifiers[I++]);
6130 IdentifierInfo *AliasId
6131 = DecodeIdentifierInfo(WeakUndeclaredIdentifiers[I++]);
6132 SourceLocation Loc
6133 = SourceLocation::getFromRawEncoding(WeakUndeclaredIdentifiers[I++]);
6134 bool Used = WeakUndeclaredIdentifiers[I++];
6135 WeakInfo WI(AliasId, Loc);
6136 WI.setUsed(Used);
6137 WeakIDs.push_back(std::make_pair(WeakId, WI));
6138 }
6139 WeakUndeclaredIdentifiers.clear();
6140}
6141
6142void ASTReader::ReadUsedVTables(SmallVectorImpl<ExternalVTableUse> &VTables) {
6143 for (unsigned Idx = 0, N = VTableUses.size(); Idx < N; /* In loop */) {
6144 ExternalVTableUse VT;
6145 VT.Record = dyn_cast_or_null<CXXRecordDecl>(GetDecl(VTableUses[Idx++]));
6146 VT.Location = SourceLocation::getFromRawEncoding(VTableUses[Idx++]);
6147 VT.DefinitionRequired = VTableUses[Idx++];
6148 VTables.push_back(VT);
6149 }
6150
6151 VTableUses.clear();
6152}
6153
6154void ASTReader::ReadPendingInstantiations(
6155 SmallVectorImpl<std::pair<ValueDecl *, SourceLocation> > &Pending) {
6156 for (unsigned Idx = 0, N = PendingInstantiations.size(); Idx < N;) {
6157 ValueDecl *D = cast<ValueDecl>(GetDecl(PendingInstantiations[Idx++]));
6158 SourceLocation Loc
6159 = SourceLocation::getFromRawEncoding(PendingInstantiations[Idx++]);
6160
6161 Pending.push_back(std::make_pair(D, Loc));
6162 }
6163 PendingInstantiations.clear();
6164}
6165
6166void ASTReader::LoadSelector(Selector Sel) {
6167 // It would be complicated to avoid reading the methods anyway. So don't.
6168 ReadMethodPool(Sel);
6169}
6170
6171void ASTReader::SetIdentifierInfo(IdentifierID ID, IdentifierInfo *II) {
6172 assert(ID && "Non-zero identifier ID required");
6173 assert(ID <= IdentifiersLoaded.size() && "identifier ID out of range");
6174 IdentifiersLoaded[ID - 1] = II;
6175 if (DeserializationListener)
6176 DeserializationListener->IdentifierRead(ID, II);
6177}
6178
6179/// \brief Set the globally-visible declarations associated with the given
6180/// identifier.
6181///
6182/// If the AST reader is currently in a state where the given declaration IDs
6183/// cannot safely be resolved, they are queued until it is safe to resolve
6184/// them.
6185///
6186/// \param II an IdentifierInfo that refers to one or more globally-visible
6187/// declarations.
6188///
6189/// \param DeclIDs the set of declaration IDs with the name @p II that are
6190/// visible at global scope.
6191///
Douglas Gregoraa945902013-02-18 15:53:43 +00006192/// \param Decls if non-null, this vector will be populated with the set of
6193/// deserialized declarations. These declarations will not be pushed into
6194/// scope.
Guy Benyei7f92f2d2012-12-18 14:30:41 +00006195void
6196ASTReader::SetGloballyVisibleDecls(IdentifierInfo *II,
6197 const SmallVectorImpl<uint32_t> &DeclIDs,
Douglas Gregoraa945902013-02-18 15:53:43 +00006198 SmallVectorImpl<Decl *> *Decls) {
6199 if (NumCurrentElementsDeserializing && !Decls) {
6200 PendingIdentifierInfos[II].append(DeclIDs.begin(), DeclIDs.end());
Guy Benyei7f92f2d2012-12-18 14:30:41 +00006201 return;
6202 }
6203
6204 for (unsigned I = 0, N = DeclIDs.size(); I != N; ++I) {
6205 NamedDecl *D = cast<NamedDecl>(GetDecl(DeclIDs[I]));
6206 if (SemaObj) {
Douglas Gregoraa945902013-02-18 15:53:43 +00006207 // If we're simply supposed to record the declarations, do so now.
6208 if (Decls) {
6209 Decls->push_back(D);
6210 continue;
6211 }
6212
Guy Benyei7f92f2d2012-12-18 14:30:41 +00006213 // Introduce this declaration into the translation-unit scope
6214 // and add it to the declaration chain for this identifier, so
6215 // that (unqualified) name lookup will find it.
Douglas Gregoraa945902013-02-18 15:53:43 +00006216 NamedDecl *ND = cast<NamedDecl>(D->getMostRecentDecl());
6217 SemaObj->pushExternalDeclIntoScope(ND, II);
Guy Benyei7f92f2d2012-12-18 14:30:41 +00006218 } else {
6219 // Queue this declaration so that it will be added to the
6220 // translation unit scope and identifier's declaration chain
6221 // once a Sema object is known.
6222 PreloadedDecls.push_back(D);
6223 }
6224 }
6225}
6226
Douglas Gregor8222b892013-01-21 16:52:34 +00006227IdentifierInfo *ASTReader::DecodeIdentifierInfo(IdentifierID ID) {
Guy Benyei7f92f2d2012-12-18 14:30:41 +00006228 if (ID == 0)
6229 return 0;
6230
6231 if (IdentifiersLoaded.empty()) {
6232 Error("no identifier table in AST file");
6233 return 0;
6234 }
6235
6236 ID -= 1;
6237 if (!IdentifiersLoaded[ID]) {
6238 GlobalIdentifierMapType::iterator I = GlobalIdentifierMap.find(ID + 1);
6239 assert(I != GlobalIdentifierMap.end() && "Corrupted global identifier map");
6240 ModuleFile *M = I->second;
6241 unsigned Index = ID - M->BaseIdentifierID;
6242 const char *Str = M->IdentifierTableData + M->IdentifierOffsets[Index];
6243
6244 // All of the strings in the AST file are preceded by a 16-bit length.
6245 // Extract that 16-bit length to avoid having to execute strlen().
6246 // NOTE: 'StrLenPtr' is an 'unsigned char*' so that we load bytes as
6247 // unsigned integers. This is important to avoid integer overflow when
6248 // we cast them to 'unsigned'.
6249 const unsigned char *StrLenPtr = (const unsigned char*) Str - 2;
6250 unsigned StrLen = (((unsigned) StrLenPtr[0])
6251 | (((unsigned) StrLenPtr[1]) << 8)) - 1;
Douglas Gregor8222b892013-01-21 16:52:34 +00006252 IdentifiersLoaded[ID]
6253 = &PP.getIdentifierTable().get(StringRef(Str, StrLen));
Guy Benyei7f92f2d2012-12-18 14:30:41 +00006254 if (DeserializationListener)
6255 DeserializationListener->IdentifierRead(ID + 1, IdentifiersLoaded[ID]);
6256 }
6257
6258 return IdentifiersLoaded[ID];
6259}
6260
Douglas Gregor8222b892013-01-21 16:52:34 +00006261IdentifierInfo *ASTReader::getLocalIdentifier(ModuleFile &M, unsigned LocalID) {
6262 return DecodeIdentifierInfo(getGlobalIdentifierID(M, LocalID));
Guy Benyei7f92f2d2012-12-18 14:30:41 +00006263}
6264
6265IdentifierID ASTReader::getGlobalIdentifierID(ModuleFile &M, unsigned LocalID) {
6266 if (LocalID < NUM_PREDEF_IDENT_IDS)
6267 return LocalID;
6268
6269 ContinuousRangeMap<uint32_t, int, 2>::iterator I
6270 = M.IdentifierRemap.find(LocalID - NUM_PREDEF_IDENT_IDS);
6271 assert(I != M.IdentifierRemap.end()
6272 && "Invalid index into identifier index remap");
6273
6274 return LocalID + I->second;
6275}
6276
Argyrios Kyrtzidis9818a1d2013-02-20 00:54:57 +00006277MacroDirective *ASTReader::getMacro(MacroID ID, MacroDirective *Hint) {
Guy Benyei7f92f2d2012-12-18 14:30:41 +00006278 if (ID == 0)
6279 return 0;
6280
6281 if (MacrosLoaded.empty()) {
6282 Error("no macro table in AST file");
6283 return 0;
6284 }
6285
6286 ID -= NUM_PREDEF_MACRO_IDS;
6287 if (!MacrosLoaded[ID]) {
6288 GlobalMacroMapType::iterator I
6289 = GlobalMacroMap.find(ID + NUM_PREDEF_MACRO_IDS);
6290 assert(I != GlobalMacroMap.end() && "Corrupted global macro map");
6291 ModuleFile *M = I->second;
6292 unsigned Index = ID - M->BaseMacroID;
Argyrios Kyrtzidisdc1088f2013-01-19 03:14:56 +00006293 ReadMacroRecord(*M, M->MacroOffsets[Index], Hint);
Guy Benyei7f92f2d2012-12-18 14:30:41 +00006294 }
6295
6296 return MacrosLoaded[ID];
6297}
6298
6299MacroID ASTReader::getGlobalMacroID(ModuleFile &M, unsigned LocalID) {
6300 if (LocalID < NUM_PREDEF_MACRO_IDS)
6301 return LocalID;
6302
6303 ContinuousRangeMap<uint32_t, int, 2>::iterator I
6304 = M.MacroRemap.find(LocalID - NUM_PREDEF_MACRO_IDS);
6305 assert(I != M.MacroRemap.end() && "Invalid index into macro index remap");
6306
6307 return LocalID + I->second;
6308}
6309
6310serialization::SubmoduleID
6311ASTReader::getGlobalSubmoduleID(ModuleFile &M, unsigned LocalID) {
6312 if (LocalID < NUM_PREDEF_SUBMODULE_IDS)
6313 return LocalID;
6314
6315 ContinuousRangeMap<uint32_t, int, 2>::iterator I
6316 = M.SubmoduleRemap.find(LocalID - NUM_PREDEF_SUBMODULE_IDS);
6317 assert(I != M.SubmoduleRemap.end()
6318 && "Invalid index into submodule index remap");
6319
6320 return LocalID + I->second;
6321}
6322
6323Module *ASTReader::getSubmodule(SubmoduleID GlobalID) {
6324 if (GlobalID < NUM_PREDEF_SUBMODULE_IDS) {
6325 assert(GlobalID == 0 && "Unhandled global submodule ID");
6326 return 0;
6327 }
6328
6329 if (GlobalID > SubmodulesLoaded.size()) {
6330 Error("submodule ID out of range in AST file");
6331 return 0;
6332 }
6333
6334 return SubmodulesLoaded[GlobalID - NUM_PREDEF_SUBMODULE_IDS];
6335}
Douglas Gregorca2ab452013-01-12 01:29:50 +00006336
6337Module *ASTReader::getModule(unsigned ID) {
6338 return getSubmodule(ID);
6339}
6340
Guy Benyei7f92f2d2012-12-18 14:30:41 +00006341Selector ASTReader::getLocalSelector(ModuleFile &M, unsigned LocalID) {
6342 return DecodeSelector(getGlobalSelectorID(M, LocalID));
6343}
6344
6345Selector ASTReader::DecodeSelector(serialization::SelectorID ID) {
6346 if (ID == 0)
6347 return Selector();
6348
6349 if (ID > SelectorsLoaded.size()) {
6350 Error("selector ID out of range in AST file");
6351 return Selector();
6352 }
6353
6354 if (SelectorsLoaded[ID - 1].getAsOpaquePtr() == 0) {
6355 // Load this selector from the selector table.
6356 GlobalSelectorMapType::iterator I = GlobalSelectorMap.find(ID);
6357 assert(I != GlobalSelectorMap.end() && "Corrupted global selector map");
6358 ModuleFile &M = *I->second;
6359 ASTSelectorLookupTrait Trait(*this, M);
6360 unsigned Idx = ID - M.BaseSelectorID - NUM_PREDEF_SELECTOR_IDS;
6361 SelectorsLoaded[ID - 1] =
6362 Trait.ReadKey(M.SelectorLookupTableData + M.SelectorOffsets[Idx], 0);
6363 if (DeserializationListener)
6364 DeserializationListener->SelectorRead(ID, SelectorsLoaded[ID - 1]);
6365 }
6366
6367 return SelectorsLoaded[ID - 1];
6368}
6369
6370Selector ASTReader::GetExternalSelector(serialization::SelectorID ID) {
6371 return DecodeSelector(ID);
6372}
6373
6374uint32_t ASTReader::GetNumExternalSelectors() {
6375 // ID 0 (the null selector) is considered an external selector.
6376 return getTotalNumSelectors() + 1;
6377}
6378
6379serialization::SelectorID
6380ASTReader::getGlobalSelectorID(ModuleFile &M, unsigned LocalID) const {
6381 if (LocalID < NUM_PREDEF_SELECTOR_IDS)
6382 return LocalID;
6383
6384 ContinuousRangeMap<uint32_t, int, 2>::iterator I
6385 = M.SelectorRemap.find(LocalID - NUM_PREDEF_SELECTOR_IDS);
6386 assert(I != M.SelectorRemap.end()
6387 && "Invalid index into selector index remap");
6388
6389 return LocalID + I->second;
6390}
6391
6392DeclarationName
6393ASTReader::ReadDeclarationName(ModuleFile &F,
6394 const RecordData &Record, unsigned &Idx) {
6395 DeclarationName::NameKind Kind = (DeclarationName::NameKind)Record[Idx++];
6396 switch (Kind) {
6397 case DeclarationName::Identifier:
Douglas Gregor8222b892013-01-21 16:52:34 +00006398 return DeclarationName(GetIdentifierInfo(F, Record, Idx));
Guy Benyei7f92f2d2012-12-18 14:30:41 +00006399
6400 case DeclarationName::ObjCZeroArgSelector:
6401 case DeclarationName::ObjCOneArgSelector:
6402 case DeclarationName::ObjCMultiArgSelector:
6403 return DeclarationName(ReadSelector(F, Record, Idx));
6404
6405 case DeclarationName::CXXConstructorName:
6406 return Context.DeclarationNames.getCXXConstructorName(
6407 Context.getCanonicalType(readType(F, Record, Idx)));
6408
6409 case DeclarationName::CXXDestructorName:
6410 return Context.DeclarationNames.getCXXDestructorName(
6411 Context.getCanonicalType(readType(F, Record, Idx)));
6412
6413 case DeclarationName::CXXConversionFunctionName:
6414 return Context.DeclarationNames.getCXXConversionFunctionName(
6415 Context.getCanonicalType(readType(F, Record, Idx)));
6416
6417 case DeclarationName::CXXOperatorName:
6418 return Context.DeclarationNames.getCXXOperatorName(
6419 (OverloadedOperatorKind)Record[Idx++]);
6420
6421 case DeclarationName::CXXLiteralOperatorName:
6422 return Context.DeclarationNames.getCXXLiteralOperatorName(
6423 GetIdentifierInfo(F, Record, Idx));
6424
6425 case DeclarationName::CXXUsingDirective:
6426 return DeclarationName::getUsingDirectiveName();
6427 }
6428
6429 llvm_unreachable("Invalid NameKind!");
6430}
6431
6432void ASTReader::ReadDeclarationNameLoc(ModuleFile &F,
6433 DeclarationNameLoc &DNLoc,
6434 DeclarationName Name,
6435 const RecordData &Record, unsigned &Idx) {
6436 switch (Name.getNameKind()) {
6437 case DeclarationName::CXXConstructorName:
6438 case DeclarationName::CXXDestructorName:
6439 case DeclarationName::CXXConversionFunctionName:
6440 DNLoc.NamedType.TInfo = GetTypeSourceInfo(F, Record, Idx);
6441 break;
6442
6443 case DeclarationName::CXXOperatorName:
6444 DNLoc.CXXOperatorName.BeginOpNameLoc
6445 = ReadSourceLocation(F, Record, Idx).getRawEncoding();
6446 DNLoc.CXXOperatorName.EndOpNameLoc
6447 = ReadSourceLocation(F, Record, Idx).getRawEncoding();
6448 break;
6449
6450 case DeclarationName::CXXLiteralOperatorName:
6451 DNLoc.CXXLiteralOperatorName.OpNameLoc
6452 = ReadSourceLocation(F, Record, Idx).getRawEncoding();
6453 break;
6454
6455 case DeclarationName::Identifier:
6456 case DeclarationName::ObjCZeroArgSelector:
6457 case DeclarationName::ObjCOneArgSelector:
6458 case DeclarationName::ObjCMultiArgSelector:
6459 case DeclarationName::CXXUsingDirective:
6460 break;
6461 }
6462}
6463
6464void ASTReader::ReadDeclarationNameInfo(ModuleFile &F,
6465 DeclarationNameInfo &NameInfo,
6466 const RecordData &Record, unsigned &Idx) {
6467 NameInfo.setName(ReadDeclarationName(F, Record, Idx));
6468 NameInfo.setLoc(ReadSourceLocation(F, Record, Idx));
6469 DeclarationNameLoc DNLoc;
6470 ReadDeclarationNameLoc(F, DNLoc, NameInfo.getName(), Record, Idx);
6471 NameInfo.setInfo(DNLoc);
6472}
6473
6474void ASTReader::ReadQualifierInfo(ModuleFile &F, QualifierInfo &Info,
6475 const RecordData &Record, unsigned &Idx) {
6476 Info.QualifierLoc = ReadNestedNameSpecifierLoc(F, Record, Idx);
6477 unsigned NumTPLists = Record[Idx++];
6478 Info.NumTemplParamLists = NumTPLists;
6479 if (NumTPLists) {
6480 Info.TemplParamLists = new (Context) TemplateParameterList*[NumTPLists];
6481 for (unsigned i=0; i != NumTPLists; ++i)
6482 Info.TemplParamLists[i] = ReadTemplateParameterList(F, Record, Idx);
6483 }
6484}
6485
6486TemplateName
6487ASTReader::ReadTemplateName(ModuleFile &F, const RecordData &Record,
6488 unsigned &Idx) {
6489 TemplateName::NameKind Kind = (TemplateName::NameKind)Record[Idx++];
6490 switch (Kind) {
6491 case TemplateName::Template:
6492 return TemplateName(ReadDeclAs<TemplateDecl>(F, Record, Idx));
6493
6494 case TemplateName::OverloadedTemplate: {
6495 unsigned size = Record[Idx++];
6496 UnresolvedSet<8> Decls;
6497 while (size--)
6498 Decls.addDecl(ReadDeclAs<NamedDecl>(F, Record, Idx));
6499
6500 return Context.getOverloadedTemplateName(Decls.begin(), Decls.end());
6501 }
6502
6503 case TemplateName::QualifiedTemplate: {
6504 NestedNameSpecifier *NNS = ReadNestedNameSpecifier(F, Record, Idx);
6505 bool hasTemplKeyword = Record[Idx++];
6506 TemplateDecl *Template = ReadDeclAs<TemplateDecl>(F, Record, Idx);
6507 return Context.getQualifiedTemplateName(NNS, hasTemplKeyword, Template);
6508 }
6509
6510 case TemplateName::DependentTemplate: {
6511 NestedNameSpecifier *NNS = ReadNestedNameSpecifier(F, Record, Idx);
6512 if (Record[Idx++]) // isIdentifier
6513 return Context.getDependentTemplateName(NNS,
6514 GetIdentifierInfo(F, Record,
6515 Idx));
6516 return Context.getDependentTemplateName(NNS,
6517 (OverloadedOperatorKind)Record[Idx++]);
6518 }
6519
6520 case TemplateName::SubstTemplateTemplateParm: {
6521 TemplateTemplateParmDecl *param
6522 = ReadDeclAs<TemplateTemplateParmDecl>(F, Record, Idx);
6523 if (!param) return TemplateName();
6524 TemplateName replacement = ReadTemplateName(F, Record, Idx);
6525 return Context.getSubstTemplateTemplateParm(param, replacement);
6526 }
6527
6528 case TemplateName::SubstTemplateTemplateParmPack: {
6529 TemplateTemplateParmDecl *Param
6530 = ReadDeclAs<TemplateTemplateParmDecl>(F, Record, Idx);
6531 if (!Param)
6532 return TemplateName();
6533
6534 TemplateArgument ArgPack = ReadTemplateArgument(F, Record, Idx);
6535 if (ArgPack.getKind() != TemplateArgument::Pack)
6536 return TemplateName();
6537
6538 return Context.getSubstTemplateTemplateParmPack(Param, ArgPack);
6539 }
6540 }
6541
6542 llvm_unreachable("Unhandled template name kind!");
6543}
6544
6545TemplateArgument
6546ASTReader::ReadTemplateArgument(ModuleFile &F,
6547 const RecordData &Record, unsigned &Idx) {
6548 TemplateArgument::ArgKind Kind = (TemplateArgument::ArgKind)Record[Idx++];
6549 switch (Kind) {
6550 case TemplateArgument::Null:
6551 return TemplateArgument();
6552 case TemplateArgument::Type:
6553 return TemplateArgument(readType(F, Record, Idx));
6554 case TemplateArgument::Declaration: {
6555 ValueDecl *D = ReadDeclAs<ValueDecl>(F, Record, Idx);
6556 bool ForReferenceParam = Record[Idx++];
6557 return TemplateArgument(D, ForReferenceParam);
6558 }
6559 case TemplateArgument::NullPtr:
6560 return TemplateArgument(readType(F, Record, Idx), /*isNullPtr*/true);
6561 case TemplateArgument::Integral: {
6562 llvm::APSInt Value = ReadAPSInt(Record, Idx);
6563 QualType T = readType(F, Record, Idx);
6564 return TemplateArgument(Context, Value, T);
6565 }
6566 case TemplateArgument::Template:
6567 return TemplateArgument(ReadTemplateName(F, Record, Idx));
6568 case TemplateArgument::TemplateExpansion: {
6569 TemplateName Name = ReadTemplateName(F, Record, Idx);
David Blaikiedc84cd52013-02-20 22:23:23 +00006570 Optional<unsigned> NumTemplateExpansions;
Guy Benyei7f92f2d2012-12-18 14:30:41 +00006571 if (unsigned NumExpansions = Record[Idx++])
6572 NumTemplateExpansions = NumExpansions - 1;
6573 return TemplateArgument(Name, NumTemplateExpansions);
6574 }
6575 case TemplateArgument::Expression:
6576 return TemplateArgument(ReadExpr(F));
6577 case TemplateArgument::Pack: {
6578 unsigned NumArgs = Record[Idx++];
6579 TemplateArgument *Args = new (Context) TemplateArgument[NumArgs];
6580 for (unsigned I = 0; I != NumArgs; ++I)
6581 Args[I] = ReadTemplateArgument(F, Record, Idx);
6582 return TemplateArgument(Args, NumArgs);
6583 }
6584 }
6585
6586 llvm_unreachable("Unhandled template argument kind!");
6587}
6588
6589TemplateParameterList *
6590ASTReader::ReadTemplateParameterList(ModuleFile &F,
6591 const RecordData &Record, unsigned &Idx) {
6592 SourceLocation TemplateLoc = ReadSourceLocation(F, Record, Idx);
6593 SourceLocation LAngleLoc = ReadSourceLocation(F, Record, Idx);
6594 SourceLocation RAngleLoc = ReadSourceLocation(F, Record, Idx);
6595
6596 unsigned NumParams = Record[Idx++];
6597 SmallVector<NamedDecl *, 16> Params;
6598 Params.reserve(NumParams);
6599 while (NumParams--)
6600 Params.push_back(ReadDeclAs<NamedDecl>(F, Record, Idx));
6601
6602 TemplateParameterList* TemplateParams =
6603 TemplateParameterList::Create(Context, TemplateLoc, LAngleLoc,
6604 Params.data(), Params.size(), RAngleLoc);
6605 return TemplateParams;
6606}
6607
6608void
6609ASTReader::
6610ReadTemplateArgumentList(SmallVector<TemplateArgument, 8> &TemplArgs,
6611 ModuleFile &F, const RecordData &Record,
6612 unsigned &Idx) {
6613 unsigned NumTemplateArgs = Record[Idx++];
6614 TemplArgs.reserve(NumTemplateArgs);
6615 while (NumTemplateArgs--)
6616 TemplArgs.push_back(ReadTemplateArgument(F, Record, Idx));
6617}
6618
6619/// \brief Read a UnresolvedSet structure.
6620void ASTReader::ReadUnresolvedSet(ModuleFile &F, ASTUnresolvedSet &Set,
6621 const RecordData &Record, unsigned &Idx) {
6622 unsigned NumDecls = Record[Idx++];
6623 Set.reserve(Context, NumDecls);
6624 while (NumDecls--) {
6625 NamedDecl *D = ReadDeclAs<NamedDecl>(F, Record, Idx);
6626 AccessSpecifier AS = (AccessSpecifier)Record[Idx++];
6627 Set.addDecl(Context, D, AS);
6628 }
6629}
6630
6631CXXBaseSpecifier
6632ASTReader::ReadCXXBaseSpecifier(ModuleFile &F,
6633 const RecordData &Record, unsigned &Idx) {
6634 bool isVirtual = static_cast<bool>(Record[Idx++]);
6635 bool isBaseOfClass = static_cast<bool>(Record[Idx++]);
6636 AccessSpecifier AS = static_cast<AccessSpecifier>(Record[Idx++]);
6637 bool inheritConstructors = static_cast<bool>(Record[Idx++]);
6638 TypeSourceInfo *TInfo = GetTypeSourceInfo(F, Record, Idx);
6639 SourceRange Range = ReadSourceRange(F, Record, Idx);
6640 SourceLocation EllipsisLoc = ReadSourceLocation(F, Record, Idx);
6641 CXXBaseSpecifier Result(Range, isVirtual, isBaseOfClass, AS, TInfo,
6642 EllipsisLoc);
6643 Result.setInheritConstructors(inheritConstructors);
6644 return Result;
6645}
6646
6647std::pair<CXXCtorInitializer **, unsigned>
6648ASTReader::ReadCXXCtorInitializers(ModuleFile &F, const RecordData &Record,
6649 unsigned &Idx) {
6650 CXXCtorInitializer **CtorInitializers = 0;
6651 unsigned NumInitializers = Record[Idx++];
6652 if (NumInitializers) {
6653 CtorInitializers
6654 = new (Context) CXXCtorInitializer*[NumInitializers];
6655 for (unsigned i=0; i != NumInitializers; ++i) {
6656 TypeSourceInfo *TInfo = 0;
6657 bool IsBaseVirtual = false;
6658 FieldDecl *Member = 0;
6659 IndirectFieldDecl *IndirectMember = 0;
6660
6661 CtorInitializerType Type = (CtorInitializerType)Record[Idx++];
6662 switch (Type) {
6663 case CTOR_INITIALIZER_BASE:
6664 TInfo = GetTypeSourceInfo(F, Record, Idx);
6665 IsBaseVirtual = Record[Idx++];
6666 break;
6667
6668 case CTOR_INITIALIZER_DELEGATING:
6669 TInfo = GetTypeSourceInfo(F, Record, Idx);
6670 break;
6671
6672 case CTOR_INITIALIZER_MEMBER:
6673 Member = ReadDeclAs<FieldDecl>(F, Record, Idx);
6674 break;
6675
6676 case CTOR_INITIALIZER_INDIRECT_MEMBER:
6677 IndirectMember = ReadDeclAs<IndirectFieldDecl>(F, Record, Idx);
6678 break;
6679 }
6680
6681 SourceLocation MemberOrEllipsisLoc = ReadSourceLocation(F, Record, Idx);
6682 Expr *Init = ReadExpr(F);
6683 SourceLocation LParenLoc = ReadSourceLocation(F, Record, Idx);
6684 SourceLocation RParenLoc = ReadSourceLocation(F, Record, Idx);
6685 bool IsWritten = Record[Idx++];
6686 unsigned SourceOrderOrNumArrayIndices;
6687 SmallVector<VarDecl *, 8> Indices;
6688 if (IsWritten) {
6689 SourceOrderOrNumArrayIndices = Record[Idx++];
6690 } else {
6691 SourceOrderOrNumArrayIndices = Record[Idx++];
6692 Indices.reserve(SourceOrderOrNumArrayIndices);
6693 for (unsigned i=0; i != SourceOrderOrNumArrayIndices; ++i)
6694 Indices.push_back(ReadDeclAs<VarDecl>(F, Record, Idx));
6695 }
6696
6697 CXXCtorInitializer *BOMInit;
6698 if (Type == CTOR_INITIALIZER_BASE) {
6699 BOMInit = new (Context) CXXCtorInitializer(Context, TInfo, IsBaseVirtual,
6700 LParenLoc, Init, RParenLoc,
6701 MemberOrEllipsisLoc);
6702 } else if (Type == CTOR_INITIALIZER_DELEGATING) {
6703 BOMInit = new (Context) CXXCtorInitializer(Context, TInfo, LParenLoc,
6704 Init, RParenLoc);
6705 } else if (IsWritten) {
6706 if (Member)
6707 BOMInit = new (Context) CXXCtorInitializer(Context, Member, MemberOrEllipsisLoc,
6708 LParenLoc, Init, RParenLoc);
6709 else
6710 BOMInit = new (Context) CXXCtorInitializer(Context, IndirectMember,
6711 MemberOrEllipsisLoc, LParenLoc,
6712 Init, RParenLoc);
6713 } else {
6714 BOMInit = CXXCtorInitializer::Create(Context, Member, MemberOrEllipsisLoc,
6715 LParenLoc, Init, RParenLoc,
6716 Indices.data(), Indices.size());
6717 }
6718
6719 if (IsWritten)
6720 BOMInit->setSourceOrder(SourceOrderOrNumArrayIndices);
6721 CtorInitializers[i] = BOMInit;
6722 }
6723 }
6724
6725 return std::make_pair(CtorInitializers, NumInitializers);
6726}
6727
6728NestedNameSpecifier *
6729ASTReader::ReadNestedNameSpecifier(ModuleFile &F,
6730 const RecordData &Record, unsigned &Idx) {
6731 unsigned N = Record[Idx++];
6732 NestedNameSpecifier *NNS = 0, *Prev = 0;
6733 for (unsigned I = 0; I != N; ++I) {
6734 NestedNameSpecifier::SpecifierKind Kind
6735 = (NestedNameSpecifier::SpecifierKind)Record[Idx++];
6736 switch (Kind) {
6737 case NestedNameSpecifier::Identifier: {
6738 IdentifierInfo *II = GetIdentifierInfo(F, Record, Idx);
6739 NNS = NestedNameSpecifier::Create(Context, Prev, II);
6740 break;
6741 }
6742
6743 case NestedNameSpecifier::Namespace: {
6744 NamespaceDecl *NS = ReadDeclAs<NamespaceDecl>(F, Record, Idx);
6745 NNS = NestedNameSpecifier::Create(Context, Prev, NS);
6746 break;
6747 }
6748
6749 case NestedNameSpecifier::NamespaceAlias: {
6750 NamespaceAliasDecl *Alias =ReadDeclAs<NamespaceAliasDecl>(F, Record, Idx);
6751 NNS = NestedNameSpecifier::Create(Context, Prev, Alias);
6752 break;
6753 }
6754
6755 case NestedNameSpecifier::TypeSpec:
6756 case NestedNameSpecifier::TypeSpecWithTemplate: {
6757 const Type *T = readType(F, Record, Idx).getTypePtrOrNull();
6758 if (!T)
6759 return 0;
6760
6761 bool Template = Record[Idx++];
6762 NNS = NestedNameSpecifier::Create(Context, Prev, Template, T);
6763 break;
6764 }
6765
6766 case NestedNameSpecifier::Global: {
6767 NNS = NestedNameSpecifier::GlobalSpecifier(Context);
6768 // No associated value, and there can't be a prefix.
6769 break;
6770 }
6771 }
6772 Prev = NNS;
6773 }
6774 return NNS;
6775}
6776
6777NestedNameSpecifierLoc
6778ASTReader::ReadNestedNameSpecifierLoc(ModuleFile &F, const RecordData &Record,
6779 unsigned &Idx) {
6780 unsigned N = Record[Idx++];
6781 NestedNameSpecifierLocBuilder Builder;
6782 for (unsigned I = 0; I != N; ++I) {
6783 NestedNameSpecifier::SpecifierKind Kind
6784 = (NestedNameSpecifier::SpecifierKind)Record[Idx++];
6785 switch (Kind) {
6786 case NestedNameSpecifier::Identifier: {
6787 IdentifierInfo *II = GetIdentifierInfo(F, Record, Idx);
6788 SourceRange Range = ReadSourceRange(F, Record, Idx);
6789 Builder.Extend(Context, II, Range.getBegin(), Range.getEnd());
6790 break;
6791 }
6792
6793 case NestedNameSpecifier::Namespace: {
6794 NamespaceDecl *NS = ReadDeclAs<NamespaceDecl>(F, Record, Idx);
6795 SourceRange Range = ReadSourceRange(F, Record, Idx);
6796 Builder.Extend(Context, NS, Range.getBegin(), Range.getEnd());
6797 break;
6798 }
6799
6800 case NestedNameSpecifier::NamespaceAlias: {
6801 NamespaceAliasDecl *Alias =ReadDeclAs<NamespaceAliasDecl>(F, Record, Idx);
6802 SourceRange Range = ReadSourceRange(F, Record, Idx);
6803 Builder.Extend(Context, Alias, Range.getBegin(), Range.getEnd());
6804 break;
6805 }
6806
6807 case NestedNameSpecifier::TypeSpec:
6808 case NestedNameSpecifier::TypeSpecWithTemplate: {
6809 bool Template = Record[Idx++];
6810 TypeSourceInfo *T = GetTypeSourceInfo(F, Record, Idx);
6811 if (!T)
6812 return NestedNameSpecifierLoc();
6813 SourceLocation ColonColonLoc = ReadSourceLocation(F, Record, Idx);
6814
6815 // FIXME: 'template' keyword location not saved anywhere, so we fake it.
6816 Builder.Extend(Context,
6817 Template? T->getTypeLoc().getBeginLoc() : SourceLocation(),
6818 T->getTypeLoc(), ColonColonLoc);
6819 break;
6820 }
6821
6822 case NestedNameSpecifier::Global: {
6823 SourceLocation ColonColonLoc = ReadSourceLocation(F, Record, Idx);
6824 Builder.MakeGlobal(Context, ColonColonLoc);
6825 break;
6826 }
6827 }
6828 }
6829
6830 return Builder.getWithLocInContext(Context);
6831}
6832
6833SourceRange
6834ASTReader::ReadSourceRange(ModuleFile &F, const RecordData &Record,
6835 unsigned &Idx) {
6836 SourceLocation beg = ReadSourceLocation(F, Record, Idx);
6837 SourceLocation end = ReadSourceLocation(F, Record, Idx);
6838 return SourceRange(beg, end);
6839}
6840
6841/// \brief Read an integral value
6842llvm::APInt ASTReader::ReadAPInt(const RecordData &Record, unsigned &Idx) {
6843 unsigned BitWidth = Record[Idx++];
6844 unsigned NumWords = llvm::APInt::getNumWords(BitWidth);
6845 llvm::APInt Result(BitWidth, NumWords, &Record[Idx]);
6846 Idx += NumWords;
6847 return Result;
6848}
6849
6850/// \brief Read a signed integral value
6851llvm::APSInt ASTReader::ReadAPSInt(const RecordData &Record, unsigned &Idx) {
6852 bool isUnsigned = Record[Idx++];
6853 return llvm::APSInt(ReadAPInt(Record, Idx), isUnsigned);
6854}
6855
6856/// \brief Read a floating-point value
Tim Northover9ec55f22013-01-22 09:46:51 +00006857llvm::APFloat ASTReader::ReadAPFloat(const RecordData &Record,
6858 const llvm::fltSemantics &Sem,
6859 unsigned &Idx) {
6860 return llvm::APFloat(Sem, ReadAPInt(Record, Idx));
Guy Benyei7f92f2d2012-12-18 14:30:41 +00006861}
6862
6863// \brief Read a string
6864std::string ASTReader::ReadString(const RecordData &Record, unsigned &Idx) {
6865 unsigned Len = Record[Idx++];
6866 std::string Result(Record.data() + Idx, Record.data() + Idx + Len);
6867 Idx += Len;
6868 return Result;
6869}
6870
6871VersionTuple ASTReader::ReadVersionTuple(const RecordData &Record,
6872 unsigned &Idx) {
6873 unsigned Major = Record[Idx++];
6874 unsigned Minor = Record[Idx++];
6875 unsigned Subminor = Record[Idx++];
6876 if (Minor == 0)
6877 return VersionTuple(Major);
6878 if (Subminor == 0)
6879 return VersionTuple(Major, Minor - 1);
6880 return VersionTuple(Major, Minor - 1, Subminor - 1);
6881}
6882
6883CXXTemporary *ASTReader::ReadCXXTemporary(ModuleFile &F,
6884 const RecordData &Record,
6885 unsigned &Idx) {
6886 CXXDestructorDecl *Decl = ReadDeclAs<CXXDestructorDecl>(F, Record, Idx);
6887 return CXXTemporary::Create(Context, Decl);
6888}
6889
6890DiagnosticBuilder ASTReader::Diag(unsigned DiagID) {
6891 return Diag(SourceLocation(), DiagID);
6892}
6893
6894DiagnosticBuilder ASTReader::Diag(SourceLocation Loc, unsigned DiagID) {
6895 return Diags.Report(Loc, DiagID);
6896}
6897
6898/// \brief Retrieve the identifier table associated with the
6899/// preprocessor.
6900IdentifierTable &ASTReader::getIdentifierTable() {
6901 return PP.getIdentifierTable();
6902}
6903
6904/// \brief Record that the given ID maps to the given switch-case
6905/// statement.
6906void ASTReader::RecordSwitchCaseID(SwitchCase *SC, unsigned ID) {
6907 assert((*CurrSwitchCaseStmts)[ID] == 0 &&
6908 "Already have a SwitchCase with this ID");
6909 (*CurrSwitchCaseStmts)[ID] = SC;
6910}
6911
6912/// \brief Retrieve the switch-case statement with the given ID.
6913SwitchCase *ASTReader::getSwitchCaseWithID(unsigned ID) {
6914 assert((*CurrSwitchCaseStmts)[ID] != 0 && "No SwitchCase with this ID");
6915 return (*CurrSwitchCaseStmts)[ID];
6916}
6917
6918void ASTReader::ClearSwitchCaseIDs() {
6919 CurrSwitchCaseStmts->clear();
6920}
6921
6922void ASTReader::ReadComments() {
6923 std::vector<RawComment *> Comments;
Chris Lattner8f9a1eb2013-01-20 00:56:42 +00006924 for (SmallVectorImpl<std::pair<BitstreamCursor,
Guy Benyei7f92f2d2012-12-18 14:30:41 +00006925 serialization::ModuleFile *> >::iterator
6926 I = CommentsCursors.begin(),
6927 E = CommentsCursors.end();
6928 I != E; ++I) {
Chris Lattner8f9a1eb2013-01-20 00:56:42 +00006929 BitstreamCursor &Cursor = I->first;
Guy Benyei7f92f2d2012-12-18 14:30:41 +00006930 serialization::ModuleFile &F = *I->second;
6931 SavedStreamPosition SavedPosition(Cursor);
6932
6933 RecordData Record;
6934 while (true) {
Chris Lattner8f9a1eb2013-01-20 00:56:42 +00006935 llvm::BitstreamEntry Entry =
6936 Cursor.advanceSkippingSubblocks(BitstreamCursor::AF_DontPopBlockAtEnd);
6937
6938 switch (Entry.Kind) {
6939 case llvm::BitstreamEntry::SubBlock: // Handled for us already.
6940 case llvm::BitstreamEntry::Error:
6941 Error("malformed block record in AST file");
6942 return;
6943 case llvm::BitstreamEntry::EndBlock:
6944 goto NextCursor;
6945 case llvm::BitstreamEntry::Record:
6946 // The interesting case.
Guy Benyei7f92f2d2012-12-18 14:30:41 +00006947 break;
Guy Benyei7f92f2d2012-12-18 14:30:41 +00006948 }
6949
6950 // Read a record.
6951 Record.clear();
Chris Lattnerb3ce3572013-01-20 02:38:54 +00006952 switch ((CommentRecordTypes)Cursor.readRecord(Entry.ID, Record)) {
Guy Benyei7f92f2d2012-12-18 14:30:41 +00006953 case COMMENTS_RAW_COMMENT: {
6954 unsigned Idx = 0;
6955 SourceRange SR = ReadSourceRange(F, Record, Idx);
6956 RawComment::CommentKind Kind =
6957 (RawComment::CommentKind) Record[Idx++];
6958 bool IsTrailingComment = Record[Idx++];
6959 bool IsAlmostTrailingComment = Record[Idx++];
6960 Comments.push_back(new (Context) RawComment(SR, Kind,
6961 IsTrailingComment,
6962 IsAlmostTrailingComment));
6963 break;
6964 }
6965 }
6966 }
Chris Lattner8f9a1eb2013-01-20 00:56:42 +00006967 NextCursor:;
Guy Benyei7f92f2d2012-12-18 14:30:41 +00006968 }
6969 Context.Comments.addCommentsToFront(Comments);
6970}
6971
6972void ASTReader::finishPendingActions() {
6973 while (!PendingIdentifierInfos.empty() || !PendingDeclChains.empty() ||
Argyrios Kyrtzidis7640b022013-02-16 00:48:59 +00006974 !PendingMacroIDs.empty() || !PendingDeclContextInfos.empty()) {
Guy Benyei7f92f2d2012-12-18 14:30:41 +00006975 // If any identifiers with corresponding top-level declarations have
6976 // been loaded, load those declarations now.
Douglas Gregoraa945902013-02-18 15:53:43 +00006977 llvm::DenseMap<IdentifierInfo *, SmallVector<Decl *, 2> > TopLevelDecls;
Guy Benyei7f92f2d2012-12-18 14:30:41 +00006978 while (!PendingIdentifierInfos.empty()) {
Douglas Gregoraa945902013-02-18 15:53:43 +00006979 // FIXME: std::move
6980 IdentifierInfo *II = PendingIdentifierInfos.back().first;
6981 SmallVector<uint32_t, 4> DeclIDs = PendingIdentifierInfos.back().second;
Douglas Gregorcc9bdcb2013-02-19 18:26:28 +00006982 PendingIdentifierInfos.pop_back();
Douglas Gregoraa945902013-02-18 15:53:43 +00006983
6984 SetGloballyVisibleDecls(II, DeclIDs, &TopLevelDecls[II]);
Guy Benyei7f92f2d2012-12-18 14:30:41 +00006985 }
6986
6987 // Load pending declaration chains.
6988 for (unsigned I = 0; I != PendingDeclChains.size(); ++I) {
6989 loadPendingDeclChain(PendingDeclChains[I]);
6990 PendingDeclChainsKnown.erase(PendingDeclChains[I]);
6991 }
6992 PendingDeclChains.clear();
6993
Douglas Gregoraa945902013-02-18 15:53:43 +00006994 // Make the most recent of the top-level declarations visible.
6995 for (llvm::DenseMap<IdentifierInfo *, SmallVector<Decl *, 2> >::iterator
6996 TLD = TopLevelDecls.begin(), TLDEnd = TopLevelDecls.end();
6997 TLD != TLDEnd; ++TLD) {
6998 IdentifierInfo *II = TLD->first;
6999 for (unsigned I = 0, N = TLD->second.size(); I != N; ++I) {
7000 NamedDecl *ND = cast<NamedDecl>(TLD->second[I]->getMostRecentDecl());
7001 SemaObj->pushExternalDeclIntoScope(ND, II);
7002 }
7003 }
7004
Guy Benyei7f92f2d2012-12-18 14:30:41 +00007005 // Load any pending macro definitions.
7006 for (unsigned I = 0; I != PendingMacroIDs.size(); ++I) {
Argyrios Kyrtzidisdc1088f2013-01-19 03:14:56 +00007007 // FIXME: std::move here
7008 SmallVector<MacroID, 2> GlobalIDs = PendingMacroIDs.begin()[I].second;
Argyrios Kyrtzidis9818a1d2013-02-20 00:54:57 +00007009 MacroDirective *Hint = 0;
Argyrios Kyrtzidisdc1088f2013-01-19 03:14:56 +00007010 for (unsigned IDIdx = 0, NumIDs = GlobalIDs.size(); IDIdx != NumIDs;
7011 ++IDIdx) {
7012 Hint = getMacro(GlobalIDs[IDIdx], Hint);
Guy Benyei7f92f2d2012-12-18 14:30:41 +00007013 }
7014 }
7015 PendingMacroIDs.clear();
Argyrios Kyrtzidis7640b022013-02-16 00:48:59 +00007016
7017 // Wire up the DeclContexts for Decls that we delayed setting until
7018 // recursive loading is completed.
7019 while (!PendingDeclContextInfos.empty()) {
7020 PendingDeclContextInfo Info = PendingDeclContextInfos.front();
7021 PendingDeclContextInfos.pop_front();
7022 DeclContext *SemaDC = cast<DeclContext>(GetDecl(Info.SemaDC));
7023 DeclContext *LexicalDC = cast<DeclContext>(GetDecl(Info.LexicalDC));
7024 Info.D->setDeclContextsImpl(SemaDC, LexicalDC, getContext());
7025 }
Guy Benyei7f92f2d2012-12-18 14:30:41 +00007026 }
7027
7028 // If we deserialized any C++ or Objective-C class definitions, any
7029 // Objective-C protocol definitions, or any redeclarable templates, make sure
7030 // that all redeclarations point to the definitions. Note that this can only
7031 // happen now, after the redeclaration chains have been fully wired.
7032 for (llvm::SmallPtrSet<Decl *, 4>::iterator D = PendingDefinitions.begin(),
7033 DEnd = PendingDefinitions.end();
7034 D != DEnd; ++D) {
7035 if (TagDecl *TD = dyn_cast<TagDecl>(*D)) {
7036 if (const TagType *TagT = dyn_cast<TagType>(TD->TypeForDecl)) {
7037 // Make sure that the TagType points at the definition.
7038 const_cast<TagType*>(TagT)->decl = TD;
7039 }
7040
7041 if (CXXRecordDecl *RD = dyn_cast<CXXRecordDecl>(*D)) {
7042 for (CXXRecordDecl::redecl_iterator R = RD->redecls_begin(),
7043 REnd = RD->redecls_end();
7044 R != REnd; ++R)
7045 cast<CXXRecordDecl>(*R)->DefinitionData = RD->DefinitionData;
7046
7047 }
7048
7049 continue;
7050 }
7051
7052 if (ObjCInterfaceDecl *ID = dyn_cast<ObjCInterfaceDecl>(*D)) {
7053 // Make sure that the ObjCInterfaceType points at the definition.
7054 const_cast<ObjCInterfaceType *>(cast<ObjCInterfaceType>(ID->TypeForDecl))
7055 ->Decl = ID;
7056
7057 for (ObjCInterfaceDecl::redecl_iterator R = ID->redecls_begin(),
7058 REnd = ID->redecls_end();
7059 R != REnd; ++R)
7060 R->Data = ID->Data;
7061
7062 continue;
7063 }
7064
7065 if (ObjCProtocolDecl *PD = dyn_cast<ObjCProtocolDecl>(*D)) {
7066 for (ObjCProtocolDecl::redecl_iterator R = PD->redecls_begin(),
7067 REnd = PD->redecls_end();
7068 R != REnd; ++R)
7069 R->Data = PD->Data;
7070
7071 continue;
7072 }
7073
7074 RedeclarableTemplateDecl *RTD
7075 = cast<RedeclarableTemplateDecl>(*D)->getCanonicalDecl();
7076 for (RedeclarableTemplateDecl::redecl_iterator R = RTD->redecls_begin(),
7077 REnd = RTD->redecls_end();
7078 R != REnd; ++R)
7079 R->Common = RTD->Common;
7080 }
7081 PendingDefinitions.clear();
7082
7083 // Load the bodies of any functions or methods we've encountered. We do
7084 // this now (delayed) so that we can be sure that the declaration chains
7085 // have been fully wired up.
7086 for (PendingBodiesMap::iterator PB = PendingBodies.begin(),
7087 PBEnd = PendingBodies.end();
7088 PB != PBEnd; ++PB) {
7089 if (FunctionDecl *FD = dyn_cast<FunctionDecl>(PB->first)) {
7090 // FIXME: Check for =delete/=default?
7091 // FIXME: Complain about ODR violations here?
7092 if (!getContext().getLangOpts().Modules || !FD->hasBody())
7093 FD->setLazyBody(PB->second);
7094 continue;
7095 }
7096
7097 ObjCMethodDecl *MD = cast<ObjCMethodDecl>(PB->first);
7098 if (!getContext().getLangOpts().Modules || !MD->hasBody())
7099 MD->setLazyBody(PB->second);
7100 }
7101 PendingBodies.clear();
7102}
7103
7104void ASTReader::FinishedDeserializing() {
7105 assert(NumCurrentElementsDeserializing &&
7106 "FinishedDeserializing not paired with StartedDeserializing");
7107 if (NumCurrentElementsDeserializing == 1) {
7108 // We decrease NumCurrentElementsDeserializing only after pending actions
7109 // are finished, to avoid recursively re-calling finishPendingActions().
7110 finishPendingActions();
7111 }
7112 --NumCurrentElementsDeserializing;
7113
7114 if (NumCurrentElementsDeserializing == 0 &&
7115 Consumer && !PassingDeclsToConsumer) {
7116 // Guard variable to avoid recursively redoing the process of passing
7117 // decls to consumer.
7118 SaveAndRestore<bool> GuardPassingDeclsToConsumer(PassingDeclsToConsumer,
7119 true);
7120
7121 while (!InterestingDecls.empty()) {
7122 // We are not in recursive loading, so it's safe to pass the "interesting"
7123 // decls to the consumer.
7124 Decl *D = InterestingDecls.front();
7125 InterestingDecls.pop_front();
7126 PassInterestingDeclToConsumer(D);
7127 }
7128 }
7129}
7130
7131ASTReader::ASTReader(Preprocessor &PP, ASTContext &Context,
7132 StringRef isysroot, bool DisableValidation,
Douglas Gregorf575d6e2013-01-25 00:45:27 +00007133 bool AllowASTWithCompilerErrors, bool UseGlobalIndex)
Guy Benyei7f92f2d2012-12-18 14:30:41 +00007134 : Listener(new PCHValidator(PP, *this)), DeserializationListener(0),
7135 SourceMgr(PP.getSourceManager()), FileMgr(PP.getFileManager()),
7136 Diags(PP.getDiagnostics()), SemaObj(0), PP(PP), Context(Context),
7137 Consumer(0), ModuleMgr(PP.getFileManager()),
7138 isysroot(isysroot), DisableValidation(DisableValidation),
Douglas Gregore1698072013-01-25 00:38:33 +00007139 AllowASTWithCompilerErrors(AllowASTWithCompilerErrors),
Douglas Gregorf575d6e2013-01-25 00:45:27 +00007140 UseGlobalIndex(UseGlobalIndex), TriedLoadingGlobalIndex(false),
Guy Benyei7f92f2d2012-12-18 14:30:41 +00007141 CurrentGeneration(0), CurrSwitchCaseStmts(&SwitchCaseStmts),
7142 NumSLocEntriesRead(0), TotalNumSLocEntries(0),
Douglas Gregore1698072013-01-25 00:38:33 +00007143 NumStatementsRead(0), TotalNumStatements(0), NumMacrosRead(0),
7144 TotalNumMacros(0), NumIdentifierLookups(0), NumIdentifierLookupHits(0),
7145 NumSelectorsRead(0), NumMethodPoolEntriesRead(0),
Douglas Gregor95fb36e2013-01-28 17:54:36 +00007146 NumMethodPoolLookups(0), NumMethodPoolHits(0),
7147 NumMethodPoolTableLookups(0), NumMethodPoolTableHits(0),
7148 TotalNumMethodPoolEntries(0),
Guy Benyei7f92f2d2012-12-18 14:30:41 +00007149 NumLexicalDeclContextsRead(0), TotalLexicalDeclContexts(0),
7150 NumVisibleDeclContextsRead(0), TotalVisibleDeclContexts(0),
7151 TotalModulesSizeInBits(0), NumCurrentElementsDeserializing(0),
7152 PassingDeclsToConsumer(false),
7153 NumCXXBaseSpecifiersLoaded(0)
7154{
7155 SourceMgr.setExternalSLocEntrySource(this);
7156}
7157
7158ASTReader::~ASTReader() {
7159 for (DeclContextVisibleUpdatesPending::iterator
7160 I = PendingVisibleUpdates.begin(),
7161 E = PendingVisibleUpdates.end();
7162 I != E; ++I) {
7163 for (DeclContextVisibleUpdates::iterator J = I->second.begin(),
7164 F = I->second.end();
7165 J != F; ++J)
7166 delete J->first;
7167 }
7168}