blob: a5fd2e324f2919b5529c901507265f9b769d70d2 [file] [log] [blame]
Nick Lewycky995e26b2013-01-31 03:23:57 +00001//===--- ASTReader.cpp - AST File Reader ----------------------------------===//
Guy Benyei7f92f2d2012-12-18 14:30:41 +00002//
3// The LLVM Compiler Infrastructure
4//
5// This file is distributed under the University of Illinois Open Source
6// License. See LICENSE.TXT for details.
7//
8//===----------------------------------------------------------------------===//
9//
10// This file defines the ASTReader class, which reads AST files.
11//
12//===----------------------------------------------------------------------===//
13
14#include "clang/Serialization/ASTReader.h"
15#include "ASTCommon.h"
16#include "ASTReaderInternals.h"
17#include "clang/AST/ASTConsumer.h"
18#include "clang/AST/ASTContext.h"
19#include "clang/AST/DeclTemplate.h"
20#include "clang/AST/Expr.h"
21#include "clang/AST/ExprCXX.h"
22#include "clang/AST/NestedNameSpecifier.h"
23#include "clang/AST/Type.h"
24#include "clang/AST/TypeLocVisitor.h"
25#include "clang/Basic/FileManager.h"
Guy Benyei7f92f2d2012-12-18 14:30:41 +000026#include "clang/Basic/SourceManager.h"
27#include "clang/Basic/SourceManagerInternals.h"
28#include "clang/Basic/TargetInfo.h"
29#include "clang/Basic/TargetOptions.h"
30#include "clang/Basic/Version.h"
31#include "clang/Basic/VersionTuple.h"
32#include "clang/Lex/HeaderSearch.h"
33#include "clang/Lex/HeaderSearchOptions.h"
34#include "clang/Lex/MacroInfo.h"
35#include "clang/Lex/PreprocessingRecord.h"
36#include "clang/Lex/Preprocessor.h"
37#include "clang/Lex/PreprocessorOptions.h"
38#include "clang/Sema/Scope.h"
39#include "clang/Sema/Sema.h"
40#include "clang/Serialization/ASTDeserializationListener.h"
Douglas Gregor1a49d972013-01-25 01:03:03 +000041#include "clang/Serialization/GlobalModuleIndex.h"
Guy Benyei7f92f2d2012-12-18 14:30:41 +000042#include "clang/Serialization/ModuleManager.h"
43#include "clang/Serialization/SerializationDiagnostic.h"
Argyrios Kyrtzidised3802e2013-03-06 18:12:47 +000044#include "llvm/ADT/Hashing.h"
Guy Benyei7f92f2d2012-12-18 14:30:41 +000045#include "llvm/ADT/StringExtras.h"
46#include "llvm/Bitcode/BitstreamReader.h"
47#include "llvm/Support/ErrorHandling.h"
48#include "llvm/Support/FileSystem.h"
49#include "llvm/Support/MemoryBuffer.h"
50#include "llvm/Support/Path.h"
51#include "llvm/Support/SaveAndRestore.h"
52#include "llvm/Support/system_error.h"
53#include <algorithm>
Chris Lattnere4e4a882013-01-20 00:57:52 +000054#include <cstdio>
Guy Benyei7f92f2d2012-12-18 14:30:41 +000055#include <iterator>
56
57using namespace clang;
58using namespace clang::serialization;
59using namespace clang::serialization::reader;
Chris Lattner8f9a1eb2013-01-20 00:56:42 +000060using llvm::BitstreamCursor;
Guy Benyei7f92f2d2012-12-18 14:30:41 +000061
62//===----------------------------------------------------------------------===//
63// PCH validator implementation
64//===----------------------------------------------------------------------===//
65
66ASTReaderListener::~ASTReaderListener() {}
67
68/// \brief Compare the given set of language options against an existing set of
69/// language options.
70///
71/// \param Diags If non-NULL, diagnostics will be emitted via this engine.
72///
73/// \returns true if the languagae options mis-match, false otherwise.
74static bool checkLanguageOptions(const LangOptions &LangOpts,
75 const LangOptions &ExistingLangOpts,
76 DiagnosticsEngine *Diags) {
77#define LANGOPT(Name, Bits, Default, Description) \
78 if (ExistingLangOpts.Name != LangOpts.Name) { \
79 if (Diags) \
80 Diags->Report(diag::err_pch_langopt_mismatch) \
81 << Description << LangOpts.Name << ExistingLangOpts.Name; \
82 return true; \
83 }
84
85#define VALUE_LANGOPT(Name, Bits, Default, Description) \
86 if (ExistingLangOpts.Name != LangOpts.Name) { \
87 if (Diags) \
88 Diags->Report(diag::err_pch_langopt_value_mismatch) \
89 << Description; \
90 return true; \
91 }
92
93#define ENUM_LANGOPT(Name, Type, Bits, Default, Description) \
94 if (ExistingLangOpts.get##Name() != LangOpts.get##Name()) { \
95 if (Diags) \
96 Diags->Report(diag::err_pch_langopt_value_mismatch) \
97 << Description; \
98 return true; \
99 }
100
101#define BENIGN_LANGOPT(Name, Bits, Default, Description)
102#define BENIGN_ENUM_LANGOPT(Name, Type, Bits, Default, Description)
103#include "clang/Basic/LangOptions.def"
104
105 if (ExistingLangOpts.ObjCRuntime != LangOpts.ObjCRuntime) {
106 if (Diags)
107 Diags->Report(diag::err_pch_langopt_value_mismatch)
108 << "target Objective-C runtime";
109 return true;
110 }
111
Dmitri Gribenko6ebf0912013-02-22 14:21:27 +0000112 if (ExistingLangOpts.CommentOpts.BlockCommandNames !=
113 LangOpts.CommentOpts.BlockCommandNames) {
114 if (Diags)
115 Diags->Report(diag::err_pch_langopt_value_mismatch)
116 << "block command names";
117 return true;
118 }
119
Guy Benyei7f92f2d2012-12-18 14:30:41 +0000120 return false;
121}
122
123/// \brief Compare the given set of target options against an existing set of
124/// target options.
125///
126/// \param Diags If non-NULL, diagnostics will be emitted via this engine.
127///
128/// \returns true if the target options mis-match, false otherwise.
129static bool checkTargetOptions(const TargetOptions &TargetOpts,
130 const TargetOptions &ExistingTargetOpts,
131 DiagnosticsEngine *Diags) {
132#define CHECK_TARGET_OPT(Field, Name) \
133 if (TargetOpts.Field != ExistingTargetOpts.Field) { \
134 if (Diags) \
135 Diags->Report(diag::err_pch_targetopt_mismatch) \
136 << Name << TargetOpts.Field << ExistingTargetOpts.Field; \
137 return true; \
138 }
139
140 CHECK_TARGET_OPT(Triple, "target");
141 CHECK_TARGET_OPT(CPU, "target CPU");
142 CHECK_TARGET_OPT(ABI, "target ABI");
143 CHECK_TARGET_OPT(CXXABI, "target C++ ABI");
144 CHECK_TARGET_OPT(LinkerVersion, "target linker version");
145#undef CHECK_TARGET_OPT
146
147 // Compare feature sets.
148 SmallVector<StringRef, 4> ExistingFeatures(
149 ExistingTargetOpts.FeaturesAsWritten.begin(),
150 ExistingTargetOpts.FeaturesAsWritten.end());
151 SmallVector<StringRef, 4> ReadFeatures(TargetOpts.FeaturesAsWritten.begin(),
152 TargetOpts.FeaturesAsWritten.end());
153 std::sort(ExistingFeatures.begin(), ExistingFeatures.end());
154 std::sort(ReadFeatures.begin(), ReadFeatures.end());
155
156 unsigned ExistingIdx = 0, ExistingN = ExistingFeatures.size();
157 unsigned ReadIdx = 0, ReadN = ReadFeatures.size();
158 while (ExistingIdx < ExistingN && ReadIdx < ReadN) {
159 if (ExistingFeatures[ExistingIdx] == ReadFeatures[ReadIdx]) {
160 ++ExistingIdx;
161 ++ReadIdx;
162 continue;
163 }
164
165 if (ReadFeatures[ReadIdx] < ExistingFeatures[ExistingIdx]) {
166 if (Diags)
167 Diags->Report(diag::err_pch_targetopt_feature_mismatch)
168 << false << ReadFeatures[ReadIdx];
169 return true;
170 }
171
172 if (Diags)
173 Diags->Report(diag::err_pch_targetopt_feature_mismatch)
174 << true << ExistingFeatures[ExistingIdx];
175 return true;
176 }
177
178 if (ExistingIdx < ExistingN) {
179 if (Diags)
180 Diags->Report(diag::err_pch_targetopt_feature_mismatch)
181 << true << ExistingFeatures[ExistingIdx];
182 return true;
183 }
184
185 if (ReadIdx < ReadN) {
186 if (Diags)
187 Diags->Report(diag::err_pch_targetopt_feature_mismatch)
188 << false << ReadFeatures[ReadIdx];
189 return true;
190 }
191
192 return false;
193}
194
195bool
196PCHValidator::ReadLanguageOptions(const LangOptions &LangOpts,
197 bool Complain) {
198 const LangOptions &ExistingLangOpts = PP.getLangOpts();
199 return checkLanguageOptions(LangOpts, ExistingLangOpts,
200 Complain? &Reader.Diags : 0);
201}
202
203bool PCHValidator::ReadTargetOptions(const TargetOptions &TargetOpts,
204 bool Complain) {
205 const TargetOptions &ExistingTargetOpts = PP.getTargetInfo().getTargetOpts();
206 return checkTargetOptions(TargetOpts, ExistingTargetOpts,
207 Complain? &Reader.Diags : 0);
208}
209
210namespace {
211 typedef llvm::StringMap<std::pair<StringRef, bool /*IsUndef*/> >
212 MacroDefinitionsMap;
213}
214
215/// \brief Collect the macro definitions provided by the given preprocessor
216/// options.
217static void collectMacroDefinitions(const PreprocessorOptions &PPOpts,
218 MacroDefinitionsMap &Macros,
219 SmallVectorImpl<StringRef> *MacroNames = 0){
220 for (unsigned I = 0, N = PPOpts.Macros.size(); I != N; ++I) {
221 StringRef Macro = PPOpts.Macros[I].first;
222 bool IsUndef = PPOpts.Macros[I].second;
223
224 std::pair<StringRef, StringRef> MacroPair = Macro.split('=');
225 StringRef MacroName = MacroPair.first;
226 StringRef MacroBody = MacroPair.second;
227
228 // For an #undef'd macro, we only care about the name.
229 if (IsUndef) {
230 if (MacroNames && !Macros.count(MacroName))
231 MacroNames->push_back(MacroName);
232
233 Macros[MacroName] = std::make_pair("", true);
234 continue;
235 }
236
237 // For a #define'd macro, figure out the actual definition.
238 if (MacroName.size() == Macro.size())
239 MacroBody = "1";
240 else {
241 // Note: GCC drops anything following an end-of-line character.
242 StringRef::size_type End = MacroBody.find_first_of("\n\r");
243 MacroBody = MacroBody.substr(0, End);
244 }
245
246 if (MacroNames && !Macros.count(MacroName))
247 MacroNames->push_back(MacroName);
248 Macros[MacroName] = std::make_pair(MacroBody, false);
249 }
250}
251
252/// \brief Check the preprocessor options deserialized from the control block
253/// against the preprocessor options in an existing preprocessor.
254///
255/// \param Diags If non-null, produce diagnostics for any mismatches incurred.
256static bool checkPreprocessorOptions(const PreprocessorOptions &PPOpts,
257 const PreprocessorOptions &ExistingPPOpts,
258 DiagnosticsEngine *Diags,
259 FileManager &FileMgr,
Argyrios Kyrtzidis65110ca2013-04-26 21:33:40 +0000260 std::string &SuggestedPredefines,
261 const LangOptions &LangOpts) {
Guy Benyei7f92f2d2012-12-18 14:30:41 +0000262 // Check macro definitions.
263 MacroDefinitionsMap ASTFileMacros;
264 collectMacroDefinitions(PPOpts, ASTFileMacros);
265 MacroDefinitionsMap ExistingMacros;
266 SmallVector<StringRef, 4> ExistingMacroNames;
267 collectMacroDefinitions(ExistingPPOpts, ExistingMacros, &ExistingMacroNames);
268
269 for (unsigned I = 0, N = ExistingMacroNames.size(); I != N; ++I) {
270 // Dig out the macro definition in the existing preprocessor options.
271 StringRef MacroName = ExistingMacroNames[I];
272 std::pair<StringRef, bool> Existing = ExistingMacros[MacroName];
273
274 // Check whether we know anything about this macro name or not.
275 llvm::StringMap<std::pair<StringRef, bool /*IsUndef*/> >::iterator Known
276 = ASTFileMacros.find(MacroName);
277 if (Known == ASTFileMacros.end()) {
278 // FIXME: Check whether this identifier was referenced anywhere in the
279 // AST file. If so, we should reject the AST file. Unfortunately, this
280 // information isn't in the control block. What shall we do about it?
281
282 if (Existing.second) {
283 SuggestedPredefines += "#undef ";
284 SuggestedPredefines += MacroName.str();
285 SuggestedPredefines += '\n';
286 } else {
287 SuggestedPredefines += "#define ";
288 SuggestedPredefines += MacroName.str();
289 SuggestedPredefines += ' ';
290 SuggestedPredefines += Existing.first.str();
291 SuggestedPredefines += '\n';
292 }
293 continue;
294 }
295
296 // If the macro was defined in one but undef'd in the other, we have a
297 // conflict.
298 if (Existing.second != Known->second.second) {
299 if (Diags) {
300 Diags->Report(diag::err_pch_macro_def_undef)
301 << MacroName << Known->second.second;
302 }
303 return true;
304 }
305
306 // If the macro was #undef'd in both, or if the macro bodies are identical,
307 // it's fine.
308 if (Existing.second || Existing.first == Known->second.first)
309 continue;
310
311 // The macro bodies differ; complain.
312 if (Diags) {
313 Diags->Report(diag::err_pch_macro_def_conflict)
314 << MacroName << Known->second.first << Existing.first;
315 }
316 return true;
317 }
318
319 // Check whether we're using predefines.
320 if (PPOpts.UsePredefines != ExistingPPOpts.UsePredefines) {
321 if (Diags) {
322 Diags->Report(diag::err_pch_undef) << ExistingPPOpts.UsePredefines;
323 }
324 return true;
325 }
326
Argyrios Kyrtzidis65110ca2013-04-26 21:33:40 +0000327 // Detailed record is important since it is used for the module cache hash.
328 if (LangOpts.Modules &&
329 PPOpts.DetailedRecord != ExistingPPOpts.DetailedRecord) {
330 if (Diags) {
331 Diags->Report(diag::err_pch_pp_detailed_record) << PPOpts.DetailedRecord;
332 }
333 return true;
334 }
335
Guy Benyei7f92f2d2012-12-18 14:30:41 +0000336 // Compute the #include and #include_macros lines we need.
337 for (unsigned I = 0, N = ExistingPPOpts.Includes.size(); I != N; ++I) {
338 StringRef File = ExistingPPOpts.Includes[I];
339 if (File == ExistingPPOpts.ImplicitPCHInclude)
340 continue;
341
342 if (std::find(PPOpts.Includes.begin(), PPOpts.Includes.end(), File)
343 != PPOpts.Includes.end())
344 continue;
345
346 SuggestedPredefines += "#include \"";
347 SuggestedPredefines +=
348 HeaderSearch::NormalizeDashIncludePath(File, FileMgr);
349 SuggestedPredefines += "\"\n";
350 }
351
352 for (unsigned I = 0, N = ExistingPPOpts.MacroIncludes.size(); I != N; ++I) {
353 StringRef File = ExistingPPOpts.MacroIncludes[I];
354 if (std::find(PPOpts.MacroIncludes.begin(), PPOpts.MacroIncludes.end(),
355 File)
356 != PPOpts.MacroIncludes.end())
357 continue;
358
359 SuggestedPredefines += "#__include_macros \"";
360 SuggestedPredefines +=
361 HeaderSearch::NormalizeDashIncludePath(File, FileMgr);
362 SuggestedPredefines += "\"\n##\n";
363 }
364
365 return false;
366}
367
368bool PCHValidator::ReadPreprocessorOptions(const PreprocessorOptions &PPOpts,
369 bool Complain,
370 std::string &SuggestedPredefines) {
371 const PreprocessorOptions &ExistingPPOpts = PP.getPreprocessorOpts();
372
373 return checkPreprocessorOptions(PPOpts, ExistingPPOpts,
374 Complain? &Reader.Diags : 0,
375 PP.getFileManager(),
Argyrios Kyrtzidis65110ca2013-04-26 21:33:40 +0000376 SuggestedPredefines,
377 PP.getLangOpts());
Guy Benyei7f92f2d2012-12-18 14:30:41 +0000378}
379
380void PCHValidator::ReadHeaderFileInfo(const HeaderFileInfo &HFI,
381 unsigned ID) {
382 PP.getHeaderSearchInfo().setHeaderFileInfoForUID(HFI, ID);
383 ++NumHeaderInfos;
384}
385
386void PCHValidator::ReadCounter(const ModuleFile &M, unsigned Value) {
387 PP.setCounterValue(Value);
388}
389
390//===----------------------------------------------------------------------===//
391// AST reader implementation
392//===----------------------------------------------------------------------===//
393
394void
395ASTReader::setDeserializationListener(ASTDeserializationListener *Listener) {
396 DeserializationListener = Listener;
397}
398
399
400
401unsigned ASTSelectorLookupTrait::ComputeHash(Selector Sel) {
402 return serialization::ComputeHash(Sel);
403}
404
405
406std::pair<unsigned, unsigned>
407ASTSelectorLookupTrait::ReadKeyDataLength(const unsigned char*& d) {
408 using namespace clang::io;
409 unsigned KeyLen = ReadUnalignedLE16(d);
410 unsigned DataLen = ReadUnalignedLE16(d);
411 return std::make_pair(KeyLen, DataLen);
412}
413
414ASTSelectorLookupTrait::internal_key_type
415ASTSelectorLookupTrait::ReadKey(const unsigned char* d, unsigned) {
416 using namespace clang::io;
417 SelectorTable &SelTable = Reader.getContext().Selectors;
418 unsigned N = ReadUnalignedLE16(d);
419 IdentifierInfo *FirstII
Douglas Gregor8222b892013-01-21 16:52:34 +0000420 = Reader.getLocalIdentifier(F, ReadUnalignedLE32(d));
Guy Benyei7f92f2d2012-12-18 14:30:41 +0000421 if (N == 0)
422 return SelTable.getNullarySelector(FirstII);
423 else if (N == 1)
424 return SelTable.getUnarySelector(FirstII);
425
426 SmallVector<IdentifierInfo *, 16> Args;
427 Args.push_back(FirstII);
428 for (unsigned I = 1; I != N; ++I)
Douglas Gregor8222b892013-01-21 16:52:34 +0000429 Args.push_back(Reader.getLocalIdentifier(F, ReadUnalignedLE32(d)));
Guy Benyei7f92f2d2012-12-18 14:30:41 +0000430
431 return SelTable.getSelector(N, Args.data());
432}
433
434ASTSelectorLookupTrait::data_type
435ASTSelectorLookupTrait::ReadData(Selector, const unsigned char* d,
436 unsigned DataLen) {
437 using namespace clang::io;
438
439 data_type Result;
440
441 Result.ID = Reader.getGlobalSelectorID(F, ReadUnalignedLE32(d));
Argyrios Kyrtzidis2e3d8c02013-04-17 00:08:58 +0000442 unsigned NumInstanceMethodsAndBits = ReadUnalignedLE16(d);
443 unsigned NumFactoryMethodsAndBits = ReadUnalignedLE16(d);
444 Result.InstanceBits = NumInstanceMethodsAndBits & 0x3;
445 Result.FactoryBits = NumFactoryMethodsAndBits & 0x3;
446 unsigned NumInstanceMethods = NumInstanceMethodsAndBits >> 2;
447 unsigned NumFactoryMethods = NumFactoryMethodsAndBits >> 2;
Guy Benyei7f92f2d2012-12-18 14:30:41 +0000448
449 // Load instance methods
450 for (unsigned I = 0; I != NumInstanceMethods; ++I) {
451 if (ObjCMethodDecl *Method
452 = Reader.GetLocalDeclAs<ObjCMethodDecl>(F, ReadUnalignedLE32(d)))
453 Result.Instance.push_back(Method);
454 }
455
456 // Load factory methods
457 for (unsigned I = 0; I != NumFactoryMethods; ++I) {
458 if (ObjCMethodDecl *Method
459 = Reader.GetLocalDeclAs<ObjCMethodDecl>(F, ReadUnalignedLE32(d)))
460 Result.Factory.push_back(Method);
461 }
462
463 return Result;
464}
465
Douglas Gregor479633c2013-01-23 18:53:14 +0000466unsigned ASTIdentifierLookupTraitBase::ComputeHash(const internal_key_type& a) {
467 return llvm::HashString(a);
Guy Benyei7f92f2d2012-12-18 14:30:41 +0000468}
469
470std::pair<unsigned, unsigned>
Douglas Gregor479633c2013-01-23 18:53:14 +0000471ASTIdentifierLookupTraitBase::ReadKeyDataLength(const unsigned char*& d) {
Guy Benyei7f92f2d2012-12-18 14:30:41 +0000472 using namespace clang::io;
473 unsigned DataLen = ReadUnalignedLE16(d);
474 unsigned KeyLen = ReadUnalignedLE16(d);
475 return std::make_pair(KeyLen, DataLen);
476}
477
Douglas Gregor479633c2013-01-23 18:53:14 +0000478ASTIdentifierLookupTraitBase::internal_key_type
479ASTIdentifierLookupTraitBase::ReadKey(const unsigned char* d, unsigned n) {
Guy Benyei7f92f2d2012-12-18 14:30:41 +0000480 assert(n >= 2 && d[n-1] == '\0');
Douglas Gregor479633c2013-01-23 18:53:14 +0000481 return StringRef((const char*) d, n-1);
Guy Benyei7f92f2d2012-12-18 14:30:41 +0000482}
483
Douglas Gregorf4e955b2013-02-11 18:16:18 +0000484/// \brief Whether the given identifier is "interesting".
485static bool isInterestingIdentifier(IdentifierInfo &II) {
486 return II.isPoisoned() ||
487 II.isExtensionToken() ||
488 II.getObjCOrBuiltinID() ||
489 II.hasRevertedTokenIDToIdentifier() ||
490 II.hadMacroDefinition() ||
491 II.getFETokenInfo<void>();
492}
493
Guy Benyei7f92f2d2012-12-18 14:30:41 +0000494IdentifierInfo *ASTIdentifierLookupTrait::ReadData(const internal_key_type& k,
495 const unsigned char* d,
496 unsigned DataLen) {
497 using namespace clang::io;
498 unsigned RawID = ReadUnalignedLE32(d);
499 bool IsInteresting = RawID & 0x01;
500
501 // Wipe out the "is interesting" bit.
502 RawID = RawID >> 1;
503
504 IdentID ID = Reader.getGlobalIdentifierID(F, RawID);
505 if (!IsInteresting) {
506 // For uninteresting identifiers, just build the IdentifierInfo
507 // and associate it with the persistent ID.
508 IdentifierInfo *II = KnownII;
509 if (!II) {
Douglas Gregor479633c2013-01-23 18:53:14 +0000510 II = &Reader.getIdentifierTable().getOwn(k);
Guy Benyei7f92f2d2012-12-18 14:30:41 +0000511 KnownII = II;
512 }
513 Reader.SetIdentifierInfo(ID, II);
Douglas Gregorf4e955b2013-02-11 18:16:18 +0000514 if (!II->isFromAST()) {
515 bool WasInteresting = isInterestingIdentifier(*II);
516 II->setIsFromAST();
517 if (WasInteresting)
518 II->setChangedSinceDeserialization();
519 }
520 Reader.markIdentifierUpToDate(II);
Guy Benyei7f92f2d2012-12-18 14:30:41 +0000521 return II;
522 }
523
524 unsigned ObjCOrBuiltinID = ReadUnalignedLE16(d);
525 unsigned Bits = ReadUnalignedLE16(d);
526 bool CPlusPlusOperatorKeyword = Bits & 0x01;
527 Bits >>= 1;
528 bool HasRevertedTokenIDToIdentifier = Bits & 0x01;
529 Bits >>= 1;
530 bool Poisoned = Bits & 0x01;
531 Bits >>= 1;
532 bool ExtensionToken = Bits & 0x01;
533 Bits >>= 1;
Argyrios Kyrtzidis9317ab92013-03-22 21:12:57 +0000534 bool hasSubmoduleMacros = Bits & 0x01;
535 Bits >>= 1;
Guy Benyei7f92f2d2012-12-18 14:30:41 +0000536 bool hadMacroDefinition = Bits & 0x01;
537 Bits >>= 1;
538
539 assert(Bits == 0 && "Extra bits in the identifier?");
540 DataLen -= 8;
541
542 // Build the IdentifierInfo itself and link the identifier ID with
543 // the new IdentifierInfo.
544 IdentifierInfo *II = KnownII;
545 if (!II) {
Douglas Gregor479633c2013-01-23 18:53:14 +0000546 II = &Reader.getIdentifierTable().getOwn(StringRef(k));
Guy Benyei7f92f2d2012-12-18 14:30:41 +0000547 KnownII = II;
548 }
549 Reader.markIdentifierUpToDate(II);
Douglas Gregorf4e955b2013-02-11 18:16:18 +0000550 if (!II->isFromAST()) {
551 bool WasInteresting = isInterestingIdentifier(*II);
552 II->setIsFromAST();
553 if (WasInteresting)
554 II->setChangedSinceDeserialization();
555 }
Guy Benyei7f92f2d2012-12-18 14:30:41 +0000556
557 // Set or check the various bits in the IdentifierInfo structure.
558 // Token IDs are read-only.
Argyrios Kyrtzidis1ebefc72013-02-27 01:13:51 +0000559 if (HasRevertedTokenIDToIdentifier && II->getTokenID() != tok::identifier)
Guy Benyei7f92f2d2012-12-18 14:30:41 +0000560 II->RevertTokenIDToIdentifier();
561 II->setObjCOrBuiltinID(ObjCOrBuiltinID);
562 assert(II->isExtensionToken() == ExtensionToken &&
563 "Incorrect extension token flag");
564 (void)ExtensionToken;
565 if (Poisoned)
566 II->setIsPoisoned(true);
567 assert(II->isCPlusPlusOperatorKeyword() == CPlusPlusOperatorKeyword &&
568 "Incorrect C++ operator keyword flag");
569 (void)CPlusPlusOperatorKeyword;
570
571 // If this identifier is a macro, deserialize the macro
572 // definition.
573 if (hadMacroDefinition) {
Argyrios Kyrtzidis9317ab92013-03-22 21:12:57 +0000574 uint32_t MacroDirectivesOffset = ReadUnalignedLE32(d);
575 DataLen -= 4;
576 SmallVector<uint32_t, 8> LocalMacroIDs;
577 if (hasSubmoduleMacros) {
578 while (uint32_t LocalMacroID = ReadUnalignedLE32(d)) {
579 DataLen -= 4;
580 LocalMacroIDs.push_back(LocalMacroID);
581 }
Argyrios Kyrtzidisdc1088f2013-01-19 03:14:56 +0000582 DataLen -= 4;
583 }
Argyrios Kyrtzidis9317ab92013-03-22 21:12:57 +0000584
585 if (F.Kind == MK_Module) {
586 for (SmallVectorImpl<uint32_t>::iterator
587 I = LocalMacroIDs.begin(), E = LocalMacroIDs.end(); I != E; ++I) {
588 MacroID MacID = Reader.getGlobalMacroID(F, *I);
589 Reader.addPendingMacroFromModule(II, &F, MacID, F.DirectImportLoc);
590 }
591 } else {
592 Reader.addPendingMacroFromPCH(II, &F, MacroDirectivesOffset);
593 }
Guy Benyei7f92f2d2012-12-18 14:30:41 +0000594 }
595
596 Reader.SetIdentifierInfo(ID, II);
597
598 // Read all of the declarations visible at global scope with this
599 // name.
600 if (DataLen > 0) {
601 SmallVector<uint32_t, 4> DeclIDs;
602 for (; DataLen > 0; DataLen -= 4)
603 DeclIDs.push_back(Reader.getGlobalDeclID(F, ReadUnalignedLE32(d)));
604 Reader.SetGloballyVisibleDecls(II, DeclIDs);
605 }
606
607 return II;
608}
609
610unsigned
611ASTDeclContextNameLookupTrait::ComputeHash(const DeclNameKey &Key) const {
612 llvm::FoldingSetNodeID ID;
613 ID.AddInteger(Key.Kind);
614
615 switch (Key.Kind) {
616 case DeclarationName::Identifier:
617 case DeclarationName::CXXLiteralOperatorName:
618 ID.AddString(((IdentifierInfo*)Key.Data)->getName());
619 break;
620 case DeclarationName::ObjCZeroArgSelector:
621 case DeclarationName::ObjCOneArgSelector:
622 case DeclarationName::ObjCMultiArgSelector:
623 ID.AddInteger(serialization::ComputeHash(Selector(Key.Data)));
624 break;
625 case DeclarationName::CXXOperatorName:
626 ID.AddInteger((OverloadedOperatorKind)Key.Data);
627 break;
628 case DeclarationName::CXXConstructorName:
629 case DeclarationName::CXXDestructorName:
630 case DeclarationName::CXXConversionFunctionName:
631 case DeclarationName::CXXUsingDirective:
632 break;
633 }
634
635 return ID.ComputeHash();
636}
637
638ASTDeclContextNameLookupTrait::internal_key_type
639ASTDeclContextNameLookupTrait::GetInternalKey(
640 const external_key_type& Name) const {
641 DeclNameKey Key;
642 Key.Kind = Name.getNameKind();
643 switch (Name.getNameKind()) {
644 case DeclarationName::Identifier:
645 Key.Data = (uint64_t)Name.getAsIdentifierInfo();
646 break;
647 case DeclarationName::ObjCZeroArgSelector:
648 case DeclarationName::ObjCOneArgSelector:
649 case DeclarationName::ObjCMultiArgSelector:
650 Key.Data = (uint64_t)Name.getObjCSelector().getAsOpaquePtr();
651 break;
652 case DeclarationName::CXXOperatorName:
653 Key.Data = Name.getCXXOverloadedOperator();
654 break;
655 case DeclarationName::CXXLiteralOperatorName:
656 Key.Data = (uint64_t)Name.getCXXLiteralIdentifier();
657 break;
658 case DeclarationName::CXXConstructorName:
659 case DeclarationName::CXXDestructorName:
660 case DeclarationName::CXXConversionFunctionName:
661 case DeclarationName::CXXUsingDirective:
662 Key.Data = 0;
663 break;
664 }
665
666 return Key;
667}
668
669std::pair<unsigned, unsigned>
670ASTDeclContextNameLookupTrait::ReadKeyDataLength(const unsigned char*& d) {
671 using namespace clang::io;
672 unsigned KeyLen = ReadUnalignedLE16(d);
673 unsigned DataLen = ReadUnalignedLE16(d);
674 return std::make_pair(KeyLen, DataLen);
675}
676
677ASTDeclContextNameLookupTrait::internal_key_type
678ASTDeclContextNameLookupTrait::ReadKey(const unsigned char* d, unsigned) {
679 using namespace clang::io;
680
681 DeclNameKey Key;
682 Key.Kind = (DeclarationName::NameKind)*d++;
683 switch (Key.Kind) {
684 case DeclarationName::Identifier:
685 Key.Data = (uint64_t)Reader.getLocalIdentifier(F, ReadUnalignedLE32(d));
686 break;
687 case DeclarationName::ObjCZeroArgSelector:
688 case DeclarationName::ObjCOneArgSelector:
689 case DeclarationName::ObjCMultiArgSelector:
690 Key.Data =
691 (uint64_t)Reader.getLocalSelector(F, ReadUnalignedLE32(d))
692 .getAsOpaquePtr();
693 break;
694 case DeclarationName::CXXOperatorName:
695 Key.Data = *d++; // OverloadedOperatorKind
696 break;
697 case DeclarationName::CXXLiteralOperatorName:
698 Key.Data = (uint64_t)Reader.getLocalIdentifier(F, ReadUnalignedLE32(d));
699 break;
700 case DeclarationName::CXXConstructorName:
701 case DeclarationName::CXXDestructorName:
702 case DeclarationName::CXXConversionFunctionName:
703 case DeclarationName::CXXUsingDirective:
704 Key.Data = 0;
705 break;
706 }
707
708 return Key;
709}
710
711ASTDeclContextNameLookupTrait::data_type
712ASTDeclContextNameLookupTrait::ReadData(internal_key_type,
713 const unsigned char* d,
714 unsigned DataLen) {
715 using namespace clang::io;
716 unsigned NumDecls = ReadUnalignedLE16(d);
Argyrios Kyrtzidise8b61cf2013-01-11 22:29:49 +0000717 LE32DeclID *Start = reinterpret_cast<LE32DeclID *>(
718 const_cast<unsigned char *>(d));
Guy Benyei7f92f2d2012-12-18 14:30:41 +0000719 return std::make_pair(Start, Start + NumDecls);
720}
721
722bool ASTReader::ReadDeclContextStorage(ModuleFile &M,
Chris Lattner8f9a1eb2013-01-20 00:56:42 +0000723 BitstreamCursor &Cursor,
Guy Benyei7f92f2d2012-12-18 14:30:41 +0000724 const std::pair<uint64_t, uint64_t> &Offsets,
725 DeclContextInfo &Info) {
726 SavedStreamPosition SavedPosition(Cursor);
727 // First the lexical decls.
728 if (Offsets.first != 0) {
729 Cursor.JumpToBit(Offsets.first);
730
731 RecordData Record;
Chris Lattnerb3ce3572013-01-20 02:38:54 +0000732 StringRef Blob;
Guy Benyei7f92f2d2012-12-18 14:30:41 +0000733 unsigned Code = Cursor.ReadCode();
Chris Lattnerb3ce3572013-01-20 02:38:54 +0000734 unsigned RecCode = Cursor.readRecord(Code, Record, &Blob);
Guy Benyei7f92f2d2012-12-18 14:30:41 +0000735 if (RecCode != DECL_CONTEXT_LEXICAL) {
736 Error("Expected lexical block");
737 return true;
738 }
739
Chris Lattnerb3ce3572013-01-20 02:38:54 +0000740 Info.LexicalDecls = reinterpret_cast<const KindDeclIDPair*>(Blob.data());
741 Info.NumLexicalDecls = Blob.size() / sizeof(KindDeclIDPair);
Guy Benyei7f92f2d2012-12-18 14:30:41 +0000742 }
743
744 // Now the lookup table.
745 if (Offsets.second != 0) {
746 Cursor.JumpToBit(Offsets.second);
747
748 RecordData Record;
Chris Lattnerb3ce3572013-01-20 02:38:54 +0000749 StringRef Blob;
Guy Benyei7f92f2d2012-12-18 14:30:41 +0000750 unsigned Code = Cursor.ReadCode();
Chris Lattnerb3ce3572013-01-20 02:38:54 +0000751 unsigned RecCode = Cursor.readRecord(Code, Record, &Blob);
Guy Benyei7f92f2d2012-12-18 14:30:41 +0000752 if (RecCode != DECL_CONTEXT_VISIBLE) {
753 Error("Expected visible lookup table block");
754 return true;
755 }
756 Info.NameLookupTableData
757 = ASTDeclContextNameLookupTable::Create(
Chris Lattnerb3ce3572013-01-20 02:38:54 +0000758 (const unsigned char *)Blob.data() + Record[0],
759 (const unsigned char *)Blob.data(),
Guy Benyei7f92f2d2012-12-18 14:30:41 +0000760 ASTDeclContextNameLookupTrait(*this, M));
761 }
762
763 return false;
764}
765
766void ASTReader::Error(StringRef Msg) {
767 Error(diag::err_fe_pch_malformed, Msg);
768}
769
770void ASTReader::Error(unsigned DiagID,
771 StringRef Arg1, StringRef Arg2) {
772 if (Diags.isDiagnosticInFlight())
773 Diags.SetDelayedDiagnostic(DiagID, Arg1, Arg2);
774 else
775 Diag(DiagID) << Arg1 << Arg2;
776}
777
778//===----------------------------------------------------------------------===//
779// Source Manager Deserialization
780//===----------------------------------------------------------------------===//
781
782/// \brief Read the line table in the source manager block.
783/// \returns true if there was an error.
784bool ASTReader::ParseLineTable(ModuleFile &F,
785 SmallVectorImpl<uint64_t> &Record) {
786 unsigned Idx = 0;
787 LineTableInfo &LineTable = SourceMgr.getLineTable();
788
789 // Parse the file names
790 std::map<int, int> FileIDs;
791 for (int I = 0, N = Record[Idx++]; I != N; ++I) {
792 // Extract the file name
793 unsigned FilenameLen = Record[Idx++];
794 std::string Filename(&Record[Idx], &Record[Idx] + FilenameLen);
795 Idx += FilenameLen;
796 MaybeAddSystemRootToFilename(F, Filename);
797 FileIDs[I] = LineTable.getLineTableFilenameID(Filename);
798 }
799
800 // Parse the line entries
801 std::vector<LineEntry> Entries;
802 while (Idx < Record.size()) {
803 int FID = Record[Idx++];
804 assert(FID >= 0 && "Serialized line entries for non-local file.");
805 // Remap FileID from 1-based old view.
806 FID += F.SLocEntryBaseID - 1;
807
808 // Extract the line entries
809 unsigned NumEntries = Record[Idx++];
810 assert(NumEntries && "Numentries is 00000");
811 Entries.clear();
812 Entries.reserve(NumEntries);
813 for (unsigned I = 0; I != NumEntries; ++I) {
814 unsigned FileOffset = Record[Idx++];
815 unsigned LineNo = Record[Idx++];
816 int FilenameID = FileIDs[Record[Idx++]];
817 SrcMgr::CharacteristicKind FileKind
818 = (SrcMgr::CharacteristicKind)Record[Idx++];
819 unsigned IncludeOffset = Record[Idx++];
820 Entries.push_back(LineEntry::get(FileOffset, LineNo, FilenameID,
821 FileKind, IncludeOffset));
822 }
823 LineTable.AddEntry(FileID::get(FID), Entries);
824 }
825
826 return false;
827}
828
829/// \brief Read a source manager block
830bool ASTReader::ReadSourceManagerBlock(ModuleFile &F) {
831 using namespace SrcMgr;
832
Chris Lattner8f9a1eb2013-01-20 00:56:42 +0000833 BitstreamCursor &SLocEntryCursor = F.SLocEntryCursor;
Guy Benyei7f92f2d2012-12-18 14:30:41 +0000834
835 // Set the source-location entry cursor to the current position in
836 // the stream. This cursor will be used to read the contents of the
837 // source manager block initially, and then lazily read
838 // source-location entries as needed.
839 SLocEntryCursor = F.Stream;
840
841 // The stream itself is going to skip over the source manager block.
842 if (F.Stream.SkipBlock()) {
843 Error("malformed block record in AST file");
844 return true;
845 }
846
847 // Enter the source manager block.
848 if (SLocEntryCursor.EnterSubBlock(SOURCE_MANAGER_BLOCK_ID)) {
849 Error("malformed source manager block record in AST file");
850 return true;
851 }
852
853 RecordData Record;
854 while (true) {
Chris Lattner88bde502013-01-19 21:39:22 +0000855 llvm::BitstreamEntry E = SLocEntryCursor.advanceSkippingSubblocks();
856
857 switch (E.Kind) {
858 case llvm::BitstreamEntry::SubBlock: // Handled for us already.
859 case llvm::BitstreamEntry::Error:
860 Error("malformed block record in AST file");
861 return true;
862 case llvm::BitstreamEntry::EndBlock:
Guy Benyei7f92f2d2012-12-18 14:30:41 +0000863 return false;
Chris Lattner88bde502013-01-19 21:39:22 +0000864 case llvm::BitstreamEntry::Record:
865 // The interesting case.
866 break;
Guy Benyei7f92f2d2012-12-18 14:30:41 +0000867 }
Chris Lattner88bde502013-01-19 21:39:22 +0000868
Guy Benyei7f92f2d2012-12-18 14:30:41 +0000869 // Read a record.
Guy Benyei7f92f2d2012-12-18 14:30:41 +0000870 Record.clear();
Chris Lattner125eb3e2013-01-21 18:28:26 +0000871 StringRef Blob;
872 switch (SLocEntryCursor.readRecord(E.ID, Record, &Blob)) {
Guy Benyei7f92f2d2012-12-18 14:30:41 +0000873 default: // Default behavior: ignore.
874 break;
875
876 case SM_SLOC_FILE_ENTRY:
877 case SM_SLOC_BUFFER_ENTRY:
878 case SM_SLOC_EXPANSION_ENTRY:
879 // Once we hit one of the source location entries, we're done.
880 return false;
881 }
882 }
883}
884
885/// \brief If a header file is not found at the path that we expect it to be
886/// and the PCH file was moved from its original location, try to resolve the
887/// file by assuming that header+PCH were moved together and the header is in
888/// the same place relative to the PCH.
889static std::string
890resolveFileRelativeToOriginalDir(const std::string &Filename,
891 const std::string &OriginalDir,
892 const std::string &CurrDir) {
893 assert(OriginalDir != CurrDir &&
894 "No point trying to resolve the file if the PCH dir didn't change");
895 using namespace llvm::sys;
896 SmallString<128> filePath(Filename);
897 fs::make_absolute(filePath);
898 assert(path::is_absolute(OriginalDir));
899 SmallString<128> currPCHPath(CurrDir);
900
901 path::const_iterator fileDirI = path::begin(path::parent_path(filePath)),
902 fileDirE = path::end(path::parent_path(filePath));
903 path::const_iterator origDirI = path::begin(OriginalDir),
904 origDirE = path::end(OriginalDir);
905 // Skip the common path components from filePath and OriginalDir.
906 while (fileDirI != fileDirE && origDirI != origDirE &&
907 *fileDirI == *origDirI) {
908 ++fileDirI;
909 ++origDirI;
910 }
911 for (; origDirI != origDirE; ++origDirI)
912 path::append(currPCHPath, "..");
913 path::append(currPCHPath, fileDirI, fileDirE);
914 path::append(currPCHPath, path::filename(Filename));
915 return currPCHPath.str();
916}
917
918bool ASTReader::ReadSLocEntry(int ID) {
919 if (ID == 0)
920 return false;
921
922 if (unsigned(-ID) - 2 >= getTotalNumSLocs() || ID > 0) {
923 Error("source location entry ID out-of-range for AST file");
924 return true;
925 }
926
927 ModuleFile *F = GlobalSLocEntryMap.find(-ID)->second;
928 F->SLocEntryCursor.JumpToBit(F->SLocEntryOffsets[ID - F->SLocEntryBaseID]);
Chris Lattner8f9a1eb2013-01-20 00:56:42 +0000929 BitstreamCursor &SLocEntryCursor = F->SLocEntryCursor;
Guy Benyei7f92f2d2012-12-18 14:30:41 +0000930 unsigned BaseOffset = F->SLocEntryBaseOffset;
931
932 ++NumSLocEntriesRead;
Chris Lattner88bde502013-01-19 21:39:22 +0000933 llvm::BitstreamEntry Entry = SLocEntryCursor.advance();
934 if (Entry.Kind != llvm::BitstreamEntry::Record) {
Guy Benyei7f92f2d2012-12-18 14:30:41 +0000935 Error("incorrectly-formatted source location entry in AST file");
936 return true;
937 }
Chris Lattner88bde502013-01-19 21:39:22 +0000938
Guy Benyei7f92f2d2012-12-18 14:30:41 +0000939 RecordData Record;
Chris Lattnerb3ce3572013-01-20 02:38:54 +0000940 StringRef Blob;
941 switch (SLocEntryCursor.readRecord(Entry.ID, Record, &Blob)) {
Guy Benyei7f92f2d2012-12-18 14:30:41 +0000942 default:
943 Error("incorrectly-formatted source location entry in AST file");
944 return true;
945
946 case SM_SLOC_FILE_ENTRY: {
947 // We will detect whether a file changed and return 'Failure' for it, but
948 // we will also try to fail gracefully by setting up the SLocEntry.
949 unsigned InputID = Record[4];
950 InputFile IF = getInputFile(*F, InputID);
Argyrios Kyrtzidis8504b7b2013-03-01 03:26:04 +0000951 const FileEntry *File = IF.getFile();
952 bool OverriddenBuffer = IF.isOverridden();
Guy Benyei7f92f2d2012-12-18 14:30:41 +0000953
Argyrios Kyrtzidis8504b7b2013-03-01 03:26:04 +0000954 // Note that we only check if a File was returned. If it was out-of-date
955 // we have complained but we will continue creating a FileID to recover
956 // gracefully.
957 if (!File)
Guy Benyei7f92f2d2012-12-18 14:30:41 +0000958 return true;
959
960 SourceLocation IncludeLoc = ReadSourceLocation(*F, Record[1]);
961 if (IncludeLoc.isInvalid() && F->Kind != MK_MainFile) {
962 // This is the module's main file.
963 IncludeLoc = getImportLocation(F);
964 }
965 SrcMgr::CharacteristicKind
966 FileCharacter = (SrcMgr::CharacteristicKind)Record[2];
967 FileID FID = SourceMgr.createFileID(File, IncludeLoc, FileCharacter,
968 ID, BaseOffset + Record[0]);
969 SrcMgr::FileInfo &FileInfo =
970 const_cast<SrcMgr::FileInfo&>(SourceMgr.getSLocEntry(FID).getFile());
971 FileInfo.NumCreatedFIDs = Record[5];
972 if (Record[3])
973 FileInfo.setHasLineDirectives();
974
975 const DeclID *FirstDecl = F->FileSortedDecls + Record[6];
976 unsigned NumFileDecls = Record[7];
977 if (NumFileDecls) {
978 assert(F->FileSortedDecls && "FILE_SORTED_DECLS not encountered yet ?");
979 FileDeclIDs[FID] = FileDeclsInfo(F, llvm::makeArrayRef(FirstDecl,
980 NumFileDecls));
981 }
982
983 const SrcMgr::ContentCache *ContentCache
984 = SourceMgr.getOrCreateContentCache(File,
985 /*isSystemFile=*/FileCharacter != SrcMgr::C_User);
986 if (OverriddenBuffer && !ContentCache->BufferOverridden &&
987 ContentCache->ContentsEntry == ContentCache->OrigEntry) {
988 unsigned Code = SLocEntryCursor.ReadCode();
989 Record.clear();
Chris Lattnerb3ce3572013-01-20 02:38:54 +0000990 unsigned RecCode = SLocEntryCursor.readRecord(Code, Record, &Blob);
Guy Benyei7f92f2d2012-12-18 14:30:41 +0000991
992 if (RecCode != SM_SLOC_BUFFER_BLOB) {
993 Error("AST record has invalid code");
994 return true;
995 }
996
997 llvm::MemoryBuffer *Buffer
Chris Lattnerb3ce3572013-01-20 02:38:54 +0000998 = llvm::MemoryBuffer::getMemBuffer(Blob.drop_back(1), File->getName());
Guy Benyei7f92f2d2012-12-18 14:30:41 +0000999 SourceMgr.overrideFileContents(File, Buffer);
1000 }
1001
1002 break;
1003 }
1004
1005 case SM_SLOC_BUFFER_ENTRY: {
Chris Lattnerb3ce3572013-01-20 02:38:54 +00001006 const char *Name = Blob.data();
Guy Benyei7f92f2d2012-12-18 14:30:41 +00001007 unsigned Offset = Record[0];
1008 SrcMgr::CharacteristicKind
1009 FileCharacter = (SrcMgr::CharacteristicKind)Record[2];
1010 SourceLocation IncludeLoc = ReadSourceLocation(*F, Record[1]);
1011 if (IncludeLoc.isInvalid() && F->Kind == MK_Module) {
1012 IncludeLoc = getImportLocation(F);
1013 }
1014 unsigned Code = SLocEntryCursor.ReadCode();
1015 Record.clear();
1016 unsigned RecCode
Chris Lattnerb3ce3572013-01-20 02:38:54 +00001017 = SLocEntryCursor.readRecord(Code, Record, &Blob);
Guy Benyei7f92f2d2012-12-18 14:30:41 +00001018
1019 if (RecCode != SM_SLOC_BUFFER_BLOB) {
1020 Error("AST record has invalid code");
1021 return true;
1022 }
1023
1024 llvm::MemoryBuffer *Buffer
Chris Lattnerb3ce3572013-01-20 02:38:54 +00001025 = llvm::MemoryBuffer::getMemBuffer(Blob.drop_back(1), Name);
Guy Benyei7f92f2d2012-12-18 14:30:41 +00001026 SourceMgr.createFileIDForMemBuffer(Buffer, FileCharacter, ID,
1027 BaseOffset + Offset, IncludeLoc);
1028 break;
1029 }
1030
1031 case SM_SLOC_EXPANSION_ENTRY: {
1032 SourceLocation SpellingLoc = ReadSourceLocation(*F, Record[1]);
1033 SourceMgr.createExpansionLoc(SpellingLoc,
1034 ReadSourceLocation(*F, Record[2]),
1035 ReadSourceLocation(*F, Record[3]),
1036 Record[4],
1037 ID,
1038 BaseOffset + Record[0]);
1039 break;
1040 }
1041 }
1042
1043 return false;
1044}
1045
1046std::pair<SourceLocation, StringRef> ASTReader::getModuleImportLoc(int ID) {
1047 if (ID == 0)
1048 return std::make_pair(SourceLocation(), "");
1049
1050 if (unsigned(-ID) - 2 >= getTotalNumSLocs() || ID > 0) {
1051 Error("source location entry ID out-of-range for AST file");
1052 return std::make_pair(SourceLocation(), "");
1053 }
1054
1055 // Find which module file this entry lands in.
1056 ModuleFile *M = GlobalSLocEntryMap.find(-ID)->second;
1057 if (M->Kind != MK_Module)
1058 return std::make_pair(SourceLocation(), "");
1059
1060 // FIXME: Can we map this down to a particular submodule? That would be
1061 // ideal.
1062 return std::make_pair(M->ImportLoc, llvm::sys::path::stem(M->FileName));
1063}
1064
1065/// \brief Find the location where the module F is imported.
1066SourceLocation ASTReader::getImportLocation(ModuleFile *F) {
1067 if (F->ImportLoc.isValid())
1068 return F->ImportLoc;
1069
1070 // Otherwise we have a PCH. It's considered to be "imported" at the first
1071 // location of its includer.
1072 if (F->ImportedBy.empty() || !F->ImportedBy[0]) {
1073 // Main file is the importer. We assume that it is the first entry in the
1074 // entry table. We can't ask the manager, because at the time of PCH loading
1075 // the main file entry doesn't exist yet.
1076 // The very first entry is the invalid instantiation loc, which takes up
1077 // offsets 0 and 1.
1078 return SourceLocation::getFromRawEncoding(2U);
1079 }
1080 //return F->Loaders[0]->FirstLoc;
1081 return F->ImportedBy[0]->FirstLoc;
1082}
1083
1084/// ReadBlockAbbrevs - Enter a subblock of the specified BlockID with the
1085/// specified cursor. Read the abbreviations that are at the top of the block
1086/// and then leave the cursor pointing into the block.
Chris Lattner8f9a1eb2013-01-20 00:56:42 +00001087bool ASTReader::ReadBlockAbbrevs(BitstreamCursor &Cursor, unsigned BlockID) {
Guy Benyei7f92f2d2012-12-18 14:30:41 +00001088 if (Cursor.EnterSubBlock(BlockID)) {
1089 Error("malformed block record in AST file");
1090 return Failure;
1091 }
1092
1093 while (true) {
1094 uint64_t Offset = Cursor.GetCurrentBitNo();
1095 unsigned Code = Cursor.ReadCode();
1096
1097 // We expect all abbrevs to be at the start of the block.
1098 if (Code != llvm::bitc::DEFINE_ABBREV) {
1099 Cursor.JumpToBit(Offset);
1100 return false;
1101 }
1102 Cursor.ReadAbbrevRecord();
1103 }
1104}
1105
Argyrios Kyrtzidis9317ab92013-03-22 21:12:57 +00001106MacroInfo *ASTReader::ReadMacroRecord(ModuleFile &F, uint64_t Offset) {
Chris Lattner8f9a1eb2013-01-20 00:56:42 +00001107 BitstreamCursor &Stream = F.MacroCursor;
Guy Benyei7f92f2d2012-12-18 14:30:41 +00001108
1109 // Keep track of where we are in the stream, then jump back there
1110 // after reading this macro.
1111 SavedStreamPosition SavedPosition(Stream);
1112
1113 Stream.JumpToBit(Offset);
1114 RecordData Record;
1115 SmallVector<IdentifierInfo*, 16> MacroArgs;
1116 MacroInfo *Macro = 0;
1117
Guy Benyei7f92f2d2012-12-18 14:30:41 +00001118 while (true) {
Chris Lattner99a5af02013-01-20 00:00:22 +00001119 // Advance to the next record, but if we get to the end of the block, don't
1120 // pop it (removing all the abbreviations from the cursor) since we want to
1121 // be able to reseek within the block and read entries.
Chris Lattner8f9a1eb2013-01-20 00:56:42 +00001122 unsigned Flags = BitstreamCursor::AF_DontPopBlockAtEnd;
Chris Lattner99a5af02013-01-20 00:00:22 +00001123 llvm::BitstreamEntry Entry = Stream.advanceSkippingSubblocks(Flags);
1124
1125 switch (Entry.Kind) {
1126 case llvm::BitstreamEntry::SubBlock: // Handled for us already.
1127 case llvm::BitstreamEntry::Error:
1128 Error("malformed block record in AST file");
Argyrios Kyrtzidis9317ab92013-03-22 21:12:57 +00001129 return Macro;
Chris Lattner99a5af02013-01-20 00:00:22 +00001130 case llvm::BitstreamEntry::EndBlock:
Argyrios Kyrtzidis9317ab92013-03-22 21:12:57 +00001131 return Macro;
Chris Lattner99a5af02013-01-20 00:00:22 +00001132 case llvm::BitstreamEntry::Record:
1133 // The interesting case.
1134 break;
Guy Benyei7f92f2d2012-12-18 14:30:41 +00001135 }
1136
1137 // Read a record.
Guy Benyei7f92f2d2012-12-18 14:30:41 +00001138 Record.clear();
1139 PreprocessorRecordTypes RecType =
Chris Lattnerb3ce3572013-01-20 02:38:54 +00001140 (PreprocessorRecordTypes)Stream.readRecord(Entry.ID, Record);
Guy Benyei7f92f2d2012-12-18 14:30:41 +00001141 switch (RecType) {
Argyrios Kyrtzidis9317ab92013-03-22 21:12:57 +00001142 case PP_MACRO_DIRECTIVE_HISTORY:
1143 return Macro;
1144
Guy Benyei7f92f2d2012-12-18 14:30:41 +00001145 case PP_MACRO_OBJECT_LIKE:
1146 case PP_MACRO_FUNCTION_LIKE: {
1147 // If we already have a macro, that means that we've hit the end
1148 // of the definition of the macro we were looking for. We're
1149 // done.
1150 if (Macro)
Argyrios Kyrtzidis9317ab92013-03-22 21:12:57 +00001151 return Macro;
Guy Benyei7f92f2d2012-12-18 14:30:41 +00001152
Argyrios Kyrtzidis9317ab92013-03-22 21:12:57 +00001153 unsigned NextIndex = 1; // Skip identifier ID.
1154 SubmoduleID SubModID = getGlobalSubmoduleID(F, Record[NextIndex++]);
Guy Benyei7f92f2d2012-12-18 14:30:41 +00001155 SourceLocation Loc = ReadSourceLocation(F, Record, NextIndex);
Argyrios Kyrtzidis9317ab92013-03-22 21:12:57 +00001156 MacroInfo *MI = PP.AllocateDeserializedMacroInfo(Loc, SubModID);
Argyrios Kyrtzidis8169b672013-01-07 19:16:23 +00001157 MI->setDefinitionEndLoc(ReadSourceLocation(F, Record, NextIndex));
Guy Benyei7f92f2d2012-12-18 14:30:41 +00001158 MI->setIsUsed(Record[NextIndex++]);
Guy Benyei7f92f2d2012-12-18 14:30:41 +00001159
Guy Benyei7f92f2d2012-12-18 14:30:41 +00001160 if (RecType == PP_MACRO_FUNCTION_LIKE) {
1161 // Decode function-like macro info.
1162 bool isC99VarArgs = Record[NextIndex++];
1163 bool isGNUVarArgs = Record[NextIndex++];
1164 bool hasCommaPasting = Record[NextIndex++];
1165 MacroArgs.clear();
1166 unsigned NumArgs = Record[NextIndex++];
1167 for (unsigned i = 0; i != NumArgs; ++i)
1168 MacroArgs.push_back(getLocalIdentifier(F, Record[NextIndex++]));
1169
1170 // Install function-like macro info.
1171 MI->setIsFunctionLike();
1172 if (isC99VarArgs) MI->setIsC99Varargs();
1173 if (isGNUVarArgs) MI->setIsGNUVarargs();
1174 if (hasCommaPasting) MI->setHasCommaPasting();
1175 MI->setArgumentList(MacroArgs.data(), MacroArgs.size(),
1176 PP.getPreprocessorAllocator());
1177 }
1178
Guy Benyei7f92f2d2012-12-18 14:30:41 +00001179 // Remember that we saw this macro last so that we add the tokens that
1180 // form its body to it.
1181 Macro = MI;
1182
1183 if (NextIndex + 1 == Record.size() && PP.getPreprocessingRecord() &&
1184 Record[NextIndex]) {
1185 // We have a macro definition. Register the association
1186 PreprocessedEntityID
1187 GlobalID = getGlobalPreprocessedEntityID(F, Record[NextIndex]);
1188 PreprocessingRecord &PPRec = *PP.getPreprocessingRecord();
Argyrios Kyrtzidis0b849d32013-02-22 18:35:59 +00001189 PreprocessingRecord::PPEntityID
1190 PPID = PPRec.getPPEntityID(GlobalID-1, /*isLoaded=*/true);
1191 MacroDefinition *PPDef =
1192 cast_or_null<MacroDefinition>(PPRec.getPreprocessedEntity(PPID));
1193 if (PPDef)
1194 PPRec.RegisterMacroDefinition(Macro, PPDef);
Guy Benyei7f92f2d2012-12-18 14:30:41 +00001195 }
1196
1197 ++NumMacrosRead;
1198 break;
1199 }
1200
1201 case PP_TOKEN: {
1202 // If we see a TOKEN before a PP_MACRO_*, then the file is
1203 // erroneous, just pretend we didn't see this.
1204 if (Macro == 0) break;
1205
1206 Token Tok;
1207 Tok.startToken();
1208 Tok.setLocation(ReadSourceLocation(F, Record[0]));
1209 Tok.setLength(Record[1]);
1210 if (IdentifierInfo *II = getLocalIdentifier(F, Record[2]))
1211 Tok.setIdentifierInfo(II);
1212 Tok.setKind((tok::TokenKind)Record[3]);
1213 Tok.setFlag((Token::TokenFlags)Record[4]);
1214 Macro->AddTokenToBody(Tok);
1215 break;
1216 }
1217 }
1218 }
1219}
1220
1221PreprocessedEntityID
1222ASTReader::getGlobalPreprocessedEntityID(ModuleFile &M, unsigned LocalID) const {
1223 ContinuousRangeMap<uint32_t, int, 2>::const_iterator
1224 I = M.PreprocessedEntityRemap.find(LocalID - NUM_PREDEF_PP_ENTITY_IDS);
1225 assert(I != M.PreprocessedEntityRemap.end()
1226 && "Invalid index into preprocessed entity index remap");
1227
1228 return LocalID + I->second;
1229}
1230
Argyrios Kyrtzidised3802e2013-03-06 18:12:47 +00001231unsigned HeaderFileInfoTrait::ComputeHash(internal_key_ref ikey) {
1232 return llvm::hash_combine(ikey.Size, ikey.ModTime);
Guy Benyei7f92f2d2012-12-18 14:30:41 +00001233}
1234
1235HeaderFileInfoTrait::internal_key_type
Argyrios Kyrtzidised3802e2013-03-06 18:12:47 +00001236HeaderFileInfoTrait::GetInternalKey(const FileEntry *FE) {
1237 internal_key_type ikey = { FE->getSize(), FE->getModificationTime(),
1238 FE->getName() };
1239 return ikey;
1240}
Guy Benyei7f92f2d2012-12-18 14:30:41 +00001241
Argyrios Kyrtzidised3802e2013-03-06 18:12:47 +00001242bool HeaderFileInfoTrait::EqualKey(internal_key_ref a, internal_key_ref b) {
1243 if (a.Size != b.Size || a.ModTime != b.ModTime)
Guy Benyei7f92f2d2012-12-18 14:30:41 +00001244 return false;
1245
Argyrios Kyrtzidised3802e2013-03-06 18:12:47 +00001246 if (strcmp(a.Filename, b.Filename) == 0)
1247 return true;
1248
Guy Benyei7f92f2d2012-12-18 14:30:41 +00001249 // Determine whether the actual files are equivalent.
Argyrios Kyrtzidis1c1508b2013-03-04 20:33:40 +00001250 FileManager &FileMgr = Reader.getFileManager();
Argyrios Kyrtzidised3802e2013-03-06 18:12:47 +00001251 const FileEntry *FEA = FileMgr.getFile(a.Filename);
1252 const FileEntry *FEB = FileMgr.getFile(b.Filename);
Argyrios Kyrtzidis1c1508b2013-03-04 20:33:40 +00001253 return (FEA && FEA == FEB);
Guy Benyei7f92f2d2012-12-18 14:30:41 +00001254}
1255
1256std::pair<unsigned, unsigned>
1257HeaderFileInfoTrait::ReadKeyDataLength(const unsigned char*& d) {
1258 unsigned KeyLen = (unsigned) clang::io::ReadUnalignedLE16(d);
1259 unsigned DataLen = (unsigned) *d++;
Argyrios Kyrtzidised3802e2013-03-06 18:12:47 +00001260 return std::make_pair(KeyLen, DataLen);
Guy Benyei7f92f2d2012-12-18 14:30:41 +00001261}
Argyrios Kyrtzidised3802e2013-03-06 18:12:47 +00001262
1263HeaderFileInfoTrait::internal_key_type
1264HeaderFileInfoTrait::ReadKey(const unsigned char *d, unsigned) {
1265 internal_key_type ikey;
1266 ikey.Size = off_t(clang::io::ReadUnalignedLE64(d));
1267 ikey.ModTime = time_t(clang::io::ReadUnalignedLE64(d));
1268 ikey.Filename = (const char *)d;
1269 return ikey;
1270}
1271
Guy Benyei7f92f2d2012-12-18 14:30:41 +00001272HeaderFileInfoTrait::data_type
Argyrios Kyrtzidis55ea75b2013-03-13 21:13:51 +00001273HeaderFileInfoTrait::ReadData(internal_key_ref key, const unsigned char *d,
Guy Benyei7f92f2d2012-12-18 14:30:41 +00001274 unsigned DataLen) {
1275 const unsigned char *End = d + DataLen;
1276 using namespace clang::io;
1277 HeaderFileInfo HFI;
1278 unsigned Flags = *d++;
1279 HFI.isImport = (Flags >> 5) & 0x01;
1280 HFI.isPragmaOnce = (Flags >> 4) & 0x01;
1281 HFI.DirInfo = (Flags >> 2) & 0x03;
1282 HFI.Resolved = (Flags >> 1) & 0x01;
1283 HFI.IndexHeaderMapHeader = Flags & 0x01;
1284 HFI.NumIncludes = ReadUnalignedLE16(d);
1285 HFI.ControllingMacroID = Reader.getGlobalIdentifierID(M,
1286 ReadUnalignedLE32(d));
1287 if (unsigned FrameworkOffset = ReadUnalignedLE32(d)) {
1288 // The framework offset is 1 greater than the actual offset,
1289 // since 0 is used as an indicator for "no framework name".
1290 StringRef FrameworkName(FrameworkStrings + FrameworkOffset - 1);
1291 HFI.Framework = HS->getUniqueFrameworkName(FrameworkName);
1292 }
1293
Argyrios Kyrtzidis55ea75b2013-03-13 21:13:51 +00001294 if (d != End) {
1295 uint32_t LocalSMID = ReadUnalignedLE32(d);
1296 if (LocalSMID) {
1297 // This header is part of a module. Associate it with the module to enable
1298 // implicit module import.
1299 SubmoduleID GlobalSMID = Reader.getGlobalSubmoduleID(M, LocalSMID);
1300 Module *Mod = Reader.getSubmodule(GlobalSMID);
1301 HFI.isModuleHeader = true;
1302 FileManager &FileMgr = Reader.getFileManager();
1303 ModuleMap &ModMap =
1304 Reader.getPreprocessor().getHeaderSearchInfo().getModuleMap();
1305 ModMap.addHeader(Mod, FileMgr.getFile(key.Filename), /*Excluded=*/false);
1306 }
1307 }
1308
Guy Benyei7f92f2d2012-12-18 14:30:41 +00001309 assert(End == d && "Wrong data length in HeaderFileInfo deserialization");
1310 (void)End;
1311
1312 // This HeaderFileInfo was externally loaded.
1313 HFI.External = true;
1314 return HFI;
1315}
1316
Argyrios Kyrtzidis9317ab92013-03-22 21:12:57 +00001317void ASTReader::addPendingMacroFromModule(IdentifierInfo *II,
1318 ModuleFile *M,
1319 GlobalMacroID GMacID,
1320 SourceLocation ImportLoc) {
Guy Benyei7f92f2d2012-12-18 14:30:41 +00001321 assert(NumCurrentElementsDeserializing > 0 &&"Missing deserialization guard");
Argyrios Kyrtzidis9317ab92013-03-22 21:12:57 +00001322 PendingMacroIDs[II].push_back(PendingMacroInfo(M, GMacID, ImportLoc));
1323}
1324
1325void ASTReader::addPendingMacroFromPCH(IdentifierInfo *II,
1326 ModuleFile *M,
1327 uint64_t MacroDirectivesOffset) {
1328 assert(NumCurrentElementsDeserializing > 0 &&"Missing deserialization guard");
1329 PendingMacroIDs[II].push_back(PendingMacroInfo(M, MacroDirectivesOffset));
Guy Benyei7f92f2d2012-12-18 14:30:41 +00001330}
1331
1332void ASTReader::ReadDefinedMacros() {
1333 // Note that we are loading defined macros.
1334 Deserializing Macros(this);
1335
1336 for (ModuleReverseIterator I = ModuleMgr.rbegin(),
1337 E = ModuleMgr.rend(); I != E; ++I) {
Chris Lattner8f9a1eb2013-01-20 00:56:42 +00001338 BitstreamCursor &MacroCursor = (*I)->MacroCursor;
Guy Benyei7f92f2d2012-12-18 14:30:41 +00001339
1340 // If there was no preprocessor block, skip this file.
1341 if (!MacroCursor.getBitStreamReader())
1342 continue;
1343
Chris Lattner8f9a1eb2013-01-20 00:56:42 +00001344 BitstreamCursor Cursor = MacroCursor;
Guy Benyei7f92f2d2012-12-18 14:30:41 +00001345 Cursor.JumpToBit((*I)->MacroStartOffset);
1346
1347 RecordData Record;
1348 while (true) {
Chris Lattner88bde502013-01-19 21:39:22 +00001349 llvm::BitstreamEntry E = Cursor.advanceSkippingSubblocks();
1350
1351 switch (E.Kind) {
1352 case llvm::BitstreamEntry::SubBlock: // Handled for us already.
1353 case llvm::BitstreamEntry::Error:
1354 Error("malformed block record in AST file");
1355 return;
1356 case llvm::BitstreamEntry::EndBlock:
1357 goto NextCursor;
1358
1359 case llvm::BitstreamEntry::Record:
Chris Lattner88bde502013-01-19 21:39:22 +00001360 Record.clear();
Chris Lattnerb3ce3572013-01-20 02:38:54 +00001361 switch (Cursor.readRecord(E.ID, Record)) {
Chris Lattner88bde502013-01-19 21:39:22 +00001362 default: // Default behavior: ignore.
1363 break;
1364
1365 case PP_MACRO_OBJECT_LIKE:
1366 case PP_MACRO_FUNCTION_LIKE:
1367 getLocalIdentifier(**I, Record[0]);
1368 break;
1369
1370 case PP_TOKEN:
1371 // Ignore tokens.
1372 break;
Guy Benyei7f92f2d2012-12-18 14:30:41 +00001373 }
Guy Benyei7f92f2d2012-12-18 14:30:41 +00001374 break;
1375 }
1376 }
Chris Lattner88bde502013-01-19 21:39:22 +00001377 NextCursor: ;
Guy Benyei7f92f2d2012-12-18 14:30:41 +00001378 }
1379}
1380
1381namespace {
1382 /// \brief Visitor class used to look up identifirs in an AST file.
1383 class IdentifierLookupVisitor {
1384 StringRef Name;
1385 unsigned PriorGeneration;
Douglas Gregore1698072013-01-25 00:38:33 +00001386 unsigned &NumIdentifierLookups;
1387 unsigned &NumIdentifierLookupHits;
Guy Benyei7f92f2d2012-12-18 14:30:41 +00001388 IdentifierInfo *Found;
Douglas Gregore1698072013-01-25 00:38:33 +00001389
Guy Benyei7f92f2d2012-12-18 14:30:41 +00001390 public:
Douglas Gregore1698072013-01-25 00:38:33 +00001391 IdentifierLookupVisitor(StringRef Name, unsigned PriorGeneration,
1392 unsigned &NumIdentifierLookups,
1393 unsigned &NumIdentifierLookupHits)
Douglas Gregor188bdcd2013-01-25 23:32:03 +00001394 : Name(Name), PriorGeneration(PriorGeneration),
Douglas Gregore1698072013-01-25 00:38:33 +00001395 NumIdentifierLookups(NumIdentifierLookups),
1396 NumIdentifierLookupHits(NumIdentifierLookupHits),
1397 Found()
1398 {
1399 }
Guy Benyei7f92f2d2012-12-18 14:30:41 +00001400
1401 static bool visit(ModuleFile &M, void *UserData) {
1402 IdentifierLookupVisitor *This
1403 = static_cast<IdentifierLookupVisitor *>(UserData);
1404
1405 // If we've already searched this module file, skip it now.
1406 if (M.Generation <= This->PriorGeneration)
1407 return true;
Douglas Gregor1a49d972013-01-25 01:03:03 +00001408
Guy Benyei7f92f2d2012-12-18 14:30:41 +00001409 ASTIdentifierLookupTable *IdTable
1410 = (ASTIdentifierLookupTable *)M.IdentifierLookupTable;
1411 if (!IdTable)
1412 return false;
1413
1414 ASTIdentifierLookupTrait Trait(IdTable->getInfoObj().getReader(),
1415 M, This->Found);
Douglas Gregore1698072013-01-25 00:38:33 +00001416 ++This->NumIdentifierLookups;
1417 ASTIdentifierLookupTable::iterator Pos = IdTable->find(This->Name,&Trait);
Guy Benyei7f92f2d2012-12-18 14:30:41 +00001418 if (Pos == IdTable->end())
1419 return false;
1420
1421 // Dereferencing the iterator has the effect of building the
1422 // IdentifierInfo node and populating it with the various
1423 // declarations it needs.
Douglas Gregore1698072013-01-25 00:38:33 +00001424 ++This->NumIdentifierLookupHits;
Guy Benyei7f92f2d2012-12-18 14:30:41 +00001425 This->Found = *Pos;
1426 return true;
1427 }
1428
1429 // \brief Retrieve the identifier info found within the module
1430 // files.
1431 IdentifierInfo *getIdentifierInfo() const { return Found; }
1432 };
1433}
1434
1435void ASTReader::updateOutOfDateIdentifier(IdentifierInfo &II) {
1436 // Note that we are loading an identifier.
1437 Deserializing AnIdentifier(this);
1438
1439 unsigned PriorGeneration = 0;
1440 if (getContext().getLangOpts().Modules)
1441 PriorGeneration = IdentifierGeneration[&II];
Douglas Gregor1a49d972013-01-25 01:03:03 +00001442
1443 // If there is a global index, look there first to determine which modules
1444 // provably do not have any results for this identifier.
Douglas Gregor188bdcd2013-01-25 23:32:03 +00001445 GlobalModuleIndex::HitSet Hits;
1446 GlobalModuleIndex::HitSet *HitsPtr = 0;
Douglas Gregor1a49d972013-01-25 01:03:03 +00001447 if (!loadGlobalIndex()) {
Douglas Gregor188bdcd2013-01-25 23:32:03 +00001448 if (GlobalIndex->lookupIdentifier(II.getName(), Hits)) {
1449 HitsPtr = &Hits;
Douglas Gregor1a49d972013-01-25 01:03:03 +00001450 }
1451 }
1452
Douglas Gregor188bdcd2013-01-25 23:32:03 +00001453 IdentifierLookupVisitor Visitor(II.getName(), PriorGeneration,
Douglas Gregore1698072013-01-25 00:38:33 +00001454 NumIdentifierLookups,
1455 NumIdentifierLookupHits);
Douglas Gregor188bdcd2013-01-25 23:32:03 +00001456 ModuleMgr.visit(IdentifierLookupVisitor::visit, &Visitor, HitsPtr);
Guy Benyei7f92f2d2012-12-18 14:30:41 +00001457 markIdentifierUpToDate(&II);
1458}
1459
1460void ASTReader::markIdentifierUpToDate(IdentifierInfo *II) {
1461 if (!II)
1462 return;
1463
1464 II->setOutOfDate(false);
1465
1466 // Update the generation for this identifier.
1467 if (getContext().getLangOpts().Modules)
1468 IdentifierGeneration[II] = CurrentGeneration;
1469}
1470
Argyrios Kyrtzidis9317ab92013-03-22 21:12:57 +00001471void ASTReader::resolvePendingMacro(IdentifierInfo *II,
1472 const PendingMacroInfo &PMInfo) {
1473 assert(II);
1474
1475 if (PMInfo.M->Kind != MK_Module) {
1476 installPCHMacroDirectives(II, *PMInfo.M,
1477 PMInfo.PCHMacroData.MacroDirectivesOffset);
1478 return;
1479 }
1480
1481 // Module Macro.
1482
1483 GlobalMacroID GMacID = PMInfo.ModuleMacroData.GMacID;
1484 SourceLocation ImportLoc =
1485 SourceLocation::getFromRawEncoding(PMInfo.ModuleMacroData.ImportLoc);
1486
1487 assert(GMacID);
1488 // If this macro has already been loaded, don't do so again.
1489 if (MacrosLoaded[GMacID - NUM_PREDEF_MACRO_IDS])
1490 return;
1491
1492 MacroInfo *MI = getMacro(GMacID);
1493 SubmoduleID SubModID = MI->getOwningModuleID();
Argyrios Kyrtzidisc56fff72013-03-26 17:17:01 +00001494 MacroDirective *MD = PP.AllocateDefMacroDirective(MI, ImportLoc,
1495 /*isImported=*/true);
Argyrios Kyrtzidis9317ab92013-03-22 21:12:57 +00001496
1497 // Determine whether this macro definition is visible.
1498 bool Hidden = false;
Argyrios Kyrtzidis52151fd2013-03-27 01:25:34 +00001499 Module *Owner = 0;
Argyrios Kyrtzidis9317ab92013-03-22 21:12:57 +00001500 if (SubModID) {
Argyrios Kyrtzidis52151fd2013-03-27 01:25:34 +00001501 if ((Owner = getSubmodule(SubModID))) {
Argyrios Kyrtzidis9317ab92013-03-22 21:12:57 +00001502 if (Owner->NameVisibility == Module::Hidden) {
1503 // The owning module is not visible, and this macro definition
1504 // should not be, either.
1505 Hidden = true;
1506
1507 // Note that this macro definition was hidden because its owning
1508 // module is not yet visible.
1509 HiddenNamesMap[Owner].push_back(HiddenName(II, MD));
1510 }
1511 }
1512 }
Argyrios Kyrtzidis9317ab92013-03-22 21:12:57 +00001513
1514 if (!Hidden)
Argyrios Kyrtzidis52151fd2013-03-27 01:25:34 +00001515 installImportedMacro(II, MD, Owner);
Argyrios Kyrtzidis9317ab92013-03-22 21:12:57 +00001516}
1517
1518void ASTReader::installPCHMacroDirectives(IdentifierInfo *II,
1519 ModuleFile &M, uint64_t Offset) {
1520 assert(M.Kind != MK_Module);
1521
1522 BitstreamCursor &Cursor = M.MacroCursor;
1523 SavedStreamPosition SavedPosition(Cursor);
1524 Cursor.JumpToBit(Offset);
1525
1526 llvm::BitstreamEntry Entry =
1527 Cursor.advance(BitstreamCursor::AF_DontPopBlockAtEnd);
1528 if (Entry.Kind != llvm::BitstreamEntry::Record) {
1529 Error("malformed block record in AST file");
1530 return;
1531 }
1532
1533 RecordData Record;
1534 PreprocessorRecordTypes RecType =
1535 (PreprocessorRecordTypes)Cursor.readRecord(Entry.ID, Record);
1536 if (RecType != PP_MACRO_DIRECTIVE_HISTORY) {
1537 Error("malformed block record in AST file");
1538 return;
1539 }
1540
1541 // Deserialize the macro directives history in reverse source-order.
1542 MacroDirective *Latest = 0, *Earliest = 0;
1543 unsigned Idx = 0, N = Record.size();
1544 while (Idx < N) {
Argyrios Kyrtzidisc56fff72013-03-26 17:17:01 +00001545 MacroDirective *MD = 0;
Argyrios Kyrtzidis9317ab92013-03-22 21:12:57 +00001546 SourceLocation Loc = ReadSourceLocation(M, Record, Idx);
Argyrios Kyrtzidisc56fff72013-03-26 17:17:01 +00001547 MacroDirective::Kind K = (MacroDirective::Kind)Record[Idx++];
1548 switch (K) {
1549 case MacroDirective::MD_Define: {
1550 GlobalMacroID GMacID = getGlobalMacroID(M, Record[Idx++]);
1551 MacroInfo *MI = getMacro(GMacID);
1552 bool isImported = Record[Idx++];
1553 bool isAmbiguous = Record[Idx++];
1554 DefMacroDirective *DefMD =
1555 PP.AllocateDefMacroDirective(MI, Loc, isImported);
1556 DefMD->setAmbiguous(isAmbiguous);
1557 MD = DefMD;
1558 break;
1559 }
1560 case MacroDirective::MD_Undefine:
1561 MD = PP.AllocateUndefMacroDirective(Loc);
1562 break;
1563 case MacroDirective::MD_Visibility: {
1564 bool isPublic = Record[Idx++];
1565 MD = PP.AllocateVisibilityMacroDirective(Loc, isPublic);
1566 break;
1567 }
1568 }
Argyrios Kyrtzidis9317ab92013-03-22 21:12:57 +00001569
1570 if (!Latest)
1571 Latest = MD;
1572 if (Earliest)
1573 Earliest->setPrevious(MD);
1574 Earliest = MD;
1575 }
1576
1577 PP.setLoadedMacroDirective(II, Latest);
1578}
1579
Argyrios Kyrtzidis52151fd2013-03-27 01:25:34 +00001580/// \brief For the given macro definitions, check if they are both in system
Douglas Gregor7332ae42013-04-12 21:00:54 +00001581/// modules.
1582static bool areDefinedInSystemModules(MacroInfo *PrevMI, MacroInfo *NewMI,
1583 Module *NewOwner, ASTReader &Reader) {
Argyrios Kyrtzidis52151fd2013-03-27 01:25:34 +00001584 assert(PrevMI && NewMI);
1585 if (!NewOwner)
1586 return false;
1587 Module *PrevOwner = 0;
1588 if (SubmoduleID PrevModID = PrevMI->getOwningModuleID())
1589 PrevOwner = Reader.getSubmodule(PrevModID);
1590 if (!PrevOwner)
1591 return false;
1592 if (PrevOwner == NewOwner)
1593 return false;
Douglas Gregor7332ae42013-04-12 21:00:54 +00001594 return PrevOwner->IsSystem && NewOwner->IsSystem;
Argyrios Kyrtzidis52151fd2013-03-27 01:25:34 +00001595}
1596
1597void ASTReader::installImportedMacro(IdentifierInfo *II, MacroDirective *MD,
1598 Module *Owner) {
Argyrios Kyrtzidis9317ab92013-03-22 21:12:57 +00001599 assert(II && MD);
1600
Argyrios Kyrtzidisc56fff72013-03-26 17:17:01 +00001601 DefMacroDirective *DefMD = cast<DefMacroDirective>(MD);
Argyrios Kyrtzidis9317ab92013-03-22 21:12:57 +00001602 MacroDirective *Prev = PP.getMacroDirective(II);
Argyrios Kyrtzidisc56fff72013-03-26 17:17:01 +00001603 if (Prev) {
1604 MacroDirective::DefInfo PrevDef = Prev->getDefinition();
Argyrios Kyrtzidis52151fd2013-03-27 01:25:34 +00001605 MacroInfo *PrevMI = PrevDef.getMacroInfo();
1606 MacroInfo *NewMI = DefMD->getInfo();
Argyrios Kyrtzidisbd25ff82013-04-03 17:39:30 +00001607 if (NewMI != PrevMI && !PrevMI->isIdenticalTo(*NewMI, PP,
1608 /*Syntactically=*/true)) {
Argyrios Kyrtzidis52151fd2013-03-27 01:25:34 +00001609 // Before marking the macros as ambiguous, check if this is a case where
Douglas Gregor7332ae42013-04-12 21:00:54 +00001610 // both macros are in system headers. If so, we trust that the system
1611 // did not get it wrong. This also handles cases where Clang's own
1612 // headers have a different spelling of certain system macros:
Argyrios Kyrtzidis52151fd2013-03-27 01:25:34 +00001613 // #define LONG_MAX __LONG_MAX__ (clang's limits.h)
1614 // #define LONG_MAX 0x7fffffffffffffffL (system's limits.h)
Douglas Gregor7332ae42013-04-12 21:00:54 +00001615 if (!areDefinedInSystemModules(PrevMI, NewMI, Owner, *this)) {
Argyrios Kyrtzidis52151fd2013-03-27 01:25:34 +00001616 PrevDef.getDirective()->setAmbiguous(true);
1617 DefMD->setAmbiguous(true);
1618 }
Argyrios Kyrtzidisc56fff72013-03-26 17:17:01 +00001619 }
Argyrios Kyrtzidis9317ab92013-03-22 21:12:57 +00001620 }
1621
Argyrios Kyrtzidisc56fff72013-03-26 17:17:01 +00001622 PP.appendMacroDirective(II, MD);
Argyrios Kyrtzidis9317ab92013-03-22 21:12:57 +00001623}
1624
Argyrios Kyrtzidis8504b7b2013-03-01 03:26:04 +00001625InputFile ASTReader::getInputFile(ModuleFile &F, unsigned ID, bool Complain) {
Guy Benyei7f92f2d2012-12-18 14:30:41 +00001626 // If this ID is bogus, just return an empty input file.
1627 if (ID == 0 || ID > F.InputFilesLoaded.size())
1628 return InputFile();
1629
1630 // If we've already loaded this input file, return it.
Argyrios Kyrtzidis8504b7b2013-03-01 03:26:04 +00001631 if (F.InputFilesLoaded[ID-1].getFile())
Guy Benyei7f92f2d2012-12-18 14:30:41 +00001632 return F.InputFilesLoaded[ID-1];
1633
1634 // Go find this input file.
Chris Lattner8f9a1eb2013-01-20 00:56:42 +00001635 BitstreamCursor &Cursor = F.InputFilesCursor;
Guy Benyei7f92f2d2012-12-18 14:30:41 +00001636 SavedStreamPosition SavedPosition(Cursor);
1637 Cursor.JumpToBit(F.InputFileOffsets[ID-1]);
1638
1639 unsigned Code = Cursor.ReadCode();
1640 RecordData Record;
Chris Lattnerb3ce3572013-01-20 02:38:54 +00001641 StringRef Blob;
1642 switch ((InputFileRecordTypes)Cursor.readRecord(Code, Record, &Blob)) {
Guy Benyei7f92f2d2012-12-18 14:30:41 +00001643 case INPUT_FILE: {
1644 unsigned StoredID = Record[0];
1645 assert(ID == StoredID && "Bogus stored ID or offset");
1646 (void)StoredID;
1647 off_t StoredSize = (off_t)Record[1];
1648 time_t StoredTime = (time_t)Record[2];
1649 bool Overridden = (bool)Record[3];
1650
1651 // Get the file entry for this input file.
Chris Lattnerb3ce3572013-01-20 02:38:54 +00001652 StringRef OrigFilename = Blob;
Guy Benyei7f92f2d2012-12-18 14:30:41 +00001653 std::string Filename = OrigFilename;
1654 MaybeAddSystemRootToFilename(F, Filename);
1655 const FileEntry *File
1656 = Overridden? FileMgr.getVirtualFile(Filename, StoredSize, StoredTime)
1657 : FileMgr.getFile(Filename, /*OpenFile=*/false);
1658
1659 // If we didn't find the file, resolve it relative to the
1660 // original directory from which this AST file was created.
1661 if (File == 0 && !F.OriginalDir.empty() && !CurrentDir.empty() &&
1662 F.OriginalDir != CurrentDir) {
1663 std::string Resolved = resolveFileRelativeToOriginalDir(Filename,
1664 F.OriginalDir,
1665 CurrentDir);
1666 if (!Resolved.empty())
1667 File = FileMgr.getFile(Resolved);
1668 }
1669
1670 // For an overridden file, create a virtual file with the stored
1671 // size/timestamp.
1672 if (Overridden && File == 0) {
1673 File = FileMgr.getVirtualFile(Filename, StoredSize, StoredTime);
1674 }
1675
1676 if (File == 0) {
1677 if (Complain) {
1678 std::string ErrorStr = "could not find file '";
1679 ErrorStr += Filename;
1680 ErrorStr += "' referenced by AST file";
1681 Error(ErrorStr.c_str());
1682 }
1683 return InputFile();
1684 }
Argyrios Kyrtzidis8504b7b2013-03-01 03:26:04 +00001685
Guy Benyei7f92f2d2012-12-18 14:30:41 +00001686 // Check if there was a request to override the contents of the file
1687 // that was part of the precompiled header. Overridding such a file
1688 // can lead to problems when lexing using the source locations from the
1689 // PCH.
1690 SourceManager &SM = getSourceManager();
1691 if (!Overridden && SM.isFileOverridden(File)) {
Argyrios Kyrtzidis8504b7b2013-03-01 03:26:04 +00001692 if (Complain)
1693 Error(diag::err_fe_pch_file_overridden, Filename);
Guy Benyei7f92f2d2012-12-18 14:30:41 +00001694 // After emitting the diagnostic, recover by disabling the override so
1695 // that the original file will be used.
1696 SM.disableFileContentsOverride(File);
1697 // The FileEntry is a virtual file entry with the size of the contents
1698 // that would override the original contents. Set it to the original's
1699 // size/time.
1700 FileMgr.modifyFileEntry(const_cast<FileEntry*>(File),
1701 StoredSize, StoredTime);
1702 }
1703
Argyrios Kyrtzidis8504b7b2013-03-01 03:26:04 +00001704 bool IsOutOfDate = false;
Guy Benyei7f92f2d2012-12-18 14:30:41 +00001705
Argyrios Kyrtzidis8504b7b2013-03-01 03:26:04 +00001706 // For an overridden file, there is nothing to validate.
1707 if (!Overridden && (StoredSize != File->getSize()
Guy Benyei7f92f2d2012-12-18 14:30:41 +00001708#if !defined(LLVM_ON_WIN32)
1709 // In our regression testing, the Windows file system seems to
1710 // have inconsistent modification times that sometimes
1711 // erroneously trigger this error-handling path.
1712 || StoredTime != File->getModificationTime()
1713#endif
1714 )) {
Douglas Gregor677e15f2013-03-19 00:28:20 +00001715 if (Complain) {
Argyrios Kyrtzidisf8f373f2013-03-08 20:42:38 +00001716 Error(diag::err_fe_pch_file_modified, Filename, F.FileName);
Douglas Gregor677e15f2013-03-19 00:28:20 +00001717 }
1718
Argyrios Kyrtzidis8504b7b2013-03-01 03:26:04 +00001719 IsOutOfDate = true;
Guy Benyei7f92f2d2012-12-18 14:30:41 +00001720 }
1721
Argyrios Kyrtzidis8504b7b2013-03-01 03:26:04 +00001722 InputFile IF = InputFile(File, Overridden, IsOutOfDate);
1723
1724 // Note that we've loaded this input file.
1725 F.InputFilesLoaded[ID-1] = IF;
1726 return IF;
Guy Benyei7f92f2d2012-12-18 14:30:41 +00001727 }
1728 }
1729
1730 return InputFile();
1731}
1732
1733const FileEntry *ASTReader::getFileEntry(StringRef filenameStrRef) {
1734 ModuleFile &M = ModuleMgr.getPrimaryModule();
1735 std::string Filename = filenameStrRef;
1736 MaybeAddSystemRootToFilename(M, Filename);
1737 const FileEntry *File = FileMgr.getFile(Filename);
1738 if (File == 0 && !M.OriginalDir.empty() && !CurrentDir.empty() &&
1739 M.OriginalDir != CurrentDir) {
1740 std::string resolved = resolveFileRelativeToOriginalDir(Filename,
1741 M.OriginalDir,
1742 CurrentDir);
1743 if (!resolved.empty())
1744 File = FileMgr.getFile(resolved);
1745 }
1746
1747 return File;
1748}
1749
1750/// \brief If we are loading a relocatable PCH file, and the filename is
1751/// not an absolute path, add the system root to the beginning of the file
1752/// name.
1753void ASTReader::MaybeAddSystemRootToFilename(ModuleFile &M,
1754 std::string &Filename) {
1755 // If this is not a relocatable PCH file, there's nothing to do.
1756 if (!M.RelocatablePCH)
1757 return;
1758
1759 if (Filename.empty() || llvm::sys::path::is_absolute(Filename))
1760 return;
1761
1762 if (isysroot.empty()) {
1763 // If no system root was given, default to '/'
1764 Filename.insert(Filename.begin(), '/');
1765 return;
1766 }
1767
1768 unsigned Length = isysroot.size();
1769 if (isysroot[Length - 1] != '/')
1770 Filename.insert(Filename.begin(), '/');
1771
1772 Filename.insert(Filename.begin(), isysroot.begin(), isysroot.end());
1773}
1774
1775ASTReader::ASTReadResult
1776ASTReader::ReadControlBlock(ModuleFile &F,
Dmitri Gribenkocfa88f82013-01-12 19:30:44 +00001777 SmallVectorImpl<ImportedModule> &Loaded,
Guy Benyei7f92f2d2012-12-18 14:30:41 +00001778 unsigned ClientLoadCapabilities) {
Chris Lattner8f9a1eb2013-01-20 00:56:42 +00001779 BitstreamCursor &Stream = F.Stream;
Guy Benyei7f92f2d2012-12-18 14:30:41 +00001780
1781 if (Stream.EnterSubBlock(CONTROL_BLOCK_ID)) {
1782 Error("malformed block record in AST file");
1783 return Failure;
1784 }
1785
1786 // Read all of the records and blocks in the control block.
1787 RecordData Record;
Chris Lattner88bde502013-01-19 21:39:22 +00001788 while (1) {
1789 llvm::BitstreamEntry Entry = Stream.advance();
1790
1791 switch (Entry.Kind) {
1792 case llvm::BitstreamEntry::Error:
1793 Error("malformed block record in AST file");
1794 return Failure;
1795 case llvm::BitstreamEntry::EndBlock:
Argyrios Kyrtzidis398253a2013-03-06 18:12:50 +00001796 // Validate all of the non-system input files.
Guy Benyei7f92f2d2012-12-18 14:30:41 +00001797 if (!DisableValidation) {
1798 bool Complain = (ClientLoadCapabilities & ARR_OutOfDate) == 0;
Argyrios Kyrtzidis398253a2013-03-06 18:12:50 +00001799 // All user input files reside at the index range [0, Record[1]).
1800 // Record is the one from INPUT_FILE_OFFSETS.
1801 for (unsigned I = 0, N = Record[1]; I < N; ++I) {
Argyrios Kyrtzidis8504b7b2013-03-01 03:26:04 +00001802 InputFile IF = getInputFile(F, I+1, Complain);
1803 if (!IF.getFile() || IF.isOutOfDate())
Guy Benyei7f92f2d2012-12-18 14:30:41 +00001804 return OutOfDate;
Argyrios Kyrtzidis8504b7b2013-03-01 03:26:04 +00001805 }
Guy Benyei7f92f2d2012-12-18 14:30:41 +00001806 }
Guy Benyei7f92f2d2012-12-18 14:30:41 +00001807 return Success;
Chris Lattner88bde502013-01-19 21:39:22 +00001808
1809 case llvm::BitstreamEntry::SubBlock:
1810 switch (Entry.ID) {
Guy Benyei7f92f2d2012-12-18 14:30:41 +00001811 case INPUT_FILES_BLOCK_ID:
1812 F.InputFilesCursor = Stream;
1813 if (Stream.SkipBlock() || // Skip with the main cursor
1814 // Read the abbreviations
1815 ReadBlockAbbrevs(F.InputFilesCursor, INPUT_FILES_BLOCK_ID)) {
1816 Error("malformed block record in AST file");
1817 return Failure;
1818 }
1819 continue;
Chris Lattner88bde502013-01-19 21:39:22 +00001820
Guy Benyei7f92f2d2012-12-18 14:30:41 +00001821 default:
Chris Lattner88bde502013-01-19 21:39:22 +00001822 if (Stream.SkipBlock()) {
1823 Error("malformed block record in AST file");
1824 return Failure;
1825 }
1826 continue;
Guy Benyei7f92f2d2012-12-18 14:30:41 +00001827 }
Chris Lattner88bde502013-01-19 21:39:22 +00001828
1829 case llvm::BitstreamEntry::Record:
1830 // The interesting case.
1831 break;
Guy Benyei7f92f2d2012-12-18 14:30:41 +00001832 }
1833
1834 // Read and process a record.
1835 Record.clear();
Chris Lattnerb3ce3572013-01-20 02:38:54 +00001836 StringRef Blob;
1837 switch ((ControlRecordTypes)Stream.readRecord(Entry.ID, Record, &Blob)) {
Guy Benyei7f92f2d2012-12-18 14:30:41 +00001838 case METADATA: {
1839 if (Record[0] != VERSION_MAJOR && !DisableValidation) {
1840 if ((ClientLoadCapabilities & ARR_VersionMismatch) == 0)
1841 Diag(Record[0] < VERSION_MAJOR? diag::warn_pch_version_too_old
1842 : diag::warn_pch_version_too_new);
1843 return VersionMismatch;
1844 }
1845
1846 bool hasErrors = Record[5];
1847 if (hasErrors && !DisableValidation && !AllowASTWithCompilerErrors) {
1848 Diag(diag::err_pch_with_compiler_errors);
1849 return HadErrors;
1850 }
1851
1852 F.RelocatablePCH = Record[4];
1853
1854 const std::string &CurBranch = getClangFullRepositoryVersion();
Chris Lattnerb3ce3572013-01-20 02:38:54 +00001855 StringRef ASTBranch = Blob;
Guy Benyei7f92f2d2012-12-18 14:30:41 +00001856 if (StringRef(CurBranch) != ASTBranch && !DisableValidation) {
1857 if ((ClientLoadCapabilities & ARR_VersionMismatch) == 0)
1858 Diag(diag::warn_pch_different_branch) << ASTBranch << CurBranch;
1859 return VersionMismatch;
1860 }
1861 break;
1862 }
1863
1864 case IMPORTS: {
1865 // Load each of the imported PCH files.
1866 unsigned Idx = 0, N = Record.size();
1867 while (Idx < N) {
1868 // Read information about the AST file.
1869 ModuleKind ImportedKind = (ModuleKind)Record[Idx++];
1870 // The import location will be the local one for now; we will adjust
1871 // all import locations of module imports after the global source
1872 // location info are setup.
1873 SourceLocation ImportLoc =
1874 SourceLocation::getFromRawEncoding(Record[Idx++]);
Douglas Gregor677e15f2013-03-19 00:28:20 +00001875 off_t StoredSize = (off_t)Record[Idx++];
1876 time_t StoredModTime = (time_t)Record[Idx++];
Guy Benyei7f92f2d2012-12-18 14:30:41 +00001877 unsigned Length = Record[Idx++];
1878 SmallString<128> ImportedFile(Record.begin() + Idx,
1879 Record.begin() + Idx + Length);
1880 Idx += Length;
1881
1882 // Load the AST file.
1883 switch(ReadASTCore(ImportedFile, ImportedKind, ImportLoc, &F, Loaded,
Douglas Gregor677e15f2013-03-19 00:28:20 +00001884 StoredSize, StoredModTime,
Guy Benyei7f92f2d2012-12-18 14:30:41 +00001885 ClientLoadCapabilities)) {
1886 case Failure: return Failure;
1887 // If we have to ignore the dependency, we'll have to ignore this too.
Douglas Gregorac39f132013-03-19 00:38:50 +00001888 case Missing:
Guy Benyei7f92f2d2012-12-18 14:30:41 +00001889 case OutOfDate: return OutOfDate;
1890 case VersionMismatch: return VersionMismatch;
1891 case ConfigurationMismatch: return ConfigurationMismatch;
1892 case HadErrors: return HadErrors;
1893 case Success: break;
1894 }
1895 }
1896 break;
1897 }
1898
1899 case LANGUAGE_OPTIONS: {
1900 bool Complain = (ClientLoadCapabilities & ARR_ConfigurationMismatch) == 0;
1901 if (Listener && &F == *ModuleMgr.begin() &&
1902 ParseLanguageOptions(Record, Complain, *Listener) &&
1903 !DisableValidation)
1904 return ConfigurationMismatch;
1905 break;
1906 }
1907
1908 case TARGET_OPTIONS: {
1909 bool Complain = (ClientLoadCapabilities & ARR_ConfigurationMismatch)==0;
1910 if (Listener && &F == *ModuleMgr.begin() &&
1911 ParseTargetOptions(Record, Complain, *Listener) &&
1912 !DisableValidation)
1913 return ConfigurationMismatch;
1914 break;
1915 }
1916
1917 case DIAGNOSTIC_OPTIONS: {
1918 bool Complain = (ClientLoadCapabilities & ARR_ConfigurationMismatch)==0;
1919 if (Listener && &F == *ModuleMgr.begin() &&
1920 ParseDiagnosticOptions(Record, Complain, *Listener) &&
1921 !DisableValidation)
1922 return ConfigurationMismatch;
1923 break;
1924 }
1925
1926 case FILE_SYSTEM_OPTIONS: {
1927 bool Complain = (ClientLoadCapabilities & ARR_ConfigurationMismatch)==0;
1928 if (Listener && &F == *ModuleMgr.begin() &&
1929 ParseFileSystemOptions(Record, Complain, *Listener) &&
1930 !DisableValidation)
1931 return ConfigurationMismatch;
1932 break;
1933 }
1934
1935 case HEADER_SEARCH_OPTIONS: {
1936 bool Complain = (ClientLoadCapabilities & ARR_ConfigurationMismatch)==0;
1937 if (Listener && &F == *ModuleMgr.begin() &&
1938 ParseHeaderSearchOptions(Record, Complain, *Listener) &&
1939 !DisableValidation)
1940 return ConfigurationMismatch;
1941 break;
1942 }
1943
1944 case PREPROCESSOR_OPTIONS: {
1945 bool Complain = (ClientLoadCapabilities & ARR_ConfigurationMismatch)==0;
1946 if (Listener && &F == *ModuleMgr.begin() &&
1947 ParsePreprocessorOptions(Record, Complain, *Listener,
1948 SuggestedPredefines) &&
1949 !DisableValidation)
1950 return ConfigurationMismatch;
1951 break;
1952 }
1953
1954 case ORIGINAL_FILE:
1955 F.OriginalSourceFileID = FileID::get(Record[0]);
Chris Lattnerb3ce3572013-01-20 02:38:54 +00001956 F.ActualOriginalSourceFileName = Blob;
Guy Benyei7f92f2d2012-12-18 14:30:41 +00001957 F.OriginalSourceFileName = F.ActualOriginalSourceFileName;
1958 MaybeAddSystemRootToFilename(F, F.OriginalSourceFileName);
1959 break;
1960
1961 case ORIGINAL_FILE_ID:
1962 F.OriginalSourceFileID = FileID::get(Record[0]);
1963 break;
1964
1965 case ORIGINAL_PCH_DIR:
Chris Lattnerb3ce3572013-01-20 02:38:54 +00001966 F.OriginalDir = Blob;
Guy Benyei7f92f2d2012-12-18 14:30:41 +00001967 break;
1968
1969 case INPUT_FILE_OFFSETS:
Chris Lattnerb3ce3572013-01-20 02:38:54 +00001970 F.InputFileOffsets = (const uint32_t *)Blob.data();
Guy Benyei7f92f2d2012-12-18 14:30:41 +00001971 F.InputFilesLoaded.resize(Record[0]);
1972 break;
1973 }
1974 }
Guy Benyei7f92f2d2012-12-18 14:30:41 +00001975}
1976
1977bool ASTReader::ReadASTBlock(ModuleFile &F) {
Chris Lattner8f9a1eb2013-01-20 00:56:42 +00001978 BitstreamCursor &Stream = F.Stream;
Guy Benyei7f92f2d2012-12-18 14:30:41 +00001979
1980 if (Stream.EnterSubBlock(AST_BLOCK_ID)) {
1981 Error("malformed block record in AST file");
1982 return true;
1983 }
1984
1985 // Read all of the records and blocks for the AST file.
1986 RecordData Record;
Chris Lattner88bde502013-01-19 21:39:22 +00001987 while (1) {
1988 llvm::BitstreamEntry Entry = Stream.advance();
1989
1990 switch (Entry.Kind) {
1991 case llvm::BitstreamEntry::Error:
1992 Error("error at end of module block in AST file");
1993 return true;
1994 case llvm::BitstreamEntry::EndBlock: {
Richard Smith43828672013-04-03 22:49:41 +00001995 // Outside of C++, we do not store a lookup map for the translation unit.
1996 // Instead, mark it as needing a lookup map to be built if this module
1997 // contains any declarations lexically within it (which it always does!).
1998 // This usually has no cost, since we very rarely need the lookup map for
1999 // the translation unit outside C++.
Guy Benyei7f92f2d2012-12-18 14:30:41 +00002000 DeclContext *DC = Context.getTranslationUnitDecl();
Richard Smith43828672013-04-03 22:49:41 +00002001 if (DC->hasExternalLexicalStorage() &&
2002 !getContext().getLangOpts().CPlusPlus)
Guy Benyei7f92f2d2012-12-18 14:30:41 +00002003 DC->setMustBuildLookupTable();
Chris Lattner88bde502013-01-19 21:39:22 +00002004
Guy Benyei7f92f2d2012-12-18 14:30:41 +00002005 return false;
2006 }
Chris Lattner88bde502013-01-19 21:39:22 +00002007 case llvm::BitstreamEntry::SubBlock:
2008 switch (Entry.ID) {
Guy Benyei7f92f2d2012-12-18 14:30:41 +00002009 case DECLTYPES_BLOCK_ID:
2010 // We lazily load the decls block, but we want to set up the
2011 // DeclsCursor cursor to point into it. Clone our current bitcode
2012 // cursor to it, enter the block and read the abbrevs in that block.
2013 // With the main cursor, we just skip over it.
2014 F.DeclsCursor = Stream;
2015 if (Stream.SkipBlock() || // Skip with the main cursor.
2016 // Read the abbrevs.
2017 ReadBlockAbbrevs(F.DeclsCursor, DECLTYPES_BLOCK_ID)) {
2018 Error("malformed block record in AST file");
2019 return true;
2020 }
2021 break;
Chris Lattner88bde502013-01-19 21:39:22 +00002022
Guy Benyei7f92f2d2012-12-18 14:30:41 +00002023 case DECL_UPDATES_BLOCK_ID:
2024 if (Stream.SkipBlock()) {
2025 Error("malformed block record in AST file");
2026 return true;
2027 }
2028 break;
Chris Lattner88bde502013-01-19 21:39:22 +00002029
Guy Benyei7f92f2d2012-12-18 14:30:41 +00002030 case PREPROCESSOR_BLOCK_ID:
2031 F.MacroCursor = Stream;
2032 if (!PP.getExternalSource())
2033 PP.setExternalSource(this);
Chris Lattner88bde502013-01-19 21:39:22 +00002034
Guy Benyei7f92f2d2012-12-18 14:30:41 +00002035 if (Stream.SkipBlock() ||
2036 ReadBlockAbbrevs(F.MacroCursor, PREPROCESSOR_BLOCK_ID)) {
2037 Error("malformed block record in AST file");
2038 return true;
2039 }
2040 F.MacroStartOffset = F.MacroCursor.GetCurrentBitNo();
2041 break;
Chris Lattner88bde502013-01-19 21:39:22 +00002042
Guy Benyei7f92f2d2012-12-18 14:30:41 +00002043 case PREPROCESSOR_DETAIL_BLOCK_ID:
2044 F.PreprocessorDetailCursor = Stream;
2045 if (Stream.SkipBlock() ||
Chris Lattner88bde502013-01-19 21:39:22 +00002046 ReadBlockAbbrevs(F.PreprocessorDetailCursor,
Guy Benyei7f92f2d2012-12-18 14:30:41 +00002047 PREPROCESSOR_DETAIL_BLOCK_ID)) {
Chris Lattner88bde502013-01-19 21:39:22 +00002048 Error("malformed preprocessor detail record in AST file");
2049 return true;
2050 }
Guy Benyei7f92f2d2012-12-18 14:30:41 +00002051 F.PreprocessorDetailStartOffset
Chris Lattner88bde502013-01-19 21:39:22 +00002052 = F.PreprocessorDetailCursor.GetCurrentBitNo();
2053
Guy Benyei7f92f2d2012-12-18 14:30:41 +00002054 if (!PP.getPreprocessingRecord())
2055 PP.createPreprocessingRecord();
2056 if (!PP.getPreprocessingRecord()->getExternalSource())
2057 PP.getPreprocessingRecord()->SetExternalSource(*this);
2058 break;
2059
2060 case SOURCE_MANAGER_BLOCK_ID:
2061 if (ReadSourceManagerBlock(F))
2062 return true;
2063 break;
Chris Lattner88bde502013-01-19 21:39:22 +00002064
Guy Benyei7f92f2d2012-12-18 14:30:41 +00002065 case SUBMODULE_BLOCK_ID:
2066 if (ReadSubmoduleBlock(F))
2067 return true;
2068 break;
Chris Lattner88bde502013-01-19 21:39:22 +00002069
Guy Benyei7f92f2d2012-12-18 14:30:41 +00002070 case COMMENTS_BLOCK_ID: {
Chris Lattner8f9a1eb2013-01-20 00:56:42 +00002071 BitstreamCursor C = Stream;
Guy Benyei7f92f2d2012-12-18 14:30:41 +00002072 if (Stream.SkipBlock() ||
2073 ReadBlockAbbrevs(C, COMMENTS_BLOCK_ID)) {
2074 Error("malformed comments block in AST file");
2075 return true;
2076 }
2077 CommentsCursors.push_back(std::make_pair(C, &F));
2078 break;
2079 }
Chris Lattner88bde502013-01-19 21:39:22 +00002080
Guy Benyei7f92f2d2012-12-18 14:30:41 +00002081 default:
Chris Lattner88bde502013-01-19 21:39:22 +00002082 if (Stream.SkipBlock()) {
2083 Error("malformed block record in AST file");
2084 return true;
2085 }
2086 break;
Guy Benyei7f92f2d2012-12-18 14:30:41 +00002087 }
2088 continue;
Chris Lattner88bde502013-01-19 21:39:22 +00002089
2090 case llvm::BitstreamEntry::Record:
2091 // The interesting case.
2092 break;
Guy Benyei7f92f2d2012-12-18 14:30:41 +00002093 }
2094
2095 // Read and process a record.
2096 Record.clear();
Chris Lattnerb3ce3572013-01-20 02:38:54 +00002097 StringRef Blob;
2098 switch ((ASTRecordTypes)Stream.readRecord(Entry.ID, Record, &Blob)) {
Guy Benyei7f92f2d2012-12-18 14:30:41 +00002099 default: // Default behavior: ignore.
2100 break;
2101
2102 case TYPE_OFFSET: {
2103 if (F.LocalNumTypes != 0) {
2104 Error("duplicate TYPE_OFFSET record in AST file");
2105 return true;
2106 }
Chris Lattnerb3ce3572013-01-20 02:38:54 +00002107 F.TypeOffsets = (const uint32_t *)Blob.data();
Guy Benyei7f92f2d2012-12-18 14:30:41 +00002108 F.LocalNumTypes = Record[0];
2109 unsigned LocalBaseTypeIndex = Record[1];
2110 F.BaseTypeIndex = getTotalNumTypes();
2111
2112 if (F.LocalNumTypes > 0) {
2113 // Introduce the global -> local mapping for types within this module.
2114 GlobalTypeMap.insert(std::make_pair(getTotalNumTypes(), &F));
2115
2116 // Introduce the local -> global mapping for types within this module.
2117 F.TypeRemap.insertOrReplace(
2118 std::make_pair(LocalBaseTypeIndex,
2119 F.BaseTypeIndex - LocalBaseTypeIndex));
2120
2121 TypesLoaded.resize(TypesLoaded.size() + F.LocalNumTypes);
2122 }
2123 break;
2124 }
2125
2126 case DECL_OFFSET: {
2127 if (F.LocalNumDecls != 0) {
2128 Error("duplicate DECL_OFFSET record in AST file");
2129 return true;
2130 }
Chris Lattnerb3ce3572013-01-20 02:38:54 +00002131 F.DeclOffsets = (const DeclOffset *)Blob.data();
Guy Benyei7f92f2d2012-12-18 14:30:41 +00002132 F.LocalNumDecls = Record[0];
2133 unsigned LocalBaseDeclID = Record[1];
2134 F.BaseDeclID = getTotalNumDecls();
2135
2136 if (F.LocalNumDecls > 0) {
2137 // Introduce the global -> local mapping for declarations within this
2138 // module.
2139 GlobalDeclMap.insert(
2140 std::make_pair(getTotalNumDecls() + NUM_PREDEF_DECL_IDS, &F));
2141
2142 // Introduce the local -> global mapping for declarations within this
2143 // module.
2144 F.DeclRemap.insertOrReplace(
2145 std::make_pair(LocalBaseDeclID, F.BaseDeclID - LocalBaseDeclID));
2146
2147 // Introduce the global -> local mapping for declarations within this
2148 // module.
2149 F.GlobalToLocalDeclIDs[&F] = LocalBaseDeclID;
2150
2151 DeclsLoaded.resize(DeclsLoaded.size() + F.LocalNumDecls);
2152 }
2153 break;
2154 }
2155
2156 case TU_UPDATE_LEXICAL: {
2157 DeclContext *TU = Context.getTranslationUnitDecl();
2158 DeclContextInfo &Info = F.DeclContextInfos[TU];
Chris Lattnerb3ce3572013-01-20 02:38:54 +00002159 Info.LexicalDecls = reinterpret_cast<const KindDeclIDPair *>(Blob.data());
Guy Benyei7f92f2d2012-12-18 14:30:41 +00002160 Info.NumLexicalDecls
Chris Lattnerb3ce3572013-01-20 02:38:54 +00002161 = static_cast<unsigned int>(Blob.size() / sizeof(KindDeclIDPair));
Guy Benyei7f92f2d2012-12-18 14:30:41 +00002162 TU->setHasExternalLexicalStorage(true);
2163 break;
2164 }
2165
2166 case UPDATE_VISIBLE: {
2167 unsigned Idx = 0;
2168 serialization::DeclID ID = ReadDeclID(F, Record, Idx);
2169 ASTDeclContextNameLookupTable *Table =
2170 ASTDeclContextNameLookupTable::Create(
Chris Lattnerb3ce3572013-01-20 02:38:54 +00002171 (const unsigned char *)Blob.data() + Record[Idx++],
2172 (const unsigned char *)Blob.data(),
Guy Benyei7f92f2d2012-12-18 14:30:41 +00002173 ASTDeclContextNameLookupTrait(*this, F));
2174 if (ID == PREDEF_DECL_TRANSLATION_UNIT_ID) { // Is it the TU?
2175 DeclContext *TU = Context.getTranslationUnitDecl();
2176 F.DeclContextInfos[TU].NameLookupTableData = Table;
2177 TU->setHasExternalVisibleStorage(true);
2178 } else
2179 PendingVisibleUpdates[ID].push_back(std::make_pair(Table, &F));
2180 break;
2181 }
2182
2183 case IDENTIFIER_TABLE:
Chris Lattnerb3ce3572013-01-20 02:38:54 +00002184 F.IdentifierTableData = Blob.data();
Guy Benyei7f92f2d2012-12-18 14:30:41 +00002185 if (Record[0]) {
2186 F.IdentifierLookupTable
2187 = ASTIdentifierLookupTable::Create(
2188 (const unsigned char *)F.IdentifierTableData + Record[0],
2189 (const unsigned char *)F.IdentifierTableData,
2190 ASTIdentifierLookupTrait(*this, F));
2191
2192 PP.getIdentifierTable().setExternalIdentifierLookup(this);
2193 }
2194 break;
2195
2196 case IDENTIFIER_OFFSET: {
2197 if (F.LocalNumIdentifiers != 0) {
2198 Error("duplicate IDENTIFIER_OFFSET record in AST file");
2199 return true;
2200 }
Chris Lattnerb3ce3572013-01-20 02:38:54 +00002201 F.IdentifierOffsets = (const uint32_t *)Blob.data();
Guy Benyei7f92f2d2012-12-18 14:30:41 +00002202 F.LocalNumIdentifiers = Record[0];
2203 unsigned LocalBaseIdentifierID = Record[1];
2204 F.BaseIdentifierID = getTotalNumIdentifiers();
2205
2206 if (F.LocalNumIdentifiers > 0) {
2207 // Introduce the global -> local mapping for identifiers within this
2208 // module.
2209 GlobalIdentifierMap.insert(std::make_pair(getTotalNumIdentifiers() + 1,
2210 &F));
2211
2212 // Introduce the local -> global mapping for identifiers within this
2213 // module.
2214 F.IdentifierRemap.insertOrReplace(
2215 std::make_pair(LocalBaseIdentifierID,
2216 F.BaseIdentifierID - LocalBaseIdentifierID));
2217
2218 IdentifiersLoaded.resize(IdentifiersLoaded.size()
2219 + F.LocalNumIdentifiers);
2220 }
2221 break;
2222 }
2223
2224 case EXTERNAL_DEFINITIONS:
2225 for (unsigned I = 0, N = Record.size(); I != N; ++I)
2226 ExternalDefinitions.push_back(getGlobalDeclID(F, Record[I]));
2227 break;
2228
2229 case SPECIAL_TYPES:
Douglas Gregorf5cfc892013-02-01 23:45:03 +00002230 if (SpecialTypes.empty()) {
2231 for (unsigned I = 0, N = Record.size(); I != N; ++I)
2232 SpecialTypes.push_back(getGlobalTypeID(F, Record[I]));
2233 break;
2234 }
2235
2236 if (SpecialTypes.size() != Record.size()) {
2237 Error("invalid special-types record");
2238 return true;
2239 }
2240
2241 for (unsigned I = 0, N = Record.size(); I != N; ++I) {
2242 serialization::TypeID ID = getGlobalTypeID(F, Record[I]);
2243 if (!SpecialTypes[I])
2244 SpecialTypes[I] = ID;
2245 // FIXME: If ID && SpecialTypes[I] != ID, do we need a separate
2246 // merge step?
2247 }
Guy Benyei7f92f2d2012-12-18 14:30:41 +00002248 break;
2249
2250 case STATISTICS:
2251 TotalNumStatements += Record[0];
2252 TotalNumMacros += Record[1];
2253 TotalLexicalDeclContexts += Record[2];
2254 TotalVisibleDeclContexts += Record[3];
2255 break;
2256
2257 case UNUSED_FILESCOPED_DECLS:
2258 for (unsigned I = 0, N = Record.size(); I != N; ++I)
2259 UnusedFileScopedDecls.push_back(getGlobalDeclID(F, Record[I]));
2260 break;
2261
2262 case DELEGATING_CTORS:
2263 for (unsigned I = 0, N = Record.size(); I != N; ++I)
2264 DelegatingCtorDecls.push_back(getGlobalDeclID(F, Record[I]));
2265 break;
2266
2267 case WEAK_UNDECLARED_IDENTIFIERS:
2268 if (Record.size() % 4 != 0) {
2269 Error("invalid weak identifiers record");
2270 return true;
2271 }
2272
2273 // FIXME: Ignore weak undeclared identifiers from non-original PCH
2274 // files. This isn't the way to do it :)
2275 WeakUndeclaredIdentifiers.clear();
2276
2277 // Translate the weak, undeclared identifiers into global IDs.
2278 for (unsigned I = 0, N = Record.size(); I < N; /* in loop */) {
2279 WeakUndeclaredIdentifiers.push_back(
2280 getGlobalIdentifierID(F, Record[I++]));
2281 WeakUndeclaredIdentifiers.push_back(
2282 getGlobalIdentifierID(F, Record[I++]));
2283 WeakUndeclaredIdentifiers.push_back(
2284 ReadSourceLocation(F, Record, I).getRawEncoding());
2285 WeakUndeclaredIdentifiers.push_back(Record[I++]);
2286 }
2287 break;
2288
Richard Smith5ea6ef42013-01-10 23:43:47 +00002289 case LOCALLY_SCOPED_EXTERN_C_DECLS:
Guy Benyei7f92f2d2012-12-18 14:30:41 +00002290 for (unsigned I = 0, N = Record.size(); I != N; ++I)
Richard Smith5ea6ef42013-01-10 23:43:47 +00002291 LocallyScopedExternCDecls.push_back(getGlobalDeclID(F, Record[I]));
Guy Benyei7f92f2d2012-12-18 14:30:41 +00002292 break;
2293
2294 case SELECTOR_OFFSETS: {
Chris Lattnerb3ce3572013-01-20 02:38:54 +00002295 F.SelectorOffsets = (const uint32_t *)Blob.data();
Guy Benyei7f92f2d2012-12-18 14:30:41 +00002296 F.LocalNumSelectors = Record[0];
2297 unsigned LocalBaseSelectorID = Record[1];
2298 F.BaseSelectorID = getTotalNumSelectors();
2299
2300 if (F.LocalNumSelectors > 0) {
2301 // Introduce the global -> local mapping for selectors within this
2302 // module.
2303 GlobalSelectorMap.insert(std::make_pair(getTotalNumSelectors()+1, &F));
2304
2305 // Introduce the local -> global mapping for selectors within this
2306 // module.
2307 F.SelectorRemap.insertOrReplace(
2308 std::make_pair(LocalBaseSelectorID,
2309 F.BaseSelectorID - LocalBaseSelectorID));
2310
2311 SelectorsLoaded.resize(SelectorsLoaded.size() + F.LocalNumSelectors);
2312 }
2313 break;
2314 }
2315
2316 case METHOD_POOL:
Chris Lattnerb3ce3572013-01-20 02:38:54 +00002317 F.SelectorLookupTableData = (const unsigned char *)Blob.data();
Guy Benyei7f92f2d2012-12-18 14:30:41 +00002318 if (Record[0])
2319 F.SelectorLookupTable
2320 = ASTSelectorLookupTable::Create(
2321 F.SelectorLookupTableData + Record[0],
2322 F.SelectorLookupTableData,
2323 ASTSelectorLookupTrait(*this, F));
2324 TotalNumMethodPoolEntries += Record[1];
2325 break;
2326
2327 case REFERENCED_SELECTOR_POOL:
2328 if (!Record.empty()) {
2329 for (unsigned Idx = 0, N = Record.size() - 1; Idx < N; /* in loop */) {
2330 ReferencedSelectorsData.push_back(getGlobalSelectorID(F,
2331 Record[Idx++]));
2332 ReferencedSelectorsData.push_back(ReadSourceLocation(F, Record, Idx).
2333 getRawEncoding());
2334 }
2335 }
2336 break;
2337
2338 case PP_COUNTER_VALUE:
2339 if (!Record.empty() && Listener)
2340 Listener->ReadCounter(F, Record[0]);
2341 break;
2342
2343 case FILE_SORTED_DECLS:
Chris Lattnerb3ce3572013-01-20 02:38:54 +00002344 F.FileSortedDecls = (const DeclID *)Blob.data();
Guy Benyei7f92f2d2012-12-18 14:30:41 +00002345 F.NumFileSortedDecls = Record[0];
2346 break;
2347
2348 case SOURCE_LOCATION_OFFSETS: {
Chris Lattnerb3ce3572013-01-20 02:38:54 +00002349 F.SLocEntryOffsets = (const uint32_t *)Blob.data();
Guy Benyei7f92f2d2012-12-18 14:30:41 +00002350 F.LocalNumSLocEntries = Record[0];
2351 unsigned SLocSpaceSize = Record[1];
2352 llvm::tie(F.SLocEntryBaseID, F.SLocEntryBaseOffset) =
2353 SourceMgr.AllocateLoadedSLocEntries(F.LocalNumSLocEntries,
2354 SLocSpaceSize);
2355 // Make our entry in the range map. BaseID is negative and growing, so
2356 // we invert it. Because we invert it, though, we need the other end of
2357 // the range.
2358 unsigned RangeStart =
2359 unsigned(-F.SLocEntryBaseID) - F.LocalNumSLocEntries + 1;
2360 GlobalSLocEntryMap.insert(std::make_pair(RangeStart, &F));
2361 F.FirstLoc = SourceLocation::getFromRawEncoding(F.SLocEntryBaseOffset);
2362
2363 // SLocEntryBaseOffset is lower than MaxLoadedOffset and decreasing.
2364 assert((F.SLocEntryBaseOffset & (1U << 31U)) == 0);
2365 GlobalSLocOffsetMap.insert(
2366 std::make_pair(SourceManager::MaxLoadedOffset - F.SLocEntryBaseOffset
2367 - SLocSpaceSize,&F));
2368
2369 // Initialize the remapping table.
2370 // Invalid stays invalid.
2371 F.SLocRemap.insert(std::make_pair(0U, 0));
2372 // This module. Base was 2 when being compiled.
2373 F.SLocRemap.insert(std::make_pair(2U,
2374 static_cast<int>(F.SLocEntryBaseOffset - 2)));
2375
2376 TotalNumSLocEntries += F.LocalNumSLocEntries;
2377 break;
2378 }
2379
2380 case MODULE_OFFSET_MAP: {
2381 // Additional remapping information.
Chris Lattnerb3ce3572013-01-20 02:38:54 +00002382 const unsigned char *Data = (const unsigned char*)Blob.data();
2383 const unsigned char *DataEnd = Data + Blob.size();
Guy Benyei7f92f2d2012-12-18 14:30:41 +00002384
2385 // Continuous range maps we may be updating in our module.
2386 ContinuousRangeMap<uint32_t, int, 2>::Builder SLocRemap(F.SLocRemap);
2387 ContinuousRangeMap<uint32_t, int, 2>::Builder
2388 IdentifierRemap(F.IdentifierRemap);
2389 ContinuousRangeMap<uint32_t, int, 2>::Builder
2390 MacroRemap(F.MacroRemap);
2391 ContinuousRangeMap<uint32_t, int, 2>::Builder
2392 PreprocessedEntityRemap(F.PreprocessedEntityRemap);
2393 ContinuousRangeMap<uint32_t, int, 2>::Builder
2394 SubmoduleRemap(F.SubmoduleRemap);
2395 ContinuousRangeMap<uint32_t, int, 2>::Builder
2396 SelectorRemap(F.SelectorRemap);
2397 ContinuousRangeMap<uint32_t, int, 2>::Builder DeclRemap(F.DeclRemap);
2398 ContinuousRangeMap<uint32_t, int, 2>::Builder TypeRemap(F.TypeRemap);
2399
2400 while(Data < DataEnd) {
2401 uint16_t Len = io::ReadUnalignedLE16(Data);
2402 StringRef Name = StringRef((const char*)Data, Len);
2403 Data += Len;
2404 ModuleFile *OM = ModuleMgr.lookup(Name);
2405 if (!OM) {
2406 Error("SourceLocation remap refers to unknown module");
2407 return true;
2408 }
2409
2410 uint32_t SLocOffset = io::ReadUnalignedLE32(Data);
2411 uint32_t IdentifierIDOffset = io::ReadUnalignedLE32(Data);
2412 uint32_t MacroIDOffset = io::ReadUnalignedLE32(Data);
2413 uint32_t PreprocessedEntityIDOffset = io::ReadUnalignedLE32(Data);
2414 uint32_t SubmoduleIDOffset = io::ReadUnalignedLE32(Data);
2415 uint32_t SelectorIDOffset = io::ReadUnalignedLE32(Data);
2416 uint32_t DeclIDOffset = io::ReadUnalignedLE32(Data);
2417 uint32_t TypeIndexOffset = io::ReadUnalignedLE32(Data);
2418
2419 // Source location offset is mapped to OM->SLocEntryBaseOffset.
2420 SLocRemap.insert(std::make_pair(SLocOffset,
2421 static_cast<int>(OM->SLocEntryBaseOffset - SLocOffset)));
2422 IdentifierRemap.insert(
2423 std::make_pair(IdentifierIDOffset,
2424 OM->BaseIdentifierID - IdentifierIDOffset));
2425 MacroRemap.insert(std::make_pair(MacroIDOffset,
2426 OM->BaseMacroID - MacroIDOffset));
2427 PreprocessedEntityRemap.insert(
2428 std::make_pair(PreprocessedEntityIDOffset,
2429 OM->BasePreprocessedEntityID - PreprocessedEntityIDOffset));
2430 SubmoduleRemap.insert(std::make_pair(SubmoduleIDOffset,
2431 OM->BaseSubmoduleID - SubmoduleIDOffset));
2432 SelectorRemap.insert(std::make_pair(SelectorIDOffset,
2433 OM->BaseSelectorID - SelectorIDOffset));
2434 DeclRemap.insert(std::make_pair(DeclIDOffset,
2435 OM->BaseDeclID - DeclIDOffset));
2436
2437 TypeRemap.insert(std::make_pair(TypeIndexOffset,
2438 OM->BaseTypeIndex - TypeIndexOffset));
2439
2440 // Global -> local mappings.
2441 F.GlobalToLocalDeclIDs[OM] = DeclIDOffset;
2442 }
2443 break;
2444 }
2445
2446 case SOURCE_MANAGER_LINE_TABLE:
2447 if (ParseLineTable(F, Record))
2448 return true;
2449 break;
2450
2451 case SOURCE_LOCATION_PRELOADS: {
2452 // Need to transform from the local view (1-based IDs) to the global view,
2453 // which is based off F.SLocEntryBaseID.
2454 if (!F.PreloadSLocEntries.empty()) {
2455 Error("Multiple SOURCE_LOCATION_PRELOADS records in AST file");
2456 return true;
2457 }
2458
2459 F.PreloadSLocEntries.swap(Record);
2460 break;
2461 }
2462
2463 case EXT_VECTOR_DECLS:
2464 for (unsigned I = 0, N = Record.size(); I != N; ++I)
2465 ExtVectorDecls.push_back(getGlobalDeclID(F, Record[I]));
2466 break;
2467
2468 case VTABLE_USES:
2469 if (Record.size() % 3 != 0) {
2470 Error("Invalid VTABLE_USES record");
2471 return true;
2472 }
2473
2474 // Later tables overwrite earlier ones.
2475 // FIXME: Modules will have some trouble with this. This is clearly not
2476 // the right way to do this.
2477 VTableUses.clear();
2478
2479 for (unsigned Idx = 0, N = Record.size(); Idx != N; /* In loop */) {
2480 VTableUses.push_back(getGlobalDeclID(F, Record[Idx++]));
2481 VTableUses.push_back(
2482 ReadSourceLocation(F, Record, Idx).getRawEncoding());
2483 VTableUses.push_back(Record[Idx++]);
2484 }
2485 break;
2486
2487 case DYNAMIC_CLASSES:
2488 for (unsigned I = 0, N = Record.size(); I != N; ++I)
2489 DynamicClasses.push_back(getGlobalDeclID(F, Record[I]));
2490 break;
2491
2492 case PENDING_IMPLICIT_INSTANTIATIONS:
2493 if (PendingInstantiations.size() % 2 != 0) {
2494 Error("Invalid existing PendingInstantiations");
2495 return true;
2496 }
2497
2498 if (Record.size() % 2 != 0) {
2499 Error("Invalid PENDING_IMPLICIT_INSTANTIATIONS block");
2500 return true;
2501 }
2502
2503 for (unsigned I = 0, N = Record.size(); I != N; /* in loop */) {
2504 PendingInstantiations.push_back(getGlobalDeclID(F, Record[I++]));
2505 PendingInstantiations.push_back(
2506 ReadSourceLocation(F, Record, I).getRawEncoding());
2507 }
2508 break;
2509
2510 case SEMA_DECL_REFS:
2511 // Later tables overwrite earlier ones.
2512 // FIXME: Modules will have some trouble with this.
2513 SemaDeclRefs.clear();
2514 for (unsigned I = 0, N = Record.size(); I != N; ++I)
2515 SemaDeclRefs.push_back(getGlobalDeclID(F, Record[I]));
2516 break;
2517
2518 case PPD_ENTITIES_OFFSETS: {
Chris Lattnerb3ce3572013-01-20 02:38:54 +00002519 F.PreprocessedEntityOffsets = (const PPEntityOffset *)Blob.data();
2520 assert(Blob.size() % sizeof(PPEntityOffset) == 0);
2521 F.NumPreprocessedEntities = Blob.size() / sizeof(PPEntityOffset);
Guy Benyei7f92f2d2012-12-18 14:30:41 +00002522
2523 unsigned LocalBasePreprocessedEntityID = Record[0];
2524
2525 unsigned StartingID;
2526 if (!PP.getPreprocessingRecord())
2527 PP.createPreprocessingRecord();
2528 if (!PP.getPreprocessingRecord()->getExternalSource())
2529 PP.getPreprocessingRecord()->SetExternalSource(*this);
2530 StartingID
2531 = PP.getPreprocessingRecord()
2532 ->allocateLoadedEntities(F.NumPreprocessedEntities);
2533 F.BasePreprocessedEntityID = StartingID;
2534
2535 if (F.NumPreprocessedEntities > 0) {
2536 // Introduce the global -> local mapping for preprocessed entities in
2537 // this module.
2538 GlobalPreprocessedEntityMap.insert(std::make_pair(StartingID, &F));
2539
2540 // Introduce the local -> global mapping for preprocessed entities in
2541 // this module.
2542 F.PreprocessedEntityRemap.insertOrReplace(
2543 std::make_pair(LocalBasePreprocessedEntityID,
2544 F.BasePreprocessedEntityID - LocalBasePreprocessedEntityID));
2545 }
2546
2547 break;
2548 }
2549
2550 case DECL_UPDATE_OFFSETS: {
2551 if (Record.size() % 2 != 0) {
2552 Error("invalid DECL_UPDATE_OFFSETS block in AST file");
2553 return true;
2554 }
2555 for (unsigned I = 0, N = Record.size(); I != N; I += 2)
2556 DeclUpdateOffsets[getGlobalDeclID(F, Record[I])]
2557 .push_back(std::make_pair(&F, Record[I+1]));
2558 break;
2559 }
2560
2561 case DECL_REPLACEMENTS: {
2562 if (Record.size() % 3 != 0) {
2563 Error("invalid DECL_REPLACEMENTS block in AST file");
2564 return true;
2565 }
2566 for (unsigned I = 0, N = Record.size(); I != N; I += 3)
2567 ReplacedDecls[getGlobalDeclID(F, Record[I])]
2568 = ReplacedDeclInfo(&F, Record[I+1], Record[I+2]);
2569 break;
2570 }
2571
2572 case OBJC_CATEGORIES_MAP: {
2573 if (F.LocalNumObjCCategoriesInMap != 0) {
2574 Error("duplicate OBJC_CATEGORIES_MAP record in AST file");
2575 return true;
2576 }
2577
2578 F.LocalNumObjCCategoriesInMap = Record[0];
Chris Lattnerb3ce3572013-01-20 02:38:54 +00002579 F.ObjCCategoriesMap = (const ObjCCategoriesInfo *)Blob.data();
Guy Benyei7f92f2d2012-12-18 14:30:41 +00002580 break;
2581 }
2582
2583 case OBJC_CATEGORIES:
2584 F.ObjCCategories.swap(Record);
2585 break;
2586
2587 case CXX_BASE_SPECIFIER_OFFSETS: {
2588 if (F.LocalNumCXXBaseSpecifiers != 0) {
2589 Error("duplicate CXX_BASE_SPECIFIER_OFFSETS record in AST file");
2590 return true;
2591 }
2592
2593 F.LocalNumCXXBaseSpecifiers = Record[0];
Chris Lattnerb3ce3572013-01-20 02:38:54 +00002594 F.CXXBaseSpecifiersOffsets = (const uint32_t *)Blob.data();
Guy Benyei7f92f2d2012-12-18 14:30:41 +00002595 NumCXXBaseSpecifiersLoaded += F.LocalNumCXXBaseSpecifiers;
2596 break;
2597 }
2598
2599 case DIAG_PRAGMA_MAPPINGS:
2600 if (F.PragmaDiagMappings.empty())
2601 F.PragmaDiagMappings.swap(Record);
2602 else
2603 F.PragmaDiagMappings.insert(F.PragmaDiagMappings.end(),
2604 Record.begin(), Record.end());
2605 break;
2606
2607 case CUDA_SPECIAL_DECL_REFS:
2608 // Later tables overwrite earlier ones.
2609 // FIXME: Modules will have trouble with this.
2610 CUDASpecialDeclRefs.clear();
2611 for (unsigned I = 0, N = Record.size(); I != N; ++I)
2612 CUDASpecialDeclRefs.push_back(getGlobalDeclID(F, Record[I]));
2613 break;
2614
2615 case HEADER_SEARCH_TABLE: {
Chris Lattnerb3ce3572013-01-20 02:38:54 +00002616 F.HeaderFileInfoTableData = Blob.data();
Guy Benyei7f92f2d2012-12-18 14:30:41 +00002617 F.LocalNumHeaderFileInfos = Record[1];
Guy Benyei7f92f2d2012-12-18 14:30:41 +00002618 if (Record[0]) {
2619 F.HeaderFileInfoTable
2620 = HeaderFileInfoLookupTable::Create(
2621 (const unsigned char *)F.HeaderFileInfoTableData + Record[0],
2622 (const unsigned char *)F.HeaderFileInfoTableData,
2623 HeaderFileInfoTrait(*this, F,
2624 &PP.getHeaderSearchInfo(),
Chris Lattnerb3ce3572013-01-20 02:38:54 +00002625 Blob.data() + Record[2]));
Guy Benyei7f92f2d2012-12-18 14:30:41 +00002626
2627 PP.getHeaderSearchInfo().SetExternalSource(this);
2628 if (!PP.getHeaderSearchInfo().getExternalLookup())
2629 PP.getHeaderSearchInfo().SetExternalLookup(this);
2630 }
2631 break;
2632 }
2633
2634 case FP_PRAGMA_OPTIONS:
2635 // Later tables overwrite earlier ones.
2636 FPPragmaOptions.swap(Record);
2637 break;
2638
2639 case OPENCL_EXTENSIONS:
2640 // Later tables overwrite earlier ones.
2641 OpenCLExtensions.swap(Record);
2642 break;
2643
2644 case TENTATIVE_DEFINITIONS:
2645 for (unsigned I = 0, N = Record.size(); I != N; ++I)
2646 TentativeDefinitions.push_back(getGlobalDeclID(F, Record[I]));
2647 break;
2648
2649 case KNOWN_NAMESPACES:
2650 for (unsigned I = 0, N = Record.size(); I != N; ++I)
2651 KnownNamespaces.push_back(getGlobalDeclID(F, Record[I]));
2652 break;
Nick Lewycky01a41142013-01-26 00:35:08 +00002653
Nick Lewyckycd0655b2013-02-01 08:13:20 +00002654 case UNDEFINED_BUT_USED:
2655 if (UndefinedButUsed.size() % 2 != 0) {
2656 Error("Invalid existing UndefinedButUsed");
Nick Lewycky01a41142013-01-26 00:35:08 +00002657 return true;
2658 }
2659
2660 if (Record.size() % 2 != 0) {
Nick Lewyckycd0655b2013-02-01 08:13:20 +00002661 Error("invalid undefined-but-used record");
Nick Lewycky01a41142013-01-26 00:35:08 +00002662 return true;
2663 }
2664 for (unsigned I = 0, N = Record.size(); I != N; /* in loop */) {
Nick Lewyckycd0655b2013-02-01 08:13:20 +00002665 UndefinedButUsed.push_back(getGlobalDeclID(F, Record[I++]));
2666 UndefinedButUsed.push_back(
Nick Lewycky01a41142013-01-26 00:35:08 +00002667 ReadSourceLocation(F, Record, I).getRawEncoding());
2668 }
2669 break;
2670
Guy Benyei7f92f2d2012-12-18 14:30:41 +00002671 case IMPORTED_MODULES: {
2672 if (F.Kind != MK_Module) {
2673 // If we aren't loading a module (which has its own exports), make
2674 // all of the imported modules visible.
2675 // FIXME: Deal with macros-only imports.
2676 for (unsigned I = 0, N = Record.size(); I != N; ++I) {
2677 if (unsigned GlobalID = getGlobalSubmoduleID(F, Record[I]))
2678 ImportedModules.push_back(GlobalID);
2679 }
2680 }
2681 break;
2682 }
2683
2684 case LOCAL_REDECLARATIONS: {
2685 F.RedeclarationChains.swap(Record);
2686 break;
2687 }
2688
2689 case LOCAL_REDECLARATIONS_MAP: {
2690 if (F.LocalNumRedeclarationsInMap != 0) {
2691 Error("duplicate LOCAL_REDECLARATIONS_MAP record in AST file");
2692 return true;
2693 }
2694
2695 F.LocalNumRedeclarationsInMap = Record[0];
Chris Lattnerb3ce3572013-01-20 02:38:54 +00002696 F.RedeclarationsMap = (const LocalRedeclarationsInfo *)Blob.data();
Guy Benyei7f92f2d2012-12-18 14:30:41 +00002697 break;
2698 }
2699
2700 case MERGED_DECLARATIONS: {
2701 for (unsigned Idx = 0; Idx < Record.size(); /* increment in loop */) {
2702 GlobalDeclID CanonID = getGlobalDeclID(F, Record[Idx++]);
2703 SmallVectorImpl<GlobalDeclID> &Decls = StoredMergedDecls[CanonID];
2704 for (unsigned N = Record[Idx++]; N > 0; --N)
2705 Decls.push_back(getGlobalDeclID(F, Record[Idx++]));
2706 }
2707 break;
2708 }
2709
2710 case MACRO_OFFSET: {
2711 if (F.LocalNumMacros != 0) {
2712 Error("duplicate MACRO_OFFSET record in AST file");
2713 return true;
2714 }
Chris Lattnerb3ce3572013-01-20 02:38:54 +00002715 F.MacroOffsets = (const uint32_t *)Blob.data();
Guy Benyei7f92f2d2012-12-18 14:30:41 +00002716 F.LocalNumMacros = Record[0];
2717 unsigned LocalBaseMacroID = Record[1];
2718 F.BaseMacroID = getTotalNumMacros();
2719
2720 if (F.LocalNumMacros > 0) {
2721 // Introduce the global -> local mapping for macros within this module.
2722 GlobalMacroMap.insert(std::make_pair(getTotalNumMacros() + 1, &F));
2723
2724 // Introduce the local -> global mapping for macros within this module.
2725 F.MacroRemap.insertOrReplace(
2726 std::make_pair(LocalBaseMacroID,
2727 F.BaseMacroID - LocalBaseMacroID));
2728
2729 MacrosLoaded.resize(MacrosLoaded.size() + F.LocalNumMacros);
2730 }
2731 break;
2732 }
2733
Argyrios Kyrtzidis9317ab92013-03-22 21:12:57 +00002734 case MACRO_TABLE: {
2735 // FIXME: Not used yet.
Guy Benyei7f92f2d2012-12-18 14:30:41 +00002736 break;
2737 }
2738 }
2739 }
Guy Benyei7f92f2d2012-12-18 14:30:41 +00002740}
2741
Douglas Gregor2cbd4272013-02-12 23:36:21 +00002742/// \brief Move the given method to the back of the global list of methods.
2743static void moveMethodToBackOfGlobalList(Sema &S, ObjCMethodDecl *Method) {
2744 // Find the entry for this selector in the method pool.
2745 Sema::GlobalMethodPool::iterator Known
2746 = S.MethodPool.find(Method->getSelector());
2747 if (Known == S.MethodPool.end())
2748 return;
2749
2750 // Retrieve the appropriate method list.
2751 ObjCMethodList &Start = Method->isInstanceMethod()? Known->second.first
2752 : Known->second.second;
2753 bool Found = false;
Argyrios Kyrtzidis2e3d8c02013-04-17 00:08:58 +00002754 for (ObjCMethodList *List = &Start; List; List = List->getNext()) {
Douglas Gregor2cbd4272013-02-12 23:36:21 +00002755 if (!Found) {
2756 if (List->Method == Method) {
2757 Found = true;
2758 } else {
2759 // Keep searching.
2760 continue;
2761 }
2762 }
2763
Argyrios Kyrtzidis2e3d8c02013-04-17 00:08:58 +00002764 if (List->getNext())
2765 List->Method = List->getNext()->Method;
Douglas Gregor2cbd4272013-02-12 23:36:21 +00002766 else
2767 List->Method = Method;
2768 }
2769}
2770
Argyrios Kyrtzidis52151fd2013-03-27 01:25:34 +00002771void ASTReader::makeNamesVisible(const HiddenNames &Names, Module *Owner) {
Guy Benyei7f92f2d2012-12-18 14:30:41 +00002772 for (unsigned I = 0, N = Names.size(); I != N; ++I) {
2773 switch (Names[I].getKind()) {
Douglas Gregor2cbd4272013-02-12 23:36:21 +00002774 case HiddenName::Declaration: {
2775 Decl *D = Names[I].getDecl();
2776 bool wasHidden = D->Hidden;
2777 D->Hidden = false;
Guy Benyei7f92f2d2012-12-18 14:30:41 +00002778
Douglas Gregor2cbd4272013-02-12 23:36:21 +00002779 if (wasHidden && SemaObj) {
2780 if (ObjCMethodDecl *Method = dyn_cast<ObjCMethodDecl>(D)) {
2781 moveMethodToBackOfGlobalList(*SemaObj, Method);
2782 }
2783 }
2784 break;
2785 }
Guy Benyei7f92f2d2012-12-18 14:30:41 +00002786 case HiddenName::MacroVisibility: {
Argyrios Kyrtzidis9818a1d2013-02-20 00:54:57 +00002787 std::pair<IdentifierInfo *, MacroDirective *> Macro = Names[I].getMacro();
Argyrios Kyrtzidis52151fd2013-03-27 01:25:34 +00002788 installImportedMacro(Macro.first, Macro.second, Owner);
Guy Benyei7f92f2d2012-12-18 14:30:41 +00002789 break;
2790 }
Guy Benyei7f92f2d2012-12-18 14:30:41 +00002791 }
2792 }
2793}
2794
2795void ASTReader::makeModuleVisible(Module *Mod,
Argyrios Kyrtzidis5ebcb202013-02-01 16:36:12 +00002796 Module::NameVisibilityKind NameVisibility,
Douglas Gregor906d66a2013-03-20 21:10:35 +00002797 SourceLocation ImportLoc,
2798 bool Complain) {
Guy Benyei7f92f2d2012-12-18 14:30:41 +00002799 llvm::SmallPtrSet<Module *, 4> Visited;
Dmitri Gribenkocfa88f82013-01-12 19:30:44 +00002800 SmallVector<Module *, 4> Stack;
Guy Benyei7f92f2d2012-12-18 14:30:41 +00002801 Stack.push_back(Mod);
2802 while (!Stack.empty()) {
2803 Mod = Stack.back();
2804 Stack.pop_back();
2805
2806 if (NameVisibility <= Mod->NameVisibility) {
2807 // This module already has this level of visibility (or greater), so
2808 // there is nothing more to do.
2809 continue;
2810 }
2811
2812 if (!Mod->isAvailable()) {
2813 // Modules that aren't available cannot be made visible.
2814 continue;
2815 }
2816
2817 // Update the module's name visibility.
2818 Mod->NameVisibility = NameVisibility;
2819
2820 // If we've already deserialized any names from this module,
2821 // mark them as visible.
2822 HiddenNamesMapType::iterator Hidden = HiddenNamesMap.find(Mod);
2823 if (Hidden != HiddenNamesMap.end()) {
Argyrios Kyrtzidis52151fd2013-03-27 01:25:34 +00002824 makeNamesVisible(Hidden->second, Hidden->first);
Guy Benyei7f92f2d2012-12-18 14:30:41 +00002825 HiddenNamesMap.erase(Hidden);
2826 }
2827
2828 // Push any non-explicit submodules onto the stack to be marked as
2829 // visible.
2830 for (Module::submodule_iterator Sub = Mod->submodule_begin(),
2831 SubEnd = Mod->submodule_end();
2832 Sub != SubEnd; ++Sub) {
2833 if (!(*Sub)->IsExplicit && Visited.insert(*Sub))
2834 Stack.push_back(*Sub);
2835 }
2836
2837 // Push any exported modules onto the stack to be marked as visible.
Argyrios Kyrtzidis21a00042013-02-19 19:34:40 +00002838 SmallVector<Module *, 16> Exports;
2839 Mod->getExportedModules(Exports);
2840 for (SmallVectorImpl<Module *>::iterator
2841 I = Exports.begin(), E = Exports.end(); I != E; ++I) {
2842 Module *Exported = *I;
2843 if (Visited.insert(Exported))
2844 Stack.push_back(Exported);
Guy Benyei7f92f2d2012-12-18 14:30:41 +00002845 }
Douglas Gregor906d66a2013-03-20 21:10:35 +00002846
2847 // Detect any conflicts.
2848 if (Complain) {
2849 assert(ImportLoc.isValid() && "Missing import location");
2850 for (unsigned I = 0, N = Mod->Conflicts.size(); I != N; ++I) {
2851 if (Mod->Conflicts[I].Other->NameVisibility >= NameVisibility) {
2852 Diag(ImportLoc, diag::warn_module_conflict)
2853 << Mod->getFullModuleName()
2854 << Mod->Conflicts[I].Other->getFullModuleName()
2855 << Mod->Conflicts[I].Message;
2856 // FIXME: Need note where the other module was imported.
2857 }
2858 }
2859 }
Guy Benyei7f92f2d2012-12-18 14:30:41 +00002860 }
2861}
2862
Douglas Gregor1a49d972013-01-25 01:03:03 +00002863bool ASTReader::loadGlobalIndex() {
2864 if (GlobalIndex)
2865 return false;
2866
2867 if (TriedLoadingGlobalIndex || !UseGlobalIndex ||
2868 !Context.getLangOpts().Modules)
2869 return true;
2870
2871 // Try to load the global index.
2872 TriedLoadingGlobalIndex = true;
2873 StringRef ModuleCachePath
2874 = getPreprocessor().getHeaderSearchInfo().getModuleCachePath();
2875 std::pair<GlobalModuleIndex *, GlobalModuleIndex::ErrorCode> Result
Douglas Gregor677e15f2013-03-19 00:28:20 +00002876 = GlobalModuleIndex::readIndex(ModuleCachePath);
Douglas Gregor1a49d972013-01-25 01:03:03 +00002877 if (!Result.first)
2878 return true;
2879
2880 GlobalIndex.reset(Result.first);
Douglas Gregor188bdcd2013-01-25 23:32:03 +00002881 ModuleMgr.setGlobalIndex(GlobalIndex.get());
Douglas Gregor1a49d972013-01-25 01:03:03 +00002882 return false;
2883}
2884
2885bool ASTReader::isGlobalIndexUnavailable() const {
2886 return Context.getLangOpts().Modules && UseGlobalIndex &&
2887 !hasGlobalIndex() && TriedLoadingGlobalIndex;
2888}
2889
Guy Benyei7f92f2d2012-12-18 14:30:41 +00002890ASTReader::ASTReadResult ASTReader::ReadAST(const std::string &FileName,
2891 ModuleKind Type,
2892 SourceLocation ImportLoc,
2893 unsigned ClientLoadCapabilities) {
2894 // Bump the generation number.
2895 unsigned PreviousGeneration = CurrentGeneration++;
2896
2897 unsigned NumModules = ModuleMgr.size();
Dmitri Gribenkocfa88f82013-01-12 19:30:44 +00002898 SmallVector<ImportedModule, 4> Loaded;
Guy Benyei7f92f2d2012-12-18 14:30:41 +00002899 switch(ASTReadResult ReadResult = ReadASTCore(FileName, Type, ImportLoc,
2900 /*ImportedBy=*/0, Loaded,
Douglas Gregor677e15f2013-03-19 00:28:20 +00002901 0, 0,
Guy Benyei7f92f2d2012-12-18 14:30:41 +00002902 ClientLoadCapabilities)) {
2903 case Failure:
Douglas Gregor677e15f2013-03-19 00:28:20 +00002904 case Missing:
Guy Benyei7f92f2d2012-12-18 14:30:41 +00002905 case OutOfDate:
2906 case VersionMismatch:
2907 case ConfigurationMismatch:
2908 case HadErrors:
Douglas Gregor677e15f2013-03-19 00:28:20 +00002909 ModuleMgr.removeModules(ModuleMgr.begin() + NumModules, ModuleMgr.end(),
2910 Context.getLangOpts().Modules
2911 ? &PP.getHeaderSearchInfo().getModuleMap()
2912 : 0);
Douglas Gregor1a49d972013-01-25 01:03:03 +00002913
2914 // If we find that any modules are unusable, the global index is going
2915 // to be out-of-date. Just remove it.
2916 GlobalIndex.reset();
Douglas Gregor188bdcd2013-01-25 23:32:03 +00002917 ModuleMgr.setGlobalIndex(0);
Guy Benyei7f92f2d2012-12-18 14:30:41 +00002918 return ReadResult;
2919
2920 case Success:
2921 break;
2922 }
2923
2924 // Here comes stuff that we only do once the entire chain is loaded.
2925
2926 // Load the AST blocks of all of the modules that we loaded.
Dmitri Gribenkocfa88f82013-01-12 19:30:44 +00002927 for (SmallVectorImpl<ImportedModule>::iterator M = Loaded.begin(),
2928 MEnd = Loaded.end();
Guy Benyei7f92f2d2012-12-18 14:30:41 +00002929 M != MEnd; ++M) {
2930 ModuleFile &F = *M->Mod;
2931
2932 // Read the AST block.
2933 if (ReadASTBlock(F))
2934 return Failure;
2935
2936 // Once read, set the ModuleFile bit base offset and update the size in
2937 // bits of all files we've seen.
2938 F.GlobalBitOffset = TotalModulesSizeInBits;
2939 TotalModulesSizeInBits += F.SizeInBits;
2940 GlobalBitOffsetsMap.insert(std::make_pair(F.GlobalBitOffset, &F));
2941
2942 // Preload SLocEntries.
2943 for (unsigned I = 0, N = F.PreloadSLocEntries.size(); I != N; ++I) {
2944 int Index = int(F.PreloadSLocEntries[I] - 1) + F.SLocEntryBaseID;
2945 // Load it through the SourceManager and don't call ReadSLocEntry()
2946 // directly because the entry may have already been loaded in which case
2947 // calling ReadSLocEntry() directly would trigger an assertion in
2948 // SourceManager.
2949 SourceMgr.getLoadedSLocEntryByID(Index);
2950 }
2951 }
2952
Douglas Gregorfa69fc12013-03-22 18:50:14 +00002953 // Setup the import locations and notify the module manager that we've
2954 // committed to these module files.
Dmitri Gribenkocfa88f82013-01-12 19:30:44 +00002955 for (SmallVectorImpl<ImportedModule>::iterator M = Loaded.begin(),
2956 MEnd = Loaded.end();
Guy Benyei7f92f2d2012-12-18 14:30:41 +00002957 M != MEnd; ++M) {
2958 ModuleFile &F = *M->Mod;
Douglas Gregorfa69fc12013-03-22 18:50:14 +00002959
2960 ModuleMgr.moduleFileAccepted(&F);
2961
2962 // Set the import location.
Argyrios Kyrtzidis8b136d82013-02-01 16:36:14 +00002963 F.DirectImportLoc = ImportLoc;
Guy Benyei7f92f2d2012-12-18 14:30:41 +00002964 if (!M->ImportedBy)
2965 F.ImportLoc = M->ImportLoc;
2966 else
2967 F.ImportLoc = ReadSourceLocation(*M->ImportedBy,
2968 M->ImportLoc.getRawEncoding());
2969 }
2970
2971 // Mark all of the identifiers in the identifier table as being out of date,
2972 // so that various accessors know to check the loaded modules when the
2973 // identifier is used.
2974 for (IdentifierTable::iterator Id = PP.getIdentifierTable().begin(),
2975 IdEnd = PP.getIdentifierTable().end();
2976 Id != IdEnd; ++Id)
2977 Id->second->setOutOfDate(true);
2978
2979 // Resolve any unresolved module exports.
Douglas Gregor906d66a2013-03-20 21:10:35 +00002980 for (unsigned I = 0, N = UnresolvedModuleRefs.size(); I != N; ++I) {
2981 UnresolvedModuleRef &Unresolved = UnresolvedModuleRefs[I];
Guy Benyei7f92f2d2012-12-18 14:30:41 +00002982 SubmoduleID GlobalID = getGlobalSubmoduleID(*Unresolved.File,Unresolved.ID);
2983 Module *ResolvedMod = getSubmodule(GlobalID);
Douglas Gregor906d66a2013-03-20 21:10:35 +00002984
2985 switch (Unresolved.Kind) {
2986 case UnresolvedModuleRef::Conflict:
2987 if (ResolvedMod) {
2988 Module::Conflict Conflict;
2989 Conflict.Other = ResolvedMod;
2990 Conflict.Message = Unresolved.String.str();
2991 Unresolved.Mod->Conflicts.push_back(Conflict);
2992 }
2993 continue;
2994
2995 case UnresolvedModuleRef::Import:
Guy Benyei7f92f2d2012-12-18 14:30:41 +00002996 if (ResolvedMod)
2997 Unresolved.Mod->Imports.push_back(ResolvedMod);
2998 continue;
Guy Benyei7f92f2d2012-12-18 14:30:41 +00002999
Douglas Gregor906d66a2013-03-20 21:10:35 +00003000 case UnresolvedModuleRef::Export:
3001 if (ResolvedMod || Unresolved.IsWildcard)
3002 Unresolved.Mod->Exports.push_back(
3003 Module::ExportDecl(ResolvedMod, Unresolved.IsWildcard));
3004 continue;
3005 }
Guy Benyei7f92f2d2012-12-18 14:30:41 +00003006 }
Douglas Gregor906d66a2013-03-20 21:10:35 +00003007 UnresolvedModuleRefs.clear();
Guy Benyei7f92f2d2012-12-18 14:30:41 +00003008
3009 InitializeContext();
3010
3011 if (DeserializationListener)
3012 DeserializationListener->ReaderInitialized(this);
3013
3014 ModuleFile &PrimaryModule = ModuleMgr.getPrimaryModule();
3015 if (!PrimaryModule.OriginalSourceFileID.isInvalid()) {
3016 PrimaryModule.OriginalSourceFileID
3017 = FileID::get(PrimaryModule.SLocEntryBaseID
3018 + PrimaryModule.OriginalSourceFileID.getOpaqueValue() - 1);
3019
3020 // If this AST file is a precompiled preamble, then set the
3021 // preamble file ID of the source manager to the file source file
3022 // from which the preamble was built.
3023 if (Type == MK_Preamble) {
3024 SourceMgr.setPreambleFileID(PrimaryModule.OriginalSourceFileID);
3025 } else if (Type == MK_MainFile) {
3026 SourceMgr.setMainFileID(PrimaryModule.OriginalSourceFileID);
3027 }
3028 }
3029
3030 // For any Objective-C class definitions we have already loaded, make sure
3031 // that we load any additional categories.
3032 for (unsigned I = 0, N = ObjCClassesLoaded.size(); I != N; ++I) {
3033 loadObjCCategories(ObjCClassesLoaded[I]->getGlobalID(),
3034 ObjCClassesLoaded[I],
3035 PreviousGeneration);
3036 }
Douglas Gregor1a49d972013-01-25 01:03:03 +00003037
Guy Benyei7f92f2d2012-12-18 14:30:41 +00003038 return Success;
3039}
3040
3041ASTReader::ASTReadResult
3042ASTReader::ReadASTCore(StringRef FileName,
3043 ModuleKind Type,
3044 SourceLocation ImportLoc,
3045 ModuleFile *ImportedBy,
Dmitri Gribenkocfa88f82013-01-12 19:30:44 +00003046 SmallVectorImpl<ImportedModule> &Loaded,
Douglas Gregor677e15f2013-03-19 00:28:20 +00003047 off_t ExpectedSize, time_t ExpectedModTime,
Guy Benyei7f92f2d2012-12-18 14:30:41 +00003048 unsigned ClientLoadCapabilities) {
3049 ModuleFile *M;
Guy Benyei7f92f2d2012-12-18 14:30:41 +00003050 std::string ErrorStr;
Douglas Gregor677e15f2013-03-19 00:28:20 +00003051 ModuleManager::AddModuleResult AddResult
3052 = ModuleMgr.addModule(FileName, Type, ImportLoc, ImportedBy,
3053 CurrentGeneration, ExpectedSize, ExpectedModTime,
3054 M, ErrorStr);
Guy Benyei7f92f2d2012-12-18 14:30:41 +00003055
Douglas Gregor677e15f2013-03-19 00:28:20 +00003056 switch (AddResult) {
3057 case ModuleManager::AlreadyLoaded:
3058 return Success;
3059
3060 case ModuleManager::NewlyLoaded:
3061 // Load module file below.
3062 break;
3063
3064 case ModuleManager::Missing:
3065 // The module file was missing; if the client handle handle, that, return
3066 // it.
3067 if (ClientLoadCapabilities & ARR_Missing)
3068 return Missing;
3069
3070 // Otherwise, return an error.
3071 {
3072 std::string Msg = "Unable to load module \"" + FileName.str() + "\": "
3073 + ErrorStr;
3074 Error(Msg);
3075 }
3076 return Failure;
3077
3078 case ModuleManager::OutOfDate:
3079 // We couldn't load the module file because it is out-of-date. If the
3080 // client can handle out-of-date, return it.
3081 if (ClientLoadCapabilities & ARR_OutOfDate)
3082 return OutOfDate;
3083
3084 // Otherwise, return an error.
3085 {
3086 std::string Msg = "Unable to load module \"" + FileName.str() + "\": "
3087 + ErrorStr;
3088 Error(Msg);
3089 }
Guy Benyei7f92f2d2012-12-18 14:30:41 +00003090 return Failure;
3091 }
3092
Douglas Gregor677e15f2013-03-19 00:28:20 +00003093 assert(M && "Missing module file");
Guy Benyei7f92f2d2012-12-18 14:30:41 +00003094
3095 // FIXME: This seems rather a hack. Should CurrentDir be part of the
3096 // module?
3097 if (FileName != "-") {
3098 CurrentDir = llvm::sys::path::parent_path(FileName);
3099 if (CurrentDir.empty()) CurrentDir = ".";
3100 }
3101
3102 ModuleFile &F = *M;
Chris Lattner8f9a1eb2013-01-20 00:56:42 +00003103 BitstreamCursor &Stream = F.Stream;
Guy Benyei7f92f2d2012-12-18 14:30:41 +00003104 Stream.init(F.StreamFile);
3105 F.SizeInBits = F.Buffer->getBufferSize() * 8;
3106
3107 // Sniff for the signature.
3108 if (Stream.Read(8) != 'C' ||
3109 Stream.Read(8) != 'P' ||
3110 Stream.Read(8) != 'C' ||
3111 Stream.Read(8) != 'H') {
3112 Diag(diag::err_not_a_pch_file) << FileName;
3113 return Failure;
3114 }
3115
3116 // This is used for compatibility with older PCH formats.
3117 bool HaveReadControlBlock = false;
3118
Chris Lattner99a5af02013-01-20 00:00:22 +00003119 while (1) {
3120 llvm::BitstreamEntry Entry = Stream.advance();
3121
3122 switch (Entry.Kind) {
3123 case llvm::BitstreamEntry::Error:
3124 case llvm::BitstreamEntry::EndBlock:
3125 case llvm::BitstreamEntry::Record:
Guy Benyei7f92f2d2012-12-18 14:30:41 +00003126 Error("invalid record at top-level of AST file");
3127 return Failure;
Chris Lattner99a5af02013-01-20 00:00:22 +00003128
3129 case llvm::BitstreamEntry::SubBlock:
3130 break;
Guy Benyei7f92f2d2012-12-18 14:30:41 +00003131 }
3132
Guy Benyei7f92f2d2012-12-18 14:30:41 +00003133 // We only know the control subblock ID.
Chris Lattner99a5af02013-01-20 00:00:22 +00003134 switch (Entry.ID) {
Guy Benyei7f92f2d2012-12-18 14:30:41 +00003135 case llvm::bitc::BLOCKINFO_BLOCK_ID:
3136 if (Stream.ReadBlockInfoBlock()) {
3137 Error("malformed BlockInfoBlock in AST file");
3138 return Failure;
3139 }
3140 break;
3141 case CONTROL_BLOCK_ID:
3142 HaveReadControlBlock = true;
3143 switch (ReadControlBlock(F, Loaded, ClientLoadCapabilities)) {
3144 case Success:
3145 break;
3146
3147 case Failure: return Failure;
Douglas Gregor677e15f2013-03-19 00:28:20 +00003148 case Missing: return Missing;
Guy Benyei7f92f2d2012-12-18 14:30:41 +00003149 case OutOfDate: return OutOfDate;
3150 case VersionMismatch: return VersionMismatch;
3151 case ConfigurationMismatch: return ConfigurationMismatch;
3152 case HadErrors: return HadErrors;
3153 }
3154 break;
3155 case AST_BLOCK_ID:
3156 if (!HaveReadControlBlock) {
3157 if ((ClientLoadCapabilities & ARR_VersionMismatch) == 0)
3158 Diag(diag::warn_pch_version_too_old);
3159 return VersionMismatch;
3160 }
3161
3162 // Record that we've loaded this module.
3163 Loaded.push_back(ImportedModule(M, ImportedBy, ImportLoc));
3164 return Success;
3165
3166 default:
3167 if (Stream.SkipBlock()) {
3168 Error("malformed block record in AST file");
3169 return Failure;
3170 }
3171 break;
3172 }
3173 }
3174
3175 return Success;
3176}
3177
3178void ASTReader::InitializeContext() {
3179 // If there's a listener, notify them that we "read" the translation unit.
3180 if (DeserializationListener)
3181 DeserializationListener->DeclRead(PREDEF_DECL_TRANSLATION_UNIT_ID,
3182 Context.getTranslationUnitDecl());
3183
3184 // Make sure we load the declaration update records for the translation unit,
3185 // if there are any.
3186 loadDeclUpdateRecords(PREDEF_DECL_TRANSLATION_UNIT_ID,
3187 Context.getTranslationUnitDecl());
3188
3189 // FIXME: Find a better way to deal with collisions between these
3190 // built-in types. Right now, we just ignore the problem.
3191
3192 // Load the special types.
3193 if (SpecialTypes.size() >= NumSpecialTypeIDs) {
3194 if (unsigned String = SpecialTypes[SPECIAL_TYPE_CF_CONSTANT_STRING]) {
3195 if (!Context.CFConstantStringTypeDecl)
3196 Context.setCFConstantStringType(GetType(String));
3197 }
3198
3199 if (unsigned File = SpecialTypes[SPECIAL_TYPE_FILE]) {
3200 QualType FileType = GetType(File);
3201 if (FileType.isNull()) {
3202 Error("FILE type is NULL");
3203 return;
3204 }
3205
3206 if (!Context.FILEDecl) {
3207 if (const TypedefType *Typedef = FileType->getAs<TypedefType>())
3208 Context.setFILEDecl(Typedef->getDecl());
3209 else {
3210 const TagType *Tag = FileType->getAs<TagType>();
3211 if (!Tag) {
3212 Error("Invalid FILE type in AST file");
3213 return;
3214 }
3215 Context.setFILEDecl(Tag->getDecl());
3216 }
3217 }
3218 }
3219
3220 if (unsigned Jmp_buf = SpecialTypes[SPECIAL_TYPE_JMP_BUF]) {
3221 QualType Jmp_bufType = GetType(Jmp_buf);
3222 if (Jmp_bufType.isNull()) {
3223 Error("jmp_buf type is NULL");
3224 return;
3225 }
3226
3227 if (!Context.jmp_bufDecl) {
3228 if (const TypedefType *Typedef = Jmp_bufType->getAs<TypedefType>())
3229 Context.setjmp_bufDecl(Typedef->getDecl());
3230 else {
3231 const TagType *Tag = Jmp_bufType->getAs<TagType>();
3232 if (!Tag) {
3233 Error("Invalid jmp_buf type in AST file");
3234 return;
3235 }
3236 Context.setjmp_bufDecl(Tag->getDecl());
3237 }
3238 }
3239 }
3240
3241 if (unsigned Sigjmp_buf = SpecialTypes[SPECIAL_TYPE_SIGJMP_BUF]) {
3242 QualType Sigjmp_bufType = GetType(Sigjmp_buf);
3243 if (Sigjmp_bufType.isNull()) {
3244 Error("sigjmp_buf type is NULL");
3245 return;
3246 }
3247
3248 if (!Context.sigjmp_bufDecl) {
3249 if (const TypedefType *Typedef = Sigjmp_bufType->getAs<TypedefType>())
3250 Context.setsigjmp_bufDecl(Typedef->getDecl());
3251 else {
3252 const TagType *Tag = Sigjmp_bufType->getAs<TagType>();
3253 assert(Tag && "Invalid sigjmp_buf type in AST file");
3254 Context.setsigjmp_bufDecl(Tag->getDecl());
3255 }
3256 }
3257 }
3258
3259 if (unsigned ObjCIdRedef
3260 = SpecialTypes[SPECIAL_TYPE_OBJC_ID_REDEFINITION]) {
3261 if (Context.ObjCIdRedefinitionType.isNull())
3262 Context.ObjCIdRedefinitionType = GetType(ObjCIdRedef);
3263 }
3264
3265 if (unsigned ObjCClassRedef
3266 = SpecialTypes[SPECIAL_TYPE_OBJC_CLASS_REDEFINITION]) {
3267 if (Context.ObjCClassRedefinitionType.isNull())
3268 Context.ObjCClassRedefinitionType = GetType(ObjCClassRedef);
3269 }
3270
3271 if (unsigned ObjCSelRedef
3272 = SpecialTypes[SPECIAL_TYPE_OBJC_SEL_REDEFINITION]) {
3273 if (Context.ObjCSelRedefinitionType.isNull())
3274 Context.ObjCSelRedefinitionType = GetType(ObjCSelRedef);
3275 }
3276
3277 if (unsigned Ucontext_t = SpecialTypes[SPECIAL_TYPE_UCONTEXT_T]) {
3278 QualType Ucontext_tType = GetType(Ucontext_t);
3279 if (Ucontext_tType.isNull()) {
3280 Error("ucontext_t type is NULL");
3281 return;
3282 }
3283
3284 if (!Context.ucontext_tDecl) {
3285 if (const TypedefType *Typedef = Ucontext_tType->getAs<TypedefType>())
3286 Context.setucontext_tDecl(Typedef->getDecl());
3287 else {
3288 const TagType *Tag = Ucontext_tType->getAs<TagType>();
3289 assert(Tag && "Invalid ucontext_t type in AST file");
3290 Context.setucontext_tDecl(Tag->getDecl());
3291 }
3292 }
3293 }
3294 }
3295
3296 ReadPragmaDiagnosticMappings(Context.getDiagnostics());
3297
3298 // If there were any CUDA special declarations, deserialize them.
3299 if (!CUDASpecialDeclRefs.empty()) {
3300 assert(CUDASpecialDeclRefs.size() == 1 && "More decl refs than expected!");
3301 Context.setcudaConfigureCallDecl(
3302 cast<FunctionDecl>(GetDecl(CUDASpecialDeclRefs[0])));
3303 }
3304
3305 // Re-export any modules that were imported by a non-module AST file.
3306 for (unsigned I = 0, N = ImportedModules.size(); I != N; ++I) {
3307 if (Module *Imported = getSubmodule(ImportedModules[I]))
Argyrios Kyrtzidis5ebcb202013-02-01 16:36:12 +00003308 makeModuleVisible(Imported, Module::AllVisible,
Douglas Gregor906d66a2013-03-20 21:10:35 +00003309 /*ImportLoc=*/SourceLocation(),
3310 /*Complain=*/false);
Guy Benyei7f92f2d2012-12-18 14:30:41 +00003311 }
3312 ImportedModules.clear();
3313}
3314
3315void ASTReader::finalizeForWriting() {
3316 for (HiddenNamesMapType::iterator Hidden = HiddenNamesMap.begin(),
3317 HiddenEnd = HiddenNamesMap.end();
3318 Hidden != HiddenEnd; ++Hidden) {
Argyrios Kyrtzidis52151fd2013-03-27 01:25:34 +00003319 makeNamesVisible(Hidden->second, Hidden->first);
Guy Benyei7f92f2d2012-12-18 14:30:41 +00003320 }
3321 HiddenNamesMap.clear();
3322}
3323
Chris Lattner8f9a1eb2013-01-20 00:56:42 +00003324/// SkipCursorToControlBlock - Given a cursor at the start of an AST file, scan
3325/// ahead and drop the cursor into the start of the CONTROL_BLOCK, returning
3326/// false on success and true on failure.
3327static bool SkipCursorToControlBlock(BitstreamCursor &Cursor) {
3328 while (1) {
3329 llvm::BitstreamEntry Entry = Cursor.advance();
3330 switch (Entry.Kind) {
3331 case llvm::BitstreamEntry::Error:
3332 case llvm::BitstreamEntry::EndBlock:
3333 return true;
3334
3335 case llvm::BitstreamEntry::Record:
3336 // Ignore top-level records.
3337 Cursor.skipRecord(Entry.ID);
3338 break;
3339
3340 case llvm::BitstreamEntry::SubBlock:
3341 if (Entry.ID == CONTROL_BLOCK_ID) {
3342 if (Cursor.EnterSubBlock(CONTROL_BLOCK_ID))
3343 return true;
3344 // Found it!
3345 return false;
3346 }
3347
3348 if (Cursor.SkipBlock())
3349 return true;
3350 }
3351 }
3352}
3353
Guy Benyei7f92f2d2012-12-18 14:30:41 +00003354/// \brief Retrieve the name of the original source file name
3355/// directly from the AST file, without actually loading the AST
3356/// file.
3357std::string ASTReader::getOriginalSourceFile(const std::string &ASTFileName,
3358 FileManager &FileMgr,
3359 DiagnosticsEngine &Diags) {
3360 // Open the AST file.
3361 std::string ErrStr;
3362 OwningPtr<llvm::MemoryBuffer> Buffer;
3363 Buffer.reset(FileMgr.getBufferForFile(ASTFileName, &ErrStr));
3364 if (!Buffer) {
3365 Diags.Report(diag::err_fe_unable_to_read_pch_file) << ASTFileName << ErrStr;
3366 return std::string();
3367 }
3368
3369 // Initialize the stream
3370 llvm::BitstreamReader StreamFile;
Chris Lattner8f9a1eb2013-01-20 00:56:42 +00003371 BitstreamCursor Stream;
Guy Benyei7f92f2d2012-12-18 14:30:41 +00003372 StreamFile.init((const unsigned char *)Buffer->getBufferStart(),
3373 (const unsigned char *)Buffer->getBufferEnd());
3374 Stream.init(StreamFile);
3375
3376 // Sniff for the signature.
3377 if (Stream.Read(8) != 'C' ||
3378 Stream.Read(8) != 'P' ||
3379 Stream.Read(8) != 'C' ||
3380 Stream.Read(8) != 'H') {
3381 Diags.Report(diag::err_fe_not_a_pch_file) << ASTFileName;
3382 return std::string();
3383 }
Chris Lattner8f9a1eb2013-01-20 00:56:42 +00003384
Chris Lattner88bde502013-01-19 21:39:22 +00003385 // Scan for the CONTROL_BLOCK_ID block.
Chris Lattner8f9a1eb2013-01-20 00:56:42 +00003386 if (SkipCursorToControlBlock(Stream)) {
3387 Diags.Report(diag::err_fe_pch_malformed_block) << ASTFileName;
3388 return std::string();
Chris Lattner88bde502013-01-19 21:39:22 +00003389 }
Guy Benyei7f92f2d2012-12-18 14:30:41 +00003390
Chris Lattner8f9a1eb2013-01-20 00:56:42 +00003391 // Scan for ORIGINAL_FILE inside the control block.
3392 RecordData Record;
Chris Lattner88bde502013-01-19 21:39:22 +00003393 while (1) {
Chris Lattner8f9a1eb2013-01-20 00:56:42 +00003394 llvm::BitstreamEntry Entry = Stream.advanceSkippingSubblocks();
Chris Lattner88bde502013-01-19 21:39:22 +00003395 if (Entry.Kind == llvm::BitstreamEntry::EndBlock)
3396 return std::string();
3397
3398 if (Entry.Kind != llvm::BitstreamEntry::Record) {
3399 Diags.Report(diag::err_fe_pch_malformed_block) << ASTFileName;
3400 return std::string();
Guy Benyei7f92f2d2012-12-18 14:30:41 +00003401 }
Chris Lattner88bde502013-01-19 21:39:22 +00003402
Guy Benyei7f92f2d2012-12-18 14:30:41 +00003403 Record.clear();
Chris Lattnerb3ce3572013-01-20 02:38:54 +00003404 StringRef Blob;
3405 if (Stream.readRecord(Entry.ID, Record, &Blob) == ORIGINAL_FILE)
3406 return Blob.str();
Guy Benyei7f92f2d2012-12-18 14:30:41 +00003407 }
Guy Benyei7f92f2d2012-12-18 14:30:41 +00003408}
3409
3410namespace {
3411 class SimplePCHValidator : public ASTReaderListener {
3412 const LangOptions &ExistingLangOpts;
3413 const TargetOptions &ExistingTargetOpts;
3414 const PreprocessorOptions &ExistingPPOpts;
3415 FileManager &FileMgr;
3416
3417 public:
3418 SimplePCHValidator(const LangOptions &ExistingLangOpts,
3419 const TargetOptions &ExistingTargetOpts,
3420 const PreprocessorOptions &ExistingPPOpts,
3421 FileManager &FileMgr)
3422 : ExistingLangOpts(ExistingLangOpts),
3423 ExistingTargetOpts(ExistingTargetOpts),
3424 ExistingPPOpts(ExistingPPOpts),
3425 FileMgr(FileMgr)
3426 {
3427 }
3428
3429 virtual bool ReadLanguageOptions(const LangOptions &LangOpts,
3430 bool Complain) {
3431 return checkLanguageOptions(ExistingLangOpts, LangOpts, 0);
3432 }
3433 virtual bool ReadTargetOptions(const TargetOptions &TargetOpts,
3434 bool Complain) {
3435 return checkTargetOptions(ExistingTargetOpts, TargetOpts, 0);
3436 }
3437 virtual bool ReadPreprocessorOptions(const PreprocessorOptions &PPOpts,
3438 bool Complain,
3439 std::string &SuggestedPredefines) {
3440 return checkPreprocessorOptions(ExistingPPOpts, PPOpts, 0, FileMgr,
Argyrios Kyrtzidis65110ca2013-04-26 21:33:40 +00003441 SuggestedPredefines, ExistingLangOpts);
Guy Benyei7f92f2d2012-12-18 14:30:41 +00003442 }
3443 };
3444}
3445
3446bool ASTReader::readASTFileControlBlock(StringRef Filename,
3447 FileManager &FileMgr,
3448 ASTReaderListener &Listener) {
3449 // Open the AST file.
3450 std::string ErrStr;
3451 OwningPtr<llvm::MemoryBuffer> Buffer;
3452 Buffer.reset(FileMgr.getBufferForFile(Filename, &ErrStr));
3453 if (!Buffer) {
3454 return true;
3455 }
3456
3457 // Initialize the stream
3458 llvm::BitstreamReader StreamFile;
Chris Lattner8f9a1eb2013-01-20 00:56:42 +00003459 BitstreamCursor Stream;
Guy Benyei7f92f2d2012-12-18 14:30:41 +00003460 StreamFile.init((const unsigned char *)Buffer->getBufferStart(),
3461 (const unsigned char *)Buffer->getBufferEnd());
3462 Stream.init(StreamFile);
3463
3464 // Sniff for the signature.
3465 if (Stream.Read(8) != 'C' ||
3466 Stream.Read(8) != 'P' ||
3467 Stream.Read(8) != 'C' ||
3468 Stream.Read(8) != 'H') {
3469 return true;
3470 }
3471
Chris Lattner8f9a1eb2013-01-20 00:56:42 +00003472 // Scan for the CONTROL_BLOCK_ID block.
3473 if (SkipCursorToControlBlock(Stream))
3474 return true;
3475
3476 // Scan for ORIGINAL_FILE inside the control block.
Guy Benyei7f92f2d2012-12-18 14:30:41 +00003477 RecordData Record;
Chris Lattner8f9a1eb2013-01-20 00:56:42 +00003478 while (1) {
3479 llvm::BitstreamEntry Entry = Stream.advanceSkippingSubblocks();
3480 if (Entry.Kind == llvm::BitstreamEntry::EndBlock)
3481 return false;
3482
3483 if (Entry.Kind != llvm::BitstreamEntry::Record)
3484 return true;
3485
Guy Benyei7f92f2d2012-12-18 14:30:41 +00003486 Record.clear();
Chris Lattnerb3ce3572013-01-20 02:38:54 +00003487 StringRef Blob;
3488 unsigned RecCode = Stream.readRecord(Entry.ID, Record, &Blob);
Chris Lattner8f9a1eb2013-01-20 00:56:42 +00003489 switch ((ControlRecordTypes)RecCode) {
3490 case METADATA: {
3491 if (Record[0] != VERSION_MAJOR)
3492 return true;
Guy Benyei7f92f2d2012-12-18 14:30:41 +00003493
Douglas Gregorc544ba02013-03-27 16:47:18 +00003494 if (Listener.ReadFullVersionInformation(Blob))
Chris Lattner8f9a1eb2013-01-20 00:56:42 +00003495 return true;
Douglas Gregorc544ba02013-03-27 16:47:18 +00003496
Chris Lattner8f9a1eb2013-01-20 00:56:42 +00003497 break;
3498 }
3499 case LANGUAGE_OPTIONS:
3500 if (ParseLanguageOptions(Record, false, Listener))
3501 return true;
3502 break;
Guy Benyei7f92f2d2012-12-18 14:30:41 +00003503
Chris Lattner8f9a1eb2013-01-20 00:56:42 +00003504 case TARGET_OPTIONS:
3505 if (ParseTargetOptions(Record, false, Listener))
3506 return true;
3507 break;
Guy Benyei7f92f2d2012-12-18 14:30:41 +00003508
Chris Lattner8f9a1eb2013-01-20 00:56:42 +00003509 case DIAGNOSTIC_OPTIONS:
3510 if (ParseDiagnosticOptions(Record, false, Listener))
3511 return true;
3512 break;
Guy Benyei7f92f2d2012-12-18 14:30:41 +00003513
Chris Lattner8f9a1eb2013-01-20 00:56:42 +00003514 case FILE_SYSTEM_OPTIONS:
3515 if (ParseFileSystemOptions(Record, false, Listener))
3516 return true;
3517 break;
Guy Benyei7f92f2d2012-12-18 14:30:41 +00003518
Chris Lattner8f9a1eb2013-01-20 00:56:42 +00003519 case HEADER_SEARCH_OPTIONS:
3520 if (ParseHeaderSearchOptions(Record, false, Listener))
3521 return true;
3522 break;
Guy Benyei7f92f2d2012-12-18 14:30:41 +00003523
Chris Lattner8f9a1eb2013-01-20 00:56:42 +00003524 case PREPROCESSOR_OPTIONS: {
3525 std::string IgnoredSuggestedPredefines;
3526 if (ParsePreprocessorOptions(Record, false, Listener,
3527 IgnoredSuggestedPredefines))
3528 return true;
3529 break;
3530 }
Guy Benyei7f92f2d2012-12-18 14:30:41 +00003531
Chris Lattner8f9a1eb2013-01-20 00:56:42 +00003532 default:
3533 // No other validation to perform.
3534 break;
Guy Benyei7f92f2d2012-12-18 14:30:41 +00003535 }
3536 }
Guy Benyei7f92f2d2012-12-18 14:30:41 +00003537}
3538
3539
3540bool ASTReader::isAcceptableASTFile(StringRef Filename,
3541 FileManager &FileMgr,
3542 const LangOptions &LangOpts,
3543 const TargetOptions &TargetOpts,
3544 const PreprocessorOptions &PPOpts) {
3545 SimplePCHValidator validator(LangOpts, TargetOpts, PPOpts, FileMgr);
3546 return !readASTFileControlBlock(Filename, FileMgr, validator);
3547}
3548
3549bool ASTReader::ReadSubmoduleBlock(ModuleFile &F) {
3550 // Enter the submodule block.
3551 if (F.Stream.EnterSubBlock(SUBMODULE_BLOCK_ID)) {
3552 Error("malformed submodule block record in AST file");
3553 return true;
3554 }
3555
3556 ModuleMap &ModMap = PP.getHeaderSearchInfo().getModuleMap();
3557 bool First = true;
3558 Module *CurrentModule = 0;
3559 RecordData Record;
3560 while (true) {
Chris Lattner8f9a1eb2013-01-20 00:56:42 +00003561 llvm::BitstreamEntry Entry = F.Stream.advanceSkippingSubblocks();
3562
3563 switch (Entry.Kind) {
3564 case llvm::BitstreamEntry::SubBlock: // Handled for us already.
3565 case llvm::BitstreamEntry::Error:
3566 Error("malformed block record in AST file");
3567 return true;
3568 case llvm::BitstreamEntry::EndBlock:
Guy Benyei7f92f2d2012-12-18 14:30:41 +00003569 return false;
Chris Lattner8f9a1eb2013-01-20 00:56:42 +00003570 case llvm::BitstreamEntry::Record:
3571 // The interesting case.
3572 break;
Guy Benyei7f92f2d2012-12-18 14:30:41 +00003573 }
Chris Lattner8f9a1eb2013-01-20 00:56:42 +00003574
Guy Benyei7f92f2d2012-12-18 14:30:41 +00003575 // Read a record.
Chris Lattnerb3ce3572013-01-20 02:38:54 +00003576 StringRef Blob;
Guy Benyei7f92f2d2012-12-18 14:30:41 +00003577 Record.clear();
Chris Lattnerb3ce3572013-01-20 02:38:54 +00003578 switch (F.Stream.readRecord(Entry.ID, Record, &Blob)) {
Guy Benyei7f92f2d2012-12-18 14:30:41 +00003579 default: // Default behavior: ignore.
3580 break;
3581
3582 case SUBMODULE_DEFINITION: {
3583 if (First) {
3584 Error("missing submodule metadata record at beginning of block");
3585 return true;
3586 }
3587
Douglas Gregor970e4412013-03-20 03:59:18 +00003588 if (Record.size() < 8) {
Guy Benyei7f92f2d2012-12-18 14:30:41 +00003589 Error("malformed module definition");
3590 return true;
3591 }
3592
Chris Lattnerb3ce3572013-01-20 02:38:54 +00003593 StringRef Name = Blob;
Guy Benyei7f92f2d2012-12-18 14:30:41 +00003594 SubmoduleID GlobalID = getGlobalSubmoduleID(F, Record[0]);
3595 SubmoduleID Parent = getGlobalSubmoduleID(F, Record[1]);
3596 bool IsFramework = Record[2];
3597 bool IsExplicit = Record[3];
3598 bool IsSystem = Record[4];
3599 bool InferSubmodules = Record[5];
3600 bool InferExplicitSubmodules = Record[6];
3601 bool InferExportWildcard = Record[7];
Douglas Gregor970e4412013-03-20 03:59:18 +00003602 bool ConfigMacrosExhaustive = Record[8];
3603
Guy Benyei7f92f2d2012-12-18 14:30:41 +00003604 Module *ParentModule = 0;
3605 if (Parent)
3606 ParentModule = getSubmodule(Parent);
3607
3608 // Retrieve this (sub)module from the module map, creating it if
3609 // necessary.
3610 CurrentModule = ModMap.findOrCreateModule(Name, ParentModule,
3611 IsFramework,
3612 IsExplicit).first;
3613 SubmoduleID GlobalIndex = GlobalID - NUM_PREDEF_SUBMODULE_IDS;
3614 if (GlobalIndex >= SubmodulesLoaded.size() ||
3615 SubmodulesLoaded[GlobalIndex]) {
3616 Error("too many submodules");
3617 return true;
3618 }
Douglas Gregor8bf778e2013-02-06 22:40:31 +00003619
Douglas Gregor677e15f2013-03-19 00:28:20 +00003620 if (!ParentModule) {
3621 if (const FileEntry *CurFile = CurrentModule->getASTFile()) {
3622 if (CurFile != F.File) {
3623 if (!Diags.isDiagnosticInFlight()) {
3624 Diag(diag::err_module_file_conflict)
3625 << CurrentModule->getTopLevelModuleName()
3626 << CurFile->getName()
3627 << F.File->getName();
3628 }
3629 return true;
Douglas Gregor8bf778e2013-02-06 22:40:31 +00003630 }
Douglas Gregor8bf778e2013-02-06 22:40:31 +00003631 }
Douglas Gregor677e15f2013-03-19 00:28:20 +00003632
3633 CurrentModule->setASTFile(F.File);
Douglas Gregor8bf778e2013-02-06 22:40:31 +00003634 }
Douglas Gregor677e15f2013-03-19 00:28:20 +00003635
Guy Benyei7f92f2d2012-12-18 14:30:41 +00003636 CurrentModule->IsFromModuleFile = true;
3637 CurrentModule->IsSystem = IsSystem || CurrentModule->IsSystem;
3638 CurrentModule->InferSubmodules = InferSubmodules;
3639 CurrentModule->InferExplicitSubmodules = InferExplicitSubmodules;
3640 CurrentModule->InferExportWildcard = InferExportWildcard;
Douglas Gregor970e4412013-03-20 03:59:18 +00003641 CurrentModule->ConfigMacrosExhaustive = ConfigMacrosExhaustive;
Guy Benyei7f92f2d2012-12-18 14:30:41 +00003642 if (DeserializationListener)
3643 DeserializationListener->ModuleRead(GlobalID, CurrentModule);
3644
3645 SubmodulesLoaded[GlobalIndex] = CurrentModule;
Douglas Gregorb6cbe512013-01-14 17:21:00 +00003646
Douglas Gregor906d66a2013-03-20 21:10:35 +00003647 // Clear out data that will be replaced by what is the module file.
Douglas Gregorb6cbe512013-01-14 17:21:00 +00003648 CurrentModule->LinkLibraries.clear();
Douglas Gregor970e4412013-03-20 03:59:18 +00003649 CurrentModule->ConfigMacros.clear();
Douglas Gregor906d66a2013-03-20 21:10:35 +00003650 CurrentModule->UnresolvedConflicts.clear();
3651 CurrentModule->Conflicts.clear();
Guy Benyei7f92f2d2012-12-18 14:30:41 +00003652 break;
3653 }
3654
3655 case SUBMODULE_UMBRELLA_HEADER: {
3656 if (First) {
3657 Error("missing submodule metadata record at beginning of block");
3658 return true;
3659 }
3660
3661 if (!CurrentModule)
3662 break;
3663
Chris Lattnerb3ce3572013-01-20 02:38:54 +00003664 if (const FileEntry *Umbrella = PP.getFileManager().getFile(Blob)) {
Guy Benyei7f92f2d2012-12-18 14:30:41 +00003665 if (!CurrentModule->getUmbrellaHeader())
3666 ModMap.setUmbrellaHeader(CurrentModule, Umbrella);
3667 else if (CurrentModule->getUmbrellaHeader() != Umbrella) {
3668 Error("mismatched umbrella headers in submodule");
3669 return true;
3670 }
3671 }
3672 break;
3673 }
3674
3675 case SUBMODULE_HEADER: {
3676 if (First) {
3677 Error("missing submodule metadata record at beginning of block");
3678 return true;
3679 }
3680
3681 if (!CurrentModule)
3682 break;
3683
Argyrios Kyrtzidis55ea75b2013-03-13 21:13:51 +00003684 // We lazily associate headers with their modules via the HeaderInfoTable.
3685 // FIXME: Re-evaluate this section; maybe only store InputFile IDs instead
3686 // of complete filenames or remove it entirely.
Guy Benyei7f92f2d2012-12-18 14:30:41 +00003687 break;
3688 }
3689
3690 case SUBMODULE_EXCLUDED_HEADER: {
3691 if (First) {
3692 Error("missing submodule metadata record at beginning of block");
3693 return true;
3694 }
3695
3696 if (!CurrentModule)
3697 break;
3698
Argyrios Kyrtzidis55ea75b2013-03-13 21:13:51 +00003699 // We lazily associate headers with their modules via the HeaderInfoTable.
3700 // FIXME: Re-evaluate this section; maybe only store InputFile IDs instead
3701 // of complete filenames or remove it entirely.
Guy Benyei7f92f2d2012-12-18 14:30:41 +00003702 break;
3703 }
3704
3705 case SUBMODULE_TOPHEADER: {
3706 if (First) {
3707 Error("missing submodule metadata record at beginning of block");
3708 return true;
3709 }
3710
3711 if (!CurrentModule)
3712 break;
3713
Argyrios Kyrtzidisc1d22392013-03-13 21:13:43 +00003714 CurrentModule->addTopHeaderFilename(Blob);
Guy Benyei7f92f2d2012-12-18 14:30:41 +00003715 break;
3716 }
3717
3718 case SUBMODULE_UMBRELLA_DIR: {
3719 if (First) {
3720 Error("missing submodule metadata record at beginning of block");
3721 return true;
3722 }
3723
3724 if (!CurrentModule)
3725 break;
3726
Guy Benyei7f92f2d2012-12-18 14:30:41 +00003727 if (const DirectoryEntry *Umbrella
Chris Lattnerb3ce3572013-01-20 02:38:54 +00003728 = PP.getFileManager().getDirectory(Blob)) {
Guy Benyei7f92f2d2012-12-18 14:30:41 +00003729 if (!CurrentModule->getUmbrellaDir())
3730 ModMap.setUmbrellaDir(CurrentModule, Umbrella);
3731 else if (CurrentModule->getUmbrellaDir() != Umbrella) {
3732 Error("mismatched umbrella directories in submodule");
3733 return true;
3734 }
3735 }
3736 break;
3737 }
3738
3739 case SUBMODULE_METADATA: {
3740 if (!First) {
3741 Error("submodule metadata record not at beginning of block");
3742 return true;
3743 }
3744 First = false;
3745
3746 F.BaseSubmoduleID = getTotalNumSubmodules();
3747 F.LocalNumSubmodules = Record[0];
3748 unsigned LocalBaseSubmoduleID = Record[1];
3749 if (F.LocalNumSubmodules > 0) {
3750 // Introduce the global -> local mapping for submodules within this
3751 // module.
3752 GlobalSubmoduleMap.insert(std::make_pair(getTotalNumSubmodules()+1,&F));
3753
3754 // Introduce the local -> global mapping for submodules within this
3755 // module.
3756 F.SubmoduleRemap.insertOrReplace(
3757 std::make_pair(LocalBaseSubmoduleID,
3758 F.BaseSubmoduleID - LocalBaseSubmoduleID));
3759
3760 SubmodulesLoaded.resize(SubmodulesLoaded.size() + F.LocalNumSubmodules);
3761 }
3762 break;
3763 }
3764
3765 case SUBMODULE_IMPORTS: {
3766 if (First) {
3767 Error("missing submodule metadata record at beginning of block");
3768 return true;
3769 }
3770
3771 if (!CurrentModule)
3772 break;
3773
3774 for (unsigned Idx = 0; Idx != Record.size(); ++Idx) {
Douglas Gregor906d66a2013-03-20 21:10:35 +00003775 UnresolvedModuleRef Unresolved;
Guy Benyei7f92f2d2012-12-18 14:30:41 +00003776 Unresolved.File = &F;
3777 Unresolved.Mod = CurrentModule;
3778 Unresolved.ID = Record[Idx];
Douglas Gregor906d66a2013-03-20 21:10:35 +00003779 Unresolved.Kind = UnresolvedModuleRef::Import;
Guy Benyei7f92f2d2012-12-18 14:30:41 +00003780 Unresolved.IsWildcard = false;
Douglas Gregor906d66a2013-03-20 21:10:35 +00003781 UnresolvedModuleRefs.push_back(Unresolved);
Guy Benyei7f92f2d2012-12-18 14:30:41 +00003782 }
3783 break;
3784 }
3785
3786 case SUBMODULE_EXPORTS: {
3787 if (First) {
3788 Error("missing submodule metadata record at beginning of block");
3789 return true;
3790 }
3791
3792 if (!CurrentModule)
3793 break;
3794
3795 for (unsigned Idx = 0; Idx + 1 < Record.size(); Idx += 2) {
Douglas Gregor906d66a2013-03-20 21:10:35 +00003796 UnresolvedModuleRef Unresolved;
Guy Benyei7f92f2d2012-12-18 14:30:41 +00003797 Unresolved.File = &F;
3798 Unresolved.Mod = CurrentModule;
3799 Unresolved.ID = Record[Idx];
Douglas Gregor906d66a2013-03-20 21:10:35 +00003800 Unresolved.Kind = UnresolvedModuleRef::Export;
Guy Benyei7f92f2d2012-12-18 14:30:41 +00003801 Unresolved.IsWildcard = Record[Idx + 1];
Douglas Gregor906d66a2013-03-20 21:10:35 +00003802 UnresolvedModuleRefs.push_back(Unresolved);
Guy Benyei7f92f2d2012-12-18 14:30:41 +00003803 }
3804
3805 // Once we've loaded the set of exports, there's no reason to keep
3806 // the parsed, unresolved exports around.
3807 CurrentModule->UnresolvedExports.clear();
3808 break;
3809 }
3810 case SUBMODULE_REQUIRES: {
3811 if (First) {
3812 Error("missing submodule metadata record at beginning of block");
3813 return true;
3814 }
3815
3816 if (!CurrentModule)
3817 break;
3818
Chris Lattnerb3ce3572013-01-20 02:38:54 +00003819 CurrentModule->addRequirement(Blob, Context.getLangOpts(),
Guy Benyei7f92f2d2012-12-18 14:30:41 +00003820 Context.getTargetInfo());
3821 break;
3822 }
Douglas Gregorb6cbe512013-01-14 17:21:00 +00003823
3824 case SUBMODULE_LINK_LIBRARY:
3825 if (First) {
3826 Error("missing submodule metadata record at beginning of block");
3827 return true;
3828 }
3829
3830 if (!CurrentModule)
3831 break;
3832
3833 CurrentModule->LinkLibraries.push_back(
Chris Lattnerb3ce3572013-01-20 02:38:54 +00003834 Module::LinkLibrary(Blob, Record[0]));
Douglas Gregorb6cbe512013-01-14 17:21:00 +00003835 break;
Douglas Gregor63a72682013-03-20 00:22:05 +00003836
3837 case SUBMODULE_CONFIG_MACRO:
3838 if (First) {
3839 Error("missing submodule metadata record at beginning of block");
3840 return true;
3841 }
3842
3843 if (!CurrentModule)
3844 break;
3845
3846 CurrentModule->ConfigMacros.push_back(Blob.str());
3847 break;
Douglas Gregor906d66a2013-03-20 21:10:35 +00003848
3849 case SUBMODULE_CONFLICT: {
3850 if (First) {
3851 Error("missing submodule metadata record at beginning of block");
3852 return true;
3853 }
3854
3855 if (!CurrentModule)
3856 break;
3857
3858 UnresolvedModuleRef Unresolved;
3859 Unresolved.File = &F;
3860 Unresolved.Mod = CurrentModule;
3861 Unresolved.ID = Record[0];
3862 Unresolved.Kind = UnresolvedModuleRef::Conflict;
3863 Unresolved.IsWildcard = false;
3864 Unresolved.String = Blob;
3865 UnresolvedModuleRefs.push_back(Unresolved);
3866 break;
3867 }
Guy Benyei7f92f2d2012-12-18 14:30:41 +00003868 }
3869 }
3870}
3871
3872/// \brief Parse the record that corresponds to a LangOptions data
3873/// structure.
3874///
3875/// This routine parses the language options from the AST file and then gives
3876/// them to the AST listener if one is set.
3877///
3878/// \returns true if the listener deems the file unacceptable, false otherwise.
3879bool ASTReader::ParseLanguageOptions(const RecordData &Record,
3880 bool Complain,
3881 ASTReaderListener &Listener) {
3882 LangOptions LangOpts;
3883 unsigned Idx = 0;
3884#define LANGOPT(Name, Bits, Default, Description) \
3885 LangOpts.Name = Record[Idx++];
3886#define ENUM_LANGOPT(Name, Type, Bits, Default, Description) \
3887 LangOpts.set##Name(static_cast<LangOptions::Type>(Record[Idx++]));
3888#include "clang/Basic/LangOptions.def"
Will Dietz4f45bc02013-01-18 11:30:38 +00003889#define SANITIZER(NAME, ID) LangOpts.Sanitize.ID = Record[Idx++];
3890#include "clang/Basic/Sanitizers.def"
Guy Benyei7f92f2d2012-12-18 14:30:41 +00003891
3892 ObjCRuntime::Kind runtimeKind = (ObjCRuntime::Kind) Record[Idx++];
3893 VersionTuple runtimeVersion = ReadVersionTuple(Record, Idx);
3894 LangOpts.ObjCRuntime = ObjCRuntime(runtimeKind, runtimeVersion);
3895
3896 unsigned Length = Record[Idx++];
3897 LangOpts.CurrentModule.assign(Record.begin() + Idx,
3898 Record.begin() + Idx + Length);
Dmitri Gribenko6ebf0912013-02-22 14:21:27 +00003899
3900 Idx += Length;
3901
3902 // Comment options.
3903 for (unsigned N = Record[Idx++]; N; --N) {
3904 LangOpts.CommentOpts.BlockCommandNames.push_back(
3905 ReadString(Record, Idx));
3906 }
Dmitri Gribenko6fd7d302013-04-10 15:35:17 +00003907 LangOpts.CommentOpts.ParseAllComments = Record[Idx++];
Dmitri Gribenko6ebf0912013-02-22 14:21:27 +00003908
Guy Benyei7f92f2d2012-12-18 14:30:41 +00003909 return Listener.ReadLanguageOptions(LangOpts, Complain);
3910}
3911
3912bool ASTReader::ParseTargetOptions(const RecordData &Record,
3913 bool Complain,
3914 ASTReaderListener &Listener) {
3915 unsigned Idx = 0;
3916 TargetOptions TargetOpts;
3917 TargetOpts.Triple = ReadString(Record, Idx);
3918 TargetOpts.CPU = ReadString(Record, Idx);
3919 TargetOpts.ABI = ReadString(Record, Idx);
3920 TargetOpts.CXXABI = ReadString(Record, Idx);
3921 TargetOpts.LinkerVersion = ReadString(Record, Idx);
3922 for (unsigned N = Record[Idx++]; N; --N) {
3923 TargetOpts.FeaturesAsWritten.push_back(ReadString(Record, Idx));
3924 }
3925 for (unsigned N = Record[Idx++]; N; --N) {
3926 TargetOpts.Features.push_back(ReadString(Record, Idx));
3927 }
3928
3929 return Listener.ReadTargetOptions(TargetOpts, Complain);
3930}
3931
3932bool ASTReader::ParseDiagnosticOptions(const RecordData &Record, bool Complain,
3933 ASTReaderListener &Listener) {
3934 DiagnosticOptions DiagOpts;
3935 unsigned Idx = 0;
3936#define DIAGOPT(Name, Bits, Default) DiagOpts.Name = Record[Idx++];
3937#define ENUM_DIAGOPT(Name, Type, Bits, Default) \
3938 DiagOpts.set##Name(static_cast<Type>(Record[Idx++]));
3939#include "clang/Basic/DiagnosticOptions.def"
3940
3941 for (unsigned N = Record[Idx++]; N; --N) {
3942 DiagOpts.Warnings.push_back(ReadString(Record, Idx));
3943 }
3944
3945 return Listener.ReadDiagnosticOptions(DiagOpts, Complain);
3946}
3947
3948bool ASTReader::ParseFileSystemOptions(const RecordData &Record, bool Complain,
3949 ASTReaderListener &Listener) {
3950 FileSystemOptions FSOpts;
3951 unsigned Idx = 0;
3952 FSOpts.WorkingDir = ReadString(Record, Idx);
3953 return Listener.ReadFileSystemOptions(FSOpts, Complain);
3954}
3955
3956bool ASTReader::ParseHeaderSearchOptions(const RecordData &Record,
3957 bool Complain,
3958 ASTReaderListener &Listener) {
3959 HeaderSearchOptions HSOpts;
3960 unsigned Idx = 0;
3961 HSOpts.Sysroot = ReadString(Record, Idx);
3962
3963 // Include entries.
3964 for (unsigned N = Record[Idx++]; N; --N) {
3965 std::string Path = ReadString(Record, Idx);
3966 frontend::IncludeDirGroup Group
3967 = static_cast<frontend::IncludeDirGroup>(Record[Idx++]);
Guy Benyei7f92f2d2012-12-18 14:30:41 +00003968 bool IsFramework = Record[Idx++];
3969 bool IgnoreSysRoot = Record[Idx++];
Guy Benyei7f92f2d2012-12-18 14:30:41 +00003970 HSOpts.UserEntries.push_back(
Daniel Dunbar59fd6352013-01-30 00:34:26 +00003971 HeaderSearchOptions::Entry(Path, Group, IsFramework, IgnoreSysRoot));
Guy Benyei7f92f2d2012-12-18 14:30:41 +00003972 }
3973
3974 // System header prefixes.
3975 for (unsigned N = Record[Idx++]; N; --N) {
3976 std::string Prefix = ReadString(Record, Idx);
3977 bool IsSystemHeader = Record[Idx++];
3978 HSOpts.SystemHeaderPrefixes.push_back(
3979 HeaderSearchOptions::SystemHeaderPrefix(Prefix, IsSystemHeader));
3980 }
3981
3982 HSOpts.ResourceDir = ReadString(Record, Idx);
3983 HSOpts.ModuleCachePath = ReadString(Record, Idx);
3984 HSOpts.DisableModuleHash = Record[Idx++];
3985 HSOpts.UseBuiltinIncludes = Record[Idx++];
3986 HSOpts.UseStandardSystemIncludes = Record[Idx++];
3987 HSOpts.UseStandardCXXIncludes = Record[Idx++];
3988 HSOpts.UseLibcxx = Record[Idx++];
3989
3990 return Listener.ReadHeaderSearchOptions(HSOpts, Complain);
3991}
3992
3993bool ASTReader::ParsePreprocessorOptions(const RecordData &Record,
3994 bool Complain,
3995 ASTReaderListener &Listener,
3996 std::string &SuggestedPredefines) {
3997 PreprocessorOptions PPOpts;
3998 unsigned Idx = 0;
3999
4000 // Macro definitions/undefs
4001 for (unsigned N = Record[Idx++]; N; --N) {
4002 std::string Macro = ReadString(Record, Idx);
4003 bool IsUndef = Record[Idx++];
4004 PPOpts.Macros.push_back(std::make_pair(Macro, IsUndef));
4005 }
4006
4007 // Includes
4008 for (unsigned N = Record[Idx++]; N; --N) {
4009 PPOpts.Includes.push_back(ReadString(Record, Idx));
4010 }
4011
4012 // Macro Includes
4013 for (unsigned N = Record[Idx++]; N; --N) {
4014 PPOpts.MacroIncludes.push_back(ReadString(Record, Idx));
4015 }
4016
4017 PPOpts.UsePredefines = Record[Idx++];
Argyrios Kyrtzidis65110ca2013-04-26 21:33:40 +00004018 PPOpts.DetailedRecord = Record[Idx++];
Guy Benyei7f92f2d2012-12-18 14:30:41 +00004019 PPOpts.ImplicitPCHInclude = ReadString(Record, Idx);
4020 PPOpts.ImplicitPTHInclude = ReadString(Record, Idx);
4021 PPOpts.ObjCXXARCStandardLibrary =
4022 static_cast<ObjCXXARCStandardLibraryKind>(Record[Idx++]);
4023 SuggestedPredefines.clear();
4024 return Listener.ReadPreprocessorOptions(PPOpts, Complain,
4025 SuggestedPredefines);
4026}
4027
4028std::pair<ModuleFile *, unsigned>
4029ASTReader::getModulePreprocessedEntity(unsigned GlobalIndex) {
4030 GlobalPreprocessedEntityMapType::iterator
4031 I = GlobalPreprocessedEntityMap.find(GlobalIndex);
4032 assert(I != GlobalPreprocessedEntityMap.end() &&
4033 "Corrupted global preprocessed entity map");
4034 ModuleFile *M = I->second;
4035 unsigned LocalIndex = GlobalIndex - M->BasePreprocessedEntityID;
4036 return std::make_pair(M, LocalIndex);
4037}
4038
4039std::pair<PreprocessingRecord::iterator, PreprocessingRecord::iterator>
4040ASTReader::getModulePreprocessedEntities(ModuleFile &Mod) const {
4041 if (PreprocessingRecord *PPRec = PP.getPreprocessingRecord())
4042 return PPRec->getIteratorsForLoadedRange(Mod.BasePreprocessedEntityID,
4043 Mod.NumPreprocessedEntities);
4044
4045 return std::make_pair(PreprocessingRecord::iterator(),
4046 PreprocessingRecord::iterator());
4047}
4048
4049std::pair<ASTReader::ModuleDeclIterator, ASTReader::ModuleDeclIterator>
4050ASTReader::getModuleFileLevelDecls(ModuleFile &Mod) {
4051 return std::make_pair(ModuleDeclIterator(this, &Mod, Mod.FileSortedDecls),
4052 ModuleDeclIterator(this, &Mod,
4053 Mod.FileSortedDecls + Mod.NumFileSortedDecls));
4054}
4055
4056PreprocessedEntity *ASTReader::ReadPreprocessedEntity(unsigned Index) {
4057 PreprocessedEntityID PPID = Index+1;
4058 std::pair<ModuleFile *, unsigned> PPInfo = getModulePreprocessedEntity(Index);
4059 ModuleFile &M = *PPInfo.first;
4060 unsigned LocalIndex = PPInfo.second;
4061 const PPEntityOffset &PPOffs = M.PreprocessedEntityOffsets[LocalIndex];
4062
Guy Benyei7f92f2d2012-12-18 14:30:41 +00004063 if (!PP.getPreprocessingRecord()) {
4064 Error("no preprocessing record");
4065 return 0;
4066 }
4067
Chris Lattner8f9a1eb2013-01-20 00:56:42 +00004068 SavedStreamPosition SavedPosition(M.PreprocessorDetailCursor);
4069 M.PreprocessorDetailCursor.JumpToBit(PPOffs.BitOffset);
4070
4071 llvm::BitstreamEntry Entry =
4072 M.PreprocessorDetailCursor.advance(BitstreamCursor::AF_DontPopBlockAtEnd);
4073 if (Entry.Kind != llvm::BitstreamEntry::Record)
4074 return 0;
4075
Guy Benyei7f92f2d2012-12-18 14:30:41 +00004076 // Read the record.
4077 SourceRange Range(ReadSourceLocation(M, PPOffs.Begin),
4078 ReadSourceLocation(M, PPOffs.End));
4079 PreprocessingRecord &PPRec = *PP.getPreprocessingRecord();
Chris Lattnerb3ce3572013-01-20 02:38:54 +00004080 StringRef Blob;
Guy Benyei7f92f2d2012-12-18 14:30:41 +00004081 RecordData Record;
4082 PreprocessorDetailRecordTypes RecType =
Chris Lattnerb3ce3572013-01-20 02:38:54 +00004083 (PreprocessorDetailRecordTypes)M.PreprocessorDetailCursor.readRecord(
4084 Entry.ID, Record, &Blob);
Guy Benyei7f92f2d2012-12-18 14:30:41 +00004085 switch (RecType) {
4086 case PPD_MACRO_EXPANSION: {
4087 bool isBuiltin = Record[0];
4088 IdentifierInfo *Name = 0;
4089 MacroDefinition *Def = 0;
4090 if (isBuiltin)
4091 Name = getLocalIdentifier(M, Record[1]);
4092 else {
4093 PreprocessedEntityID
4094 GlobalID = getGlobalPreprocessedEntityID(M, Record[1]);
4095 Def =cast<MacroDefinition>(PPRec.getLoadedPreprocessedEntity(GlobalID-1));
4096 }
4097
4098 MacroExpansion *ME;
4099 if (isBuiltin)
4100 ME = new (PPRec) MacroExpansion(Name, Range);
4101 else
4102 ME = new (PPRec) MacroExpansion(Def, Range);
4103
4104 return ME;
4105 }
4106
4107 case PPD_MACRO_DEFINITION: {
4108 // Decode the identifier info and then check again; if the macro is
4109 // still defined and associated with the identifier,
4110 IdentifierInfo *II = getLocalIdentifier(M, Record[0]);
4111 MacroDefinition *MD
4112 = new (PPRec) MacroDefinition(II, Range);
4113
4114 if (DeserializationListener)
4115 DeserializationListener->MacroDefinitionRead(PPID, MD);
4116
4117 return MD;
4118 }
4119
4120 case PPD_INCLUSION_DIRECTIVE: {
Chris Lattnerb3ce3572013-01-20 02:38:54 +00004121 const char *FullFileNameStart = Blob.data() + Record[0];
4122 StringRef FullFileName(FullFileNameStart, Blob.size() - Record[0]);
Guy Benyei7f92f2d2012-12-18 14:30:41 +00004123 const FileEntry *File = 0;
4124 if (!FullFileName.empty())
4125 File = PP.getFileManager().getFile(FullFileName);
4126
4127 // FIXME: Stable encoding
4128 InclusionDirective::InclusionKind Kind
4129 = static_cast<InclusionDirective::InclusionKind>(Record[2]);
4130 InclusionDirective *ID
4131 = new (PPRec) InclusionDirective(PPRec, Kind,
Chris Lattnerb3ce3572013-01-20 02:38:54 +00004132 StringRef(Blob.data(), Record[0]),
Guy Benyei7f92f2d2012-12-18 14:30:41 +00004133 Record[1], Record[3],
4134 File,
4135 Range);
4136 return ID;
4137 }
4138 }
4139
4140 llvm_unreachable("Invalid PreprocessorDetailRecordTypes");
4141}
4142
4143/// \brief \arg SLocMapI points at a chunk of a module that contains no
4144/// preprocessed entities or the entities it contains are not the ones we are
4145/// looking for. Find the next module that contains entities and return the ID
4146/// of the first entry.
4147PreprocessedEntityID ASTReader::findNextPreprocessedEntity(
4148 GlobalSLocOffsetMapType::const_iterator SLocMapI) const {
4149 ++SLocMapI;
4150 for (GlobalSLocOffsetMapType::const_iterator
4151 EndI = GlobalSLocOffsetMap.end(); SLocMapI != EndI; ++SLocMapI) {
4152 ModuleFile &M = *SLocMapI->second;
4153 if (M.NumPreprocessedEntities)
4154 return M.BasePreprocessedEntityID;
4155 }
4156
4157 return getTotalNumPreprocessedEntities();
4158}
4159
4160namespace {
4161
4162template <unsigned PPEntityOffset::*PPLoc>
4163struct PPEntityComp {
4164 const ASTReader &Reader;
4165 ModuleFile &M;
4166
4167 PPEntityComp(const ASTReader &Reader, ModuleFile &M) : Reader(Reader), M(M) { }
4168
4169 bool operator()(const PPEntityOffset &L, const PPEntityOffset &R) const {
4170 SourceLocation LHS = getLoc(L);
4171 SourceLocation RHS = getLoc(R);
4172 return Reader.getSourceManager().isBeforeInTranslationUnit(LHS, RHS);
4173 }
4174
4175 bool operator()(const PPEntityOffset &L, SourceLocation RHS) const {
4176 SourceLocation LHS = getLoc(L);
4177 return Reader.getSourceManager().isBeforeInTranslationUnit(LHS, RHS);
4178 }
4179
4180 bool operator()(SourceLocation LHS, const PPEntityOffset &R) const {
4181 SourceLocation RHS = getLoc(R);
4182 return Reader.getSourceManager().isBeforeInTranslationUnit(LHS, RHS);
4183 }
4184
4185 SourceLocation getLoc(const PPEntityOffset &PPE) const {
4186 return Reader.ReadSourceLocation(M, PPE.*PPLoc);
4187 }
4188};
4189
4190}
4191
4192/// \brief Returns the first preprocessed entity ID that ends after \arg BLoc.
4193PreprocessedEntityID
4194ASTReader::findBeginPreprocessedEntity(SourceLocation BLoc) const {
4195 if (SourceMgr.isLocalSourceLocation(BLoc))
4196 return getTotalNumPreprocessedEntities();
4197
4198 GlobalSLocOffsetMapType::const_iterator
4199 SLocMapI = GlobalSLocOffsetMap.find(SourceManager::MaxLoadedOffset -
Argyrios Kyrtzidisee2d5fd2013-03-08 02:32:34 +00004200 BLoc.getOffset() - 1);
Guy Benyei7f92f2d2012-12-18 14:30:41 +00004201 assert(SLocMapI != GlobalSLocOffsetMap.end() &&
4202 "Corrupted global sloc offset map");
4203
4204 if (SLocMapI->second->NumPreprocessedEntities == 0)
4205 return findNextPreprocessedEntity(SLocMapI);
4206
4207 ModuleFile &M = *SLocMapI->second;
4208 typedef const PPEntityOffset *pp_iterator;
4209 pp_iterator pp_begin = M.PreprocessedEntityOffsets;
4210 pp_iterator pp_end = pp_begin + M.NumPreprocessedEntities;
4211
4212 size_t Count = M.NumPreprocessedEntities;
4213 size_t Half;
4214 pp_iterator First = pp_begin;
4215 pp_iterator PPI;
4216
4217 // Do a binary search manually instead of using std::lower_bound because
4218 // The end locations of entities may be unordered (when a macro expansion
4219 // is inside another macro argument), but for this case it is not important
4220 // whether we get the first macro expansion or its containing macro.
4221 while (Count > 0) {
4222 Half = Count/2;
4223 PPI = First;
4224 std::advance(PPI, Half);
4225 if (SourceMgr.isBeforeInTranslationUnit(ReadSourceLocation(M, PPI->End),
4226 BLoc)){
4227 First = PPI;
4228 ++First;
4229 Count = Count - Half - 1;
4230 } else
4231 Count = Half;
4232 }
4233
4234 if (PPI == pp_end)
4235 return findNextPreprocessedEntity(SLocMapI);
4236
4237 return M.BasePreprocessedEntityID + (PPI - pp_begin);
4238}
4239
4240/// \brief Returns the first preprocessed entity ID that begins after \arg ELoc.
4241PreprocessedEntityID
4242ASTReader::findEndPreprocessedEntity(SourceLocation ELoc) const {
4243 if (SourceMgr.isLocalSourceLocation(ELoc))
4244 return getTotalNumPreprocessedEntities();
4245
4246 GlobalSLocOffsetMapType::const_iterator
4247 SLocMapI = GlobalSLocOffsetMap.find(SourceManager::MaxLoadedOffset -
Argyrios Kyrtzidisee2d5fd2013-03-08 02:32:34 +00004248 ELoc.getOffset() - 1);
Guy Benyei7f92f2d2012-12-18 14:30:41 +00004249 assert(SLocMapI != GlobalSLocOffsetMap.end() &&
4250 "Corrupted global sloc offset map");
4251
4252 if (SLocMapI->second->NumPreprocessedEntities == 0)
4253 return findNextPreprocessedEntity(SLocMapI);
4254
4255 ModuleFile &M = *SLocMapI->second;
4256 typedef const PPEntityOffset *pp_iterator;
4257 pp_iterator pp_begin = M.PreprocessedEntityOffsets;
4258 pp_iterator pp_end = pp_begin + M.NumPreprocessedEntities;
4259 pp_iterator PPI =
4260 std::upper_bound(pp_begin, pp_end, ELoc,
4261 PPEntityComp<&PPEntityOffset::Begin>(*this, M));
4262
4263 if (PPI == pp_end)
4264 return findNextPreprocessedEntity(SLocMapI);
4265
4266 return M.BasePreprocessedEntityID + (PPI - pp_begin);
4267}
4268
4269/// \brief Returns a pair of [Begin, End) indices of preallocated
4270/// preprocessed entities that \arg Range encompasses.
4271std::pair<unsigned, unsigned>
4272 ASTReader::findPreprocessedEntitiesInRange(SourceRange Range) {
4273 if (Range.isInvalid())
4274 return std::make_pair(0,0);
4275 assert(!SourceMgr.isBeforeInTranslationUnit(Range.getEnd(),Range.getBegin()));
4276
4277 PreprocessedEntityID BeginID = findBeginPreprocessedEntity(Range.getBegin());
4278 PreprocessedEntityID EndID = findEndPreprocessedEntity(Range.getEnd());
4279 return std::make_pair(BeginID, EndID);
4280}
4281
4282/// \brief Optionally returns true or false if the preallocated preprocessed
4283/// entity with index \arg Index came from file \arg FID.
David Blaikiedc84cd52013-02-20 22:23:23 +00004284Optional<bool> ASTReader::isPreprocessedEntityInFileID(unsigned Index,
Guy Benyei7f92f2d2012-12-18 14:30:41 +00004285 FileID FID) {
4286 if (FID.isInvalid())
4287 return false;
4288
4289 std::pair<ModuleFile *, unsigned> PPInfo = getModulePreprocessedEntity(Index);
4290 ModuleFile &M = *PPInfo.first;
4291 unsigned LocalIndex = PPInfo.second;
4292 const PPEntityOffset &PPOffs = M.PreprocessedEntityOffsets[LocalIndex];
4293
4294 SourceLocation Loc = ReadSourceLocation(M, PPOffs.Begin);
4295 if (Loc.isInvalid())
4296 return false;
4297
4298 if (SourceMgr.isInFileID(SourceMgr.getFileLoc(Loc), FID))
4299 return true;
4300 else
4301 return false;
4302}
4303
4304namespace {
4305 /// \brief Visitor used to search for information about a header file.
4306 class HeaderFileInfoVisitor {
Guy Benyei7f92f2d2012-12-18 14:30:41 +00004307 const FileEntry *FE;
4308
David Blaikiedc84cd52013-02-20 22:23:23 +00004309 Optional<HeaderFileInfo> HFI;
Guy Benyei7f92f2d2012-12-18 14:30:41 +00004310
4311 public:
Argyrios Kyrtzidis36592b12013-03-06 18:12:44 +00004312 explicit HeaderFileInfoVisitor(const FileEntry *FE)
4313 : FE(FE) { }
Guy Benyei7f92f2d2012-12-18 14:30:41 +00004314
4315 static bool visit(ModuleFile &M, void *UserData) {
4316 HeaderFileInfoVisitor *This
4317 = static_cast<HeaderFileInfoVisitor *>(UserData);
4318
Guy Benyei7f92f2d2012-12-18 14:30:41 +00004319 HeaderFileInfoLookupTable *Table
4320 = static_cast<HeaderFileInfoLookupTable *>(M.HeaderFileInfoTable);
4321 if (!Table)
4322 return false;
4323
4324 // Look in the on-disk hash table for an entry for this file name.
Argyrios Kyrtzidised3802e2013-03-06 18:12:47 +00004325 HeaderFileInfoLookupTable::iterator Pos = Table->find(This->FE);
Guy Benyei7f92f2d2012-12-18 14:30:41 +00004326 if (Pos == Table->end())
4327 return false;
4328
4329 This->HFI = *Pos;
4330 return true;
4331 }
4332
David Blaikiedc84cd52013-02-20 22:23:23 +00004333 Optional<HeaderFileInfo> getHeaderFileInfo() const { return HFI; }
Guy Benyei7f92f2d2012-12-18 14:30:41 +00004334 };
4335}
4336
4337HeaderFileInfo ASTReader::GetHeaderFileInfo(const FileEntry *FE) {
Argyrios Kyrtzidis36592b12013-03-06 18:12:44 +00004338 HeaderFileInfoVisitor Visitor(FE);
Guy Benyei7f92f2d2012-12-18 14:30:41 +00004339 ModuleMgr.visit(&HeaderFileInfoVisitor::visit, &Visitor);
David Blaikiedc84cd52013-02-20 22:23:23 +00004340 if (Optional<HeaderFileInfo> HFI = Visitor.getHeaderFileInfo()) {
Guy Benyei7f92f2d2012-12-18 14:30:41 +00004341 if (Listener)
4342 Listener->ReadHeaderFileInfo(*HFI, FE->getUID());
4343 return *HFI;
4344 }
4345
4346 return HeaderFileInfo();
4347}
4348
4349void ASTReader::ReadPragmaDiagnosticMappings(DiagnosticsEngine &Diag) {
4350 // FIXME: Make it work properly with modules.
Dmitri Gribenkocfa88f82013-01-12 19:30:44 +00004351 SmallVector<DiagnosticsEngine::DiagState *, 32> DiagStates;
Guy Benyei7f92f2d2012-12-18 14:30:41 +00004352 for (ModuleIterator I = ModuleMgr.begin(), E = ModuleMgr.end(); I != E; ++I) {
4353 ModuleFile &F = *(*I);
4354 unsigned Idx = 0;
4355 DiagStates.clear();
4356 assert(!Diag.DiagStates.empty());
4357 DiagStates.push_back(&Diag.DiagStates.front()); // the command-line one.
4358 while (Idx < F.PragmaDiagMappings.size()) {
4359 SourceLocation Loc = ReadSourceLocation(F, F.PragmaDiagMappings[Idx++]);
4360 unsigned DiagStateID = F.PragmaDiagMappings[Idx++];
4361 if (DiagStateID != 0) {
4362 Diag.DiagStatePoints.push_back(
4363 DiagnosticsEngine::DiagStatePoint(DiagStates[DiagStateID-1],
4364 FullSourceLoc(Loc, SourceMgr)));
4365 continue;
4366 }
4367
4368 assert(DiagStateID == 0);
4369 // A new DiagState was created here.
4370 Diag.DiagStates.push_back(*Diag.GetCurDiagState());
4371 DiagnosticsEngine::DiagState *NewState = &Diag.DiagStates.back();
4372 DiagStates.push_back(NewState);
4373 Diag.DiagStatePoints.push_back(
4374 DiagnosticsEngine::DiagStatePoint(NewState,
4375 FullSourceLoc(Loc, SourceMgr)));
4376 while (1) {
4377 assert(Idx < F.PragmaDiagMappings.size() &&
4378 "Invalid data, didn't find '-1' marking end of diag/map pairs");
4379 if (Idx >= F.PragmaDiagMappings.size()) {
4380 break; // Something is messed up but at least avoid infinite loop in
4381 // release build.
4382 }
4383 unsigned DiagID = F.PragmaDiagMappings[Idx++];
4384 if (DiagID == (unsigned)-1) {
4385 break; // no more diag/map pairs for this location.
4386 }
4387 diag::Mapping Map = (diag::Mapping)F.PragmaDiagMappings[Idx++];
4388 DiagnosticMappingInfo MappingInfo = Diag.makeMappingInfo(Map, Loc);
4389 Diag.GetCurDiagState()->setMappingInfo(DiagID, MappingInfo);
4390 }
4391 }
4392 }
4393}
4394
4395/// \brief Get the correct cursor and offset for loading a type.
4396ASTReader::RecordLocation ASTReader::TypeCursorForIndex(unsigned Index) {
4397 GlobalTypeMapType::iterator I = GlobalTypeMap.find(Index);
4398 assert(I != GlobalTypeMap.end() && "Corrupted global type map");
4399 ModuleFile *M = I->second;
4400 return RecordLocation(M, M->TypeOffsets[Index - M->BaseTypeIndex]);
4401}
4402
4403/// \brief Read and return the type with the given index..
4404///
4405/// The index is the type ID, shifted and minus the number of predefs. This
4406/// routine actually reads the record corresponding to the type at the given
4407/// location. It is a helper routine for GetType, which deals with reading type
4408/// IDs.
4409QualType ASTReader::readTypeRecord(unsigned Index) {
4410 RecordLocation Loc = TypeCursorForIndex(Index);
Chris Lattner8f9a1eb2013-01-20 00:56:42 +00004411 BitstreamCursor &DeclsCursor = Loc.F->DeclsCursor;
Guy Benyei7f92f2d2012-12-18 14:30:41 +00004412
4413 // Keep track of where we are in the stream, then jump back there
4414 // after reading this type.
4415 SavedStreamPosition SavedPosition(DeclsCursor);
4416
4417 ReadingKindTracker ReadingKind(Read_Type, *this);
4418
4419 // Note that we are loading a type record.
4420 Deserializing AType(this);
4421
4422 unsigned Idx = 0;
4423 DeclsCursor.JumpToBit(Loc.Offset);
4424 RecordData Record;
4425 unsigned Code = DeclsCursor.ReadCode();
Chris Lattnerb3ce3572013-01-20 02:38:54 +00004426 switch ((TypeCode)DeclsCursor.readRecord(Code, Record)) {
Guy Benyei7f92f2d2012-12-18 14:30:41 +00004427 case TYPE_EXT_QUAL: {
4428 if (Record.size() != 2) {
4429 Error("Incorrect encoding of extended qualifier type");
4430 return QualType();
4431 }
4432 QualType Base = readType(*Loc.F, Record, Idx);
4433 Qualifiers Quals = Qualifiers::fromOpaqueValue(Record[Idx++]);
4434 return Context.getQualifiedType(Base, Quals);
4435 }
4436
4437 case TYPE_COMPLEX: {
4438 if (Record.size() != 1) {
4439 Error("Incorrect encoding of complex type");
4440 return QualType();
4441 }
4442 QualType ElemType = readType(*Loc.F, Record, Idx);
4443 return Context.getComplexType(ElemType);
4444 }
4445
4446 case TYPE_POINTER: {
4447 if (Record.size() != 1) {
4448 Error("Incorrect encoding of pointer type");
4449 return QualType();
4450 }
4451 QualType PointeeType = readType(*Loc.F, Record, Idx);
4452 return Context.getPointerType(PointeeType);
4453 }
4454
4455 case TYPE_BLOCK_POINTER: {
4456 if (Record.size() != 1) {
4457 Error("Incorrect encoding of block pointer type");
4458 return QualType();
4459 }
4460 QualType PointeeType = readType(*Loc.F, Record, Idx);
4461 return Context.getBlockPointerType(PointeeType);
4462 }
4463
4464 case TYPE_LVALUE_REFERENCE: {
4465 if (Record.size() != 2) {
4466 Error("Incorrect encoding of lvalue reference type");
4467 return QualType();
4468 }
4469 QualType PointeeType = readType(*Loc.F, Record, Idx);
4470 return Context.getLValueReferenceType(PointeeType, Record[1]);
4471 }
4472
4473 case TYPE_RVALUE_REFERENCE: {
4474 if (Record.size() != 1) {
4475 Error("Incorrect encoding of rvalue reference type");
4476 return QualType();
4477 }
4478 QualType PointeeType = readType(*Loc.F, Record, Idx);
4479 return Context.getRValueReferenceType(PointeeType);
4480 }
4481
4482 case TYPE_MEMBER_POINTER: {
4483 if (Record.size() != 2) {
4484 Error("Incorrect encoding of member pointer type");
4485 return QualType();
4486 }
4487 QualType PointeeType = readType(*Loc.F, Record, Idx);
4488 QualType ClassType = readType(*Loc.F, Record, Idx);
4489 if (PointeeType.isNull() || ClassType.isNull())
4490 return QualType();
4491
4492 return Context.getMemberPointerType(PointeeType, ClassType.getTypePtr());
4493 }
4494
4495 case TYPE_CONSTANT_ARRAY: {
4496 QualType ElementType = readType(*Loc.F, Record, Idx);
4497 ArrayType::ArraySizeModifier ASM = (ArrayType::ArraySizeModifier)Record[1];
4498 unsigned IndexTypeQuals = Record[2];
4499 unsigned Idx = 3;
4500 llvm::APInt Size = ReadAPInt(Record, Idx);
4501 return Context.getConstantArrayType(ElementType, Size,
4502 ASM, IndexTypeQuals);
4503 }
4504
4505 case TYPE_INCOMPLETE_ARRAY: {
4506 QualType ElementType = readType(*Loc.F, Record, Idx);
4507 ArrayType::ArraySizeModifier ASM = (ArrayType::ArraySizeModifier)Record[1];
4508 unsigned IndexTypeQuals = Record[2];
4509 return Context.getIncompleteArrayType(ElementType, ASM, IndexTypeQuals);
4510 }
4511
4512 case TYPE_VARIABLE_ARRAY: {
4513 QualType ElementType = readType(*Loc.F, Record, Idx);
4514 ArrayType::ArraySizeModifier ASM = (ArrayType::ArraySizeModifier)Record[1];
4515 unsigned IndexTypeQuals = Record[2];
4516 SourceLocation LBLoc = ReadSourceLocation(*Loc.F, Record[3]);
4517 SourceLocation RBLoc = ReadSourceLocation(*Loc.F, Record[4]);
4518 return Context.getVariableArrayType(ElementType, ReadExpr(*Loc.F),
4519 ASM, IndexTypeQuals,
4520 SourceRange(LBLoc, RBLoc));
4521 }
4522
4523 case TYPE_VECTOR: {
4524 if (Record.size() != 3) {
4525 Error("incorrect encoding of vector type in AST file");
4526 return QualType();
4527 }
4528
4529 QualType ElementType = readType(*Loc.F, Record, Idx);
4530 unsigned NumElements = Record[1];
4531 unsigned VecKind = Record[2];
4532 return Context.getVectorType(ElementType, NumElements,
4533 (VectorType::VectorKind)VecKind);
4534 }
4535
4536 case TYPE_EXT_VECTOR: {
4537 if (Record.size() != 3) {
4538 Error("incorrect encoding of extended vector type in AST file");
4539 return QualType();
4540 }
4541
4542 QualType ElementType = readType(*Loc.F, Record, Idx);
4543 unsigned NumElements = Record[1];
4544 return Context.getExtVectorType(ElementType, NumElements);
4545 }
4546
4547 case TYPE_FUNCTION_NO_PROTO: {
4548 if (Record.size() != 6) {
4549 Error("incorrect encoding of no-proto function type");
4550 return QualType();
4551 }
4552 QualType ResultType = readType(*Loc.F, Record, Idx);
4553 FunctionType::ExtInfo Info(Record[1], Record[2], Record[3],
4554 (CallingConv)Record[4], Record[5]);
4555 return Context.getFunctionNoProtoType(ResultType, Info);
4556 }
4557
4558 case TYPE_FUNCTION_PROTO: {
4559 QualType ResultType = readType(*Loc.F, Record, Idx);
4560
4561 FunctionProtoType::ExtProtoInfo EPI;
4562 EPI.ExtInfo = FunctionType::ExtInfo(/*noreturn*/ Record[1],
4563 /*hasregparm*/ Record[2],
4564 /*regparm*/ Record[3],
4565 static_cast<CallingConv>(Record[4]),
4566 /*produces*/ Record[5]);
4567
4568 unsigned Idx = 6;
4569 unsigned NumParams = Record[Idx++];
4570 SmallVector<QualType, 16> ParamTypes;
4571 for (unsigned I = 0; I != NumParams; ++I)
4572 ParamTypes.push_back(readType(*Loc.F, Record, Idx));
4573
4574 EPI.Variadic = Record[Idx++];
4575 EPI.HasTrailingReturn = Record[Idx++];
4576 EPI.TypeQuals = Record[Idx++];
4577 EPI.RefQualifier = static_cast<RefQualifierKind>(Record[Idx++]);
4578 ExceptionSpecificationType EST =
4579 static_cast<ExceptionSpecificationType>(Record[Idx++]);
4580 EPI.ExceptionSpecType = EST;
4581 SmallVector<QualType, 2> Exceptions;
4582 if (EST == EST_Dynamic) {
4583 EPI.NumExceptions = Record[Idx++];
4584 for (unsigned I = 0; I != EPI.NumExceptions; ++I)
4585 Exceptions.push_back(readType(*Loc.F, Record, Idx));
4586 EPI.Exceptions = Exceptions.data();
4587 } else if (EST == EST_ComputedNoexcept) {
4588 EPI.NoexceptExpr = ReadExpr(*Loc.F);
4589 } else if (EST == EST_Uninstantiated) {
4590 EPI.ExceptionSpecDecl = ReadDeclAs<FunctionDecl>(*Loc.F, Record, Idx);
4591 EPI.ExceptionSpecTemplate = ReadDeclAs<FunctionDecl>(*Loc.F, Record, Idx);
4592 } else if (EST == EST_Unevaluated) {
4593 EPI.ExceptionSpecDecl = ReadDeclAs<FunctionDecl>(*Loc.F, Record, Idx);
4594 }
Jordan Rosebea522f2013-03-08 21:51:21 +00004595 return Context.getFunctionType(ResultType, ParamTypes, EPI);
Guy Benyei7f92f2d2012-12-18 14:30:41 +00004596 }
4597
4598 case TYPE_UNRESOLVED_USING: {
4599 unsigned Idx = 0;
4600 return Context.getTypeDeclType(
4601 ReadDeclAs<UnresolvedUsingTypenameDecl>(*Loc.F, Record, Idx));
4602 }
4603
4604 case TYPE_TYPEDEF: {
4605 if (Record.size() != 2) {
4606 Error("incorrect encoding of typedef type");
4607 return QualType();
4608 }
4609 unsigned Idx = 0;
4610 TypedefNameDecl *Decl = ReadDeclAs<TypedefNameDecl>(*Loc.F, Record, Idx);
4611 QualType Canonical = readType(*Loc.F, Record, Idx);
4612 if (!Canonical.isNull())
4613 Canonical = Context.getCanonicalType(Canonical);
4614 return Context.getTypedefType(Decl, Canonical);
4615 }
4616
4617 case TYPE_TYPEOF_EXPR:
4618 return Context.getTypeOfExprType(ReadExpr(*Loc.F));
4619
4620 case TYPE_TYPEOF: {
4621 if (Record.size() != 1) {
4622 Error("incorrect encoding of typeof(type) in AST file");
4623 return QualType();
4624 }
4625 QualType UnderlyingType = readType(*Loc.F, Record, Idx);
4626 return Context.getTypeOfType(UnderlyingType);
4627 }
4628
4629 case TYPE_DECLTYPE: {
4630 QualType UnderlyingType = readType(*Loc.F, Record, Idx);
4631 return Context.getDecltypeType(ReadExpr(*Loc.F), UnderlyingType);
4632 }
4633
4634 case TYPE_UNARY_TRANSFORM: {
4635 QualType BaseType = readType(*Loc.F, Record, Idx);
4636 QualType UnderlyingType = readType(*Loc.F, Record, Idx);
4637 UnaryTransformType::UTTKind UKind = (UnaryTransformType::UTTKind)Record[2];
4638 return Context.getUnaryTransformType(BaseType, UnderlyingType, UKind);
4639 }
4640
Richard Smitha2c36462013-04-26 16:15:35 +00004641 case TYPE_AUTO: {
4642 QualType Deduced = readType(*Loc.F, Record, Idx);
4643 bool IsDecltypeAuto = Record[Idx++];
Richard Smithdc7a4f52013-04-30 13:56:41 +00004644 bool IsDependent = Deduced.isNull() ? Record[Idx++] : false;
4645 return Context.getAutoType(Deduced, IsDecltypeAuto, IsDependent);
Richard Smitha2c36462013-04-26 16:15:35 +00004646 }
Guy Benyei7f92f2d2012-12-18 14:30:41 +00004647
4648 case TYPE_RECORD: {
4649 if (Record.size() != 2) {
4650 Error("incorrect encoding of record type");
4651 return QualType();
4652 }
4653 unsigned Idx = 0;
4654 bool IsDependent = Record[Idx++];
4655 RecordDecl *RD = ReadDeclAs<RecordDecl>(*Loc.F, Record, Idx);
4656 RD = cast_or_null<RecordDecl>(RD->getCanonicalDecl());
4657 QualType T = Context.getRecordType(RD);
4658 const_cast<Type*>(T.getTypePtr())->setDependent(IsDependent);
4659 return T;
4660 }
4661
4662 case TYPE_ENUM: {
4663 if (Record.size() != 2) {
4664 Error("incorrect encoding of enum type");
4665 return QualType();
4666 }
4667 unsigned Idx = 0;
4668 bool IsDependent = Record[Idx++];
4669 QualType T
4670 = Context.getEnumType(ReadDeclAs<EnumDecl>(*Loc.F, Record, Idx));
4671 const_cast<Type*>(T.getTypePtr())->setDependent(IsDependent);
4672 return T;
4673 }
4674
4675 case TYPE_ATTRIBUTED: {
4676 if (Record.size() != 3) {
4677 Error("incorrect encoding of attributed type");
4678 return QualType();
4679 }
4680 QualType modifiedType = readType(*Loc.F, Record, Idx);
4681 QualType equivalentType = readType(*Loc.F, Record, Idx);
4682 AttributedType::Kind kind = static_cast<AttributedType::Kind>(Record[2]);
4683 return Context.getAttributedType(kind, modifiedType, equivalentType);
4684 }
4685
4686 case TYPE_PAREN: {
4687 if (Record.size() != 1) {
4688 Error("incorrect encoding of paren type");
4689 return QualType();
4690 }
4691 QualType InnerType = readType(*Loc.F, Record, Idx);
4692 return Context.getParenType(InnerType);
4693 }
4694
4695 case TYPE_PACK_EXPANSION: {
4696 if (Record.size() != 2) {
4697 Error("incorrect encoding of pack expansion type");
4698 return QualType();
4699 }
4700 QualType Pattern = readType(*Loc.F, Record, Idx);
4701 if (Pattern.isNull())
4702 return QualType();
David Blaikiedc84cd52013-02-20 22:23:23 +00004703 Optional<unsigned> NumExpansions;
Guy Benyei7f92f2d2012-12-18 14:30:41 +00004704 if (Record[1])
4705 NumExpansions = Record[1] - 1;
4706 return Context.getPackExpansionType(Pattern, NumExpansions);
4707 }
4708
4709 case TYPE_ELABORATED: {
4710 unsigned Idx = 0;
4711 ElaboratedTypeKeyword Keyword = (ElaboratedTypeKeyword)Record[Idx++];
4712 NestedNameSpecifier *NNS = ReadNestedNameSpecifier(*Loc.F, Record, Idx);
4713 QualType NamedType = readType(*Loc.F, Record, Idx);
4714 return Context.getElaboratedType(Keyword, NNS, NamedType);
4715 }
4716
4717 case TYPE_OBJC_INTERFACE: {
4718 unsigned Idx = 0;
4719 ObjCInterfaceDecl *ItfD
4720 = ReadDeclAs<ObjCInterfaceDecl>(*Loc.F, Record, Idx);
4721 return Context.getObjCInterfaceType(ItfD->getCanonicalDecl());
4722 }
4723
4724 case TYPE_OBJC_OBJECT: {
4725 unsigned Idx = 0;
4726 QualType Base = readType(*Loc.F, Record, Idx);
4727 unsigned NumProtos = Record[Idx++];
4728 SmallVector<ObjCProtocolDecl*, 4> Protos;
4729 for (unsigned I = 0; I != NumProtos; ++I)
4730 Protos.push_back(ReadDeclAs<ObjCProtocolDecl>(*Loc.F, Record, Idx));
4731 return Context.getObjCObjectType(Base, Protos.data(), NumProtos);
4732 }
4733
4734 case TYPE_OBJC_OBJECT_POINTER: {
4735 unsigned Idx = 0;
4736 QualType Pointee = readType(*Loc.F, Record, Idx);
4737 return Context.getObjCObjectPointerType(Pointee);
4738 }
4739
4740 case TYPE_SUBST_TEMPLATE_TYPE_PARM: {
4741 unsigned Idx = 0;
4742 QualType Parm = readType(*Loc.F, Record, Idx);
4743 QualType Replacement = readType(*Loc.F, Record, Idx);
4744 return
4745 Context.getSubstTemplateTypeParmType(cast<TemplateTypeParmType>(Parm),
4746 Replacement);
4747 }
4748
4749 case TYPE_SUBST_TEMPLATE_TYPE_PARM_PACK: {
4750 unsigned Idx = 0;
4751 QualType Parm = readType(*Loc.F, Record, Idx);
4752 TemplateArgument ArgPack = ReadTemplateArgument(*Loc.F, Record, Idx);
4753 return Context.getSubstTemplateTypeParmPackType(
4754 cast<TemplateTypeParmType>(Parm),
4755 ArgPack);
4756 }
4757
4758 case TYPE_INJECTED_CLASS_NAME: {
4759 CXXRecordDecl *D = ReadDeclAs<CXXRecordDecl>(*Loc.F, Record, Idx);
4760 QualType TST = readType(*Loc.F, Record, Idx); // probably derivable
4761 // FIXME: ASTContext::getInjectedClassNameType is not currently suitable
4762 // for AST reading, too much interdependencies.
4763 return
4764 QualType(new (Context, TypeAlignment) InjectedClassNameType(D, TST), 0);
4765 }
4766
4767 case TYPE_TEMPLATE_TYPE_PARM: {
4768 unsigned Idx = 0;
4769 unsigned Depth = Record[Idx++];
4770 unsigned Index = Record[Idx++];
4771 bool Pack = Record[Idx++];
4772 TemplateTypeParmDecl *D
4773 = ReadDeclAs<TemplateTypeParmDecl>(*Loc.F, Record, Idx);
4774 return Context.getTemplateTypeParmType(Depth, Index, Pack, D);
4775 }
4776
4777 case TYPE_DEPENDENT_NAME: {
4778 unsigned Idx = 0;
4779 ElaboratedTypeKeyword Keyword = (ElaboratedTypeKeyword)Record[Idx++];
4780 NestedNameSpecifier *NNS = ReadNestedNameSpecifier(*Loc.F, Record, Idx);
4781 const IdentifierInfo *Name = this->GetIdentifierInfo(*Loc.F, Record, Idx);
4782 QualType Canon = readType(*Loc.F, Record, Idx);
4783 if (!Canon.isNull())
4784 Canon = Context.getCanonicalType(Canon);
4785 return Context.getDependentNameType(Keyword, NNS, Name, Canon);
4786 }
4787
4788 case TYPE_DEPENDENT_TEMPLATE_SPECIALIZATION: {
4789 unsigned Idx = 0;
4790 ElaboratedTypeKeyword Keyword = (ElaboratedTypeKeyword)Record[Idx++];
4791 NestedNameSpecifier *NNS = ReadNestedNameSpecifier(*Loc.F, Record, Idx);
4792 const IdentifierInfo *Name = this->GetIdentifierInfo(*Loc.F, Record, Idx);
4793 unsigned NumArgs = Record[Idx++];
4794 SmallVector<TemplateArgument, 8> Args;
4795 Args.reserve(NumArgs);
4796 while (NumArgs--)
4797 Args.push_back(ReadTemplateArgument(*Loc.F, Record, Idx));
4798 return Context.getDependentTemplateSpecializationType(Keyword, NNS, Name,
4799 Args.size(), Args.data());
4800 }
4801
4802 case TYPE_DEPENDENT_SIZED_ARRAY: {
4803 unsigned Idx = 0;
4804
4805 // ArrayType
4806 QualType ElementType = readType(*Loc.F, Record, Idx);
4807 ArrayType::ArraySizeModifier ASM
4808 = (ArrayType::ArraySizeModifier)Record[Idx++];
4809 unsigned IndexTypeQuals = Record[Idx++];
4810
4811 // DependentSizedArrayType
4812 Expr *NumElts = ReadExpr(*Loc.F);
4813 SourceRange Brackets = ReadSourceRange(*Loc.F, Record, Idx);
4814
4815 return Context.getDependentSizedArrayType(ElementType, NumElts, ASM,
4816 IndexTypeQuals, Brackets);
4817 }
4818
4819 case TYPE_TEMPLATE_SPECIALIZATION: {
4820 unsigned Idx = 0;
4821 bool IsDependent = Record[Idx++];
4822 TemplateName Name = ReadTemplateName(*Loc.F, Record, Idx);
4823 SmallVector<TemplateArgument, 8> Args;
4824 ReadTemplateArgumentList(Args, *Loc.F, Record, Idx);
4825 QualType Underlying = readType(*Loc.F, Record, Idx);
4826 QualType T;
4827 if (Underlying.isNull())
4828 T = Context.getCanonicalTemplateSpecializationType(Name, Args.data(),
4829 Args.size());
4830 else
4831 T = Context.getTemplateSpecializationType(Name, Args.data(),
4832 Args.size(), Underlying);
4833 const_cast<Type*>(T.getTypePtr())->setDependent(IsDependent);
4834 return T;
4835 }
4836
4837 case TYPE_ATOMIC: {
4838 if (Record.size() != 1) {
4839 Error("Incorrect encoding of atomic type");
4840 return QualType();
4841 }
4842 QualType ValueType = readType(*Loc.F, Record, Idx);
4843 return Context.getAtomicType(ValueType);
4844 }
4845 }
4846 llvm_unreachable("Invalid TypeCode!");
4847}
4848
4849class clang::TypeLocReader : public TypeLocVisitor<TypeLocReader> {
4850 ASTReader &Reader;
4851 ModuleFile &F;
4852 const ASTReader::RecordData &Record;
4853 unsigned &Idx;
4854
4855 SourceLocation ReadSourceLocation(const ASTReader::RecordData &R,
4856 unsigned &I) {
4857 return Reader.ReadSourceLocation(F, R, I);
4858 }
4859
4860 template<typename T>
4861 T *ReadDeclAs(const ASTReader::RecordData &Record, unsigned &Idx) {
4862 return Reader.ReadDeclAs<T>(F, Record, Idx);
4863 }
4864
4865public:
4866 TypeLocReader(ASTReader &Reader, ModuleFile &F,
4867 const ASTReader::RecordData &Record, unsigned &Idx)
4868 : Reader(Reader), F(F), Record(Record), Idx(Idx)
4869 { }
4870
4871 // We want compile-time assurance that we've enumerated all of
4872 // these, so unfortunately we have to declare them first, then
4873 // define them out-of-line.
4874#define ABSTRACT_TYPELOC(CLASS, PARENT)
4875#define TYPELOC(CLASS, PARENT) \
4876 void Visit##CLASS##TypeLoc(CLASS##TypeLoc TyLoc);
4877#include "clang/AST/TypeLocNodes.def"
4878
4879 void VisitFunctionTypeLoc(FunctionTypeLoc);
4880 void VisitArrayTypeLoc(ArrayTypeLoc);
4881};
4882
4883void TypeLocReader::VisitQualifiedTypeLoc(QualifiedTypeLoc TL) {
4884 // nothing to do
4885}
4886void TypeLocReader::VisitBuiltinTypeLoc(BuiltinTypeLoc TL) {
4887 TL.setBuiltinLoc(ReadSourceLocation(Record, Idx));
4888 if (TL.needsExtraLocalData()) {
4889 TL.setWrittenTypeSpec(static_cast<DeclSpec::TST>(Record[Idx++]));
4890 TL.setWrittenSignSpec(static_cast<DeclSpec::TSS>(Record[Idx++]));
4891 TL.setWrittenWidthSpec(static_cast<DeclSpec::TSW>(Record[Idx++]));
4892 TL.setModeAttr(Record[Idx++]);
4893 }
4894}
4895void TypeLocReader::VisitComplexTypeLoc(ComplexTypeLoc TL) {
4896 TL.setNameLoc(ReadSourceLocation(Record, Idx));
4897}
4898void TypeLocReader::VisitPointerTypeLoc(PointerTypeLoc TL) {
4899 TL.setStarLoc(ReadSourceLocation(Record, Idx));
4900}
4901void TypeLocReader::VisitBlockPointerTypeLoc(BlockPointerTypeLoc TL) {
4902 TL.setCaretLoc(ReadSourceLocation(Record, Idx));
4903}
4904void TypeLocReader::VisitLValueReferenceTypeLoc(LValueReferenceTypeLoc TL) {
4905 TL.setAmpLoc(ReadSourceLocation(Record, Idx));
4906}
4907void TypeLocReader::VisitRValueReferenceTypeLoc(RValueReferenceTypeLoc TL) {
4908 TL.setAmpAmpLoc(ReadSourceLocation(Record, Idx));
4909}
4910void TypeLocReader::VisitMemberPointerTypeLoc(MemberPointerTypeLoc TL) {
4911 TL.setStarLoc(ReadSourceLocation(Record, Idx));
4912 TL.setClassTInfo(Reader.GetTypeSourceInfo(F, Record, Idx));
4913}
4914void TypeLocReader::VisitArrayTypeLoc(ArrayTypeLoc TL) {
4915 TL.setLBracketLoc(ReadSourceLocation(Record, Idx));
4916 TL.setRBracketLoc(ReadSourceLocation(Record, Idx));
4917 if (Record[Idx++])
4918 TL.setSizeExpr(Reader.ReadExpr(F));
4919 else
4920 TL.setSizeExpr(0);
4921}
4922void TypeLocReader::VisitConstantArrayTypeLoc(ConstantArrayTypeLoc TL) {
4923 VisitArrayTypeLoc(TL);
4924}
4925void TypeLocReader::VisitIncompleteArrayTypeLoc(IncompleteArrayTypeLoc TL) {
4926 VisitArrayTypeLoc(TL);
4927}
4928void TypeLocReader::VisitVariableArrayTypeLoc(VariableArrayTypeLoc TL) {
4929 VisitArrayTypeLoc(TL);
4930}
4931void TypeLocReader::VisitDependentSizedArrayTypeLoc(
4932 DependentSizedArrayTypeLoc TL) {
4933 VisitArrayTypeLoc(TL);
4934}
4935void TypeLocReader::VisitDependentSizedExtVectorTypeLoc(
4936 DependentSizedExtVectorTypeLoc TL) {
4937 TL.setNameLoc(ReadSourceLocation(Record, Idx));
4938}
4939void TypeLocReader::VisitVectorTypeLoc(VectorTypeLoc TL) {
4940 TL.setNameLoc(ReadSourceLocation(Record, Idx));
4941}
4942void TypeLocReader::VisitExtVectorTypeLoc(ExtVectorTypeLoc TL) {
4943 TL.setNameLoc(ReadSourceLocation(Record, Idx));
4944}
4945void TypeLocReader::VisitFunctionTypeLoc(FunctionTypeLoc TL) {
4946 TL.setLocalRangeBegin(ReadSourceLocation(Record, Idx));
4947 TL.setLParenLoc(ReadSourceLocation(Record, Idx));
4948 TL.setRParenLoc(ReadSourceLocation(Record, Idx));
4949 TL.setLocalRangeEnd(ReadSourceLocation(Record, Idx));
4950 for (unsigned i = 0, e = TL.getNumArgs(); i != e; ++i) {
4951 TL.setArg(i, ReadDeclAs<ParmVarDecl>(Record, Idx));
4952 }
4953}
4954void TypeLocReader::VisitFunctionProtoTypeLoc(FunctionProtoTypeLoc TL) {
4955 VisitFunctionTypeLoc(TL);
4956}
4957void TypeLocReader::VisitFunctionNoProtoTypeLoc(FunctionNoProtoTypeLoc TL) {
4958 VisitFunctionTypeLoc(TL);
4959}
4960void TypeLocReader::VisitUnresolvedUsingTypeLoc(UnresolvedUsingTypeLoc TL) {
4961 TL.setNameLoc(ReadSourceLocation(Record, Idx));
4962}
4963void TypeLocReader::VisitTypedefTypeLoc(TypedefTypeLoc TL) {
4964 TL.setNameLoc(ReadSourceLocation(Record, Idx));
4965}
4966void TypeLocReader::VisitTypeOfExprTypeLoc(TypeOfExprTypeLoc TL) {
4967 TL.setTypeofLoc(ReadSourceLocation(Record, Idx));
4968 TL.setLParenLoc(ReadSourceLocation(Record, Idx));
4969 TL.setRParenLoc(ReadSourceLocation(Record, Idx));
4970}
4971void TypeLocReader::VisitTypeOfTypeLoc(TypeOfTypeLoc TL) {
4972 TL.setTypeofLoc(ReadSourceLocation(Record, Idx));
4973 TL.setLParenLoc(ReadSourceLocation(Record, Idx));
4974 TL.setRParenLoc(ReadSourceLocation(Record, Idx));
4975 TL.setUnderlyingTInfo(Reader.GetTypeSourceInfo(F, Record, Idx));
4976}
4977void TypeLocReader::VisitDecltypeTypeLoc(DecltypeTypeLoc TL) {
4978 TL.setNameLoc(ReadSourceLocation(Record, Idx));
4979}
4980void TypeLocReader::VisitUnaryTransformTypeLoc(UnaryTransformTypeLoc TL) {
4981 TL.setKWLoc(ReadSourceLocation(Record, Idx));
4982 TL.setLParenLoc(ReadSourceLocation(Record, Idx));
4983 TL.setRParenLoc(ReadSourceLocation(Record, Idx));
4984 TL.setUnderlyingTInfo(Reader.GetTypeSourceInfo(F, Record, Idx));
4985}
4986void TypeLocReader::VisitAutoTypeLoc(AutoTypeLoc TL) {
4987 TL.setNameLoc(ReadSourceLocation(Record, Idx));
4988}
4989void TypeLocReader::VisitRecordTypeLoc(RecordTypeLoc TL) {
4990 TL.setNameLoc(ReadSourceLocation(Record, Idx));
4991}
4992void TypeLocReader::VisitEnumTypeLoc(EnumTypeLoc TL) {
4993 TL.setNameLoc(ReadSourceLocation(Record, Idx));
4994}
4995void TypeLocReader::VisitAttributedTypeLoc(AttributedTypeLoc TL) {
4996 TL.setAttrNameLoc(ReadSourceLocation(Record, Idx));
4997 if (TL.hasAttrOperand()) {
4998 SourceRange range;
4999 range.setBegin(ReadSourceLocation(Record, Idx));
5000 range.setEnd(ReadSourceLocation(Record, Idx));
5001 TL.setAttrOperandParensRange(range);
5002 }
5003 if (TL.hasAttrExprOperand()) {
5004 if (Record[Idx++])
5005 TL.setAttrExprOperand(Reader.ReadExpr(F));
5006 else
5007 TL.setAttrExprOperand(0);
5008 } else if (TL.hasAttrEnumOperand())
5009 TL.setAttrEnumOperandLoc(ReadSourceLocation(Record, Idx));
5010}
5011void TypeLocReader::VisitTemplateTypeParmTypeLoc(TemplateTypeParmTypeLoc TL) {
5012 TL.setNameLoc(ReadSourceLocation(Record, Idx));
5013}
5014void TypeLocReader::VisitSubstTemplateTypeParmTypeLoc(
5015 SubstTemplateTypeParmTypeLoc TL) {
5016 TL.setNameLoc(ReadSourceLocation(Record, Idx));
5017}
5018void TypeLocReader::VisitSubstTemplateTypeParmPackTypeLoc(
5019 SubstTemplateTypeParmPackTypeLoc TL) {
5020 TL.setNameLoc(ReadSourceLocation(Record, Idx));
5021}
5022void TypeLocReader::VisitTemplateSpecializationTypeLoc(
5023 TemplateSpecializationTypeLoc TL) {
5024 TL.setTemplateKeywordLoc(ReadSourceLocation(Record, Idx));
5025 TL.setTemplateNameLoc(ReadSourceLocation(Record, Idx));
5026 TL.setLAngleLoc(ReadSourceLocation(Record, Idx));
5027 TL.setRAngleLoc(ReadSourceLocation(Record, Idx));
5028 for (unsigned i = 0, e = TL.getNumArgs(); i != e; ++i)
5029 TL.setArgLocInfo(i,
5030 Reader.GetTemplateArgumentLocInfo(F,
5031 TL.getTypePtr()->getArg(i).getKind(),
5032 Record, Idx));
5033}
5034void TypeLocReader::VisitParenTypeLoc(ParenTypeLoc TL) {
5035 TL.setLParenLoc(ReadSourceLocation(Record, Idx));
5036 TL.setRParenLoc(ReadSourceLocation(Record, Idx));
5037}
5038void TypeLocReader::VisitElaboratedTypeLoc(ElaboratedTypeLoc TL) {
5039 TL.setElaboratedKeywordLoc(ReadSourceLocation(Record, Idx));
5040 TL.setQualifierLoc(Reader.ReadNestedNameSpecifierLoc(F, Record, Idx));
5041}
5042void TypeLocReader::VisitInjectedClassNameTypeLoc(InjectedClassNameTypeLoc TL) {
5043 TL.setNameLoc(ReadSourceLocation(Record, Idx));
5044}
5045void TypeLocReader::VisitDependentNameTypeLoc(DependentNameTypeLoc TL) {
5046 TL.setElaboratedKeywordLoc(ReadSourceLocation(Record, Idx));
5047 TL.setQualifierLoc(Reader.ReadNestedNameSpecifierLoc(F, Record, Idx));
5048 TL.setNameLoc(ReadSourceLocation(Record, Idx));
5049}
5050void TypeLocReader::VisitDependentTemplateSpecializationTypeLoc(
5051 DependentTemplateSpecializationTypeLoc TL) {
5052 TL.setElaboratedKeywordLoc(ReadSourceLocation(Record, Idx));
5053 TL.setQualifierLoc(Reader.ReadNestedNameSpecifierLoc(F, Record, Idx));
5054 TL.setTemplateKeywordLoc(ReadSourceLocation(Record, Idx));
5055 TL.setTemplateNameLoc(ReadSourceLocation(Record, Idx));
5056 TL.setLAngleLoc(ReadSourceLocation(Record, Idx));
5057 TL.setRAngleLoc(ReadSourceLocation(Record, Idx));
5058 for (unsigned I = 0, E = TL.getNumArgs(); I != E; ++I)
5059 TL.setArgLocInfo(I,
5060 Reader.GetTemplateArgumentLocInfo(F,
5061 TL.getTypePtr()->getArg(I).getKind(),
5062 Record, Idx));
5063}
5064void TypeLocReader::VisitPackExpansionTypeLoc(PackExpansionTypeLoc TL) {
5065 TL.setEllipsisLoc(ReadSourceLocation(Record, Idx));
5066}
5067void TypeLocReader::VisitObjCInterfaceTypeLoc(ObjCInterfaceTypeLoc TL) {
5068 TL.setNameLoc(ReadSourceLocation(Record, Idx));
5069}
5070void TypeLocReader::VisitObjCObjectTypeLoc(ObjCObjectTypeLoc TL) {
5071 TL.setHasBaseTypeAsWritten(Record[Idx++]);
5072 TL.setLAngleLoc(ReadSourceLocation(Record, Idx));
5073 TL.setRAngleLoc(ReadSourceLocation(Record, Idx));
5074 for (unsigned i = 0, e = TL.getNumProtocols(); i != e; ++i)
5075 TL.setProtocolLoc(i, ReadSourceLocation(Record, Idx));
5076}
5077void TypeLocReader::VisitObjCObjectPointerTypeLoc(ObjCObjectPointerTypeLoc TL) {
5078 TL.setStarLoc(ReadSourceLocation(Record, Idx));
5079}
5080void TypeLocReader::VisitAtomicTypeLoc(AtomicTypeLoc TL) {
5081 TL.setKWLoc(ReadSourceLocation(Record, Idx));
5082 TL.setLParenLoc(ReadSourceLocation(Record, Idx));
5083 TL.setRParenLoc(ReadSourceLocation(Record, Idx));
5084}
5085
5086TypeSourceInfo *ASTReader::GetTypeSourceInfo(ModuleFile &F,
5087 const RecordData &Record,
5088 unsigned &Idx) {
5089 QualType InfoTy = readType(F, Record, Idx);
5090 if (InfoTy.isNull())
5091 return 0;
5092
5093 TypeSourceInfo *TInfo = getContext().CreateTypeSourceInfo(InfoTy);
5094 TypeLocReader TLR(*this, F, Record, Idx);
5095 for (TypeLoc TL = TInfo->getTypeLoc(); !TL.isNull(); TL = TL.getNextTypeLoc())
5096 TLR.Visit(TL);
5097 return TInfo;
5098}
5099
5100QualType ASTReader::GetType(TypeID ID) {
5101 unsigned FastQuals = ID & Qualifiers::FastMask;
5102 unsigned Index = ID >> Qualifiers::FastWidth;
5103
5104 if (Index < NUM_PREDEF_TYPE_IDS) {
5105 QualType T;
5106 switch ((PredefinedTypeIDs)Index) {
5107 case PREDEF_TYPE_NULL_ID: return QualType();
5108 case PREDEF_TYPE_VOID_ID: T = Context.VoidTy; break;
5109 case PREDEF_TYPE_BOOL_ID: T = Context.BoolTy; break;
5110
5111 case PREDEF_TYPE_CHAR_U_ID:
5112 case PREDEF_TYPE_CHAR_S_ID:
5113 // FIXME: Check that the signedness of CharTy is correct!
5114 T = Context.CharTy;
5115 break;
5116
5117 case PREDEF_TYPE_UCHAR_ID: T = Context.UnsignedCharTy; break;
5118 case PREDEF_TYPE_USHORT_ID: T = Context.UnsignedShortTy; break;
5119 case PREDEF_TYPE_UINT_ID: T = Context.UnsignedIntTy; break;
5120 case PREDEF_TYPE_ULONG_ID: T = Context.UnsignedLongTy; break;
5121 case PREDEF_TYPE_ULONGLONG_ID: T = Context.UnsignedLongLongTy; break;
5122 case PREDEF_TYPE_UINT128_ID: T = Context.UnsignedInt128Ty; break;
5123 case PREDEF_TYPE_SCHAR_ID: T = Context.SignedCharTy; break;
5124 case PREDEF_TYPE_WCHAR_ID: T = Context.WCharTy; break;
5125 case PREDEF_TYPE_SHORT_ID: T = Context.ShortTy; break;
5126 case PREDEF_TYPE_INT_ID: T = Context.IntTy; break;
5127 case PREDEF_TYPE_LONG_ID: T = Context.LongTy; break;
5128 case PREDEF_TYPE_LONGLONG_ID: T = Context.LongLongTy; break;
5129 case PREDEF_TYPE_INT128_ID: T = Context.Int128Ty; break;
5130 case PREDEF_TYPE_HALF_ID: T = Context.HalfTy; break;
5131 case PREDEF_TYPE_FLOAT_ID: T = Context.FloatTy; break;
5132 case PREDEF_TYPE_DOUBLE_ID: T = Context.DoubleTy; break;
5133 case PREDEF_TYPE_LONGDOUBLE_ID: T = Context.LongDoubleTy; break;
5134 case PREDEF_TYPE_OVERLOAD_ID: T = Context.OverloadTy; break;
5135 case PREDEF_TYPE_BOUND_MEMBER: T = Context.BoundMemberTy; break;
5136 case PREDEF_TYPE_PSEUDO_OBJECT: T = Context.PseudoObjectTy; break;
5137 case PREDEF_TYPE_DEPENDENT_ID: T = Context.DependentTy; break;
5138 case PREDEF_TYPE_UNKNOWN_ANY: T = Context.UnknownAnyTy; break;
5139 case PREDEF_TYPE_NULLPTR_ID: T = Context.NullPtrTy; break;
5140 case PREDEF_TYPE_CHAR16_ID: T = Context.Char16Ty; break;
5141 case PREDEF_TYPE_CHAR32_ID: T = Context.Char32Ty; break;
5142 case PREDEF_TYPE_OBJC_ID: T = Context.ObjCBuiltinIdTy; break;
5143 case PREDEF_TYPE_OBJC_CLASS: T = Context.ObjCBuiltinClassTy; break;
5144 case PREDEF_TYPE_OBJC_SEL: T = Context.ObjCBuiltinSelTy; break;
Guy Benyeib13621d2012-12-18 14:38:23 +00005145 case PREDEF_TYPE_IMAGE1D_ID: T = Context.OCLImage1dTy; break;
5146 case PREDEF_TYPE_IMAGE1D_ARR_ID: T = Context.OCLImage1dArrayTy; break;
5147 case PREDEF_TYPE_IMAGE1D_BUFF_ID: T = Context.OCLImage1dBufferTy; break;
5148 case PREDEF_TYPE_IMAGE2D_ID: T = Context.OCLImage2dTy; break;
5149 case PREDEF_TYPE_IMAGE2D_ARR_ID: T = Context.OCLImage2dArrayTy; break;
5150 case PREDEF_TYPE_IMAGE3D_ID: T = Context.OCLImage3dTy; break;
Guy Benyei21f18c42013-02-07 10:55:47 +00005151 case PREDEF_TYPE_SAMPLER_ID: T = Context.OCLSamplerTy; break;
Guy Benyeie6b9d802013-01-20 12:31:11 +00005152 case PREDEF_TYPE_EVENT_ID: T = Context.OCLEventTy; break;
Guy Benyei7f92f2d2012-12-18 14:30:41 +00005153 case PREDEF_TYPE_AUTO_DEDUCT: T = Context.getAutoDeductType(); break;
5154
5155 case PREDEF_TYPE_AUTO_RREF_DEDUCT:
5156 T = Context.getAutoRRefDeductType();
5157 break;
5158
5159 case PREDEF_TYPE_ARC_UNBRIDGED_CAST:
5160 T = Context.ARCUnbridgedCastTy;
5161 break;
5162
5163 case PREDEF_TYPE_VA_LIST_TAG:
5164 T = Context.getVaListTagType();
5165 break;
5166
5167 case PREDEF_TYPE_BUILTIN_FN:
5168 T = Context.BuiltinFnTy;
5169 break;
5170 }
5171
5172 assert(!T.isNull() && "Unknown predefined type");
5173 return T.withFastQualifiers(FastQuals);
5174 }
5175
5176 Index -= NUM_PREDEF_TYPE_IDS;
5177 assert(Index < TypesLoaded.size() && "Type index out-of-range");
5178 if (TypesLoaded[Index].isNull()) {
5179 TypesLoaded[Index] = readTypeRecord(Index);
5180 if (TypesLoaded[Index].isNull())
5181 return QualType();
5182
5183 TypesLoaded[Index]->setFromAST();
5184 if (DeserializationListener)
5185 DeserializationListener->TypeRead(TypeIdx::fromTypeID(ID),
5186 TypesLoaded[Index]);
5187 }
5188
5189 return TypesLoaded[Index].withFastQualifiers(FastQuals);
5190}
5191
5192QualType ASTReader::getLocalType(ModuleFile &F, unsigned LocalID) {
5193 return GetType(getGlobalTypeID(F, LocalID));
5194}
5195
5196serialization::TypeID
5197ASTReader::getGlobalTypeID(ModuleFile &F, unsigned LocalID) const {
5198 unsigned FastQuals = LocalID & Qualifiers::FastMask;
5199 unsigned LocalIndex = LocalID >> Qualifiers::FastWidth;
5200
5201 if (LocalIndex < NUM_PREDEF_TYPE_IDS)
5202 return LocalID;
5203
5204 ContinuousRangeMap<uint32_t, int, 2>::iterator I
5205 = F.TypeRemap.find(LocalIndex - NUM_PREDEF_TYPE_IDS);
5206 assert(I != F.TypeRemap.end() && "Invalid index into type index remap");
5207
5208 unsigned GlobalIndex = LocalIndex + I->second;
5209 return (GlobalIndex << Qualifiers::FastWidth) | FastQuals;
5210}
5211
5212TemplateArgumentLocInfo
5213ASTReader::GetTemplateArgumentLocInfo(ModuleFile &F,
5214 TemplateArgument::ArgKind Kind,
5215 const RecordData &Record,
5216 unsigned &Index) {
5217 switch (Kind) {
5218 case TemplateArgument::Expression:
5219 return ReadExpr(F);
5220 case TemplateArgument::Type:
5221 return GetTypeSourceInfo(F, Record, Index);
5222 case TemplateArgument::Template: {
5223 NestedNameSpecifierLoc QualifierLoc = ReadNestedNameSpecifierLoc(F, Record,
5224 Index);
5225 SourceLocation TemplateNameLoc = ReadSourceLocation(F, Record, Index);
5226 return TemplateArgumentLocInfo(QualifierLoc, TemplateNameLoc,
5227 SourceLocation());
5228 }
5229 case TemplateArgument::TemplateExpansion: {
5230 NestedNameSpecifierLoc QualifierLoc = ReadNestedNameSpecifierLoc(F, Record,
5231 Index);
5232 SourceLocation TemplateNameLoc = ReadSourceLocation(F, Record, Index);
5233 SourceLocation EllipsisLoc = ReadSourceLocation(F, Record, Index);
5234 return TemplateArgumentLocInfo(QualifierLoc, TemplateNameLoc,
5235 EllipsisLoc);
5236 }
5237 case TemplateArgument::Null:
5238 case TemplateArgument::Integral:
5239 case TemplateArgument::Declaration:
5240 case TemplateArgument::NullPtr:
5241 case TemplateArgument::Pack:
5242 // FIXME: Is this right?
5243 return TemplateArgumentLocInfo();
5244 }
5245 llvm_unreachable("unexpected template argument loc");
5246}
5247
5248TemplateArgumentLoc
5249ASTReader::ReadTemplateArgumentLoc(ModuleFile &F,
5250 const RecordData &Record, unsigned &Index) {
5251 TemplateArgument Arg = ReadTemplateArgument(F, Record, Index);
5252
5253 if (Arg.getKind() == TemplateArgument::Expression) {
5254 if (Record[Index++]) // bool InfoHasSameExpr.
5255 return TemplateArgumentLoc(Arg, TemplateArgumentLocInfo(Arg.getAsExpr()));
5256 }
5257 return TemplateArgumentLoc(Arg, GetTemplateArgumentLocInfo(F, Arg.getKind(),
5258 Record, Index));
5259}
5260
5261Decl *ASTReader::GetExternalDecl(uint32_t ID) {
5262 return GetDecl(ID);
5263}
5264
5265uint64_t ASTReader::readCXXBaseSpecifiers(ModuleFile &M, const RecordData &Record,
5266 unsigned &Idx){
5267 if (Idx >= Record.size())
5268 return 0;
5269
5270 unsigned LocalID = Record[Idx++];
5271 return getGlobalBitOffset(M, M.CXXBaseSpecifiersOffsets[LocalID - 1]);
5272}
5273
5274CXXBaseSpecifier *ASTReader::GetExternalCXXBaseSpecifiers(uint64_t Offset) {
5275 RecordLocation Loc = getLocalBitOffset(Offset);
Chris Lattner8f9a1eb2013-01-20 00:56:42 +00005276 BitstreamCursor &Cursor = Loc.F->DeclsCursor;
Guy Benyei7f92f2d2012-12-18 14:30:41 +00005277 SavedStreamPosition SavedPosition(Cursor);
5278 Cursor.JumpToBit(Loc.Offset);
5279 ReadingKindTracker ReadingKind(Read_Decl, *this);
5280 RecordData Record;
5281 unsigned Code = Cursor.ReadCode();
Chris Lattnerb3ce3572013-01-20 02:38:54 +00005282 unsigned RecCode = Cursor.readRecord(Code, Record);
Guy Benyei7f92f2d2012-12-18 14:30:41 +00005283 if (RecCode != DECL_CXX_BASE_SPECIFIERS) {
5284 Error("Malformed AST file: missing C++ base specifiers");
5285 return 0;
5286 }
5287
5288 unsigned Idx = 0;
5289 unsigned NumBases = Record[Idx++];
5290 void *Mem = Context.Allocate(sizeof(CXXBaseSpecifier) * NumBases);
5291 CXXBaseSpecifier *Bases = new (Mem) CXXBaseSpecifier [NumBases];
5292 for (unsigned I = 0; I != NumBases; ++I)
5293 Bases[I] = ReadCXXBaseSpecifier(*Loc.F, Record, Idx);
5294 return Bases;
5295}
5296
5297serialization::DeclID
5298ASTReader::getGlobalDeclID(ModuleFile &F, LocalDeclID LocalID) const {
5299 if (LocalID < NUM_PREDEF_DECL_IDS)
5300 return LocalID;
5301
5302 ContinuousRangeMap<uint32_t, int, 2>::iterator I
5303 = F.DeclRemap.find(LocalID - NUM_PREDEF_DECL_IDS);
5304 assert(I != F.DeclRemap.end() && "Invalid index into decl index remap");
5305
5306 return LocalID + I->second;
5307}
5308
5309bool ASTReader::isDeclIDFromModule(serialization::GlobalDeclID ID,
5310 ModuleFile &M) const {
5311 GlobalDeclMapType::const_iterator I = GlobalDeclMap.find(ID);
5312 assert(I != GlobalDeclMap.end() && "Corrupted global declaration map");
5313 return &M == I->second;
5314}
5315
Douglas Gregor5a04f9f2013-01-21 15:25:38 +00005316ModuleFile *ASTReader::getOwningModuleFile(const Decl *D) {
Guy Benyei7f92f2d2012-12-18 14:30:41 +00005317 if (!D->isFromASTFile())
5318 return 0;
5319 GlobalDeclMapType::const_iterator I = GlobalDeclMap.find(D->getGlobalID());
5320 assert(I != GlobalDeclMap.end() && "Corrupted global declaration map");
5321 return I->second;
5322}
5323
5324SourceLocation ASTReader::getSourceLocationForDeclID(GlobalDeclID ID) {
5325 if (ID < NUM_PREDEF_DECL_IDS)
5326 return SourceLocation();
5327
5328 unsigned Index = ID - NUM_PREDEF_DECL_IDS;
5329
5330 if (Index > DeclsLoaded.size()) {
5331 Error("declaration ID out-of-range for AST file");
5332 return SourceLocation();
5333 }
5334
5335 if (Decl *D = DeclsLoaded[Index])
5336 return D->getLocation();
5337
5338 unsigned RawLocation = 0;
5339 RecordLocation Rec = DeclCursorForID(ID, RawLocation);
5340 return ReadSourceLocation(*Rec.F, RawLocation);
5341}
5342
5343Decl *ASTReader::GetDecl(DeclID ID) {
5344 if (ID < NUM_PREDEF_DECL_IDS) {
5345 switch ((PredefinedDeclIDs)ID) {
5346 case PREDEF_DECL_NULL_ID:
5347 return 0;
5348
5349 case PREDEF_DECL_TRANSLATION_UNIT_ID:
5350 return Context.getTranslationUnitDecl();
5351
5352 case PREDEF_DECL_OBJC_ID_ID:
5353 return Context.getObjCIdDecl();
5354
5355 case PREDEF_DECL_OBJC_SEL_ID:
5356 return Context.getObjCSelDecl();
5357
5358 case PREDEF_DECL_OBJC_CLASS_ID:
5359 return Context.getObjCClassDecl();
5360
5361 case PREDEF_DECL_OBJC_PROTOCOL_ID:
5362 return Context.getObjCProtocolDecl();
5363
5364 case PREDEF_DECL_INT_128_ID:
5365 return Context.getInt128Decl();
5366
5367 case PREDEF_DECL_UNSIGNED_INT_128_ID:
5368 return Context.getUInt128Decl();
5369
5370 case PREDEF_DECL_OBJC_INSTANCETYPE_ID:
5371 return Context.getObjCInstanceTypeDecl();
5372
5373 case PREDEF_DECL_BUILTIN_VA_LIST_ID:
5374 return Context.getBuiltinVaListDecl();
5375 }
5376 }
5377
5378 unsigned Index = ID - NUM_PREDEF_DECL_IDS;
5379
5380 if (Index >= DeclsLoaded.size()) {
5381 assert(0 && "declaration ID out-of-range for AST file");
5382 Error("declaration ID out-of-range for AST file");
5383 return 0;
5384 }
5385
5386 if (!DeclsLoaded[Index]) {
5387 ReadDeclRecord(ID);
5388 if (DeserializationListener)
5389 DeserializationListener->DeclRead(ID, DeclsLoaded[Index]);
5390 }
5391
5392 return DeclsLoaded[Index];
5393}
5394
5395DeclID ASTReader::mapGlobalIDToModuleFileGlobalID(ModuleFile &M,
5396 DeclID GlobalID) {
5397 if (GlobalID < NUM_PREDEF_DECL_IDS)
5398 return GlobalID;
5399
5400 GlobalDeclMapType::const_iterator I = GlobalDeclMap.find(GlobalID);
5401 assert(I != GlobalDeclMap.end() && "Corrupted global declaration map");
5402 ModuleFile *Owner = I->second;
5403
5404 llvm::DenseMap<ModuleFile *, serialization::DeclID>::iterator Pos
5405 = M.GlobalToLocalDeclIDs.find(Owner);
5406 if (Pos == M.GlobalToLocalDeclIDs.end())
5407 return 0;
5408
5409 return GlobalID - Owner->BaseDeclID + Pos->second;
5410}
5411
5412serialization::DeclID ASTReader::ReadDeclID(ModuleFile &F,
5413 const RecordData &Record,
5414 unsigned &Idx) {
5415 if (Idx >= Record.size()) {
5416 Error("Corrupted AST file");
5417 return 0;
5418 }
5419
5420 return getGlobalDeclID(F, Record[Idx++]);
5421}
5422
5423/// \brief Resolve the offset of a statement into a statement.
5424///
5425/// This operation will read a new statement from the external
5426/// source each time it is called, and is meant to be used via a
5427/// LazyOffsetPtr (which is used by Decls for the body of functions, etc).
5428Stmt *ASTReader::GetExternalDeclStmt(uint64_t Offset) {
5429 // Switch case IDs are per Decl.
5430 ClearSwitchCaseIDs();
5431
5432 // Offset here is a global offset across the entire chain.
5433 RecordLocation Loc = getLocalBitOffset(Offset);
5434 Loc.F->DeclsCursor.JumpToBit(Loc.Offset);
5435 return ReadStmtFromStream(*Loc.F);
5436}
5437
5438namespace {
5439 class FindExternalLexicalDeclsVisitor {
5440 ASTReader &Reader;
5441 const DeclContext *DC;
5442 bool (*isKindWeWant)(Decl::Kind);
5443
5444 SmallVectorImpl<Decl*> &Decls;
5445 bool PredefsVisited[NUM_PREDEF_DECL_IDS];
5446
5447 public:
5448 FindExternalLexicalDeclsVisitor(ASTReader &Reader, const DeclContext *DC,
5449 bool (*isKindWeWant)(Decl::Kind),
5450 SmallVectorImpl<Decl*> &Decls)
5451 : Reader(Reader), DC(DC), isKindWeWant(isKindWeWant), Decls(Decls)
5452 {
5453 for (unsigned I = 0; I != NUM_PREDEF_DECL_IDS; ++I)
5454 PredefsVisited[I] = false;
5455 }
5456
5457 static bool visit(ModuleFile &M, bool Preorder, void *UserData) {
5458 if (Preorder)
5459 return false;
5460
5461 FindExternalLexicalDeclsVisitor *This
5462 = static_cast<FindExternalLexicalDeclsVisitor *>(UserData);
5463
5464 ModuleFile::DeclContextInfosMap::iterator Info
5465 = M.DeclContextInfos.find(This->DC);
5466 if (Info == M.DeclContextInfos.end() || !Info->second.LexicalDecls)
5467 return false;
5468
5469 // Load all of the declaration IDs
5470 for (const KindDeclIDPair *ID = Info->second.LexicalDecls,
5471 *IDE = ID + Info->second.NumLexicalDecls;
5472 ID != IDE; ++ID) {
5473 if (This->isKindWeWant && !This->isKindWeWant((Decl::Kind)ID->first))
5474 continue;
5475
5476 // Don't add predefined declarations to the lexical context more
5477 // than once.
5478 if (ID->second < NUM_PREDEF_DECL_IDS) {
5479 if (This->PredefsVisited[ID->second])
5480 continue;
5481
5482 This->PredefsVisited[ID->second] = true;
5483 }
5484
5485 if (Decl *D = This->Reader.GetLocalDecl(M, ID->second)) {
5486 if (!This->DC->isDeclInLexicalTraversal(D))
5487 This->Decls.push_back(D);
5488 }
5489 }
5490
5491 return false;
5492 }
5493 };
5494}
5495
5496ExternalLoadResult ASTReader::FindExternalLexicalDecls(const DeclContext *DC,
5497 bool (*isKindWeWant)(Decl::Kind),
5498 SmallVectorImpl<Decl*> &Decls) {
5499 // There might be lexical decls in multiple modules, for the TU at
5500 // least. Walk all of the modules in the order they were loaded.
5501 FindExternalLexicalDeclsVisitor Visitor(*this, DC, isKindWeWant, Decls);
5502 ModuleMgr.visitDepthFirst(&FindExternalLexicalDeclsVisitor::visit, &Visitor);
5503 ++NumLexicalDeclContextsRead;
5504 return ELR_Success;
5505}
5506
5507namespace {
5508
5509class DeclIDComp {
5510 ASTReader &Reader;
5511 ModuleFile &Mod;
5512
5513public:
5514 DeclIDComp(ASTReader &Reader, ModuleFile &M) : Reader(Reader), Mod(M) {}
5515
5516 bool operator()(LocalDeclID L, LocalDeclID R) const {
5517 SourceLocation LHS = getLocation(L);
5518 SourceLocation RHS = getLocation(R);
5519 return Reader.getSourceManager().isBeforeInTranslationUnit(LHS, RHS);
5520 }
5521
5522 bool operator()(SourceLocation LHS, LocalDeclID R) const {
5523 SourceLocation RHS = getLocation(R);
5524 return Reader.getSourceManager().isBeforeInTranslationUnit(LHS, RHS);
5525 }
5526
5527 bool operator()(LocalDeclID L, SourceLocation RHS) const {
5528 SourceLocation LHS = getLocation(L);
5529 return Reader.getSourceManager().isBeforeInTranslationUnit(LHS, RHS);
5530 }
5531
5532 SourceLocation getLocation(LocalDeclID ID) const {
5533 return Reader.getSourceManager().getFileLoc(
5534 Reader.getSourceLocationForDeclID(Reader.getGlobalDeclID(Mod, ID)));
5535 }
5536};
5537
5538}
5539
5540void ASTReader::FindFileRegionDecls(FileID File,
5541 unsigned Offset, unsigned Length,
5542 SmallVectorImpl<Decl *> &Decls) {
5543 SourceManager &SM = getSourceManager();
5544
5545 llvm::DenseMap<FileID, FileDeclsInfo>::iterator I = FileDeclIDs.find(File);
5546 if (I == FileDeclIDs.end())
5547 return;
5548
5549 FileDeclsInfo &DInfo = I->second;
5550 if (DInfo.Decls.empty())
5551 return;
5552
5553 SourceLocation
5554 BeginLoc = SM.getLocForStartOfFile(File).getLocWithOffset(Offset);
5555 SourceLocation EndLoc = BeginLoc.getLocWithOffset(Length);
5556
5557 DeclIDComp DIDComp(*this, *DInfo.Mod);
5558 ArrayRef<serialization::LocalDeclID>::iterator
5559 BeginIt = std::lower_bound(DInfo.Decls.begin(), DInfo.Decls.end(),
5560 BeginLoc, DIDComp);
5561 if (BeginIt != DInfo.Decls.begin())
5562 --BeginIt;
5563
5564 // If we are pointing at a top-level decl inside an objc container, we need
5565 // to backtrack until we find it otherwise we will fail to report that the
5566 // region overlaps with an objc container.
5567 while (BeginIt != DInfo.Decls.begin() &&
5568 GetDecl(getGlobalDeclID(*DInfo.Mod, *BeginIt))
5569 ->isTopLevelDeclInObjCContainer())
5570 --BeginIt;
5571
5572 ArrayRef<serialization::LocalDeclID>::iterator
5573 EndIt = std::upper_bound(DInfo.Decls.begin(), DInfo.Decls.end(),
5574 EndLoc, DIDComp);
5575 if (EndIt != DInfo.Decls.end())
5576 ++EndIt;
5577
5578 for (ArrayRef<serialization::LocalDeclID>::iterator
5579 DIt = BeginIt; DIt != EndIt; ++DIt)
5580 Decls.push_back(GetDecl(getGlobalDeclID(*DInfo.Mod, *DIt)));
5581}
5582
5583namespace {
5584 /// \brief ModuleFile visitor used to perform name lookup into a
5585 /// declaration context.
5586 class DeclContextNameLookupVisitor {
5587 ASTReader &Reader;
Dmitri Gribenkocfa88f82013-01-12 19:30:44 +00005588 SmallVectorImpl<const DeclContext *> &Contexts;
Guy Benyei7f92f2d2012-12-18 14:30:41 +00005589 DeclarationName Name;
5590 SmallVectorImpl<NamedDecl *> &Decls;
5591
5592 public:
5593 DeclContextNameLookupVisitor(ASTReader &Reader,
5594 SmallVectorImpl<const DeclContext *> &Contexts,
5595 DeclarationName Name,
5596 SmallVectorImpl<NamedDecl *> &Decls)
5597 : Reader(Reader), Contexts(Contexts), Name(Name), Decls(Decls) { }
5598
5599 static bool visit(ModuleFile &M, void *UserData) {
5600 DeclContextNameLookupVisitor *This
5601 = static_cast<DeclContextNameLookupVisitor *>(UserData);
5602
5603 // Check whether we have any visible declaration information for
5604 // this context in this module.
5605 ModuleFile::DeclContextInfosMap::iterator Info;
5606 bool FoundInfo = false;
5607 for (unsigned I = 0, N = This->Contexts.size(); I != N; ++I) {
5608 Info = M.DeclContextInfos.find(This->Contexts[I]);
5609 if (Info != M.DeclContextInfos.end() &&
5610 Info->second.NameLookupTableData) {
5611 FoundInfo = true;
5612 break;
5613 }
5614 }
5615
5616 if (!FoundInfo)
5617 return false;
5618
5619 // Look for this name within this module.
5620 ASTDeclContextNameLookupTable *LookupTable =
5621 Info->second.NameLookupTableData;
5622 ASTDeclContextNameLookupTable::iterator Pos
5623 = LookupTable->find(This->Name);
5624 if (Pos == LookupTable->end())
5625 return false;
5626
5627 bool FoundAnything = false;
5628 ASTDeclContextNameLookupTrait::data_type Data = *Pos;
5629 for (; Data.first != Data.second; ++Data.first) {
5630 NamedDecl *ND = This->Reader.GetLocalDeclAs<NamedDecl>(M, *Data.first);
5631 if (!ND)
5632 continue;
5633
5634 if (ND->getDeclName() != This->Name) {
5635 // A name might be null because the decl's redeclarable part is
5636 // currently read before reading its name. The lookup is triggered by
5637 // building that decl (likely indirectly), and so it is later in the
5638 // sense of "already existing" and can be ignored here.
5639 continue;
5640 }
5641
5642 // Record this declaration.
5643 FoundAnything = true;
5644 This->Decls.push_back(ND);
5645 }
5646
5647 return FoundAnything;
5648 }
5649 };
5650}
5651
Douglas Gregor5a04f9f2013-01-21 15:25:38 +00005652/// \brief Retrieve the "definitive" module file for the definition of the
5653/// given declaration context, if there is one.
5654///
5655/// The "definitive" module file is the only place where we need to look to
5656/// find information about the declarations within the given declaration
5657/// context. For example, C++ and Objective-C classes, C structs/unions, and
5658/// Objective-C protocols, categories, and extensions are all defined in a
5659/// single place in the source code, so they have definitive module files
5660/// associated with them. C++ namespaces, on the other hand, can have
5661/// definitions in multiple different module files.
5662///
5663/// Note: this needs to be kept in sync with ASTWriter::AddedVisibleDecl's
5664/// NDEBUG checking.
5665static ModuleFile *getDefinitiveModuleFileFor(const DeclContext *DC,
5666 ASTReader &Reader) {
Douglas Gregore0d20662013-01-22 17:08:30 +00005667 if (const DeclContext *DefDC = getDefinitiveDeclContext(DC))
5668 return Reader.getOwningModuleFile(cast<Decl>(DefDC));
Douglas Gregor5a04f9f2013-01-21 15:25:38 +00005669
5670 return 0;
5671}
5672
Richard Smith3646c682013-02-07 03:30:24 +00005673bool
Guy Benyei7f92f2d2012-12-18 14:30:41 +00005674ASTReader::FindExternalVisibleDeclsByName(const DeclContext *DC,
5675 DeclarationName Name) {
5676 assert(DC->hasExternalVisibleStorage() &&
5677 "DeclContext has no visible decls in storage");
5678 if (!Name)
Richard Smith3646c682013-02-07 03:30:24 +00005679 return false;
Guy Benyei7f92f2d2012-12-18 14:30:41 +00005680
5681 SmallVector<NamedDecl *, 64> Decls;
5682
5683 // Compute the declaration contexts we need to look into. Multiple such
5684 // declaration contexts occur when two declaration contexts from disjoint
5685 // modules get merged, e.g., when two namespaces with the same name are
5686 // independently defined in separate modules.
5687 SmallVector<const DeclContext *, 2> Contexts;
5688 Contexts.push_back(DC);
5689
5690 if (DC->isNamespace()) {
5691 MergedDeclsMap::iterator Merged
5692 = MergedDecls.find(const_cast<Decl *>(cast<Decl>(DC)));
5693 if (Merged != MergedDecls.end()) {
5694 for (unsigned I = 0, N = Merged->second.size(); I != N; ++I)
5695 Contexts.push_back(cast<DeclContext>(GetDecl(Merged->second[I])));
5696 }
5697 }
5698
5699 DeclContextNameLookupVisitor Visitor(*this, Contexts, Name, Decls);
Douglas Gregor5a04f9f2013-01-21 15:25:38 +00005700
5701 // If we can definitively determine which module file to look into,
5702 // only look there. Otherwise, look in all module files.
5703 ModuleFile *Definitive;
5704 if (Contexts.size() == 1 &&
5705 (Definitive = getDefinitiveModuleFileFor(DC, *this))) {
5706 DeclContextNameLookupVisitor::visit(*Definitive, &Visitor);
5707 } else {
5708 ModuleMgr.visit(&DeclContextNameLookupVisitor::visit, &Visitor);
5709 }
Guy Benyei7f92f2d2012-12-18 14:30:41 +00005710 ++NumVisibleDeclContextsRead;
5711 SetExternalVisibleDeclsForName(DC, Name, Decls);
Richard Smith3646c682013-02-07 03:30:24 +00005712 return !Decls.empty();
Guy Benyei7f92f2d2012-12-18 14:30:41 +00005713}
5714
5715namespace {
5716 /// \brief ModuleFile visitor used to retrieve all visible names in a
5717 /// declaration context.
5718 class DeclContextAllNamesVisitor {
5719 ASTReader &Reader;
Dmitri Gribenkocfa88f82013-01-12 19:30:44 +00005720 SmallVectorImpl<const DeclContext *> &Contexts;
Guy Benyei7f92f2d2012-12-18 14:30:41 +00005721 llvm::DenseMap<DeclarationName, SmallVector<NamedDecl *, 8> > &Decls;
Argyrios Kyrtzidisca40f302012-12-19 22:21:18 +00005722 bool VisitAll;
Guy Benyei7f92f2d2012-12-18 14:30:41 +00005723
5724 public:
5725 DeclContextAllNamesVisitor(ASTReader &Reader,
5726 SmallVectorImpl<const DeclContext *> &Contexts,
5727 llvm::DenseMap<DeclarationName,
Argyrios Kyrtzidisca40f302012-12-19 22:21:18 +00005728 SmallVector<NamedDecl *, 8> > &Decls,
5729 bool VisitAll)
5730 : Reader(Reader), Contexts(Contexts), Decls(Decls), VisitAll(VisitAll) { }
Guy Benyei7f92f2d2012-12-18 14:30:41 +00005731
5732 static bool visit(ModuleFile &M, void *UserData) {
5733 DeclContextAllNamesVisitor *This
5734 = static_cast<DeclContextAllNamesVisitor *>(UserData);
5735
5736 // Check whether we have any visible declaration information for
5737 // this context in this module.
5738 ModuleFile::DeclContextInfosMap::iterator Info;
5739 bool FoundInfo = false;
5740 for (unsigned I = 0, N = This->Contexts.size(); I != N; ++I) {
5741 Info = M.DeclContextInfos.find(This->Contexts[I]);
5742 if (Info != M.DeclContextInfos.end() &&
5743 Info->second.NameLookupTableData) {
5744 FoundInfo = true;
5745 break;
5746 }
5747 }
5748
5749 if (!FoundInfo)
5750 return false;
5751
5752 ASTDeclContextNameLookupTable *LookupTable =
5753 Info->second.NameLookupTableData;
5754 bool FoundAnything = false;
5755 for (ASTDeclContextNameLookupTable::data_iterator
Douglas Gregora6b00fc2013-01-23 22:38:11 +00005756 I = LookupTable->data_begin(), E = LookupTable->data_end();
5757 I != E;
5758 ++I) {
Guy Benyei7f92f2d2012-12-18 14:30:41 +00005759 ASTDeclContextNameLookupTrait::data_type Data = *I;
5760 for (; Data.first != Data.second; ++Data.first) {
5761 NamedDecl *ND = This->Reader.GetLocalDeclAs<NamedDecl>(M,
5762 *Data.first);
5763 if (!ND)
5764 continue;
5765
5766 // Record this declaration.
5767 FoundAnything = true;
5768 This->Decls[ND->getDeclName()].push_back(ND);
5769 }
5770 }
5771
Argyrios Kyrtzidisca40f302012-12-19 22:21:18 +00005772 return FoundAnything && !This->VisitAll;
Guy Benyei7f92f2d2012-12-18 14:30:41 +00005773 }
5774 };
5775}
5776
5777void ASTReader::completeVisibleDeclsMap(const DeclContext *DC) {
5778 if (!DC->hasExternalVisibleStorage())
5779 return;
Dmitri Gribenkocfa88f82013-01-12 19:30:44 +00005780 llvm::DenseMap<DeclarationName, SmallVector<NamedDecl *, 8> > Decls;
Guy Benyei7f92f2d2012-12-18 14:30:41 +00005781
5782 // Compute the declaration contexts we need to look into. Multiple such
5783 // declaration contexts occur when two declaration contexts from disjoint
5784 // modules get merged, e.g., when two namespaces with the same name are
5785 // independently defined in separate modules.
5786 SmallVector<const DeclContext *, 2> Contexts;
5787 Contexts.push_back(DC);
5788
5789 if (DC->isNamespace()) {
5790 MergedDeclsMap::iterator Merged
5791 = MergedDecls.find(const_cast<Decl *>(cast<Decl>(DC)));
5792 if (Merged != MergedDecls.end()) {
5793 for (unsigned I = 0, N = Merged->second.size(); I != N; ++I)
5794 Contexts.push_back(cast<DeclContext>(GetDecl(Merged->second[I])));
5795 }
5796 }
5797
Argyrios Kyrtzidisca40f302012-12-19 22:21:18 +00005798 DeclContextAllNamesVisitor Visitor(*this, Contexts, Decls,
5799 /*VisitAll=*/DC->isFileContext());
Guy Benyei7f92f2d2012-12-18 14:30:41 +00005800 ModuleMgr.visit(&DeclContextAllNamesVisitor::visit, &Visitor);
5801 ++NumVisibleDeclContextsRead;
5802
5803 for (llvm::DenseMap<DeclarationName,
Dmitri Gribenkocfa88f82013-01-12 19:30:44 +00005804 SmallVector<NamedDecl *, 8> >::iterator
Guy Benyei7f92f2d2012-12-18 14:30:41 +00005805 I = Decls.begin(), E = Decls.end(); I != E; ++I) {
5806 SetExternalVisibleDeclsForName(DC, I->first, I->second);
5807 }
5808 const_cast<DeclContext *>(DC)->setHasExternalVisibleStorage(false);
5809}
5810
5811/// \brief Under non-PCH compilation the consumer receives the objc methods
5812/// before receiving the implementation, and codegen depends on this.
5813/// We simulate this by deserializing and passing to consumer the methods of the
5814/// implementation before passing the deserialized implementation decl.
5815static void PassObjCImplDeclToConsumer(ObjCImplDecl *ImplD,
5816 ASTConsumer *Consumer) {
5817 assert(ImplD && Consumer);
5818
5819 for (ObjCImplDecl::method_iterator
5820 I = ImplD->meth_begin(), E = ImplD->meth_end(); I != E; ++I)
5821 Consumer->HandleInterestingDecl(DeclGroupRef(*I));
5822
5823 Consumer->HandleInterestingDecl(DeclGroupRef(ImplD));
5824}
5825
5826void ASTReader::PassInterestingDeclsToConsumer() {
5827 assert(Consumer);
5828 while (!InterestingDecls.empty()) {
5829 Decl *D = InterestingDecls.front();
5830 InterestingDecls.pop_front();
5831
5832 PassInterestingDeclToConsumer(D);
5833 }
5834}
5835
5836void ASTReader::PassInterestingDeclToConsumer(Decl *D) {
5837 if (ObjCImplDecl *ImplD = dyn_cast<ObjCImplDecl>(D))
5838 PassObjCImplDeclToConsumer(ImplD, Consumer);
5839 else
5840 Consumer->HandleInterestingDecl(DeclGroupRef(D));
5841}
5842
5843void ASTReader::StartTranslationUnit(ASTConsumer *Consumer) {
5844 this->Consumer = Consumer;
5845
5846 if (!Consumer)
5847 return;
5848
5849 for (unsigned I = 0, N = ExternalDefinitions.size(); I != N; ++I) {
5850 // Force deserialization of this decl, which will cause it to be queued for
5851 // passing to the consumer.
5852 GetDecl(ExternalDefinitions[I]);
5853 }
5854 ExternalDefinitions.clear();
5855
5856 PassInterestingDeclsToConsumer();
5857}
5858
5859void ASTReader::PrintStats() {
5860 std::fprintf(stderr, "*** AST File Statistics:\n");
5861
5862 unsigned NumTypesLoaded
5863 = TypesLoaded.size() - std::count(TypesLoaded.begin(), TypesLoaded.end(),
5864 QualType());
5865 unsigned NumDeclsLoaded
5866 = DeclsLoaded.size() - std::count(DeclsLoaded.begin(), DeclsLoaded.end(),
5867 (Decl *)0);
5868 unsigned NumIdentifiersLoaded
5869 = IdentifiersLoaded.size() - std::count(IdentifiersLoaded.begin(),
5870 IdentifiersLoaded.end(),
5871 (IdentifierInfo *)0);
5872 unsigned NumMacrosLoaded
5873 = MacrosLoaded.size() - std::count(MacrosLoaded.begin(),
5874 MacrosLoaded.end(),
Argyrios Kyrtzidis9317ab92013-03-22 21:12:57 +00005875 (MacroInfo *)0);
Guy Benyei7f92f2d2012-12-18 14:30:41 +00005876 unsigned NumSelectorsLoaded
5877 = SelectorsLoaded.size() - std::count(SelectorsLoaded.begin(),
5878 SelectorsLoaded.end(),
5879 Selector());
5880
5881 if (unsigned TotalNumSLocEntries = getTotalNumSLocs())
5882 std::fprintf(stderr, " %u/%u source location entries read (%f%%)\n",
5883 NumSLocEntriesRead, TotalNumSLocEntries,
5884 ((float)NumSLocEntriesRead/TotalNumSLocEntries * 100));
5885 if (!TypesLoaded.empty())
5886 std::fprintf(stderr, " %u/%u types read (%f%%)\n",
5887 NumTypesLoaded, (unsigned)TypesLoaded.size(),
5888 ((float)NumTypesLoaded/TypesLoaded.size() * 100));
5889 if (!DeclsLoaded.empty())
5890 std::fprintf(stderr, " %u/%u declarations read (%f%%)\n",
5891 NumDeclsLoaded, (unsigned)DeclsLoaded.size(),
5892 ((float)NumDeclsLoaded/DeclsLoaded.size() * 100));
5893 if (!IdentifiersLoaded.empty())
5894 std::fprintf(stderr, " %u/%u identifiers read (%f%%)\n",
5895 NumIdentifiersLoaded, (unsigned)IdentifiersLoaded.size(),
5896 ((float)NumIdentifiersLoaded/IdentifiersLoaded.size() * 100));
5897 if (!MacrosLoaded.empty())
5898 std::fprintf(stderr, " %u/%u macros read (%f%%)\n",
5899 NumMacrosLoaded, (unsigned)MacrosLoaded.size(),
5900 ((float)NumMacrosLoaded/MacrosLoaded.size() * 100));
5901 if (!SelectorsLoaded.empty())
5902 std::fprintf(stderr, " %u/%u selectors read (%f%%)\n",
5903 NumSelectorsLoaded, (unsigned)SelectorsLoaded.size(),
5904 ((float)NumSelectorsLoaded/SelectorsLoaded.size() * 100));
5905 if (TotalNumStatements)
5906 std::fprintf(stderr, " %u/%u statements read (%f%%)\n",
5907 NumStatementsRead, TotalNumStatements,
5908 ((float)NumStatementsRead/TotalNumStatements * 100));
5909 if (TotalNumMacros)
5910 std::fprintf(stderr, " %u/%u macros read (%f%%)\n",
5911 NumMacrosRead, TotalNumMacros,
5912 ((float)NumMacrosRead/TotalNumMacros * 100));
5913 if (TotalLexicalDeclContexts)
5914 std::fprintf(stderr, " %u/%u lexical declcontexts read (%f%%)\n",
5915 NumLexicalDeclContextsRead, TotalLexicalDeclContexts,
5916 ((float)NumLexicalDeclContextsRead/TotalLexicalDeclContexts
5917 * 100));
5918 if (TotalVisibleDeclContexts)
5919 std::fprintf(stderr, " %u/%u visible declcontexts read (%f%%)\n",
5920 NumVisibleDeclContextsRead, TotalVisibleDeclContexts,
5921 ((float)NumVisibleDeclContextsRead/TotalVisibleDeclContexts
5922 * 100));
5923 if (TotalNumMethodPoolEntries) {
5924 std::fprintf(stderr, " %u/%u method pool entries read (%f%%)\n",
5925 NumMethodPoolEntriesRead, TotalNumMethodPoolEntries,
5926 ((float)NumMethodPoolEntriesRead/TotalNumMethodPoolEntries
5927 * 100));
Guy Benyei7f92f2d2012-12-18 14:30:41 +00005928 }
Douglas Gregor95fb36e2013-01-28 17:54:36 +00005929 if (NumMethodPoolLookups) {
5930 std::fprintf(stderr, " %u/%u method pool lookups succeeded (%f%%)\n",
5931 NumMethodPoolHits, NumMethodPoolLookups,
5932 ((float)NumMethodPoolHits/NumMethodPoolLookups * 100.0));
5933 }
5934 if (NumMethodPoolTableLookups) {
5935 std::fprintf(stderr, " %u/%u method pool table lookups succeeded (%f%%)\n",
5936 NumMethodPoolTableHits, NumMethodPoolTableLookups,
5937 ((float)NumMethodPoolTableHits/NumMethodPoolTableLookups
5938 * 100.0));
5939 }
5940
Douglas Gregore1698072013-01-25 00:38:33 +00005941 if (NumIdentifierLookupHits) {
5942 std::fprintf(stderr,
5943 " %u / %u identifier table lookups succeeded (%f%%)\n",
5944 NumIdentifierLookupHits, NumIdentifierLookups,
5945 (double)NumIdentifierLookupHits*100.0/NumIdentifierLookups);
5946 }
5947
Douglas Gregor1a49d972013-01-25 01:03:03 +00005948 if (GlobalIndex) {
5949 std::fprintf(stderr, "\n");
5950 GlobalIndex->printStats();
5951 }
5952
Guy Benyei7f92f2d2012-12-18 14:30:41 +00005953 std::fprintf(stderr, "\n");
5954 dump();
5955 std::fprintf(stderr, "\n");
5956}
5957
5958template<typename Key, typename ModuleFile, unsigned InitialCapacity>
5959static void
5960dumpModuleIDMap(StringRef Name,
5961 const ContinuousRangeMap<Key, ModuleFile *,
5962 InitialCapacity> &Map) {
5963 if (Map.begin() == Map.end())
5964 return;
5965
5966 typedef ContinuousRangeMap<Key, ModuleFile *, InitialCapacity> MapType;
5967 llvm::errs() << Name << ":\n";
5968 for (typename MapType::const_iterator I = Map.begin(), IEnd = Map.end();
5969 I != IEnd; ++I) {
5970 llvm::errs() << " " << I->first << " -> " << I->second->FileName
5971 << "\n";
5972 }
5973}
5974
5975void ASTReader::dump() {
5976 llvm::errs() << "*** PCH/ModuleFile Remappings:\n";
5977 dumpModuleIDMap("Global bit offset map", GlobalBitOffsetsMap);
5978 dumpModuleIDMap("Global source location entry map", GlobalSLocEntryMap);
5979 dumpModuleIDMap("Global type map", GlobalTypeMap);
5980 dumpModuleIDMap("Global declaration map", GlobalDeclMap);
5981 dumpModuleIDMap("Global identifier map", GlobalIdentifierMap);
5982 dumpModuleIDMap("Global macro map", GlobalMacroMap);
5983 dumpModuleIDMap("Global submodule map", GlobalSubmoduleMap);
5984 dumpModuleIDMap("Global selector map", GlobalSelectorMap);
5985 dumpModuleIDMap("Global preprocessed entity map",
5986 GlobalPreprocessedEntityMap);
5987
5988 llvm::errs() << "\n*** PCH/Modules Loaded:";
5989 for (ModuleManager::ModuleConstIterator M = ModuleMgr.begin(),
5990 MEnd = ModuleMgr.end();
5991 M != MEnd; ++M)
5992 (*M)->dump();
5993}
5994
5995/// Return the amount of memory used by memory buffers, breaking down
5996/// by heap-backed versus mmap'ed memory.
5997void ASTReader::getMemoryBufferSizes(MemoryBufferSizes &sizes) const {
5998 for (ModuleConstIterator I = ModuleMgr.begin(),
5999 E = ModuleMgr.end(); I != E; ++I) {
6000 if (llvm::MemoryBuffer *buf = (*I)->Buffer.get()) {
6001 size_t bytes = buf->getBufferSize();
6002 switch (buf->getBufferKind()) {
6003 case llvm::MemoryBuffer::MemoryBuffer_Malloc:
6004 sizes.malloc_bytes += bytes;
6005 break;
6006 case llvm::MemoryBuffer::MemoryBuffer_MMap:
6007 sizes.mmap_bytes += bytes;
6008 break;
6009 }
6010 }
6011 }
6012}
6013
6014void ASTReader::InitializeSema(Sema &S) {
6015 SemaObj = &S;
6016 S.addExternalSource(this);
6017
6018 // Makes sure any declarations that were deserialized "too early"
6019 // still get added to the identifier's declaration chains.
6020 for (unsigned I = 0, N = PreloadedDecls.size(); I != N; ++I) {
Argyrios Kyrtzidis0532df02013-04-26 21:33:35 +00006021 pushExternalDeclIntoScope(PreloadedDecls[I],
6022 PreloadedDecls[I]->getDeclName());
Guy Benyei7f92f2d2012-12-18 14:30:41 +00006023 }
6024 PreloadedDecls.clear();
6025
6026 // Load the offsets of the declarations that Sema references.
6027 // They will be lazily deserialized when needed.
6028 if (!SemaDeclRefs.empty()) {
6029 assert(SemaDeclRefs.size() == 2 && "More decl refs than expected!");
6030 if (!SemaObj->StdNamespace)
6031 SemaObj->StdNamespace = SemaDeclRefs[0];
6032 if (!SemaObj->StdBadAlloc)
6033 SemaObj->StdBadAlloc = SemaDeclRefs[1];
6034 }
6035
6036 if (!FPPragmaOptions.empty()) {
6037 assert(FPPragmaOptions.size() == 1 && "Wrong number of FP_PRAGMA_OPTIONS");
6038 SemaObj->FPFeatures.fp_contract = FPPragmaOptions[0];
6039 }
6040
6041 if (!OpenCLExtensions.empty()) {
6042 unsigned I = 0;
6043#define OPENCLEXT(nm) SemaObj->OpenCLFeatures.nm = OpenCLExtensions[I++];
6044#include "clang/Basic/OpenCLExtensions.def"
6045
6046 assert(OpenCLExtensions.size() == I && "Wrong number of OPENCL_EXTENSIONS");
6047 }
6048}
6049
6050IdentifierInfo* ASTReader::get(const char *NameStart, const char *NameEnd) {
6051 // Note that we are loading an identifier.
6052 Deserializing AnIdentifier(this);
Douglas Gregor1a49d972013-01-25 01:03:03 +00006053 StringRef Name(NameStart, NameEnd - NameStart);
6054
6055 // If there is a global index, look there first to determine which modules
6056 // provably do not have any results for this identifier.
Douglas Gregor188bdcd2013-01-25 23:32:03 +00006057 GlobalModuleIndex::HitSet Hits;
6058 GlobalModuleIndex::HitSet *HitsPtr = 0;
Douglas Gregor1a49d972013-01-25 01:03:03 +00006059 if (!loadGlobalIndex()) {
Douglas Gregor188bdcd2013-01-25 23:32:03 +00006060 if (GlobalIndex->lookupIdentifier(Name, Hits)) {
6061 HitsPtr = &Hits;
Douglas Gregor1a49d972013-01-25 01:03:03 +00006062 }
6063 }
Douglas Gregor188bdcd2013-01-25 23:32:03 +00006064 IdentifierLookupVisitor Visitor(Name, /*PriorGeneration=*/0,
Douglas Gregore1698072013-01-25 00:38:33 +00006065 NumIdentifierLookups,
6066 NumIdentifierLookupHits);
Douglas Gregor188bdcd2013-01-25 23:32:03 +00006067 ModuleMgr.visit(IdentifierLookupVisitor::visit, &Visitor, HitsPtr);
Guy Benyei7f92f2d2012-12-18 14:30:41 +00006068 IdentifierInfo *II = Visitor.getIdentifierInfo();
6069 markIdentifierUpToDate(II);
6070 return II;
6071}
6072
6073namespace clang {
6074 /// \brief An identifier-lookup iterator that enumerates all of the
6075 /// identifiers stored within a set of AST files.
6076 class ASTIdentifierIterator : public IdentifierIterator {
6077 /// \brief The AST reader whose identifiers are being enumerated.
6078 const ASTReader &Reader;
6079
6080 /// \brief The current index into the chain of AST files stored in
6081 /// the AST reader.
6082 unsigned Index;
6083
6084 /// \brief The current position within the identifier lookup table
6085 /// of the current AST file.
6086 ASTIdentifierLookupTable::key_iterator Current;
6087
6088 /// \brief The end position within the identifier lookup table of
6089 /// the current AST file.
6090 ASTIdentifierLookupTable::key_iterator End;
6091
6092 public:
6093 explicit ASTIdentifierIterator(const ASTReader &Reader);
6094
6095 virtual StringRef Next();
6096 };
6097}
6098
6099ASTIdentifierIterator::ASTIdentifierIterator(const ASTReader &Reader)
6100 : Reader(Reader), Index(Reader.ModuleMgr.size() - 1) {
6101 ASTIdentifierLookupTable *IdTable
6102 = (ASTIdentifierLookupTable *)Reader.ModuleMgr[Index].IdentifierLookupTable;
6103 Current = IdTable->key_begin();
6104 End = IdTable->key_end();
6105}
6106
6107StringRef ASTIdentifierIterator::Next() {
6108 while (Current == End) {
6109 // If we have exhausted all of our AST files, we're done.
6110 if (Index == 0)
6111 return StringRef();
6112
6113 --Index;
6114 ASTIdentifierLookupTable *IdTable
6115 = (ASTIdentifierLookupTable *)Reader.ModuleMgr[Index].
6116 IdentifierLookupTable;
6117 Current = IdTable->key_begin();
6118 End = IdTable->key_end();
6119 }
6120
6121 // We have any identifiers remaining in the current AST file; return
6122 // the next one.
Douglas Gregor479633c2013-01-23 18:53:14 +00006123 StringRef Result = *Current;
Guy Benyei7f92f2d2012-12-18 14:30:41 +00006124 ++Current;
Douglas Gregor479633c2013-01-23 18:53:14 +00006125 return Result;
Guy Benyei7f92f2d2012-12-18 14:30:41 +00006126}
6127
Argyrios Kyrtzidis87f9d812013-04-17 22:10:55 +00006128IdentifierIterator *ASTReader::getIdentifiers() {
6129 if (!loadGlobalIndex())
6130 return GlobalIndex->createIdentifierIterator();
6131
Guy Benyei7f92f2d2012-12-18 14:30:41 +00006132 return new ASTIdentifierIterator(*this);
6133}
6134
6135namespace clang { namespace serialization {
6136 class ReadMethodPoolVisitor {
6137 ASTReader &Reader;
6138 Selector Sel;
6139 unsigned PriorGeneration;
Argyrios Kyrtzidis2e3d8c02013-04-17 00:08:58 +00006140 unsigned InstanceBits;
6141 unsigned FactoryBits;
Dmitri Gribenkocfa88f82013-01-12 19:30:44 +00006142 SmallVector<ObjCMethodDecl *, 4> InstanceMethods;
6143 SmallVector<ObjCMethodDecl *, 4> FactoryMethods;
Guy Benyei7f92f2d2012-12-18 14:30:41 +00006144
6145 public:
6146 ReadMethodPoolVisitor(ASTReader &Reader, Selector Sel,
6147 unsigned PriorGeneration)
Argyrios Kyrtzidis2e3d8c02013-04-17 00:08:58 +00006148 : Reader(Reader), Sel(Sel), PriorGeneration(PriorGeneration),
6149 InstanceBits(0), FactoryBits(0) { }
Guy Benyei7f92f2d2012-12-18 14:30:41 +00006150
6151 static bool visit(ModuleFile &M, void *UserData) {
6152 ReadMethodPoolVisitor *This
6153 = static_cast<ReadMethodPoolVisitor *>(UserData);
6154
6155 if (!M.SelectorLookupTable)
6156 return false;
6157
6158 // If we've already searched this module file, skip it now.
6159 if (M.Generation <= This->PriorGeneration)
6160 return true;
6161
Douglas Gregor95fb36e2013-01-28 17:54:36 +00006162 ++This->Reader.NumMethodPoolTableLookups;
Guy Benyei7f92f2d2012-12-18 14:30:41 +00006163 ASTSelectorLookupTable *PoolTable
6164 = (ASTSelectorLookupTable*)M.SelectorLookupTable;
6165 ASTSelectorLookupTable::iterator Pos = PoolTable->find(This->Sel);
6166 if (Pos == PoolTable->end())
6167 return false;
Douglas Gregor95fb36e2013-01-28 17:54:36 +00006168
6169 ++This->Reader.NumMethodPoolTableHits;
Guy Benyei7f92f2d2012-12-18 14:30:41 +00006170 ++This->Reader.NumSelectorsRead;
6171 // FIXME: Not quite happy with the statistics here. We probably should
6172 // disable this tracking when called via LoadSelector.
6173 // Also, should entries without methods count as misses?
6174 ++This->Reader.NumMethodPoolEntriesRead;
6175 ASTSelectorLookupTrait::data_type Data = *Pos;
6176 if (This->Reader.DeserializationListener)
6177 This->Reader.DeserializationListener->SelectorRead(Data.ID,
6178 This->Sel);
6179
6180 This->InstanceMethods.append(Data.Instance.begin(), Data.Instance.end());
6181 This->FactoryMethods.append(Data.Factory.begin(), Data.Factory.end());
Argyrios Kyrtzidis2e3d8c02013-04-17 00:08:58 +00006182 This->InstanceBits = Data.InstanceBits;
6183 This->FactoryBits = Data.FactoryBits;
Guy Benyei7f92f2d2012-12-18 14:30:41 +00006184 return true;
6185 }
6186
6187 /// \brief Retrieve the instance methods found by this visitor.
6188 ArrayRef<ObjCMethodDecl *> getInstanceMethods() const {
6189 return InstanceMethods;
6190 }
6191
6192 /// \brief Retrieve the instance methods found by this visitor.
6193 ArrayRef<ObjCMethodDecl *> getFactoryMethods() const {
6194 return FactoryMethods;
6195 }
Argyrios Kyrtzidis2e3d8c02013-04-17 00:08:58 +00006196
6197 unsigned getInstanceBits() const { return InstanceBits; }
6198 unsigned getFactoryBits() const { return FactoryBits; }
Guy Benyei7f92f2d2012-12-18 14:30:41 +00006199 };
6200} } // end namespace clang::serialization
6201
6202/// \brief Add the given set of methods to the method list.
6203static void addMethodsToPool(Sema &S, ArrayRef<ObjCMethodDecl *> Methods,
6204 ObjCMethodList &List) {
6205 for (unsigned I = 0, N = Methods.size(); I != N; ++I) {
6206 S.addMethodToGlobalList(&List, Methods[I]);
6207 }
6208}
6209
6210void ASTReader::ReadMethodPool(Selector Sel) {
6211 // Get the selector generation and update it to the current generation.
6212 unsigned &Generation = SelectorGeneration[Sel];
6213 unsigned PriorGeneration = Generation;
6214 Generation = CurrentGeneration;
6215
6216 // Search for methods defined with this selector.
Douglas Gregor95fb36e2013-01-28 17:54:36 +00006217 ++NumMethodPoolLookups;
Guy Benyei7f92f2d2012-12-18 14:30:41 +00006218 ReadMethodPoolVisitor Visitor(*this, Sel, PriorGeneration);
6219 ModuleMgr.visit(&ReadMethodPoolVisitor::visit, &Visitor);
6220
6221 if (Visitor.getInstanceMethods().empty() &&
Douglas Gregor95fb36e2013-01-28 17:54:36 +00006222 Visitor.getFactoryMethods().empty())
Guy Benyei7f92f2d2012-12-18 14:30:41 +00006223 return;
Douglas Gregor95fb36e2013-01-28 17:54:36 +00006224
6225 ++NumMethodPoolHits;
6226
Guy Benyei7f92f2d2012-12-18 14:30:41 +00006227 if (!getSema())
6228 return;
6229
6230 Sema &S = *getSema();
6231 Sema::GlobalMethodPool::iterator Pos
6232 = S.MethodPool.insert(std::make_pair(Sel, Sema::GlobalMethods())).first;
6233
6234 addMethodsToPool(S, Visitor.getInstanceMethods(), Pos->second.first);
6235 addMethodsToPool(S, Visitor.getFactoryMethods(), Pos->second.second);
Argyrios Kyrtzidis2e3d8c02013-04-17 00:08:58 +00006236 Pos->second.first.setBits(Visitor.getInstanceBits());
6237 Pos->second.second.setBits(Visitor.getFactoryBits());
Guy Benyei7f92f2d2012-12-18 14:30:41 +00006238}
6239
6240void ASTReader::ReadKnownNamespaces(
6241 SmallVectorImpl<NamespaceDecl *> &Namespaces) {
6242 Namespaces.clear();
6243
6244 for (unsigned I = 0, N = KnownNamespaces.size(); I != N; ++I) {
6245 if (NamespaceDecl *Namespace
6246 = dyn_cast_or_null<NamespaceDecl>(GetDecl(KnownNamespaces[I])))
6247 Namespaces.push_back(Namespace);
6248 }
6249}
6250
Nick Lewyckycd0655b2013-02-01 08:13:20 +00006251void ASTReader::ReadUndefinedButUsed(
Nick Lewycky995e26b2013-01-31 03:23:57 +00006252 llvm::DenseMap<NamedDecl*, SourceLocation> &Undefined) {
Nick Lewyckycd0655b2013-02-01 08:13:20 +00006253 for (unsigned Idx = 0, N = UndefinedButUsed.size(); Idx != N;) {
6254 NamedDecl *D = cast<NamedDecl>(GetDecl(UndefinedButUsed[Idx++]));
Nick Lewycky01a41142013-01-26 00:35:08 +00006255 SourceLocation Loc =
Nick Lewyckycd0655b2013-02-01 08:13:20 +00006256 SourceLocation::getFromRawEncoding(UndefinedButUsed[Idx++]);
Nick Lewycky01a41142013-01-26 00:35:08 +00006257 Undefined.insert(std::make_pair(D, Loc));
6258 }
6259}
Nick Lewycky01a41142013-01-26 00:35:08 +00006260
Guy Benyei7f92f2d2012-12-18 14:30:41 +00006261void ASTReader::ReadTentativeDefinitions(
6262 SmallVectorImpl<VarDecl *> &TentativeDefs) {
6263 for (unsigned I = 0, N = TentativeDefinitions.size(); I != N; ++I) {
6264 VarDecl *Var = dyn_cast_or_null<VarDecl>(GetDecl(TentativeDefinitions[I]));
6265 if (Var)
6266 TentativeDefs.push_back(Var);
6267 }
6268 TentativeDefinitions.clear();
6269}
6270
6271void ASTReader::ReadUnusedFileScopedDecls(
6272 SmallVectorImpl<const DeclaratorDecl *> &Decls) {
6273 for (unsigned I = 0, N = UnusedFileScopedDecls.size(); I != N; ++I) {
6274 DeclaratorDecl *D
6275 = dyn_cast_or_null<DeclaratorDecl>(GetDecl(UnusedFileScopedDecls[I]));
6276 if (D)
6277 Decls.push_back(D);
6278 }
6279 UnusedFileScopedDecls.clear();
6280}
6281
6282void ASTReader::ReadDelegatingConstructors(
6283 SmallVectorImpl<CXXConstructorDecl *> &Decls) {
6284 for (unsigned I = 0, N = DelegatingCtorDecls.size(); I != N; ++I) {
6285 CXXConstructorDecl *D
6286 = dyn_cast_or_null<CXXConstructorDecl>(GetDecl(DelegatingCtorDecls[I]));
6287 if (D)
6288 Decls.push_back(D);
6289 }
6290 DelegatingCtorDecls.clear();
6291}
6292
6293void ASTReader::ReadExtVectorDecls(SmallVectorImpl<TypedefNameDecl *> &Decls) {
6294 for (unsigned I = 0, N = ExtVectorDecls.size(); I != N; ++I) {
6295 TypedefNameDecl *D
6296 = dyn_cast_or_null<TypedefNameDecl>(GetDecl(ExtVectorDecls[I]));
6297 if (D)
6298 Decls.push_back(D);
6299 }
6300 ExtVectorDecls.clear();
6301}
6302
6303void ASTReader::ReadDynamicClasses(SmallVectorImpl<CXXRecordDecl *> &Decls) {
6304 for (unsigned I = 0, N = DynamicClasses.size(); I != N; ++I) {
6305 CXXRecordDecl *D
6306 = dyn_cast_or_null<CXXRecordDecl>(GetDecl(DynamicClasses[I]));
6307 if (D)
6308 Decls.push_back(D);
6309 }
6310 DynamicClasses.clear();
6311}
6312
6313void
Richard Smith5ea6ef42013-01-10 23:43:47 +00006314ASTReader::ReadLocallyScopedExternCDecls(SmallVectorImpl<NamedDecl *> &Decls) {
6315 for (unsigned I = 0, N = LocallyScopedExternCDecls.size(); I != N; ++I) {
6316 NamedDecl *D
6317 = dyn_cast_or_null<NamedDecl>(GetDecl(LocallyScopedExternCDecls[I]));
Guy Benyei7f92f2d2012-12-18 14:30:41 +00006318 if (D)
6319 Decls.push_back(D);
6320 }
Richard Smith5ea6ef42013-01-10 23:43:47 +00006321 LocallyScopedExternCDecls.clear();
Guy Benyei7f92f2d2012-12-18 14:30:41 +00006322}
6323
6324void ASTReader::ReadReferencedSelectors(
6325 SmallVectorImpl<std::pair<Selector, SourceLocation> > &Sels) {
6326 if (ReferencedSelectorsData.empty())
6327 return;
6328
6329 // If there are @selector references added them to its pool. This is for
6330 // implementation of -Wselector.
6331 unsigned int DataSize = ReferencedSelectorsData.size()-1;
6332 unsigned I = 0;
6333 while (I < DataSize) {
6334 Selector Sel = DecodeSelector(ReferencedSelectorsData[I++]);
6335 SourceLocation SelLoc
6336 = SourceLocation::getFromRawEncoding(ReferencedSelectorsData[I++]);
6337 Sels.push_back(std::make_pair(Sel, SelLoc));
6338 }
6339 ReferencedSelectorsData.clear();
6340}
6341
6342void ASTReader::ReadWeakUndeclaredIdentifiers(
6343 SmallVectorImpl<std::pair<IdentifierInfo *, WeakInfo> > &WeakIDs) {
6344 if (WeakUndeclaredIdentifiers.empty())
6345 return;
6346
6347 for (unsigned I = 0, N = WeakUndeclaredIdentifiers.size(); I < N; /*none*/) {
6348 IdentifierInfo *WeakId
6349 = DecodeIdentifierInfo(WeakUndeclaredIdentifiers[I++]);
6350 IdentifierInfo *AliasId
6351 = DecodeIdentifierInfo(WeakUndeclaredIdentifiers[I++]);
6352 SourceLocation Loc
6353 = SourceLocation::getFromRawEncoding(WeakUndeclaredIdentifiers[I++]);
6354 bool Used = WeakUndeclaredIdentifiers[I++];
6355 WeakInfo WI(AliasId, Loc);
6356 WI.setUsed(Used);
6357 WeakIDs.push_back(std::make_pair(WeakId, WI));
6358 }
6359 WeakUndeclaredIdentifiers.clear();
6360}
6361
6362void ASTReader::ReadUsedVTables(SmallVectorImpl<ExternalVTableUse> &VTables) {
6363 for (unsigned Idx = 0, N = VTableUses.size(); Idx < N; /* In loop */) {
6364 ExternalVTableUse VT;
6365 VT.Record = dyn_cast_or_null<CXXRecordDecl>(GetDecl(VTableUses[Idx++]));
6366 VT.Location = SourceLocation::getFromRawEncoding(VTableUses[Idx++]);
6367 VT.DefinitionRequired = VTableUses[Idx++];
6368 VTables.push_back(VT);
6369 }
6370
6371 VTableUses.clear();
6372}
6373
6374void ASTReader::ReadPendingInstantiations(
6375 SmallVectorImpl<std::pair<ValueDecl *, SourceLocation> > &Pending) {
6376 for (unsigned Idx = 0, N = PendingInstantiations.size(); Idx < N;) {
6377 ValueDecl *D = cast<ValueDecl>(GetDecl(PendingInstantiations[Idx++]));
6378 SourceLocation Loc
6379 = SourceLocation::getFromRawEncoding(PendingInstantiations[Idx++]);
6380
6381 Pending.push_back(std::make_pair(D, Loc));
6382 }
6383 PendingInstantiations.clear();
6384}
6385
6386void ASTReader::LoadSelector(Selector Sel) {
6387 // It would be complicated to avoid reading the methods anyway. So don't.
6388 ReadMethodPool(Sel);
6389}
6390
6391void ASTReader::SetIdentifierInfo(IdentifierID ID, IdentifierInfo *II) {
6392 assert(ID && "Non-zero identifier ID required");
6393 assert(ID <= IdentifiersLoaded.size() && "identifier ID out of range");
6394 IdentifiersLoaded[ID - 1] = II;
6395 if (DeserializationListener)
6396 DeserializationListener->IdentifierRead(ID, II);
6397}
6398
6399/// \brief Set the globally-visible declarations associated with the given
6400/// identifier.
6401///
6402/// If the AST reader is currently in a state where the given declaration IDs
6403/// cannot safely be resolved, they are queued until it is safe to resolve
6404/// them.
6405///
6406/// \param II an IdentifierInfo that refers to one or more globally-visible
6407/// declarations.
6408///
6409/// \param DeclIDs the set of declaration IDs with the name @p II that are
6410/// visible at global scope.
6411///
Douglas Gregoraa945902013-02-18 15:53:43 +00006412/// \param Decls if non-null, this vector will be populated with the set of
6413/// deserialized declarations. These declarations will not be pushed into
6414/// scope.
Guy Benyei7f92f2d2012-12-18 14:30:41 +00006415void
6416ASTReader::SetGloballyVisibleDecls(IdentifierInfo *II,
6417 const SmallVectorImpl<uint32_t> &DeclIDs,
Douglas Gregoraa945902013-02-18 15:53:43 +00006418 SmallVectorImpl<Decl *> *Decls) {
6419 if (NumCurrentElementsDeserializing && !Decls) {
6420 PendingIdentifierInfos[II].append(DeclIDs.begin(), DeclIDs.end());
Guy Benyei7f92f2d2012-12-18 14:30:41 +00006421 return;
6422 }
6423
6424 for (unsigned I = 0, N = DeclIDs.size(); I != N; ++I) {
6425 NamedDecl *D = cast<NamedDecl>(GetDecl(DeclIDs[I]));
6426 if (SemaObj) {
Douglas Gregoraa945902013-02-18 15:53:43 +00006427 // If we're simply supposed to record the declarations, do so now.
6428 if (Decls) {
6429 Decls->push_back(D);
6430 continue;
6431 }
6432
Guy Benyei7f92f2d2012-12-18 14:30:41 +00006433 // Introduce this declaration into the translation-unit scope
6434 // and add it to the declaration chain for this identifier, so
6435 // that (unqualified) name lookup will find it.
Argyrios Kyrtzidis0532df02013-04-26 21:33:35 +00006436 pushExternalDeclIntoScope(D, II);
Guy Benyei7f92f2d2012-12-18 14:30:41 +00006437 } else {
6438 // Queue this declaration so that it will be added to the
6439 // translation unit scope and identifier's declaration chain
6440 // once a Sema object is known.
6441 PreloadedDecls.push_back(D);
6442 }
6443 }
6444}
6445
Douglas Gregor8222b892013-01-21 16:52:34 +00006446IdentifierInfo *ASTReader::DecodeIdentifierInfo(IdentifierID ID) {
Guy Benyei7f92f2d2012-12-18 14:30:41 +00006447 if (ID == 0)
6448 return 0;
6449
6450 if (IdentifiersLoaded.empty()) {
6451 Error("no identifier table in AST file");
6452 return 0;
6453 }
6454
6455 ID -= 1;
6456 if (!IdentifiersLoaded[ID]) {
6457 GlobalIdentifierMapType::iterator I = GlobalIdentifierMap.find(ID + 1);
6458 assert(I != GlobalIdentifierMap.end() && "Corrupted global identifier map");
6459 ModuleFile *M = I->second;
6460 unsigned Index = ID - M->BaseIdentifierID;
6461 const char *Str = M->IdentifierTableData + M->IdentifierOffsets[Index];
6462
6463 // All of the strings in the AST file are preceded by a 16-bit length.
6464 // Extract that 16-bit length to avoid having to execute strlen().
6465 // NOTE: 'StrLenPtr' is an 'unsigned char*' so that we load bytes as
6466 // unsigned integers. This is important to avoid integer overflow when
6467 // we cast them to 'unsigned'.
6468 const unsigned char *StrLenPtr = (const unsigned char*) Str - 2;
6469 unsigned StrLen = (((unsigned) StrLenPtr[0])
6470 | (((unsigned) StrLenPtr[1]) << 8)) - 1;
Douglas Gregor8222b892013-01-21 16:52:34 +00006471 IdentifiersLoaded[ID]
6472 = &PP.getIdentifierTable().get(StringRef(Str, StrLen));
Guy Benyei7f92f2d2012-12-18 14:30:41 +00006473 if (DeserializationListener)
6474 DeserializationListener->IdentifierRead(ID + 1, IdentifiersLoaded[ID]);
6475 }
6476
6477 return IdentifiersLoaded[ID];
6478}
6479
Douglas Gregor8222b892013-01-21 16:52:34 +00006480IdentifierInfo *ASTReader::getLocalIdentifier(ModuleFile &M, unsigned LocalID) {
6481 return DecodeIdentifierInfo(getGlobalIdentifierID(M, LocalID));
Guy Benyei7f92f2d2012-12-18 14:30:41 +00006482}
6483
6484IdentifierID ASTReader::getGlobalIdentifierID(ModuleFile &M, unsigned LocalID) {
6485 if (LocalID < NUM_PREDEF_IDENT_IDS)
6486 return LocalID;
6487
6488 ContinuousRangeMap<uint32_t, int, 2>::iterator I
6489 = M.IdentifierRemap.find(LocalID - NUM_PREDEF_IDENT_IDS);
6490 assert(I != M.IdentifierRemap.end()
6491 && "Invalid index into identifier index remap");
6492
6493 return LocalID + I->second;
6494}
6495
Argyrios Kyrtzidis9317ab92013-03-22 21:12:57 +00006496MacroInfo *ASTReader::getMacro(MacroID ID) {
Guy Benyei7f92f2d2012-12-18 14:30:41 +00006497 if (ID == 0)
6498 return 0;
6499
6500 if (MacrosLoaded.empty()) {
6501 Error("no macro table in AST file");
6502 return 0;
6503 }
6504
6505 ID -= NUM_PREDEF_MACRO_IDS;
6506 if (!MacrosLoaded[ID]) {
6507 GlobalMacroMapType::iterator I
6508 = GlobalMacroMap.find(ID + NUM_PREDEF_MACRO_IDS);
6509 assert(I != GlobalMacroMap.end() && "Corrupted global macro map");
6510 ModuleFile *M = I->second;
6511 unsigned Index = ID - M->BaseMacroID;
Argyrios Kyrtzidis9317ab92013-03-22 21:12:57 +00006512 MacrosLoaded[ID] = ReadMacroRecord(*M, M->MacroOffsets[Index]);
6513
6514 if (DeserializationListener)
6515 DeserializationListener->MacroRead(ID + NUM_PREDEF_MACRO_IDS,
6516 MacrosLoaded[ID]);
Guy Benyei7f92f2d2012-12-18 14:30:41 +00006517 }
6518
6519 return MacrosLoaded[ID];
6520}
6521
6522MacroID ASTReader::getGlobalMacroID(ModuleFile &M, unsigned LocalID) {
6523 if (LocalID < NUM_PREDEF_MACRO_IDS)
6524 return LocalID;
6525
6526 ContinuousRangeMap<uint32_t, int, 2>::iterator I
6527 = M.MacroRemap.find(LocalID - NUM_PREDEF_MACRO_IDS);
6528 assert(I != M.MacroRemap.end() && "Invalid index into macro index remap");
6529
6530 return LocalID + I->second;
6531}
6532
6533serialization::SubmoduleID
6534ASTReader::getGlobalSubmoduleID(ModuleFile &M, unsigned LocalID) {
6535 if (LocalID < NUM_PREDEF_SUBMODULE_IDS)
6536 return LocalID;
6537
6538 ContinuousRangeMap<uint32_t, int, 2>::iterator I
6539 = M.SubmoduleRemap.find(LocalID - NUM_PREDEF_SUBMODULE_IDS);
6540 assert(I != M.SubmoduleRemap.end()
6541 && "Invalid index into submodule index remap");
6542
6543 return LocalID + I->second;
6544}
6545
6546Module *ASTReader::getSubmodule(SubmoduleID GlobalID) {
6547 if (GlobalID < NUM_PREDEF_SUBMODULE_IDS) {
6548 assert(GlobalID == 0 && "Unhandled global submodule ID");
6549 return 0;
6550 }
6551
6552 if (GlobalID > SubmodulesLoaded.size()) {
6553 Error("submodule ID out of range in AST file");
6554 return 0;
6555 }
6556
6557 return SubmodulesLoaded[GlobalID - NUM_PREDEF_SUBMODULE_IDS];
6558}
Douglas Gregorca2ab452013-01-12 01:29:50 +00006559
6560Module *ASTReader::getModule(unsigned ID) {
6561 return getSubmodule(ID);
6562}
6563
Guy Benyei7f92f2d2012-12-18 14:30:41 +00006564Selector ASTReader::getLocalSelector(ModuleFile &M, unsigned LocalID) {
6565 return DecodeSelector(getGlobalSelectorID(M, LocalID));
6566}
6567
6568Selector ASTReader::DecodeSelector(serialization::SelectorID ID) {
6569 if (ID == 0)
6570 return Selector();
6571
6572 if (ID > SelectorsLoaded.size()) {
6573 Error("selector ID out of range in AST file");
6574 return Selector();
6575 }
6576
6577 if (SelectorsLoaded[ID - 1].getAsOpaquePtr() == 0) {
6578 // Load this selector from the selector table.
6579 GlobalSelectorMapType::iterator I = GlobalSelectorMap.find(ID);
6580 assert(I != GlobalSelectorMap.end() && "Corrupted global selector map");
6581 ModuleFile &M = *I->second;
6582 ASTSelectorLookupTrait Trait(*this, M);
6583 unsigned Idx = ID - M.BaseSelectorID - NUM_PREDEF_SELECTOR_IDS;
6584 SelectorsLoaded[ID - 1] =
6585 Trait.ReadKey(M.SelectorLookupTableData + M.SelectorOffsets[Idx], 0);
6586 if (DeserializationListener)
6587 DeserializationListener->SelectorRead(ID, SelectorsLoaded[ID - 1]);
6588 }
6589
6590 return SelectorsLoaded[ID - 1];
6591}
6592
6593Selector ASTReader::GetExternalSelector(serialization::SelectorID ID) {
6594 return DecodeSelector(ID);
6595}
6596
6597uint32_t ASTReader::GetNumExternalSelectors() {
6598 // ID 0 (the null selector) is considered an external selector.
6599 return getTotalNumSelectors() + 1;
6600}
6601
6602serialization::SelectorID
6603ASTReader::getGlobalSelectorID(ModuleFile &M, unsigned LocalID) const {
6604 if (LocalID < NUM_PREDEF_SELECTOR_IDS)
6605 return LocalID;
6606
6607 ContinuousRangeMap<uint32_t, int, 2>::iterator I
6608 = M.SelectorRemap.find(LocalID - NUM_PREDEF_SELECTOR_IDS);
6609 assert(I != M.SelectorRemap.end()
6610 && "Invalid index into selector index remap");
6611
6612 return LocalID + I->second;
6613}
6614
6615DeclarationName
6616ASTReader::ReadDeclarationName(ModuleFile &F,
6617 const RecordData &Record, unsigned &Idx) {
6618 DeclarationName::NameKind Kind = (DeclarationName::NameKind)Record[Idx++];
6619 switch (Kind) {
6620 case DeclarationName::Identifier:
Douglas Gregor8222b892013-01-21 16:52:34 +00006621 return DeclarationName(GetIdentifierInfo(F, Record, Idx));
Guy Benyei7f92f2d2012-12-18 14:30:41 +00006622
6623 case DeclarationName::ObjCZeroArgSelector:
6624 case DeclarationName::ObjCOneArgSelector:
6625 case DeclarationName::ObjCMultiArgSelector:
6626 return DeclarationName(ReadSelector(F, Record, Idx));
6627
6628 case DeclarationName::CXXConstructorName:
6629 return Context.DeclarationNames.getCXXConstructorName(
6630 Context.getCanonicalType(readType(F, Record, Idx)));
6631
6632 case DeclarationName::CXXDestructorName:
6633 return Context.DeclarationNames.getCXXDestructorName(
6634 Context.getCanonicalType(readType(F, Record, Idx)));
6635
6636 case DeclarationName::CXXConversionFunctionName:
6637 return Context.DeclarationNames.getCXXConversionFunctionName(
6638 Context.getCanonicalType(readType(F, Record, Idx)));
6639
6640 case DeclarationName::CXXOperatorName:
6641 return Context.DeclarationNames.getCXXOperatorName(
6642 (OverloadedOperatorKind)Record[Idx++]);
6643
6644 case DeclarationName::CXXLiteralOperatorName:
6645 return Context.DeclarationNames.getCXXLiteralOperatorName(
6646 GetIdentifierInfo(F, Record, Idx));
6647
6648 case DeclarationName::CXXUsingDirective:
6649 return DeclarationName::getUsingDirectiveName();
6650 }
6651
6652 llvm_unreachable("Invalid NameKind!");
6653}
6654
6655void ASTReader::ReadDeclarationNameLoc(ModuleFile &F,
6656 DeclarationNameLoc &DNLoc,
6657 DeclarationName Name,
6658 const RecordData &Record, unsigned &Idx) {
6659 switch (Name.getNameKind()) {
6660 case DeclarationName::CXXConstructorName:
6661 case DeclarationName::CXXDestructorName:
6662 case DeclarationName::CXXConversionFunctionName:
6663 DNLoc.NamedType.TInfo = GetTypeSourceInfo(F, Record, Idx);
6664 break;
6665
6666 case DeclarationName::CXXOperatorName:
6667 DNLoc.CXXOperatorName.BeginOpNameLoc
6668 = ReadSourceLocation(F, Record, Idx).getRawEncoding();
6669 DNLoc.CXXOperatorName.EndOpNameLoc
6670 = ReadSourceLocation(F, Record, Idx).getRawEncoding();
6671 break;
6672
6673 case DeclarationName::CXXLiteralOperatorName:
6674 DNLoc.CXXLiteralOperatorName.OpNameLoc
6675 = ReadSourceLocation(F, Record, Idx).getRawEncoding();
6676 break;
6677
6678 case DeclarationName::Identifier:
6679 case DeclarationName::ObjCZeroArgSelector:
6680 case DeclarationName::ObjCOneArgSelector:
6681 case DeclarationName::ObjCMultiArgSelector:
6682 case DeclarationName::CXXUsingDirective:
6683 break;
6684 }
6685}
6686
6687void ASTReader::ReadDeclarationNameInfo(ModuleFile &F,
6688 DeclarationNameInfo &NameInfo,
6689 const RecordData &Record, unsigned &Idx) {
6690 NameInfo.setName(ReadDeclarationName(F, Record, Idx));
6691 NameInfo.setLoc(ReadSourceLocation(F, Record, Idx));
6692 DeclarationNameLoc DNLoc;
6693 ReadDeclarationNameLoc(F, DNLoc, NameInfo.getName(), Record, Idx);
6694 NameInfo.setInfo(DNLoc);
6695}
6696
6697void ASTReader::ReadQualifierInfo(ModuleFile &F, QualifierInfo &Info,
6698 const RecordData &Record, unsigned &Idx) {
6699 Info.QualifierLoc = ReadNestedNameSpecifierLoc(F, Record, Idx);
6700 unsigned NumTPLists = Record[Idx++];
6701 Info.NumTemplParamLists = NumTPLists;
6702 if (NumTPLists) {
6703 Info.TemplParamLists = new (Context) TemplateParameterList*[NumTPLists];
6704 for (unsigned i=0; i != NumTPLists; ++i)
6705 Info.TemplParamLists[i] = ReadTemplateParameterList(F, Record, Idx);
6706 }
6707}
6708
6709TemplateName
6710ASTReader::ReadTemplateName(ModuleFile &F, const RecordData &Record,
6711 unsigned &Idx) {
6712 TemplateName::NameKind Kind = (TemplateName::NameKind)Record[Idx++];
6713 switch (Kind) {
6714 case TemplateName::Template:
6715 return TemplateName(ReadDeclAs<TemplateDecl>(F, Record, Idx));
6716
6717 case TemplateName::OverloadedTemplate: {
6718 unsigned size = Record[Idx++];
6719 UnresolvedSet<8> Decls;
6720 while (size--)
6721 Decls.addDecl(ReadDeclAs<NamedDecl>(F, Record, Idx));
6722
6723 return Context.getOverloadedTemplateName(Decls.begin(), Decls.end());
6724 }
6725
6726 case TemplateName::QualifiedTemplate: {
6727 NestedNameSpecifier *NNS = ReadNestedNameSpecifier(F, Record, Idx);
6728 bool hasTemplKeyword = Record[Idx++];
6729 TemplateDecl *Template = ReadDeclAs<TemplateDecl>(F, Record, Idx);
6730 return Context.getQualifiedTemplateName(NNS, hasTemplKeyword, Template);
6731 }
6732
6733 case TemplateName::DependentTemplate: {
6734 NestedNameSpecifier *NNS = ReadNestedNameSpecifier(F, Record, Idx);
6735 if (Record[Idx++]) // isIdentifier
6736 return Context.getDependentTemplateName(NNS,
6737 GetIdentifierInfo(F, Record,
6738 Idx));
6739 return Context.getDependentTemplateName(NNS,
6740 (OverloadedOperatorKind)Record[Idx++]);
6741 }
6742
6743 case TemplateName::SubstTemplateTemplateParm: {
6744 TemplateTemplateParmDecl *param
6745 = ReadDeclAs<TemplateTemplateParmDecl>(F, Record, Idx);
6746 if (!param) return TemplateName();
6747 TemplateName replacement = ReadTemplateName(F, Record, Idx);
6748 return Context.getSubstTemplateTemplateParm(param, replacement);
6749 }
6750
6751 case TemplateName::SubstTemplateTemplateParmPack: {
6752 TemplateTemplateParmDecl *Param
6753 = ReadDeclAs<TemplateTemplateParmDecl>(F, Record, Idx);
6754 if (!Param)
6755 return TemplateName();
6756
6757 TemplateArgument ArgPack = ReadTemplateArgument(F, Record, Idx);
6758 if (ArgPack.getKind() != TemplateArgument::Pack)
6759 return TemplateName();
6760
6761 return Context.getSubstTemplateTemplateParmPack(Param, ArgPack);
6762 }
6763 }
6764
6765 llvm_unreachable("Unhandled template name kind!");
6766}
6767
6768TemplateArgument
6769ASTReader::ReadTemplateArgument(ModuleFile &F,
6770 const RecordData &Record, unsigned &Idx) {
6771 TemplateArgument::ArgKind Kind = (TemplateArgument::ArgKind)Record[Idx++];
6772 switch (Kind) {
6773 case TemplateArgument::Null:
6774 return TemplateArgument();
6775 case TemplateArgument::Type:
6776 return TemplateArgument(readType(F, Record, Idx));
6777 case TemplateArgument::Declaration: {
6778 ValueDecl *D = ReadDeclAs<ValueDecl>(F, Record, Idx);
6779 bool ForReferenceParam = Record[Idx++];
6780 return TemplateArgument(D, ForReferenceParam);
6781 }
6782 case TemplateArgument::NullPtr:
6783 return TemplateArgument(readType(F, Record, Idx), /*isNullPtr*/true);
6784 case TemplateArgument::Integral: {
6785 llvm::APSInt Value = ReadAPSInt(Record, Idx);
6786 QualType T = readType(F, Record, Idx);
6787 return TemplateArgument(Context, Value, T);
6788 }
6789 case TemplateArgument::Template:
6790 return TemplateArgument(ReadTemplateName(F, Record, Idx));
6791 case TemplateArgument::TemplateExpansion: {
6792 TemplateName Name = ReadTemplateName(F, Record, Idx);
David Blaikiedc84cd52013-02-20 22:23:23 +00006793 Optional<unsigned> NumTemplateExpansions;
Guy Benyei7f92f2d2012-12-18 14:30:41 +00006794 if (unsigned NumExpansions = Record[Idx++])
6795 NumTemplateExpansions = NumExpansions - 1;
6796 return TemplateArgument(Name, NumTemplateExpansions);
6797 }
6798 case TemplateArgument::Expression:
6799 return TemplateArgument(ReadExpr(F));
6800 case TemplateArgument::Pack: {
6801 unsigned NumArgs = Record[Idx++];
6802 TemplateArgument *Args = new (Context) TemplateArgument[NumArgs];
6803 for (unsigned I = 0; I != NumArgs; ++I)
6804 Args[I] = ReadTemplateArgument(F, Record, Idx);
6805 return TemplateArgument(Args, NumArgs);
6806 }
6807 }
6808
6809 llvm_unreachable("Unhandled template argument kind!");
6810}
6811
6812TemplateParameterList *
6813ASTReader::ReadTemplateParameterList(ModuleFile &F,
6814 const RecordData &Record, unsigned &Idx) {
6815 SourceLocation TemplateLoc = ReadSourceLocation(F, Record, Idx);
6816 SourceLocation LAngleLoc = ReadSourceLocation(F, Record, Idx);
6817 SourceLocation RAngleLoc = ReadSourceLocation(F, Record, Idx);
6818
6819 unsigned NumParams = Record[Idx++];
6820 SmallVector<NamedDecl *, 16> Params;
6821 Params.reserve(NumParams);
6822 while (NumParams--)
6823 Params.push_back(ReadDeclAs<NamedDecl>(F, Record, Idx));
6824
6825 TemplateParameterList* TemplateParams =
6826 TemplateParameterList::Create(Context, TemplateLoc, LAngleLoc,
6827 Params.data(), Params.size(), RAngleLoc);
6828 return TemplateParams;
6829}
6830
6831void
6832ASTReader::
6833ReadTemplateArgumentList(SmallVector<TemplateArgument, 8> &TemplArgs,
6834 ModuleFile &F, const RecordData &Record,
6835 unsigned &Idx) {
6836 unsigned NumTemplateArgs = Record[Idx++];
6837 TemplArgs.reserve(NumTemplateArgs);
6838 while (NumTemplateArgs--)
6839 TemplArgs.push_back(ReadTemplateArgument(F, Record, Idx));
6840}
6841
6842/// \brief Read a UnresolvedSet structure.
6843void ASTReader::ReadUnresolvedSet(ModuleFile &F, ASTUnresolvedSet &Set,
6844 const RecordData &Record, unsigned &Idx) {
6845 unsigned NumDecls = Record[Idx++];
6846 Set.reserve(Context, NumDecls);
6847 while (NumDecls--) {
6848 NamedDecl *D = ReadDeclAs<NamedDecl>(F, Record, Idx);
6849 AccessSpecifier AS = (AccessSpecifier)Record[Idx++];
6850 Set.addDecl(Context, D, AS);
6851 }
6852}
6853
6854CXXBaseSpecifier
6855ASTReader::ReadCXXBaseSpecifier(ModuleFile &F,
6856 const RecordData &Record, unsigned &Idx) {
6857 bool isVirtual = static_cast<bool>(Record[Idx++]);
6858 bool isBaseOfClass = static_cast<bool>(Record[Idx++]);
6859 AccessSpecifier AS = static_cast<AccessSpecifier>(Record[Idx++]);
6860 bool inheritConstructors = static_cast<bool>(Record[Idx++]);
6861 TypeSourceInfo *TInfo = GetTypeSourceInfo(F, Record, Idx);
6862 SourceRange Range = ReadSourceRange(F, Record, Idx);
6863 SourceLocation EllipsisLoc = ReadSourceLocation(F, Record, Idx);
6864 CXXBaseSpecifier Result(Range, isVirtual, isBaseOfClass, AS, TInfo,
6865 EllipsisLoc);
6866 Result.setInheritConstructors(inheritConstructors);
6867 return Result;
6868}
6869
6870std::pair<CXXCtorInitializer **, unsigned>
6871ASTReader::ReadCXXCtorInitializers(ModuleFile &F, const RecordData &Record,
6872 unsigned &Idx) {
6873 CXXCtorInitializer **CtorInitializers = 0;
6874 unsigned NumInitializers = Record[Idx++];
6875 if (NumInitializers) {
6876 CtorInitializers
6877 = new (Context) CXXCtorInitializer*[NumInitializers];
6878 for (unsigned i=0; i != NumInitializers; ++i) {
6879 TypeSourceInfo *TInfo = 0;
6880 bool IsBaseVirtual = false;
6881 FieldDecl *Member = 0;
6882 IndirectFieldDecl *IndirectMember = 0;
6883
6884 CtorInitializerType Type = (CtorInitializerType)Record[Idx++];
6885 switch (Type) {
6886 case CTOR_INITIALIZER_BASE:
6887 TInfo = GetTypeSourceInfo(F, Record, Idx);
6888 IsBaseVirtual = Record[Idx++];
6889 break;
6890
6891 case CTOR_INITIALIZER_DELEGATING:
6892 TInfo = GetTypeSourceInfo(F, Record, Idx);
6893 break;
6894
6895 case CTOR_INITIALIZER_MEMBER:
6896 Member = ReadDeclAs<FieldDecl>(F, Record, Idx);
6897 break;
6898
6899 case CTOR_INITIALIZER_INDIRECT_MEMBER:
6900 IndirectMember = ReadDeclAs<IndirectFieldDecl>(F, Record, Idx);
6901 break;
6902 }
6903
6904 SourceLocation MemberOrEllipsisLoc = ReadSourceLocation(F, Record, Idx);
6905 Expr *Init = ReadExpr(F);
6906 SourceLocation LParenLoc = ReadSourceLocation(F, Record, Idx);
6907 SourceLocation RParenLoc = ReadSourceLocation(F, Record, Idx);
6908 bool IsWritten = Record[Idx++];
6909 unsigned SourceOrderOrNumArrayIndices;
6910 SmallVector<VarDecl *, 8> Indices;
6911 if (IsWritten) {
6912 SourceOrderOrNumArrayIndices = Record[Idx++];
6913 } else {
6914 SourceOrderOrNumArrayIndices = Record[Idx++];
6915 Indices.reserve(SourceOrderOrNumArrayIndices);
6916 for (unsigned i=0; i != SourceOrderOrNumArrayIndices; ++i)
6917 Indices.push_back(ReadDeclAs<VarDecl>(F, Record, Idx));
6918 }
6919
6920 CXXCtorInitializer *BOMInit;
6921 if (Type == CTOR_INITIALIZER_BASE) {
6922 BOMInit = new (Context) CXXCtorInitializer(Context, TInfo, IsBaseVirtual,
6923 LParenLoc, Init, RParenLoc,
6924 MemberOrEllipsisLoc);
6925 } else if (Type == CTOR_INITIALIZER_DELEGATING) {
6926 BOMInit = new (Context) CXXCtorInitializer(Context, TInfo, LParenLoc,
6927 Init, RParenLoc);
6928 } else if (IsWritten) {
6929 if (Member)
6930 BOMInit = new (Context) CXXCtorInitializer(Context, Member, MemberOrEllipsisLoc,
6931 LParenLoc, Init, RParenLoc);
6932 else
6933 BOMInit = new (Context) CXXCtorInitializer(Context, IndirectMember,
6934 MemberOrEllipsisLoc, LParenLoc,
6935 Init, RParenLoc);
6936 } else {
6937 BOMInit = CXXCtorInitializer::Create(Context, Member, MemberOrEllipsisLoc,
6938 LParenLoc, Init, RParenLoc,
6939 Indices.data(), Indices.size());
6940 }
6941
6942 if (IsWritten)
6943 BOMInit->setSourceOrder(SourceOrderOrNumArrayIndices);
6944 CtorInitializers[i] = BOMInit;
6945 }
6946 }
6947
6948 return std::make_pair(CtorInitializers, NumInitializers);
6949}
6950
6951NestedNameSpecifier *
6952ASTReader::ReadNestedNameSpecifier(ModuleFile &F,
6953 const RecordData &Record, unsigned &Idx) {
6954 unsigned N = Record[Idx++];
6955 NestedNameSpecifier *NNS = 0, *Prev = 0;
6956 for (unsigned I = 0; I != N; ++I) {
6957 NestedNameSpecifier::SpecifierKind Kind
6958 = (NestedNameSpecifier::SpecifierKind)Record[Idx++];
6959 switch (Kind) {
6960 case NestedNameSpecifier::Identifier: {
6961 IdentifierInfo *II = GetIdentifierInfo(F, Record, Idx);
6962 NNS = NestedNameSpecifier::Create(Context, Prev, II);
6963 break;
6964 }
6965
6966 case NestedNameSpecifier::Namespace: {
6967 NamespaceDecl *NS = ReadDeclAs<NamespaceDecl>(F, Record, Idx);
6968 NNS = NestedNameSpecifier::Create(Context, Prev, NS);
6969 break;
6970 }
6971
6972 case NestedNameSpecifier::NamespaceAlias: {
6973 NamespaceAliasDecl *Alias =ReadDeclAs<NamespaceAliasDecl>(F, Record, Idx);
6974 NNS = NestedNameSpecifier::Create(Context, Prev, Alias);
6975 break;
6976 }
6977
6978 case NestedNameSpecifier::TypeSpec:
6979 case NestedNameSpecifier::TypeSpecWithTemplate: {
6980 const Type *T = readType(F, Record, Idx).getTypePtrOrNull();
6981 if (!T)
6982 return 0;
6983
6984 bool Template = Record[Idx++];
6985 NNS = NestedNameSpecifier::Create(Context, Prev, Template, T);
6986 break;
6987 }
6988
6989 case NestedNameSpecifier::Global: {
6990 NNS = NestedNameSpecifier::GlobalSpecifier(Context);
6991 // No associated value, and there can't be a prefix.
6992 break;
6993 }
6994 }
6995 Prev = NNS;
6996 }
6997 return NNS;
6998}
6999
7000NestedNameSpecifierLoc
7001ASTReader::ReadNestedNameSpecifierLoc(ModuleFile &F, const RecordData &Record,
7002 unsigned &Idx) {
7003 unsigned N = Record[Idx++];
7004 NestedNameSpecifierLocBuilder Builder;
7005 for (unsigned I = 0; I != N; ++I) {
7006 NestedNameSpecifier::SpecifierKind Kind
7007 = (NestedNameSpecifier::SpecifierKind)Record[Idx++];
7008 switch (Kind) {
7009 case NestedNameSpecifier::Identifier: {
7010 IdentifierInfo *II = GetIdentifierInfo(F, Record, Idx);
7011 SourceRange Range = ReadSourceRange(F, Record, Idx);
7012 Builder.Extend(Context, II, Range.getBegin(), Range.getEnd());
7013 break;
7014 }
7015
7016 case NestedNameSpecifier::Namespace: {
7017 NamespaceDecl *NS = ReadDeclAs<NamespaceDecl>(F, Record, Idx);
7018 SourceRange Range = ReadSourceRange(F, Record, Idx);
7019 Builder.Extend(Context, NS, Range.getBegin(), Range.getEnd());
7020 break;
7021 }
7022
7023 case NestedNameSpecifier::NamespaceAlias: {
7024 NamespaceAliasDecl *Alias =ReadDeclAs<NamespaceAliasDecl>(F, Record, Idx);
7025 SourceRange Range = ReadSourceRange(F, Record, Idx);
7026 Builder.Extend(Context, Alias, Range.getBegin(), Range.getEnd());
7027 break;
7028 }
7029
7030 case NestedNameSpecifier::TypeSpec:
7031 case NestedNameSpecifier::TypeSpecWithTemplate: {
7032 bool Template = Record[Idx++];
7033 TypeSourceInfo *T = GetTypeSourceInfo(F, Record, Idx);
7034 if (!T)
7035 return NestedNameSpecifierLoc();
7036 SourceLocation ColonColonLoc = ReadSourceLocation(F, Record, Idx);
7037
7038 // FIXME: 'template' keyword location not saved anywhere, so we fake it.
7039 Builder.Extend(Context,
7040 Template? T->getTypeLoc().getBeginLoc() : SourceLocation(),
7041 T->getTypeLoc(), ColonColonLoc);
7042 break;
7043 }
7044
7045 case NestedNameSpecifier::Global: {
7046 SourceLocation ColonColonLoc = ReadSourceLocation(F, Record, Idx);
7047 Builder.MakeGlobal(Context, ColonColonLoc);
7048 break;
7049 }
7050 }
7051 }
7052
7053 return Builder.getWithLocInContext(Context);
7054}
7055
7056SourceRange
7057ASTReader::ReadSourceRange(ModuleFile &F, const RecordData &Record,
7058 unsigned &Idx) {
7059 SourceLocation beg = ReadSourceLocation(F, Record, Idx);
7060 SourceLocation end = ReadSourceLocation(F, Record, Idx);
7061 return SourceRange(beg, end);
7062}
7063
7064/// \brief Read an integral value
7065llvm::APInt ASTReader::ReadAPInt(const RecordData &Record, unsigned &Idx) {
7066 unsigned BitWidth = Record[Idx++];
7067 unsigned NumWords = llvm::APInt::getNumWords(BitWidth);
7068 llvm::APInt Result(BitWidth, NumWords, &Record[Idx]);
7069 Idx += NumWords;
7070 return Result;
7071}
7072
7073/// \brief Read a signed integral value
7074llvm::APSInt ASTReader::ReadAPSInt(const RecordData &Record, unsigned &Idx) {
7075 bool isUnsigned = Record[Idx++];
7076 return llvm::APSInt(ReadAPInt(Record, Idx), isUnsigned);
7077}
7078
7079/// \brief Read a floating-point value
Tim Northover9ec55f22013-01-22 09:46:51 +00007080llvm::APFloat ASTReader::ReadAPFloat(const RecordData &Record,
7081 const llvm::fltSemantics &Sem,
7082 unsigned &Idx) {
7083 return llvm::APFloat(Sem, ReadAPInt(Record, Idx));
Guy Benyei7f92f2d2012-12-18 14:30:41 +00007084}
7085
7086// \brief Read a string
7087std::string ASTReader::ReadString(const RecordData &Record, unsigned &Idx) {
7088 unsigned Len = Record[Idx++];
7089 std::string Result(Record.data() + Idx, Record.data() + Idx + Len);
7090 Idx += Len;
7091 return Result;
7092}
7093
7094VersionTuple ASTReader::ReadVersionTuple(const RecordData &Record,
7095 unsigned &Idx) {
7096 unsigned Major = Record[Idx++];
7097 unsigned Minor = Record[Idx++];
7098 unsigned Subminor = Record[Idx++];
7099 if (Minor == 0)
7100 return VersionTuple(Major);
7101 if (Subminor == 0)
7102 return VersionTuple(Major, Minor - 1);
7103 return VersionTuple(Major, Minor - 1, Subminor - 1);
7104}
7105
7106CXXTemporary *ASTReader::ReadCXXTemporary(ModuleFile &F,
7107 const RecordData &Record,
7108 unsigned &Idx) {
7109 CXXDestructorDecl *Decl = ReadDeclAs<CXXDestructorDecl>(F, Record, Idx);
7110 return CXXTemporary::Create(Context, Decl);
7111}
7112
7113DiagnosticBuilder ASTReader::Diag(unsigned DiagID) {
7114 return Diag(SourceLocation(), DiagID);
7115}
7116
7117DiagnosticBuilder ASTReader::Diag(SourceLocation Loc, unsigned DiagID) {
7118 return Diags.Report(Loc, DiagID);
7119}
7120
7121/// \brief Retrieve the identifier table associated with the
7122/// preprocessor.
7123IdentifierTable &ASTReader::getIdentifierTable() {
7124 return PP.getIdentifierTable();
7125}
7126
7127/// \brief Record that the given ID maps to the given switch-case
7128/// statement.
7129void ASTReader::RecordSwitchCaseID(SwitchCase *SC, unsigned ID) {
7130 assert((*CurrSwitchCaseStmts)[ID] == 0 &&
7131 "Already have a SwitchCase with this ID");
7132 (*CurrSwitchCaseStmts)[ID] = SC;
7133}
7134
7135/// \brief Retrieve the switch-case statement with the given ID.
7136SwitchCase *ASTReader::getSwitchCaseWithID(unsigned ID) {
7137 assert((*CurrSwitchCaseStmts)[ID] != 0 && "No SwitchCase with this ID");
7138 return (*CurrSwitchCaseStmts)[ID];
7139}
7140
7141void ASTReader::ClearSwitchCaseIDs() {
7142 CurrSwitchCaseStmts->clear();
7143}
7144
7145void ASTReader::ReadComments() {
7146 std::vector<RawComment *> Comments;
Chris Lattner8f9a1eb2013-01-20 00:56:42 +00007147 for (SmallVectorImpl<std::pair<BitstreamCursor,
Guy Benyei7f92f2d2012-12-18 14:30:41 +00007148 serialization::ModuleFile *> >::iterator
7149 I = CommentsCursors.begin(),
7150 E = CommentsCursors.end();
7151 I != E; ++I) {
Chris Lattner8f9a1eb2013-01-20 00:56:42 +00007152 BitstreamCursor &Cursor = I->first;
Guy Benyei7f92f2d2012-12-18 14:30:41 +00007153 serialization::ModuleFile &F = *I->second;
7154 SavedStreamPosition SavedPosition(Cursor);
7155
7156 RecordData Record;
7157 while (true) {
Chris Lattner8f9a1eb2013-01-20 00:56:42 +00007158 llvm::BitstreamEntry Entry =
7159 Cursor.advanceSkippingSubblocks(BitstreamCursor::AF_DontPopBlockAtEnd);
7160
7161 switch (Entry.Kind) {
7162 case llvm::BitstreamEntry::SubBlock: // Handled for us already.
7163 case llvm::BitstreamEntry::Error:
7164 Error("malformed block record in AST file");
7165 return;
7166 case llvm::BitstreamEntry::EndBlock:
7167 goto NextCursor;
7168 case llvm::BitstreamEntry::Record:
7169 // The interesting case.
Guy Benyei7f92f2d2012-12-18 14:30:41 +00007170 break;
Guy Benyei7f92f2d2012-12-18 14:30:41 +00007171 }
7172
7173 // Read a record.
7174 Record.clear();
Chris Lattnerb3ce3572013-01-20 02:38:54 +00007175 switch ((CommentRecordTypes)Cursor.readRecord(Entry.ID, Record)) {
Guy Benyei7f92f2d2012-12-18 14:30:41 +00007176 case COMMENTS_RAW_COMMENT: {
7177 unsigned Idx = 0;
7178 SourceRange SR = ReadSourceRange(F, Record, Idx);
7179 RawComment::CommentKind Kind =
7180 (RawComment::CommentKind) Record[Idx++];
7181 bool IsTrailingComment = Record[Idx++];
7182 bool IsAlmostTrailingComment = Record[Idx++];
Dmitri Gribenko6fd7d302013-04-10 15:35:17 +00007183 Comments.push_back(new (Context) RawComment(
7184 SR, Kind, IsTrailingComment, IsAlmostTrailingComment,
7185 Context.getLangOpts().CommentOpts.ParseAllComments));
Guy Benyei7f92f2d2012-12-18 14:30:41 +00007186 break;
7187 }
7188 }
7189 }
Chris Lattner8f9a1eb2013-01-20 00:56:42 +00007190 NextCursor:;
Guy Benyei7f92f2d2012-12-18 14:30:41 +00007191 }
7192 Context.Comments.addCommentsToFront(Comments);
7193}
7194
7195void ASTReader::finishPendingActions() {
7196 while (!PendingIdentifierInfos.empty() || !PendingDeclChains.empty() ||
Argyrios Kyrtzidis7640b022013-02-16 00:48:59 +00007197 !PendingMacroIDs.empty() || !PendingDeclContextInfos.empty()) {
Guy Benyei7f92f2d2012-12-18 14:30:41 +00007198 // If any identifiers with corresponding top-level declarations have
7199 // been loaded, load those declarations now.
Douglas Gregoraa945902013-02-18 15:53:43 +00007200 llvm::DenseMap<IdentifierInfo *, SmallVector<Decl *, 2> > TopLevelDecls;
Guy Benyei7f92f2d2012-12-18 14:30:41 +00007201 while (!PendingIdentifierInfos.empty()) {
Douglas Gregoraa945902013-02-18 15:53:43 +00007202 // FIXME: std::move
7203 IdentifierInfo *II = PendingIdentifierInfos.back().first;
7204 SmallVector<uint32_t, 4> DeclIDs = PendingIdentifierInfos.back().second;
Douglas Gregorcc9bdcb2013-02-19 18:26:28 +00007205 PendingIdentifierInfos.pop_back();
Douglas Gregoraa945902013-02-18 15:53:43 +00007206
7207 SetGloballyVisibleDecls(II, DeclIDs, &TopLevelDecls[II]);
Guy Benyei7f92f2d2012-12-18 14:30:41 +00007208 }
7209
7210 // Load pending declaration chains.
7211 for (unsigned I = 0; I != PendingDeclChains.size(); ++I) {
7212 loadPendingDeclChain(PendingDeclChains[I]);
7213 PendingDeclChainsKnown.erase(PendingDeclChains[I]);
7214 }
7215 PendingDeclChains.clear();
7216
Douglas Gregoraa945902013-02-18 15:53:43 +00007217 // Make the most recent of the top-level declarations visible.
7218 for (llvm::DenseMap<IdentifierInfo *, SmallVector<Decl *, 2> >::iterator
7219 TLD = TopLevelDecls.begin(), TLDEnd = TopLevelDecls.end();
7220 TLD != TLDEnd; ++TLD) {
7221 IdentifierInfo *II = TLD->first;
7222 for (unsigned I = 0, N = TLD->second.size(); I != N; ++I) {
Argyrios Kyrtzidis0532df02013-04-26 21:33:35 +00007223 pushExternalDeclIntoScope(cast<NamedDecl>(TLD->second[I]), II);
Douglas Gregoraa945902013-02-18 15:53:43 +00007224 }
7225 }
7226
Guy Benyei7f92f2d2012-12-18 14:30:41 +00007227 // Load any pending macro definitions.
7228 for (unsigned I = 0; I != PendingMacroIDs.size(); ++I) {
Argyrios Kyrtzidis9317ab92013-03-22 21:12:57 +00007229 IdentifierInfo *II = PendingMacroIDs.begin()[I].first;
7230 SmallVector<PendingMacroInfo, 2> GlobalIDs;
7231 GlobalIDs.swap(PendingMacroIDs.begin()[I].second);
7232 // Initialize the macro history from chained-PCHs ahead of module imports.
Argyrios Kyrtzidisdc1088f2013-01-19 03:14:56 +00007233 for (unsigned IDIdx = 0, NumIDs = GlobalIDs.size(); IDIdx != NumIDs;
7234 ++IDIdx) {
Argyrios Kyrtzidis9317ab92013-03-22 21:12:57 +00007235 const PendingMacroInfo &Info = GlobalIDs[IDIdx];
7236 if (Info.M->Kind != MK_Module)
7237 resolvePendingMacro(II, Info);
7238 }
7239 // Handle module imports.
7240 for (unsigned IDIdx = 0, NumIDs = GlobalIDs.size(); IDIdx != NumIDs;
7241 ++IDIdx) {
7242 const PendingMacroInfo &Info = GlobalIDs[IDIdx];
7243 if (Info.M->Kind == MK_Module)
7244 resolvePendingMacro(II, Info);
Guy Benyei7f92f2d2012-12-18 14:30:41 +00007245 }
7246 }
7247 PendingMacroIDs.clear();
Argyrios Kyrtzidis7640b022013-02-16 00:48:59 +00007248
7249 // Wire up the DeclContexts for Decls that we delayed setting until
7250 // recursive loading is completed.
7251 while (!PendingDeclContextInfos.empty()) {
7252 PendingDeclContextInfo Info = PendingDeclContextInfos.front();
7253 PendingDeclContextInfos.pop_front();
7254 DeclContext *SemaDC = cast<DeclContext>(GetDecl(Info.SemaDC));
7255 DeclContext *LexicalDC = cast<DeclContext>(GetDecl(Info.LexicalDC));
7256 Info.D->setDeclContextsImpl(SemaDC, LexicalDC, getContext());
7257 }
Guy Benyei7f92f2d2012-12-18 14:30:41 +00007258 }
7259
7260 // If we deserialized any C++ or Objective-C class definitions, any
7261 // Objective-C protocol definitions, or any redeclarable templates, make sure
7262 // that all redeclarations point to the definitions. Note that this can only
7263 // happen now, after the redeclaration chains have been fully wired.
7264 for (llvm::SmallPtrSet<Decl *, 4>::iterator D = PendingDefinitions.begin(),
7265 DEnd = PendingDefinitions.end();
7266 D != DEnd; ++D) {
7267 if (TagDecl *TD = dyn_cast<TagDecl>(*D)) {
7268 if (const TagType *TagT = dyn_cast<TagType>(TD->TypeForDecl)) {
7269 // Make sure that the TagType points at the definition.
7270 const_cast<TagType*>(TagT)->decl = TD;
7271 }
7272
7273 if (CXXRecordDecl *RD = dyn_cast<CXXRecordDecl>(*D)) {
7274 for (CXXRecordDecl::redecl_iterator R = RD->redecls_begin(),
7275 REnd = RD->redecls_end();
7276 R != REnd; ++R)
7277 cast<CXXRecordDecl>(*R)->DefinitionData = RD->DefinitionData;
7278
7279 }
7280
7281 continue;
7282 }
7283
7284 if (ObjCInterfaceDecl *ID = dyn_cast<ObjCInterfaceDecl>(*D)) {
7285 // Make sure that the ObjCInterfaceType points at the definition.
7286 const_cast<ObjCInterfaceType *>(cast<ObjCInterfaceType>(ID->TypeForDecl))
7287 ->Decl = ID;
7288
7289 for (ObjCInterfaceDecl::redecl_iterator R = ID->redecls_begin(),
7290 REnd = ID->redecls_end();
7291 R != REnd; ++R)
7292 R->Data = ID->Data;
7293
7294 continue;
7295 }
7296
7297 if (ObjCProtocolDecl *PD = dyn_cast<ObjCProtocolDecl>(*D)) {
7298 for (ObjCProtocolDecl::redecl_iterator R = PD->redecls_begin(),
7299 REnd = PD->redecls_end();
7300 R != REnd; ++R)
7301 R->Data = PD->Data;
7302
7303 continue;
7304 }
7305
7306 RedeclarableTemplateDecl *RTD
7307 = cast<RedeclarableTemplateDecl>(*D)->getCanonicalDecl();
7308 for (RedeclarableTemplateDecl::redecl_iterator R = RTD->redecls_begin(),
7309 REnd = RTD->redecls_end();
7310 R != REnd; ++R)
7311 R->Common = RTD->Common;
7312 }
7313 PendingDefinitions.clear();
7314
7315 // Load the bodies of any functions or methods we've encountered. We do
7316 // this now (delayed) so that we can be sure that the declaration chains
7317 // have been fully wired up.
7318 for (PendingBodiesMap::iterator PB = PendingBodies.begin(),
7319 PBEnd = PendingBodies.end();
7320 PB != PBEnd; ++PB) {
7321 if (FunctionDecl *FD = dyn_cast<FunctionDecl>(PB->first)) {
7322 // FIXME: Check for =delete/=default?
7323 // FIXME: Complain about ODR violations here?
7324 if (!getContext().getLangOpts().Modules || !FD->hasBody())
7325 FD->setLazyBody(PB->second);
7326 continue;
7327 }
7328
7329 ObjCMethodDecl *MD = cast<ObjCMethodDecl>(PB->first);
7330 if (!getContext().getLangOpts().Modules || !MD->hasBody())
7331 MD->setLazyBody(PB->second);
7332 }
7333 PendingBodies.clear();
7334}
7335
7336void ASTReader::FinishedDeserializing() {
7337 assert(NumCurrentElementsDeserializing &&
7338 "FinishedDeserializing not paired with StartedDeserializing");
7339 if (NumCurrentElementsDeserializing == 1) {
7340 // We decrease NumCurrentElementsDeserializing only after pending actions
7341 // are finished, to avoid recursively re-calling finishPendingActions().
7342 finishPendingActions();
7343 }
7344 --NumCurrentElementsDeserializing;
7345
7346 if (NumCurrentElementsDeserializing == 0 &&
7347 Consumer && !PassingDeclsToConsumer) {
7348 // Guard variable to avoid recursively redoing the process of passing
7349 // decls to consumer.
7350 SaveAndRestore<bool> GuardPassingDeclsToConsumer(PassingDeclsToConsumer,
7351 true);
7352
7353 while (!InterestingDecls.empty()) {
7354 // We are not in recursive loading, so it's safe to pass the "interesting"
7355 // decls to the consumer.
7356 Decl *D = InterestingDecls.front();
7357 InterestingDecls.pop_front();
7358 PassInterestingDeclToConsumer(D);
7359 }
7360 }
7361}
7362
Argyrios Kyrtzidis0532df02013-04-26 21:33:35 +00007363void ASTReader::pushExternalDeclIntoScope(NamedDecl *D, DeclarationName Name) {
7364 D = cast<NamedDecl>(D->getMostRecentDecl());
7365
7366 if (SemaObj->IdResolver.tryAddTopLevelDecl(D, Name) && SemaObj->TUScope) {
7367 SemaObj->TUScope->AddDecl(D);
7368 } else if (SemaObj->TUScope) {
7369 // Adding the decl to IdResolver may have failed because it was already in
7370 // (even though it was not added in scope). If it is already in, make sure
7371 // it gets in the scope as well.
7372 if (std::find(SemaObj->IdResolver.begin(Name),
7373 SemaObj->IdResolver.end(), D) != SemaObj->IdResolver.end())
7374 SemaObj->TUScope->AddDecl(D);
7375 }
7376}
7377
Guy Benyei7f92f2d2012-12-18 14:30:41 +00007378ASTReader::ASTReader(Preprocessor &PP, ASTContext &Context,
7379 StringRef isysroot, bool DisableValidation,
Douglas Gregorf575d6e2013-01-25 00:45:27 +00007380 bool AllowASTWithCompilerErrors, bool UseGlobalIndex)
Guy Benyei7f92f2d2012-12-18 14:30:41 +00007381 : Listener(new PCHValidator(PP, *this)), DeserializationListener(0),
7382 SourceMgr(PP.getSourceManager()), FileMgr(PP.getFileManager()),
7383 Diags(PP.getDiagnostics()), SemaObj(0), PP(PP), Context(Context),
7384 Consumer(0), ModuleMgr(PP.getFileManager()),
7385 isysroot(isysroot), DisableValidation(DisableValidation),
Douglas Gregore1698072013-01-25 00:38:33 +00007386 AllowASTWithCompilerErrors(AllowASTWithCompilerErrors),
Douglas Gregorf575d6e2013-01-25 00:45:27 +00007387 UseGlobalIndex(UseGlobalIndex), TriedLoadingGlobalIndex(false),
Guy Benyei7f92f2d2012-12-18 14:30:41 +00007388 CurrentGeneration(0), CurrSwitchCaseStmts(&SwitchCaseStmts),
7389 NumSLocEntriesRead(0), TotalNumSLocEntries(0),
Douglas Gregore1698072013-01-25 00:38:33 +00007390 NumStatementsRead(0), TotalNumStatements(0), NumMacrosRead(0),
7391 TotalNumMacros(0), NumIdentifierLookups(0), NumIdentifierLookupHits(0),
7392 NumSelectorsRead(0), NumMethodPoolEntriesRead(0),
Douglas Gregor95fb36e2013-01-28 17:54:36 +00007393 NumMethodPoolLookups(0), NumMethodPoolHits(0),
7394 NumMethodPoolTableLookups(0), NumMethodPoolTableHits(0),
7395 TotalNumMethodPoolEntries(0),
Guy Benyei7f92f2d2012-12-18 14:30:41 +00007396 NumLexicalDeclContextsRead(0), TotalLexicalDeclContexts(0),
7397 NumVisibleDeclContextsRead(0), TotalVisibleDeclContexts(0),
7398 TotalModulesSizeInBits(0), NumCurrentElementsDeserializing(0),
7399 PassingDeclsToConsumer(false),
7400 NumCXXBaseSpecifiersLoaded(0)
7401{
7402 SourceMgr.setExternalSLocEntrySource(this);
7403}
7404
7405ASTReader::~ASTReader() {
7406 for (DeclContextVisibleUpdatesPending::iterator
7407 I = PendingVisibleUpdates.begin(),
7408 E = PendingVisibleUpdates.end();
7409 I != E; ++I) {
7410 for (DeclContextVisibleUpdates::iterator J = I->second.begin(),
7411 F = I->second.end();
7412 J != F; ++J)
7413 delete J->first;
7414 }
7415}