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