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