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