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