blob: 99361d207e8d5f756c96fd72ddd1cc3b6a5658d4 [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"
Dmitri Gribenkof430da42014-02-12 10:33:14 +000052#include "llvm/Support/raw_ostream.h"
Guy Benyei11169dd2012-12-18 14:30:41 +000053#include "llvm/Support/system_error.h"
54#include <algorithm>
Chris Lattner91f373e2013-01-20 00:57:52 +000055#include <cstdio>
Guy Benyei11169dd2012-12-18 14:30:41 +000056#include <iterator>
57
58using namespace clang;
59using namespace clang::serialization;
60using namespace clang::serialization::reader;
Chris Lattner7fb3bef2013-01-20 00:56:42 +000061using llvm::BitstreamCursor;
Guy Benyei11169dd2012-12-18 14:30:41 +000062
63//===----------------------------------------------------------------------===//
64// PCH validator implementation
65//===----------------------------------------------------------------------===//
66
67ASTReaderListener::~ASTReaderListener() {}
68
69/// \brief Compare the given set of language options against an existing set of
70/// language options.
71///
72/// \param Diags If non-NULL, diagnostics will be emitted via this engine.
73///
74/// \returns true if the languagae options mis-match, false otherwise.
75static bool checkLanguageOptions(const LangOptions &LangOpts,
76 const LangOptions &ExistingLangOpts,
77 DiagnosticsEngine *Diags) {
78#define LANGOPT(Name, Bits, Default, Description) \
79 if (ExistingLangOpts.Name != LangOpts.Name) { \
80 if (Diags) \
81 Diags->Report(diag::err_pch_langopt_mismatch) \
82 << Description << LangOpts.Name << ExistingLangOpts.Name; \
83 return true; \
84 }
85
86#define VALUE_LANGOPT(Name, Bits, Default, Description) \
87 if (ExistingLangOpts.Name != LangOpts.Name) { \
88 if (Diags) \
89 Diags->Report(diag::err_pch_langopt_value_mismatch) \
90 << Description; \
91 return true; \
92 }
93
94#define ENUM_LANGOPT(Name, Type, Bits, Default, Description) \
95 if (ExistingLangOpts.get##Name() != LangOpts.get##Name()) { \
96 if (Diags) \
97 Diags->Report(diag::err_pch_langopt_value_mismatch) \
98 << Description; \
99 return true; \
100 }
101
102#define BENIGN_LANGOPT(Name, Bits, Default, Description)
103#define BENIGN_ENUM_LANGOPT(Name, Type, Bits, Default, Description)
104#include "clang/Basic/LangOptions.def"
105
106 if (ExistingLangOpts.ObjCRuntime != LangOpts.ObjCRuntime) {
107 if (Diags)
108 Diags->Report(diag::err_pch_langopt_value_mismatch)
109 << "target Objective-C runtime";
110 return true;
111 }
112
Dmitri Gribenkoacf2e782013-02-22 14:21:27 +0000113 if (ExistingLangOpts.CommentOpts.BlockCommandNames !=
114 LangOpts.CommentOpts.BlockCommandNames) {
115 if (Diags)
116 Diags->Report(diag::err_pch_langopt_value_mismatch)
117 << "block command names";
118 return true;
119 }
120
Guy Benyei11169dd2012-12-18 14:30:41 +0000121 return false;
122}
123
124/// \brief Compare the given set of target options against an existing set of
125/// target options.
126///
127/// \param Diags If non-NULL, diagnostics will be emitted via this engine.
128///
129/// \returns true if the target options mis-match, false otherwise.
130static bool checkTargetOptions(const TargetOptions &TargetOpts,
131 const TargetOptions &ExistingTargetOpts,
132 DiagnosticsEngine *Diags) {
133#define CHECK_TARGET_OPT(Field, Name) \
134 if (TargetOpts.Field != ExistingTargetOpts.Field) { \
135 if (Diags) \
136 Diags->Report(diag::err_pch_targetopt_mismatch) \
137 << Name << TargetOpts.Field << ExistingTargetOpts.Field; \
138 return true; \
139 }
140
141 CHECK_TARGET_OPT(Triple, "target");
142 CHECK_TARGET_OPT(CPU, "target CPU");
143 CHECK_TARGET_OPT(ABI, "target ABI");
Guy Benyei11169dd2012-12-18 14:30:41 +0000144 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;
Craig Topper3598eb72013-07-05 04:43:31 +0000213 typedef llvm::DenseMap<DeclarationName, SmallVector<NamedDecl *, 8> >
214 DeclsMap;
Guy Benyei11169dd2012-12-18 14:30:41 +0000215}
216
217/// \brief Collect the macro definitions provided by the given preprocessor
218/// options.
219static void collectMacroDefinitions(const PreprocessorOptions &PPOpts,
220 MacroDefinitionsMap &Macros,
221 SmallVectorImpl<StringRef> *MacroNames = 0){
222 for (unsigned I = 0, N = PPOpts.Macros.size(); I != N; ++I) {
223 StringRef Macro = PPOpts.Macros[I].first;
224 bool IsUndef = PPOpts.Macros[I].second;
225
226 std::pair<StringRef, StringRef> MacroPair = Macro.split('=');
227 StringRef MacroName = MacroPair.first;
228 StringRef MacroBody = MacroPair.second;
229
230 // For an #undef'd macro, we only care about the name.
231 if (IsUndef) {
232 if (MacroNames && !Macros.count(MacroName))
233 MacroNames->push_back(MacroName);
234
235 Macros[MacroName] = std::make_pair("", true);
236 continue;
237 }
238
239 // For a #define'd macro, figure out the actual definition.
240 if (MacroName.size() == Macro.size())
241 MacroBody = "1";
242 else {
243 // Note: GCC drops anything following an end-of-line character.
244 StringRef::size_type End = MacroBody.find_first_of("\n\r");
245 MacroBody = MacroBody.substr(0, End);
246 }
247
248 if (MacroNames && !Macros.count(MacroName))
249 MacroNames->push_back(MacroName);
250 Macros[MacroName] = std::make_pair(MacroBody, false);
251 }
252}
253
254/// \brief Check the preprocessor options deserialized from the control block
255/// against the preprocessor options in an existing preprocessor.
256///
257/// \param Diags If non-null, produce diagnostics for any mismatches incurred.
258static bool checkPreprocessorOptions(const PreprocessorOptions &PPOpts,
259 const PreprocessorOptions &ExistingPPOpts,
260 DiagnosticsEngine *Diags,
261 FileManager &FileMgr,
Argyrios Kyrtzidisd3afa0c2013-04-26 21:33:40 +0000262 std::string &SuggestedPredefines,
263 const LangOptions &LangOpts) {
Guy Benyei11169dd2012-12-18 14:30:41 +0000264 // Check macro definitions.
265 MacroDefinitionsMap ASTFileMacros;
266 collectMacroDefinitions(PPOpts, ASTFileMacros);
267 MacroDefinitionsMap ExistingMacros;
268 SmallVector<StringRef, 4> ExistingMacroNames;
269 collectMacroDefinitions(ExistingPPOpts, ExistingMacros, &ExistingMacroNames);
270
271 for (unsigned I = 0, N = ExistingMacroNames.size(); I != N; ++I) {
272 // Dig out the macro definition in the existing preprocessor options.
273 StringRef MacroName = ExistingMacroNames[I];
274 std::pair<StringRef, bool> Existing = ExistingMacros[MacroName];
275
276 // Check whether we know anything about this macro name or not.
277 llvm::StringMap<std::pair<StringRef, bool /*IsUndef*/> >::iterator Known
278 = ASTFileMacros.find(MacroName);
279 if (Known == ASTFileMacros.end()) {
280 // FIXME: Check whether this identifier was referenced anywhere in the
281 // AST file. If so, we should reject the AST file. Unfortunately, this
282 // information isn't in the control block. What shall we do about it?
283
284 if (Existing.second) {
285 SuggestedPredefines += "#undef ";
286 SuggestedPredefines += MacroName.str();
287 SuggestedPredefines += '\n';
288 } else {
289 SuggestedPredefines += "#define ";
290 SuggestedPredefines += MacroName.str();
291 SuggestedPredefines += ' ';
292 SuggestedPredefines += Existing.first.str();
293 SuggestedPredefines += '\n';
294 }
295 continue;
296 }
297
298 // If the macro was defined in one but undef'd in the other, we have a
299 // conflict.
300 if (Existing.second != Known->second.second) {
301 if (Diags) {
302 Diags->Report(diag::err_pch_macro_def_undef)
303 << MacroName << Known->second.second;
304 }
305 return true;
306 }
307
308 // If the macro was #undef'd in both, or if the macro bodies are identical,
309 // it's fine.
310 if (Existing.second || Existing.first == Known->second.first)
311 continue;
312
313 // The macro bodies differ; complain.
314 if (Diags) {
315 Diags->Report(diag::err_pch_macro_def_conflict)
316 << MacroName << Known->second.first << Existing.first;
317 }
318 return true;
319 }
320
321 // Check whether we're using predefines.
322 if (PPOpts.UsePredefines != ExistingPPOpts.UsePredefines) {
323 if (Diags) {
324 Diags->Report(diag::err_pch_undef) << ExistingPPOpts.UsePredefines;
325 }
326 return true;
327 }
328
Argyrios Kyrtzidisd3afa0c2013-04-26 21:33:40 +0000329 // Detailed record is important since it is used for the module cache hash.
330 if (LangOpts.Modules &&
331 PPOpts.DetailedRecord != ExistingPPOpts.DetailedRecord) {
332 if (Diags) {
333 Diags->Report(diag::err_pch_pp_detailed_record) << PPOpts.DetailedRecord;
334 }
335 return true;
336 }
337
Guy Benyei11169dd2012-12-18 14:30:41 +0000338 // Compute the #include and #include_macros lines we need.
339 for (unsigned I = 0, N = ExistingPPOpts.Includes.size(); I != N; ++I) {
340 StringRef File = ExistingPPOpts.Includes[I];
341 if (File == ExistingPPOpts.ImplicitPCHInclude)
342 continue;
343
344 if (std::find(PPOpts.Includes.begin(), PPOpts.Includes.end(), File)
345 != PPOpts.Includes.end())
346 continue;
347
348 SuggestedPredefines += "#include \"";
349 SuggestedPredefines +=
350 HeaderSearch::NormalizeDashIncludePath(File, FileMgr);
351 SuggestedPredefines += "\"\n";
352 }
353
354 for (unsigned I = 0, N = ExistingPPOpts.MacroIncludes.size(); I != N; ++I) {
355 StringRef File = ExistingPPOpts.MacroIncludes[I];
356 if (std::find(PPOpts.MacroIncludes.begin(), PPOpts.MacroIncludes.end(),
357 File)
358 != PPOpts.MacroIncludes.end())
359 continue;
360
361 SuggestedPredefines += "#__include_macros \"";
362 SuggestedPredefines +=
363 HeaderSearch::NormalizeDashIncludePath(File, FileMgr);
364 SuggestedPredefines += "\"\n##\n";
365 }
366
367 return false;
368}
369
370bool PCHValidator::ReadPreprocessorOptions(const PreprocessorOptions &PPOpts,
371 bool Complain,
372 std::string &SuggestedPredefines) {
373 const PreprocessorOptions &ExistingPPOpts = PP.getPreprocessorOpts();
374
375 return checkPreprocessorOptions(PPOpts, ExistingPPOpts,
376 Complain? &Reader.Diags : 0,
377 PP.getFileManager(),
Argyrios Kyrtzidisd3afa0c2013-04-26 21:33:40 +0000378 SuggestedPredefines,
379 PP.getLangOpts());
Guy Benyei11169dd2012-12-18 14:30:41 +0000380}
381
Guy Benyei11169dd2012-12-18 14:30:41 +0000382void PCHValidator::ReadCounter(const ModuleFile &M, unsigned Value) {
383 PP.setCounterValue(Value);
384}
385
386//===----------------------------------------------------------------------===//
387// AST reader implementation
388//===----------------------------------------------------------------------===//
389
390void
391ASTReader::setDeserializationListener(ASTDeserializationListener *Listener) {
392 DeserializationListener = Listener;
393}
394
395
396
397unsigned ASTSelectorLookupTrait::ComputeHash(Selector Sel) {
398 return serialization::ComputeHash(Sel);
399}
400
401
402std::pair<unsigned, unsigned>
403ASTSelectorLookupTrait::ReadKeyDataLength(const unsigned char*& d) {
404 using namespace clang::io;
405 unsigned KeyLen = ReadUnalignedLE16(d);
406 unsigned DataLen = ReadUnalignedLE16(d);
407 return std::make_pair(KeyLen, DataLen);
408}
409
410ASTSelectorLookupTrait::internal_key_type
411ASTSelectorLookupTrait::ReadKey(const unsigned char* d, unsigned) {
412 using namespace clang::io;
413 SelectorTable &SelTable = Reader.getContext().Selectors;
414 unsigned N = ReadUnalignedLE16(d);
415 IdentifierInfo *FirstII
Douglas Gregorc8a992f2013-01-21 16:52:34 +0000416 = Reader.getLocalIdentifier(F, ReadUnalignedLE32(d));
Guy Benyei11169dd2012-12-18 14:30:41 +0000417 if (N == 0)
418 return SelTable.getNullarySelector(FirstII);
419 else if (N == 1)
420 return SelTable.getUnarySelector(FirstII);
421
422 SmallVector<IdentifierInfo *, 16> Args;
423 Args.push_back(FirstII);
424 for (unsigned I = 1; I != N; ++I)
Douglas Gregorc8a992f2013-01-21 16:52:34 +0000425 Args.push_back(Reader.getLocalIdentifier(F, ReadUnalignedLE32(d)));
Guy Benyei11169dd2012-12-18 14:30:41 +0000426
427 return SelTable.getSelector(N, Args.data());
428}
429
430ASTSelectorLookupTrait::data_type
431ASTSelectorLookupTrait::ReadData(Selector, const unsigned char* d,
432 unsigned DataLen) {
433 using namespace clang::io;
434
435 data_type Result;
436
437 Result.ID = Reader.getGlobalSelectorID(F, ReadUnalignedLE32(d));
Argyrios Kyrtzidisd3da6e02013-04-17 00:08:58 +0000438 unsigned NumInstanceMethodsAndBits = ReadUnalignedLE16(d);
439 unsigned NumFactoryMethodsAndBits = ReadUnalignedLE16(d);
440 Result.InstanceBits = NumInstanceMethodsAndBits & 0x3;
441 Result.FactoryBits = NumFactoryMethodsAndBits & 0x3;
442 unsigned NumInstanceMethods = NumInstanceMethodsAndBits >> 2;
443 unsigned NumFactoryMethods = NumFactoryMethodsAndBits >> 2;
Guy Benyei11169dd2012-12-18 14:30:41 +0000444
445 // Load instance methods
446 for (unsigned I = 0; I != NumInstanceMethods; ++I) {
447 if (ObjCMethodDecl *Method
448 = Reader.GetLocalDeclAs<ObjCMethodDecl>(F, ReadUnalignedLE32(d)))
449 Result.Instance.push_back(Method);
450 }
451
452 // Load factory methods
453 for (unsigned I = 0; I != NumFactoryMethods; ++I) {
454 if (ObjCMethodDecl *Method
455 = Reader.GetLocalDeclAs<ObjCMethodDecl>(F, ReadUnalignedLE32(d)))
456 Result.Factory.push_back(Method);
457 }
458
459 return Result;
460}
461
Douglas Gregorbfd73d72013-01-23 18:53:14 +0000462unsigned ASTIdentifierLookupTraitBase::ComputeHash(const internal_key_type& a) {
463 return llvm::HashString(a);
Guy Benyei11169dd2012-12-18 14:30:41 +0000464}
465
466std::pair<unsigned, unsigned>
Douglas Gregorbfd73d72013-01-23 18:53:14 +0000467ASTIdentifierLookupTraitBase::ReadKeyDataLength(const unsigned char*& d) {
Guy Benyei11169dd2012-12-18 14:30:41 +0000468 using namespace clang::io;
469 unsigned DataLen = ReadUnalignedLE16(d);
470 unsigned KeyLen = ReadUnalignedLE16(d);
471 return std::make_pair(KeyLen, DataLen);
472}
473
Douglas Gregorbfd73d72013-01-23 18:53:14 +0000474ASTIdentifierLookupTraitBase::internal_key_type
475ASTIdentifierLookupTraitBase::ReadKey(const unsigned char* d, unsigned n) {
Guy Benyei11169dd2012-12-18 14:30:41 +0000476 assert(n >= 2 && d[n-1] == '\0');
Douglas Gregorbfd73d72013-01-23 18:53:14 +0000477 return StringRef((const char*) d, n-1);
Guy Benyei11169dd2012-12-18 14:30:41 +0000478}
479
Douglas Gregordcf25082013-02-11 18:16:18 +0000480/// \brief Whether the given identifier is "interesting".
481static bool isInterestingIdentifier(IdentifierInfo &II) {
482 return II.isPoisoned() ||
483 II.isExtensionToken() ||
484 II.getObjCOrBuiltinID() ||
485 II.hasRevertedTokenIDToIdentifier() ||
486 II.hadMacroDefinition() ||
487 II.getFETokenInfo<void>();
488}
489
Guy Benyei11169dd2012-12-18 14:30:41 +0000490IdentifierInfo *ASTIdentifierLookupTrait::ReadData(const internal_key_type& k,
491 const unsigned char* d,
492 unsigned DataLen) {
493 using namespace clang::io;
494 unsigned RawID = ReadUnalignedLE32(d);
495 bool IsInteresting = RawID & 0x01;
496
497 // Wipe out the "is interesting" bit.
498 RawID = RawID >> 1;
499
500 IdentID ID = Reader.getGlobalIdentifierID(F, RawID);
501 if (!IsInteresting) {
502 // For uninteresting identifiers, just build the IdentifierInfo
503 // and associate it with the persistent ID.
504 IdentifierInfo *II = KnownII;
505 if (!II) {
Douglas Gregorbfd73d72013-01-23 18:53:14 +0000506 II = &Reader.getIdentifierTable().getOwn(k);
Guy Benyei11169dd2012-12-18 14:30:41 +0000507 KnownII = II;
508 }
509 Reader.SetIdentifierInfo(ID, II);
Douglas Gregordcf25082013-02-11 18:16:18 +0000510 if (!II->isFromAST()) {
511 bool WasInteresting = isInterestingIdentifier(*II);
512 II->setIsFromAST();
513 if (WasInteresting)
514 II->setChangedSinceDeserialization();
515 }
516 Reader.markIdentifierUpToDate(II);
Guy Benyei11169dd2012-12-18 14:30:41 +0000517 return II;
518 }
519
520 unsigned ObjCOrBuiltinID = ReadUnalignedLE16(d);
521 unsigned Bits = ReadUnalignedLE16(d);
522 bool CPlusPlusOperatorKeyword = Bits & 0x01;
523 Bits >>= 1;
524 bool HasRevertedTokenIDToIdentifier = Bits & 0x01;
525 Bits >>= 1;
526 bool Poisoned = Bits & 0x01;
527 Bits >>= 1;
528 bool ExtensionToken = Bits & 0x01;
529 Bits >>= 1;
Argyrios Kyrtzidiseb663da2013-03-22 21:12:57 +0000530 bool hasSubmoduleMacros = Bits & 0x01;
531 Bits >>= 1;
Guy Benyei11169dd2012-12-18 14:30:41 +0000532 bool hadMacroDefinition = Bits & 0x01;
533 Bits >>= 1;
534
535 assert(Bits == 0 && "Extra bits in the identifier?");
536 DataLen -= 8;
537
538 // Build the IdentifierInfo itself and link the identifier ID with
539 // the new IdentifierInfo.
540 IdentifierInfo *II = KnownII;
541 if (!II) {
Douglas Gregorbfd73d72013-01-23 18:53:14 +0000542 II = &Reader.getIdentifierTable().getOwn(StringRef(k));
Guy Benyei11169dd2012-12-18 14:30:41 +0000543 KnownII = II;
544 }
545 Reader.markIdentifierUpToDate(II);
Douglas Gregordcf25082013-02-11 18:16:18 +0000546 if (!II->isFromAST()) {
547 bool WasInteresting = isInterestingIdentifier(*II);
548 II->setIsFromAST();
549 if (WasInteresting)
550 II->setChangedSinceDeserialization();
551 }
Guy Benyei11169dd2012-12-18 14:30:41 +0000552
553 // Set or check the various bits in the IdentifierInfo structure.
554 // Token IDs are read-only.
Argyrios Kyrtzidisddee8c92013-02-27 01:13:51 +0000555 if (HasRevertedTokenIDToIdentifier && II->getTokenID() != tok::identifier)
Guy Benyei11169dd2012-12-18 14:30:41 +0000556 II->RevertTokenIDToIdentifier();
557 II->setObjCOrBuiltinID(ObjCOrBuiltinID);
558 assert(II->isExtensionToken() == ExtensionToken &&
559 "Incorrect extension token flag");
560 (void)ExtensionToken;
561 if (Poisoned)
562 II->setIsPoisoned(true);
563 assert(II->isCPlusPlusOperatorKeyword() == CPlusPlusOperatorKeyword &&
564 "Incorrect C++ operator keyword flag");
565 (void)CPlusPlusOperatorKeyword;
566
567 // If this identifier is a macro, deserialize the macro
568 // definition.
569 if (hadMacroDefinition) {
Argyrios Kyrtzidiseb663da2013-03-22 21:12:57 +0000570 uint32_t MacroDirectivesOffset = ReadUnalignedLE32(d);
571 DataLen -= 4;
572 SmallVector<uint32_t, 8> LocalMacroIDs;
573 if (hasSubmoduleMacros) {
574 while (uint32_t LocalMacroID = ReadUnalignedLE32(d)) {
575 DataLen -= 4;
576 LocalMacroIDs.push_back(LocalMacroID);
577 }
Argyrios Kyrtzidis719736c2013-01-19 03:14:56 +0000578 DataLen -= 4;
579 }
Argyrios Kyrtzidiseb663da2013-03-22 21:12:57 +0000580
581 if (F.Kind == MK_Module) {
Richard Smith49f906a2014-03-01 00:08:04 +0000582 // Macro definitions are stored from newest to oldest, so reverse them
583 // before registering them.
584 llvm::SmallVector<unsigned, 8> MacroSizes;
Argyrios Kyrtzidiseb663da2013-03-22 21:12:57 +0000585 for (SmallVectorImpl<uint32_t>::iterator
Richard Smith49f906a2014-03-01 00:08:04 +0000586 I = LocalMacroIDs.begin(), E = LocalMacroIDs.end(); I != E; /**/) {
587 unsigned Size = 1;
588
589 static const uint32_t HasOverridesFlag = 0x80000000U;
590 if (I + 1 != E && (I[1] & HasOverridesFlag))
591 Size += 1 + (I[1] & ~HasOverridesFlag);
592
593 MacroSizes.push_back(Size);
594 I += Size;
Argyrios Kyrtzidiseb663da2013-03-22 21:12:57 +0000595 }
Richard Smith49f906a2014-03-01 00:08:04 +0000596
597 SmallVectorImpl<uint32_t>::iterator I = LocalMacroIDs.end();
598 for (SmallVectorImpl<unsigned>::reverse_iterator SI = MacroSizes.rbegin(),
599 SE = MacroSizes.rend();
600 SI != SE; ++SI) {
601 I -= *SI;
602
603 uint32_t LocalMacroID = *I;
604 llvm::ArrayRef<uint32_t> Overrides;
605 if (*SI != 1)
606 Overrides = llvm::makeArrayRef(&I[2], *SI - 2);
607 Reader.addPendingMacroFromModule(II, &F, LocalMacroID, Overrides);
608 }
609 assert(I == LocalMacroIDs.begin());
Argyrios Kyrtzidiseb663da2013-03-22 21:12:57 +0000610 } else {
611 Reader.addPendingMacroFromPCH(II, &F, MacroDirectivesOffset);
612 }
Guy Benyei11169dd2012-12-18 14:30:41 +0000613 }
614
615 Reader.SetIdentifierInfo(ID, II);
616
617 // Read all of the declarations visible at global scope with this
618 // name.
619 if (DataLen > 0) {
620 SmallVector<uint32_t, 4> DeclIDs;
621 for (; DataLen > 0; DataLen -= 4)
622 DeclIDs.push_back(Reader.getGlobalDeclID(F, ReadUnalignedLE32(d)));
623 Reader.SetGloballyVisibleDecls(II, DeclIDs);
624 }
625
626 return II;
627}
628
629unsigned
630ASTDeclContextNameLookupTrait::ComputeHash(const DeclNameKey &Key) const {
631 llvm::FoldingSetNodeID ID;
632 ID.AddInteger(Key.Kind);
633
634 switch (Key.Kind) {
635 case DeclarationName::Identifier:
636 case DeclarationName::CXXLiteralOperatorName:
637 ID.AddString(((IdentifierInfo*)Key.Data)->getName());
638 break;
639 case DeclarationName::ObjCZeroArgSelector:
640 case DeclarationName::ObjCOneArgSelector:
641 case DeclarationName::ObjCMultiArgSelector:
642 ID.AddInteger(serialization::ComputeHash(Selector(Key.Data)));
643 break;
644 case DeclarationName::CXXOperatorName:
645 ID.AddInteger((OverloadedOperatorKind)Key.Data);
646 break;
647 case DeclarationName::CXXConstructorName:
648 case DeclarationName::CXXDestructorName:
649 case DeclarationName::CXXConversionFunctionName:
650 case DeclarationName::CXXUsingDirective:
651 break;
652 }
653
654 return ID.ComputeHash();
655}
656
657ASTDeclContextNameLookupTrait::internal_key_type
658ASTDeclContextNameLookupTrait::GetInternalKey(
659 const external_key_type& Name) const {
660 DeclNameKey Key;
661 Key.Kind = Name.getNameKind();
662 switch (Name.getNameKind()) {
663 case DeclarationName::Identifier:
664 Key.Data = (uint64_t)Name.getAsIdentifierInfo();
665 break;
666 case DeclarationName::ObjCZeroArgSelector:
667 case DeclarationName::ObjCOneArgSelector:
668 case DeclarationName::ObjCMultiArgSelector:
669 Key.Data = (uint64_t)Name.getObjCSelector().getAsOpaquePtr();
670 break;
671 case DeclarationName::CXXOperatorName:
672 Key.Data = Name.getCXXOverloadedOperator();
673 break;
674 case DeclarationName::CXXLiteralOperatorName:
675 Key.Data = (uint64_t)Name.getCXXLiteralIdentifier();
676 break;
677 case DeclarationName::CXXConstructorName:
678 case DeclarationName::CXXDestructorName:
679 case DeclarationName::CXXConversionFunctionName:
680 case DeclarationName::CXXUsingDirective:
681 Key.Data = 0;
682 break;
683 }
684
685 return Key;
686}
687
688std::pair<unsigned, unsigned>
689ASTDeclContextNameLookupTrait::ReadKeyDataLength(const unsigned char*& d) {
690 using namespace clang::io;
691 unsigned KeyLen = ReadUnalignedLE16(d);
692 unsigned DataLen = ReadUnalignedLE16(d);
693 return std::make_pair(KeyLen, DataLen);
694}
695
696ASTDeclContextNameLookupTrait::internal_key_type
697ASTDeclContextNameLookupTrait::ReadKey(const unsigned char* d, unsigned) {
698 using namespace clang::io;
699
700 DeclNameKey Key;
701 Key.Kind = (DeclarationName::NameKind)*d++;
702 switch (Key.Kind) {
703 case DeclarationName::Identifier:
704 Key.Data = (uint64_t)Reader.getLocalIdentifier(F, ReadUnalignedLE32(d));
705 break;
706 case DeclarationName::ObjCZeroArgSelector:
707 case DeclarationName::ObjCOneArgSelector:
708 case DeclarationName::ObjCMultiArgSelector:
709 Key.Data =
710 (uint64_t)Reader.getLocalSelector(F, ReadUnalignedLE32(d))
711 .getAsOpaquePtr();
712 break;
713 case DeclarationName::CXXOperatorName:
714 Key.Data = *d++; // OverloadedOperatorKind
715 break;
716 case DeclarationName::CXXLiteralOperatorName:
717 Key.Data = (uint64_t)Reader.getLocalIdentifier(F, ReadUnalignedLE32(d));
718 break;
719 case DeclarationName::CXXConstructorName:
720 case DeclarationName::CXXDestructorName:
721 case DeclarationName::CXXConversionFunctionName:
722 case DeclarationName::CXXUsingDirective:
723 Key.Data = 0;
724 break;
725 }
726
727 return Key;
728}
729
730ASTDeclContextNameLookupTrait::data_type
731ASTDeclContextNameLookupTrait::ReadData(internal_key_type,
732 const unsigned char* d,
733 unsigned DataLen) {
734 using namespace clang::io;
735 unsigned NumDecls = ReadUnalignedLE16(d);
Argyrios Kyrtzidisc57e5032013-01-11 22:29:49 +0000736 LE32DeclID *Start = reinterpret_cast<LE32DeclID *>(
737 const_cast<unsigned char *>(d));
Guy Benyei11169dd2012-12-18 14:30:41 +0000738 return std::make_pair(Start, Start + NumDecls);
739}
740
741bool ASTReader::ReadDeclContextStorage(ModuleFile &M,
Chris Lattner7fb3bef2013-01-20 00:56:42 +0000742 BitstreamCursor &Cursor,
Guy Benyei11169dd2012-12-18 14:30:41 +0000743 const std::pair<uint64_t, uint64_t> &Offsets,
744 DeclContextInfo &Info) {
745 SavedStreamPosition SavedPosition(Cursor);
746 // First the lexical decls.
747 if (Offsets.first != 0) {
748 Cursor.JumpToBit(Offsets.first);
749
750 RecordData Record;
Chris Lattner0e6c9402013-01-20 02:38:54 +0000751 StringRef Blob;
Guy Benyei11169dd2012-12-18 14:30:41 +0000752 unsigned Code = Cursor.ReadCode();
Chris Lattner0e6c9402013-01-20 02:38:54 +0000753 unsigned RecCode = Cursor.readRecord(Code, Record, &Blob);
Guy Benyei11169dd2012-12-18 14:30:41 +0000754 if (RecCode != DECL_CONTEXT_LEXICAL) {
755 Error("Expected lexical block");
756 return true;
757 }
758
Chris Lattner0e6c9402013-01-20 02:38:54 +0000759 Info.LexicalDecls = reinterpret_cast<const KindDeclIDPair*>(Blob.data());
760 Info.NumLexicalDecls = Blob.size() / sizeof(KindDeclIDPair);
Guy Benyei11169dd2012-12-18 14:30:41 +0000761 }
762
763 // Now the lookup table.
764 if (Offsets.second != 0) {
765 Cursor.JumpToBit(Offsets.second);
766
767 RecordData Record;
Chris Lattner0e6c9402013-01-20 02:38:54 +0000768 StringRef Blob;
Guy Benyei11169dd2012-12-18 14:30:41 +0000769 unsigned Code = Cursor.ReadCode();
Chris Lattner0e6c9402013-01-20 02:38:54 +0000770 unsigned RecCode = Cursor.readRecord(Code, Record, &Blob);
Guy Benyei11169dd2012-12-18 14:30:41 +0000771 if (RecCode != DECL_CONTEXT_VISIBLE) {
772 Error("Expected visible lookup table block");
773 return true;
774 }
775 Info.NameLookupTableData
776 = ASTDeclContextNameLookupTable::Create(
Chris Lattner0e6c9402013-01-20 02:38:54 +0000777 (const unsigned char *)Blob.data() + Record[0],
778 (const unsigned char *)Blob.data(),
Guy Benyei11169dd2012-12-18 14:30:41 +0000779 ASTDeclContextNameLookupTrait(*this, M));
780 }
781
782 return false;
783}
784
785void ASTReader::Error(StringRef Msg) {
786 Error(diag::err_fe_pch_malformed, Msg);
Douglas Gregor940e8052013-05-10 22:15:13 +0000787 if (Context.getLangOpts().Modules && !Diags.isDiagnosticInFlight()) {
788 Diag(diag::note_module_cache_path)
789 << PP.getHeaderSearchInfo().getModuleCachePath();
790 }
Guy Benyei11169dd2012-12-18 14:30:41 +0000791}
792
793void ASTReader::Error(unsigned DiagID,
794 StringRef Arg1, StringRef Arg2) {
795 if (Diags.isDiagnosticInFlight())
796 Diags.SetDelayedDiagnostic(DiagID, Arg1, Arg2);
797 else
798 Diag(DiagID) << Arg1 << Arg2;
799}
800
801//===----------------------------------------------------------------------===//
802// Source Manager Deserialization
803//===----------------------------------------------------------------------===//
804
805/// \brief Read the line table in the source manager block.
806/// \returns true if there was an error.
807bool ASTReader::ParseLineTable(ModuleFile &F,
808 SmallVectorImpl<uint64_t> &Record) {
809 unsigned Idx = 0;
810 LineTableInfo &LineTable = SourceMgr.getLineTable();
811
812 // Parse the file names
813 std::map<int, int> FileIDs;
814 for (int I = 0, N = Record[Idx++]; I != N; ++I) {
815 // Extract the file name
816 unsigned FilenameLen = Record[Idx++];
817 std::string Filename(&Record[Idx], &Record[Idx] + FilenameLen);
818 Idx += FilenameLen;
819 MaybeAddSystemRootToFilename(F, Filename);
820 FileIDs[I] = LineTable.getLineTableFilenameID(Filename);
821 }
822
823 // Parse the line entries
824 std::vector<LineEntry> Entries;
825 while (Idx < Record.size()) {
826 int FID = Record[Idx++];
827 assert(FID >= 0 && "Serialized line entries for non-local file.");
828 // Remap FileID from 1-based old view.
829 FID += F.SLocEntryBaseID - 1;
830
831 // Extract the line entries
832 unsigned NumEntries = Record[Idx++];
833 assert(NumEntries && "Numentries is 00000");
834 Entries.clear();
835 Entries.reserve(NumEntries);
836 for (unsigned I = 0; I != NumEntries; ++I) {
837 unsigned FileOffset = Record[Idx++];
838 unsigned LineNo = Record[Idx++];
839 int FilenameID = FileIDs[Record[Idx++]];
840 SrcMgr::CharacteristicKind FileKind
841 = (SrcMgr::CharacteristicKind)Record[Idx++];
842 unsigned IncludeOffset = Record[Idx++];
843 Entries.push_back(LineEntry::get(FileOffset, LineNo, FilenameID,
844 FileKind, IncludeOffset));
845 }
846 LineTable.AddEntry(FileID::get(FID), Entries);
847 }
848
849 return false;
850}
851
852/// \brief Read a source manager block
853bool ASTReader::ReadSourceManagerBlock(ModuleFile &F) {
854 using namespace SrcMgr;
855
Chris Lattner7fb3bef2013-01-20 00:56:42 +0000856 BitstreamCursor &SLocEntryCursor = F.SLocEntryCursor;
Guy Benyei11169dd2012-12-18 14:30:41 +0000857
858 // Set the source-location entry cursor to the current position in
859 // the stream. This cursor will be used to read the contents of the
860 // source manager block initially, and then lazily read
861 // source-location entries as needed.
862 SLocEntryCursor = F.Stream;
863
864 // The stream itself is going to skip over the source manager block.
865 if (F.Stream.SkipBlock()) {
866 Error("malformed block record in AST file");
867 return true;
868 }
869
870 // Enter the source manager block.
871 if (SLocEntryCursor.EnterSubBlock(SOURCE_MANAGER_BLOCK_ID)) {
872 Error("malformed source manager block record in AST file");
873 return true;
874 }
875
876 RecordData Record;
877 while (true) {
Chris Lattnere7b154b2013-01-19 21:39:22 +0000878 llvm::BitstreamEntry E = SLocEntryCursor.advanceSkippingSubblocks();
879
880 switch (E.Kind) {
881 case llvm::BitstreamEntry::SubBlock: // Handled for us already.
882 case llvm::BitstreamEntry::Error:
883 Error("malformed block record in AST file");
884 return true;
885 case llvm::BitstreamEntry::EndBlock:
Guy Benyei11169dd2012-12-18 14:30:41 +0000886 return false;
Chris Lattnere7b154b2013-01-19 21:39:22 +0000887 case llvm::BitstreamEntry::Record:
888 // The interesting case.
889 break;
Guy Benyei11169dd2012-12-18 14:30:41 +0000890 }
Chris Lattnere7b154b2013-01-19 21:39:22 +0000891
Guy Benyei11169dd2012-12-18 14:30:41 +0000892 // Read a record.
Guy Benyei11169dd2012-12-18 14:30:41 +0000893 Record.clear();
Chris Lattner15c3e7d2013-01-21 18:28:26 +0000894 StringRef Blob;
895 switch (SLocEntryCursor.readRecord(E.ID, Record, &Blob)) {
Guy Benyei11169dd2012-12-18 14:30:41 +0000896 default: // Default behavior: ignore.
897 break;
898
899 case SM_SLOC_FILE_ENTRY:
900 case SM_SLOC_BUFFER_ENTRY:
901 case SM_SLOC_EXPANSION_ENTRY:
902 // Once we hit one of the source location entries, we're done.
903 return false;
904 }
905 }
906}
907
908/// \brief If a header file is not found at the path that we expect it to be
909/// and the PCH file was moved from its original location, try to resolve the
910/// file by assuming that header+PCH were moved together and the header is in
911/// the same place relative to the PCH.
912static std::string
913resolveFileRelativeToOriginalDir(const std::string &Filename,
914 const std::string &OriginalDir,
915 const std::string &CurrDir) {
916 assert(OriginalDir != CurrDir &&
917 "No point trying to resolve the file if the PCH dir didn't change");
918 using namespace llvm::sys;
919 SmallString<128> filePath(Filename);
920 fs::make_absolute(filePath);
921 assert(path::is_absolute(OriginalDir));
922 SmallString<128> currPCHPath(CurrDir);
923
924 path::const_iterator fileDirI = path::begin(path::parent_path(filePath)),
925 fileDirE = path::end(path::parent_path(filePath));
926 path::const_iterator origDirI = path::begin(OriginalDir),
927 origDirE = path::end(OriginalDir);
928 // Skip the common path components from filePath and OriginalDir.
929 while (fileDirI != fileDirE && origDirI != origDirE &&
930 *fileDirI == *origDirI) {
931 ++fileDirI;
932 ++origDirI;
933 }
934 for (; origDirI != origDirE; ++origDirI)
935 path::append(currPCHPath, "..");
936 path::append(currPCHPath, fileDirI, fileDirE);
937 path::append(currPCHPath, path::filename(Filename));
938 return currPCHPath.str();
939}
940
941bool ASTReader::ReadSLocEntry(int ID) {
942 if (ID == 0)
943 return false;
944
945 if (unsigned(-ID) - 2 >= getTotalNumSLocs() || ID > 0) {
946 Error("source location entry ID out-of-range for AST file");
947 return true;
948 }
949
950 ModuleFile *F = GlobalSLocEntryMap.find(-ID)->second;
951 F->SLocEntryCursor.JumpToBit(F->SLocEntryOffsets[ID - F->SLocEntryBaseID]);
Chris Lattner7fb3bef2013-01-20 00:56:42 +0000952 BitstreamCursor &SLocEntryCursor = F->SLocEntryCursor;
Guy Benyei11169dd2012-12-18 14:30:41 +0000953 unsigned BaseOffset = F->SLocEntryBaseOffset;
954
955 ++NumSLocEntriesRead;
Chris Lattnere7b154b2013-01-19 21:39:22 +0000956 llvm::BitstreamEntry Entry = SLocEntryCursor.advance();
957 if (Entry.Kind != llvm::BitstreamEntry::Record) {
Guy Benyei11169dd2012-12-18 14:30:41 +0000958 Error("incorrectly-formatted source location entry in AST file");
959 return true;
960 }
Chris Lattnere7b154b2013-01-19 21:39:22 +0000961
Guy Benyei11169dd2012-12-18 14:30:41 +0000962 RecordData Record;
Chris Lattner0e6c9402013-01-20 02:38:54 +0000963 StringRef Blob;
964 switch (SLocEntryCursor.readRecord(Entry.ID, Record, &Blob)) {
Guy Benyei11169dd2012-12-18 14:30:41 +0000965 default:
966 Error("incorrectly-formatted source location entry in AST file");
967 return true;
968
969 case SM_SLOC_FILE_ENTRY: {
970 // We will detect whether a file changed and return 'Failure' for it, but
971 // we will also try to fail gracefully by setting up the SLocEntry.
972 unsigned InputID = Record[4];
973 InputFile IF = getInputFile(*F, InputID);
Argyrios Kyrtzidis61c3d872013-03-01 03:26:04 +0000974 const FileEntry *File = IF.getFile();
975 bool OverriddenBuffer = IF.isOverridden();
Guy Benyei11169dd2012-12-18 14:30:41 +0000976
Argyrios Kyrtzidis61c3d872013-03-01 03:26:04 +0000977 // Note that we only check if a File was returned. If it was out-of-date
978 // we have complained but we will continue creating a FileID to recover
979 // gracefully.
980 if (!File)
Guy Benyei11169dd2012-12-18 14:30:41 +0000981 return true;
982
983 SourceLocation IncludeLoc = ReadSourceLocation(*F, Record[1]);
984 if (IncludeLoc.isInvalid() && F->Kind != MK_MainFile) {
985 // This is the module's main file.
986 IncludeLoc = getImportLocation(F);
987 }
988 SrcMgr::CharacteristicKind
989 FileCharacter = (SrcMgr::CharacteristicKind)Record[2];
990 FileID FID = SourceMgr.createFileID(File, IncludeLoc, FileCharacter,
991 ID, BaseOffset + Record[0]);
992 SrcMgr::FileInfo &FileInfo =
993 const_cast<SrcMgr::FileInfo&>(SourceMgr.getSLocEntry(FID).getFile());
994 FileInfo.NumCreatedFIDs = Record[5];
995 if (Record[3])
996 FileInfo.setHasLineDirectives();
997
998 const DeclID *FirstDecl = F->FileSortedDecls + Record[6];
999 unsigned NumFileDecls = Record[7];
1000 if (NumFileDecls) {
1001 assert(F->FileSortedDecls && "FILE_SORTED_DECLS not encountered yet ?");
1002 FileDeclIDs[FID] = FileDeclsInfo(F, llvm::makeArrayRef(FirstDecl,
1003 NumFileDecls));
1004 }
1005
1006 const SrcMgr::ContentCache *ContentCache
1007 = SourceMgr.getOrCreateContentCache(File,
1008 /*isSystemFile=*/FileCharacter != SrcMgr::C_User);
1009 if (OverriddenBuffer && !ContentCache->BufferOverridden &&
1010 ContentCache->ContentsEntry == ContentCache->OrigEntry) {
1011 unsigned Code = SLocEntryCursor.ReadCode();
1012 Record.clear();
Chris Lattner0e6c9402013-01-20 02:38:54 +00001013 unsigned RecCode = SLocEntryCursor.readRecord(Code, Record, &Blob);
Guy Benyei11169dd2012-12-18 14:30:41 +00001014
1015 if (RecCode != SM_SLOC_BUFFER_BLOB) {
1016 Error("AST record has invalid code");
1017 return true;
1018 }
1019
1020 llvm::MemoryBuffer *Buffer
Chris Lattner0e6c9402013-01-20 02:38:54 +00001021 = llvm::MemoryBuffer::getMemBuffer(Blob.drop_back(1), File->getName());
Guy Benyei11169dd2012-12-18 14:30:41 +00001022 SourceMgr.overrideFileContents(File, Buffer);
1023 }
1024
1025 break;
1026 }
1027
1028 case SM_SLOC_BUFFER_ENTRY: {
Chris Lattner0e6c9402013-01-20 02:38:54 +00001029 const char *Name = Blob.data();
Guy Benyei11169dd2012-12-18 14:30:41 +00001030 unsigned Offset = Record[0];
1031 SrcMgr::CharacteristicKind
1032 FileCharacter = (SrcMgr::CharacteristicKind)Record[2];
1033 SourceLocation IncludeLoc = ReadSourceLocation(*F, Record[1]);
1034 if (IncludeLoc.isInvalid() && F->Kind == MK_Module) {
1035 IncludeLoc = getImportLocation(F);
1036 }
1037 unsigned Code = SLocEntryCursor.ReadCode();
1038 Record.clear();
1039 unsigned RecCode
Chris Lattner0e6c9402013-01-20 02:38:54 +00001040 = SLocEntryCursor.readRecord(Code, Record, &Blob);
Guy Benyei11169dd2012-12-18 14:30:41 +00001041
1042 if (RecCode != SM_SLOC_BUFFER_BLOB) {
1043 Error("AST record has invalid code");
1044 return true;
1045 }
1046
1047 llvm::MemoryBuffer *Buffer
Chris Lattner0e6c9402013-01-20 02:38:54 +00001048 = llvm::MemoryBuffer::getMemBuffer(Blob.drop_back(1), Name);
Guy Benyei11169dd2012-12-18 14:30:41 +00001049 SourceMgr.createFileIDForMemBuffer(Buffer, FileCharacter, ID,
1050 BaseOffset + Offset, IncludeLoc);
1051 break;
1052 }
1053
1054 case SM_SLOC_EXPANSION_ENTRY: {
1055 SourceLocation SpellingLoc = ReadSourceLocation(*F, Record[1]);
1056 SourceMgr.createExpansionLoc(SpellingLoc,
1057 ReadSourceLocation(*F, Record[2]),
1058 ReadSourceLocation(*F, Record[3]),
1059 Record[4],
1060 ID,
1061 BaseOffset + Record[0]);
1062 break;
1063 }
1064 }
1065
1066 return false;
1067}
1068
1069std::pair<SourceLocation, StringRef> ASTReader::getModuleImportLoc(int ID) {
1070 if (ID == 0)
1071 return std::make_pair(SourceLocation(), "");
1072
1073 if (unsigned(-ID) - 2 >= getTotalNumSLocs() || ID > 0) {
1074 Error("source location entry ID out-of-range for AST file");
1075 return std::make_pair(SourceLocation(), "");
1076 }
1077
1078 // Find which module file this entry lands in.
1079 ModuleFile *M = GlobalSLocEntryMap.find(-ID)->second;
1080 if (M->Kind != MK_Module)
1081 return std::make_pair(SourceLocation(), "");
1082
1083 // FIXME: Can we map this down to a particular submodule? That would be
1084 // ideal.
1085 return std::make_pair(M->ImportLoc, llvm::sys::path::stem(M->FileName));
1086}
1087
1088/// \brief Find the location where the module F is imported.
1089SourceLocation ASTReader::getImportLocation(ModuleFile *F) {
1090 if (F->ImportLoc.isValid())
1091 return F->ImportLoc;
1092
1093 // Otherwise we have a PCH. It's considered to be "imported" at the first
1094 // location of its includer.
1095 if (F->ImportedBy.empty() || !F->ImportedBy[0]) {
1096 // Main file is the importer. We assume that it is the first entry in the
1097 // entry table. We can't ask the manager, because at the time of PCH loading
1098 // the main file entry doesn't exist yet.
1099 // The very first entry is the invalid instantiation loc, which takes up
1100 // offsets 0 and 1.
1101 return SourceLocation::getFromRawEncoding(2U);
1102 }
1103 //return F->Loaders[0]->FirstLoc;
1104 return F->ImportedBy[0]->FirstLoc;
1105}
1106
1107/// ReadBlockAbbrevs - Enter a subblock of the specified BlockID with the
1108/// specified cursor. Read the abbreviations that are at the top of the block
1109/// and then leave the cursor pointing into the block.
Chris Lattner7fb3bef2013-01-20 00:56:42 +00001110bool ASTReader::ReadBlockAbbrevs(BitstreamCursor &Cursor, unsigned BlockID) {
Guy Benyei11169dd2012-12-18 14:30:41 +00001111 if (Cursor.EnterSubBlock(BlockID)) {
1112 Error("malformed block record in AST file");
1113 return Failure;
1114 }
1115
1116 while (true) {
1117 uint64_t Offset = Cursor.GetCurrentBitNo();
1118 unsigned Code = Cursor.ReadCode();
1119
1120 // We expect all abbrevs to be at the start of the block.
1121 if (Code != llvm::bitc::DEFINE_ABBREV) {
1122 Cursor.JumpToBit(Offset);
1123 return false;
1124 }
1125 Cursor.ReadAbbrevRecord();
1126 }
1127}
1128
Richard Smithe40f2ba2013-08-07 21:41:30 +00001129Token ASTReader::ReadToken(ModuleFile &F, const RecordDataImpl &Record,
John McCallf413f5e2013-05-03 00:10:13 +00001130 unsigned &Idx) {
1131 Token Tok;
1132 Tok.startToken();
1133 Tok.setLocation(ReadSourceLocation(F, Record, Idx));
1134 Tok.setLength(Record[Idx++]);
1135 if (IdentifierInfo *II = getLocalIdentifier(F, Record[Idx++]))
1136 Tok.setIdentifierInfo(II);
1137 Tok.setKind((tok::TokenKind)Record[Idx++]);
1138 Tok.setFlag((Token::TokenFlags)Record[Idx++]);
1139 return Tok;
1140}
1141
Argyrios Kyrtzidiseb663da2013-03-22 21:12:57 +00001142MacroInfo *ASTReader::ReadMacroRecord(ModuleFile &F, uint64_t Offset) {
Chris Lattner7fb3bef2013-01-20 00:56:42 +00001143 BitstreamCursor &Stream = F.MacroCursor;
Guy Benyei11169dd2012-12-18 14:30:41 +00001144
1145 // Keep track of where we are in the stream, then jump back there
1146 // after reading this macro.
1147 SavedStreamPosition SavedPosition(Stream);
1148
1149 Stream.JumpToBit(Offset);
1150 RecordData Record;
1151 SmallVector<IdentifierInfo*, 16> MacroArgs;
1152 MacroInfo *Macro = 0;
1153
Guy Benyei11169dd2012-12-18 14:30:41 +00001154 while (true) {
Chris Lattnerefa77172013-01-20 00:00:22 +00001155 // Advance to the next record, but if we get to the end of the block, don't
1156 // pop it (removing all the abbreviations from the cursor) since we want to
1157 // be able to reseek within the block and read entries.
Chris Lattner7fb3bef2013-01-20 00:56:42 +00001158 unsigned Flags = BitstreamCursor::AF_DontPopBlockAtEnd;
Chris Lattnerefa77172013-01-20 00:00:22 +00001159 llvm::BitstreamEntry Entry = Stream.advanceSkippingSubblocks(Flags);
1160
1161 switch (Entry.Kind) {
1162 case llvm::BitstreamEntry::SubBlock: // Handled for us already.
1163 case llvm::BitstreamEntry::Error:
1164 Error("malformed block record in AST file");
Argyrios Kyrtzidiseb663da2013-03-22 21:12:57 +00001165 return Macro;
Chris Lattnerefa77172013-01-20 00:00:22 +00001166 case llvm::BitstreamEntry::EndBlock:
Argyrios Kyrtzidiseb663da2013-03-22 21:12:57 +00001167 return Macro;
Chris Lattnerefa77172013-01-20 00:00:22 +00001168 case llvm::BitstreamEntry::Record:
1169 // The interesting case.
1170 break;
Guy Benyei11169dd2012-12-18 14:30:41 +00001171 }
1172
1173 // Read a record.
Guy Benyei11169dd2012-12-18 14:30:41 +00001174 Record.clear();
1175 PreprocessorRecordTypes RecType =
Chris Lattner0e6c9402013-01-20 02:38:54 +00001176 (PreprocessorRecordTypes)Stream.readRecord(Entry.ID, Record);
Guy Benyei11169dd2012-12-18 14:30:41 +00001177 switch (RecType) {
Argyrios Kyrtzidiseb663da2013-03-22 21:12:57 +00001178 case PP_MACRO_DIRECTIVE_HISTORY:
1179 return Macro;
1180
Guy Benyei11169dd2012-12-18 14:30:41 +00001181 case PP_MACRO_OBJECT_LIKE:
1182 case PP_MACRO_FUNCTION_LIKE: {
1183 // If we already have a macro, that means that we've hit the end
1184 // of the definition of the macro we were looking for. We're
1185 // done.
1186 if (Macro)
Argyrios Kyrtzidiseb663da2013-03-22 21:12:57 +00001187 return Macro;
Guy Benyei11169dd2012-12-18 14:30:41 +00001188
Argyrios Kyrtzidiseb663da2013-03-22 21:12:57 +00001189 unsigned NextIndex = 1; // Skip identifier ID.
1190 SubmoduleID SubModID = getGlobalSubmoduleID(F, Record[NextIndex++]);
Guy Benyei11169dd2012-12-18 14:30:41 +00001191 SourceLocation Loc = ReadSourceLocation(F, Record, NextIndex);
Argyrios Kyrtzidiseb663da2013-03-22 21:12:57 +00001192 MacroInfo *MI = PP.AllocateDeserializedMacroInfo(Loc, SubModID);
Argyrios Kyrtzidis7572be22013-01-07 19:16:23 +00001193 MI->setDefinitionEndLoc(ReadSourceLocation(F, Record, NextIndex));
Guy Benyei11169dd2012-12-18 14:30:41 +00001194 MI->setIsUsed(Record[NextIndex++]);
Guy Benyei11169dd2012-12-18 14:30:41 +00001195
Guy Benyei11169dd2012-12-18 14:30:41 +00001196 if (RecType == PP_MACRO_FUNCTION_LIKE) {
1197 // Decode function-like macro info.
1198 bool isC99VarArgs = Record[NextIndex++];
1199 bool isGNUVarArgs = Record[NextIndex++];
1200 bool hasCommaPasting = Record[NextIndex++];
1201 MacroArgs.clear();
1202 unsigned NumArgs = Record[NextIndex++];
1203 for (unsigned i = 0; i != NumArgs; ++i)
1204 MacroArgs.push_back(getLocalIdentifier(F, Record[NextIndex++]));
1205
1206 // Install function-like macro info.
1207 MI->setIsFunctionLike();
1208 if (isC99VarArgs) MI->setIsC99Varargs();
1209 if (isGNUVarArgs) MI->setIsGNUVarargs();
1210 if (hasCommaPasting) MI->setHasCommaPasting();
1211 MI->setArgumentList(MacroArgs.data(), MacroArgs.size(),
1212 PP.getPreprocessorAllocator());
1213 }
1214
Guy Benyei11169dd2012-12-18 14:30:41 +00001215 // Remember that we saw this macro last so that we add the tokens that
1216 // form its body to it.
1217 Macro = MI;
1218
1219 if (NextIndex + 1 == Record.size() && PP.getPreprocessingRecord() &&
1220 Record[NextIndex]) {
1221 // We have a macro definition. Register the association
1222 PreprocessedEntityID
1223 GlobalID = getGlobalPreprocessedEntityID(F, Record[NextIndex]);
1224 PreprocessingRecord &PPRec = *PP.getPreprocessingRecord();
Argyrios Kyrtzidis832de9f2013-02-22 18:35:59 +00001225 PreprocessingRecord::PPEntityID
1226 PPID = PPRec.getPPEntityID(GlobalID-1, /*isLoaded=*/true);
1227 MacroDefinition *PPDef =
1228 cast_or_null<MacroDefinition>(PPRec.getPreprocessedEntity(PPID));
1229 if (PPDef)
1230 PPRec.RegisterMacroDefinition(Macro, PPDef);
Guy Benyei11169dd2012-12-18 14:30:41 +00001231 }
1232
1233 ++NumMacrosRead;
1234 break;
1235 }
1236
1237 case PP_TOKEN: {
1238 // If we see a TOKEN before a PP_MACRO_*, then the file is
1239 // erroneous, just pretend we didn't see this.
1240 if (Macro == 0) break;
1241
John McCallf413f5e2013-05-03 00:10:13 +00001242 unsigned Idx = 0;
1243 Token Tok = ReadToken(F, Record, Idx);
Guy Benyei11169dd2012-12-18 14:30:41 +00001244 Macro->AddTokenToBody(Tok);
1245 break;
1246 }
1247 }
1248 }
1249}
1250
1251PreprocessedEntityID
1252ASTReader::getGlobalPreprocessedEntityID(ModuleFile &M, unsigned LocalID) const {
1253 ContinuousRangeMap<uint32_t, int, 2>::const_iterator
1254 I = M.PreprocessedEntityRemap.find(LocalID - NUM_PREDEF_PP_ENTITY_IDS);
1255 assert(I != M.PreprocessedEntityRemap.end()
1256 && "Invalid index into preprocessed entity index remap");
1257
1258 return LocalID + I->second;
1259}
1260
Argyrios Kyrtzidis5c2a3452013-03-06 18:12:47 +00001261unsigned HeaderFileInfoTrait::ComputeHash(internal_key_ref ikey) {
1262 return llvm::hash_combine(ikey.Size, ikey.ModTime);
Guy Benyei11169dd2012-12-18 14:30:41 +00001263}
1264
1265HeaderFileInfoTrait::internal_key_type
Argyrios Kyrtzidis5c2a3452013-03-06 18:12:47 +00001266HeaderFileInfoTrait::GetInternalKey(const FileEntry *FE) {
1267 internal_key_type ikey = { FE->getSize(), FE->getModificationTime(),
1268 FE->getName() };
1269 return ikey;
1270}
Guy Benyei11169dd2012-12-18 14:30:41 +00001271
Argyrios Kyrtzidis5c2a3452013-03-06 18:12:47 +00001272bool HeaderFileInfoTrait::EqualKey(internal_key_ref a, internal_key_ref b) {
1273 if (a.Size != b.Size || a.ModTime != b.ModTime)
Guy Benyei11169dd2012-12-18 14:30:41 +00001274 return false;
1275
Argyrios Kyrtzidis5c2a3452013-03-06 18:12:47 +00001276 if (strcmp(a.Filename, b.Filename) == 0)
1277 return true;
1278
Guy Benyei11169dd2012-12-18 14:30:41 +00001279 // Determine whether the actual files are equivalent.
Argyrios Kyrtzidis2a513e82013-03-04 20:33:40 +00001280 FileManager &FileMgr = Reader.getFileManager();
Argyrios Kyrtzidis5c2a3452013-03-06 18:12:47 +00001281 const FileEntry *FEA = FileMgr.getFile(a.Filename);
1282 const FileEntry *FEB = FileMgr.getFile(b.Filename);
Argyrios Kyrtzidis2a513e82013-03-04 20:33:40 +00001283 return (FEA && FEA == FEB);
Guy Benyei11169dd2012-12-18 14:30:41 +00001284}
1285
1286std::pair<unsigned, unsigned>
1287HeaderFileInfoTrait::ReadKeyDataLength(const unsigned char*& d) {
1288 unsigned KeyLen = (unsigned) clang::io::ReadUnalignedLE16(d);
1289 unsigned DataLen = (unsigned) *d++;
Argyrios Kyrtzidis5c2a3452013-03-06 18:12:47 +00001290 return std::make_pair(KeyLen, DataLen);
Guy Benyei11169dd2012-12-18 14:30:41 +00001291}
Argyrios Kyrtzidis5c2a3452013-03-06 18:12:47 +00001292
1293HeaderFileInfoTrait::internal_key_type
1294HeaderFileInfoTrait::ReadKey(const unsigned char *d, unsigned) {
1295 internal_key_type ikey;
1296 ikey.Size = off_t(clang::io::ReadUnalignedLE64(d));
1297 ikey.ModTime = time_t(clang::io::ReadUnalignedLE64(d));
1298 ikey.Filename = (const char *)d;
1299 return ikey;
1300}
1301
Guy Benyei11169dd2012-12-18 14:30:41 +00001302HeaderFileInfoTrait::data_type
Argyrios Kyrtzidisb146baa2013-03-13 21:13:51 +00001303HeaderFileInfoTrait::ReadData(internal_key_ref key, const unsigned char *d,
Guy Benyei11169dd2012-12-18 14:30:41 +00001304 unsigned DataLen) {
1305 const unsigned char *End = d + DataLen;
1306 using namespace clang::io;
1307 HeaderFileInfo HFI;
1308 unsigned Flags = *d++;
Lawrence Crowlb53e5482013-06-20 21:14:14 +00001309 HFI.HeaderRole = static_cast<ModuleMap::ModuleHeaderRole>
1310 ((Flags >> 6) & 0x03);
Guy Benyei11169dd2012-12-18 14:30:41 +00001311 HFI.isImport = (Flags >> 5) & 0x01;
1312 HFI.isPragmaOnce = (Flags >> 4) & 0x01;
1313 HFI.DirInfo = (Flags >> 2) & 0x03;
1314 HFI.Resolved = (Flags >> 1) & 0x01;
1315 HFI.IndexHeaderMapHeader = Flags & 0x01;
1316 HFI.NumIncludes = ReadUnalignedLE16(d);
1317 HFI.ControllingMacroID = Reader.getGlobalIdentifierID(M,
1318 ReadUnalignedLE32(d));
1319 if (unsigned FrameworkOffset = ReadUnalignedLE32(d)) {
1320 // The framework offset is 1 greater than the actual offset,
1321 // since 0 is used as an indicator for "no framework name".
1322 StringRef FrameworkName(FrameworkStrings + FrameworkOffset - 1);
1323 HFI.Framework = HS->getUniqueFrameworkName(FrameworkName);
1324 }
1325
Argyrios Kyrtzidisb146baa2013-03-13 21:13:51 +00001326 if (d != End) {
1327 uint32_t LocalSMID = ReadUnalignedLE32(d);
1328 if (LocalSMID) {
1329 // This header is part of a module. Associate it with the module to enable
1330 // implicit module import.
1331 SubmoduleID GlobalSMID = Reader.getGlobalSubmoduleID(M, LocalSMID);
1332 Module *Mod = Reader.getSubmodule(GlobalSMID);
1333 HFI.isModuleHeader = true;
1334 FileManager &FileMgr = Reader.getFileManager();
1335 ModuleMap &ModMap =
1336 Reader.getPreprocessor().getHeaderSearchInfo().getModuleMap();
Lawrence Crowlb53e5482013-06-20 21:14:14 +00001337 ModMap.addHeader(Mod, FileMgr.getFile(key.Filename), HFI.getHeaderRole());
Argyrios Kyrtzidisb146baa2013-03-13 21:13:51 +00001338 }
1339 }
1340
Guy Benyei11169dd2012-12-18 14:30:41 +00001341 assert(End == d && "Wrong data length in HeaderFileInfo deserialization");
1342 (void)End;
1343
1344 // This HeaderFileInfo was externally loaded.
1345 HFI.External = true;
1346 return HFI;
1347}
1348
Richard Smith49f906a2014-03-01 00:08:04 +00001349void
1350ASTReader::addPendingMacroFromModule(IdentifierInfo *II, ModuleFile *M,
1351 GlobalMacroID GMacID,
1352 llvm::ArrayRef<SubmoduleID> Overrides) {
Guy Benyei11169dd2012-12-18 14:30:41 +00001353 assert(NumCurrentElementsDeserializing > 0 &&"Missing deserialization guard");
Richard Smith49f906a2014-03-01 00:08:04 +00001354 SubmoduleID *OverrideData = 0;
1355 if (!Overrides.empty()) {
1356 OverrideData = new (Context) SubmoduleID[Overrides.size() + 1];
1357 OverrideData[0] = Overrides.size();
1358 for (unsigned I = 0; I != Overrides.size(); ++I)
1359 OverrideData[I + 1] = getGlobalSubmoduleID(*M, Overrides[I]);
1360 }
1361 PendingMacroIDs[II].push_back(PendingMacroInfo(M, GMacID, OverrideData));
Argyrios Kyrtzidiseb663da2013-03-22 21:12:57 +00001362}
1363
1364void ASTReader::addPendingMacroFromPCH(IdentifierInfo *II,
1365 ModuleFile *M,
1366 uint64_t MacroDirectivesOffset) {
1367 assert(NumCurrentElementsDeserializing > 0 &&"Missing deserialization guard");
1368 PendingMacroIDs[II].push_back(PendingMacroInfo(M, MacroDirectivesOffset));
Guy Benyei11169dd2012-12-18 14:30:41 +00001369}
1370
1371void ASTReader::ReadDefinedMacros() {
1372 // Note that we are loading defined macros.
1373 Deserializing Macros(this);
1374
1375 for (ModuleReverseIterator I = ModuleMgr.rbegin(),
1376 E = ModuleMgr.rend(); I != E; ++I) {
Chris Lattner7fb3bef2013-01-20 00:56:42 +00001377 BitstreamCursor &MacroCursor = (*I)->MacroCursor;
Guy Benyei11169dd2012-12-18 14:30:41 +00001378
1379 // If there was no preprocessor block, skip this file.
1380 if (!MacroCursor.getBitStreamReader())
1381 continue;
1382
Chris Lattner7fb3bef2013-01-20 00:56:42 +00001383 BitstreamCursor Cursor = MacroCursor;
Guy Benyei11169dd2012-12-18 14:30:41 +00001384 Cursor.JumpToBit((*I)->MacroStartOffset);
1385
1386 RecordData Record;
1387 while (true) {
Chris Lattnere7b154b2013-01-19 21:39:22 +00001388 llvm::BitstreamEntry E = Cursor.advanceSkippingSubblocks();
1389
1390 switch (E.Kind) {
1391 case llvm::BitstreamEntry::SubBlock: // Handled for us already.
1392 case llvm::BitstreamEntry::Error:
1393 Error("malformed block record in AST file");
1394 return;
1395 case llvm::BitstreamEntry::EndBlock:
1396 goto NextCursor;
1397
1398 case llvm::BitstreamEntry::Record:
Chris Lattnere7b154b2013-01-19 21:39:22 +00001399 Record.clear();
Chris Lattner0e6c9402013-01-20 02:38:54 +00001400 switch (Cursor.readRecord(E.ID, Record)) {
Chris Lattnere7b154b2013-01-19 21:39:22 +00001401 default: // Default behavior: ignore.
1402 break;
1403
1404 case PP_MACRO_OBJECT_LIKE:
1405 case PP_MACRO_FUNCTION_LIKE:
1406 getLocalIdentifier(**I, Record[0]);
1407 break;
1408
1409 case PP_TOKEN:
1410 // Ignore tokens.
1411 break;
Guy Benyei11169dd2012-12-18 14:30:41 +00001412 }
Guy Benyei11169dd2012-12-18 14:30:41 +00001413 break;
1414 }
1415 }
Chris Lattnere7b154b2013-01-19 21:39:22 +00001416 NextCursor: ;
Guy Benyei11169dd2012-12-18 14:30:41 +00001417 }
1418}
1419
1420namespace {
1421 /// \brief Visitor class used to look up identifirs in an AST file.
1422 class IdentifierLookupVisitor {
1423 StringRef Name;
1424 unsigned PriorGeneration;
Douglas Gregor00a50f72013-01-25 00:38:33 +00001425 unsigned &NumIdentifierLookups;
1426 unsigned &NumIdentifierLookupHits;
Guy Benyei11169dd2012-12-18 14:30:41 +00001427 IdentifierInfo *Found;
Douglas Gregor00a50f72013-01-25 00:38:33 +00001428
Guy Benyei11169dd2012-12-18 14:30:41 +00001429 public:
Douglas Gregor00a50f72013-01-25 00:38:33 +00001430 IdentifierLookupVisitor(StringRef Name, unsigned PriorGeneration,
1431 unsigned &NumIdentifierLookups,
1432 unsigned &NumIdentifierLookupHits)
Douglas Gregor7211ac12013-01-25 23:32:03 +00001433 : Name(Name), PriorGeneration(PriorGeneration),
Douglas Gregor00a50f72013-01-25 00:38:33 +00001434 NumIdentifierLookups(NumIdentifierLookups),
1435 NumIdentifierLookupHits(NumIdentifierLookupHits),
1436 Found()
1437 {
1438 }
Guy Benyei11169dd2012-12-18 14:30:41 +00001439
1440 static bool visit(ModuleFile &M, void *UserData) {
1441 IdentifierLookupVisitor *This
1442 = static_cast<IdentifierLookupVisitor *>(UserData);
1443
1444 // If we've already searched this module file, skip it now.
1445 if (M.Generation <= This->PriorGeneration)
1446 return true;
Douglas Gregore060e572013-01-25 01:03:03 +00001447
Guy Benyei11169dd2012-12-18 14:30:41 +00001448 ASTIdentifierLookupTable *IdTable
1449 = (ASTIdentifierLookupTable *)M.IdentifierLookupTable;
1450 if (!IdTable)
1451 return false;
1452
1453 ASTIdentifierLookupTrait Trait(IdTable->getInfoObj().getReader(),
1454 M, This->Found);
Douglas Gregor00a50f72013-01-25 00:38:33 +00001455 ++This->NumIdentifierLookups;
1456 ASTIdentifierLookupTable::iterator Pos = IdTable->find(This->Name,&Trait);
Guy Benyei11169dd2012-12-18 14:30:41 +00001457 if (Pos == IdTable->end())
1458 return false;
1459
1460 // Dereferencing the iterator has the effect of building the
1461 // IdentifierInfo node and populating it with the various
1462 // declarations it needs.
Douglas Gregor00a50f72013-01-25 00:38:33 +00001463 ++This->NumIdentifierLookupHits;
Guy Benyei11169dd2012-12-18 14:30:41 +00001464 This->Found = *Pos;
1465 return true;
1466 }
1467
1468 // \brief Retrieve the identifier info found within the module
1469 // files.
1470 IdentifierInfo *getIdentifierInfo() const { return Found; }
1471 };
1472}
1473
1474void ASTReader::updateOutOfDateIdentifier(IdentifierInfo &II) {
1475 // Note that we are loading an identifier.
1476 Deserializing AnIdentifier(this);
1477
1478 unsigned PriorGeneration = 0;
1479 if (getContext().getLangOpts().Modules)
1480 PriorGeneration = IdentifierGeneration[&II];
Douglas Gregore060e572013-01-25 01:03:03 +00001481
1482 // If there is a global index, look there first to determine which modules
1483 // provably do not have any results for this identifier.
Douglas Gregor7211ac12013-01-25 23:32:03 +00001484 GlobalModuleIndex::HitSet Hits;
1485 GlobalModuleIndex::HitSet *HitsPtr = 0;
Douglas Gregore060e572013-01-25 01:03:03 +00001486 if (!loadGlobalIndex()) {
Douglas Gregor7211ac12013-01-25 23:32:03 +00001487 if (GlobalIndex->lookupIdentifier(II.getName(), Hits)) {
1488 HitsPtr = &Hits;
Douglas Gregore060e572013-01-25 01:03:03 +00001489 }
1490 }
1491
Douglas Gregor7211ac12013-01-25 23:32:03 +00001492 IdentifierLookupVisitor Visitor(II.getName(), PriorGeneration,
Douglas Gregor00a50f72013-01-25 00:38:33 +00001493 NumIdentifierLookups,
1494 NumIdentifierLookupHits);
Douglas Gregor7211ac12013-01-25 23:32:03 +00001495 ModuleMgr.visit(IdentifierLookupVisitor::visit, &Visitor, HitsPtr);
Guy Benyei11169dd2012-12-18 14:30:41 +00001496 markIdentifierUpToDate(&II);
1497}
1498
1499void ASTReader::markIdentifierUpToDate(IdentifierInfo *II) {
1500 if (!II)
1501 return;
1502
1503 II->setOutOfDate(false);
1504
1505 // Update the generation for this identifier.
1506 if (getContext().getLangOpts().Modules)
1507 IdentifierGeneration[II] = CurrentGeneration;
1508}
1509
Richard Smith49f906a2014-03-01 00:08:04 +00001510struct ASTReader::ModuleMacroInfo {
1511 SubmoduleID SubModID;
1512 MacroInfo *MI;
1513 SubmoduleID *Overrides;
1514 // FIXME: Remove this.
1515 ModuleFile *F;
1516
1517 bool isDefine() const { return MI; }
1518
1519 SubmoduleID getSubmoduleID() const { return SubModID; }
1520
1521 llvm::ArrayRef<SubmoduleID> getOverriddenSubmodules() const {
1522 if (!Overrides)
1523 return llvm::ArrayRef<SubmoduleID>();
1524 return llvm::makeArrayRef(Overrides + 1, *Overrides);
1525 }
1526
1527 DefMacroDirective *import(Preprocessor &PP, SourceLocation ImportLoc) const {
1528 if (!MI)
1529 return 0;
1530 return PP.AllocateDefMacroDirective(MI, ImportLoc, /*isImported=*/true);
1531 }
1532};
1533
1534ASTReader::ModuleMacroInfo *
1535ASTReader::getModuleMacro(const PendingMacroInfo &PMInfo) {
1536 ModuleMacroInfo Info;
1537
1538 uint32_t ID = PMInfo.ModuleMacroData.MacID;
1539 if (ID & 1) {
1540 // Macro undefinition.
1541 Info.SubModID = getGlobalSubmoduleID(*PMInfo.M, ID >> 1);
1542 Info.MI = 0;
1543 } else {
1544 // Macro definition.
1545 GlobalMacroID GMacID = getGlobalMacroID(*PMInfo.M, ID >> 1);
1546 assert(GMacID);
1547
1548 // If this macro has already been loaded, don't do so again.
1549 // FIXME: This is highly dubious. Multiple macro definitions can have the
1550 // same MacroInfo (and hence the same GMacID) due to #pragma push_macro etc.
1551 if (MacrosLoaded[GMacID - NUM_PREDEF_MACRO_IDS])
1552 return 0;
1553
1554 Info.MI = getMacro(GMacID);
1555 Info.SubModID = Info.MI->getOwningModuleID();
1556 }
1557 Info.Overrides = PMInfo.ModuleMacroData.Overrides;
1558 Info.F = PMInfo.M;
1559
1560 return new (Context) ModuleMacroInfo(Info);
1561}
1562
Argyrios Kyrtzidiseb663da2013-03-22 21:12:57 +00001563void ASTReader::resolvePendingMacro(IdentifierInfo *II,
1564 const PendingMacroInfo &PMInfo) {
1565 assert(II);
1566
1567 if (PMInfo.M->Kind != MK_Module) {
1568 installPCHMacroDirectives(II, *PMInfo.M,
1569 PMInfo.PCHMacroData.MacroDirectivesOffset);
1570 return;
1571 }
Richard Smith49f906a2014-03-01 00:08:04 +00001572
Argyrios Kyrtzidiseb663da2013-03-22 21:12:57 +00001573 // Module Macro.
1574
Richard Smith49f906a2014-03-01 00:08:04 +00001575 ModuleMacroInfo *MMI = getModuleMacro(PMInfo);
1576 if (!MMI)
Argyrios Kyrtzidiseb663da2013-03-22 21:12:57 +00001577 return;
1578
Richard Smith49f906a2014-03-01 00:08:04 +00001579 Module *Owner = getSubmodule(MMI->getSubmoduleID());
1580 if (Owner && Owner->NameVisibility == Module::Hidden) {
1581 // Macros in the owning module are hidden. Just remember this macro to
1582 // install if we make this module visible.
1583 HiddenNamesMap[Owner].HiddenMacros.insert(std::make_pair(II, MMI));
1584 } else {
1585 installImportedMacro(II, MMI, Owner);
Argyrios Kyrtzidiseb663da2013-03-22 21:12:57 +00001586 }
Argyrios Kyrtzidiseb663da2013-03-22 21:12:57 +00001587}
1588
1589void ASTReader::installPCHMacroDirectives(IdentifierInfo *II,
1590 ModuleFile &M, uint64_t Offset) {
1591 assert(M.Kind != MK_Module);
1592
1593 BitstreamCursor &Cursor = M.MacroCursor;
1594 SavedStreamPosition SavedPosition(Cursor);
1595 Cursor.JumpToBit(Offset);
1596
1597 llvm::BitstreamEntry Entry =
1598 Cursor.advance(BitstreamCursor::AF_DontPopBlockAtEnd);
1599 if (Entry.Kind != llvm::BitstreamEntry::Record) {
1600 Error("malformed block record in AST file");
1601 return;
1602 }
1603
1604 RecordData Record;
1605 PreprocessorRecordTypes RecType =
1606 (PreprocessorRecordTypes)Cursor.readRecord(Entry.ID, Record);
1607 if (RecType != PP_MACRO_DIRECTIVE_HISTORY) {
1608 Error("malformed block record in AST file");
1609 return;
1610 }
1611
1612 // Deserialize the macro directives history in reverse source-order.
1613 MacroDirective *Latest = 0, *Earliest = 0;
1614 unsigned Idx = 0, N = Record.size();
1615 while (Idx < N) {
Argyrios Kyrtzidisb6210df2013-03-26 17:17:01 +00001616 MacroDirective *MD = 0;
Argyrios Kyrtzidiseb663da2013-03-22 21:12:57 +00001617 SourceLocation Loc = ReadSourceLocation(M, Record, Idx);
Argyrios Kyrtzidisb6210df2013-03-26 17:17:01 +00001618 MacroDirective::Kind K = (MacroDirective::Kind)Record[Idx++];
1619 switch (K) {
1620 case MacroDirective::MD_Define: {
1621 GlobalMacroID GMacID = getGlobalMacroID(M, Record[Idx++]);
1622 MacroInfo *MI = getMacro(GMacID);
1623 bool isImported = Record[Idx++];
1624 bool isAmbiguous = Record[Idx++];
1625 DefMacroDirective *DefMD =
1626 PP.AllocateDefMacroDirective(MI, Loc, isImported);
1627 DefMD->setAmbiguous(isAmbiguous);
1628 MD = DefMD;
1629 break;
1630 }
1631 case MacroDirective::MD_Undefine:
1632 MD = PP.AllocateUndefMacroDirective(Loc);
1633 break;
1634 case MacroDirective::MD_Visibility: {
1635 bool isPublic = Record[Idx++];
1636 MD = PP.AllocateVisibilityMacroDirective(Loc, isPublic);
1637 break;
1638 }
1639 }
Argyrios Kyrtzidiseb663da2013-03-22 21:12:57 +00001640
1641 if (!Latest)
1642 Latest = MD;
1643 if (Earliest)
1644 Earliest->setPrevious(MD);
1645 Earliest = MD;
1646 }
1647
1648 PP.setLoadedMacroDirective(II, Latest);
1649}
1650
Argyrios Kyrtzidis3a9c42c2013-03-27 01:25:34 +00001651/// \brief For the given macro definitions, check if they are both in system
Douglas Gregor0b202052013-04-12 21:00:54 +00001652/// modules.
1653static bool areDefinedInSystemModules(MacroInfo *PrevMI, MacroInfo *NewMI,
Douglas Gregor5e461192013-06-07 22:56:11 +00001654 Module *NewOwner, ASTReader &Reader) {
Argyrios Kyrtzidis3a9c42c2013-03-27 01:25:34 +00001655 assert(PrevMI && NewMI);
Argyrios Kyrtzidis3a9c42c2013-03-27 01:25:34 +00001656 Module *PrevOwner = 0;
1657 if (SubmoduleID PrevModID = PrevMI->getOwningModuleID())
1658 PrevOwner = Reader.getSubmodule(PrevModID);
Douglas Gregor5e461192013-06-07 22:56:11 +00001659 SourceManager &SrcMgr = Reader.getSourceManager();
1660 bool PrevInSystem
1661 = PrevOwner? PrevOwner->IsSystem
1662 : SrcMgr.isInSystemHeader(PrevMI->getDefinitionLoc());
1663 bool NewInSystem
1664 = NewOwner? NewOwner->IsSystem
1665 : SrcMgr.isInSystemHeader(NewMI->getDefinitionLoc());
1666 if (PrevOwner && PrevOwner == NewOwner)
Argyrios Kyrtzidis3a9c42c2013-03-27 01:25:34 +00001667 return false;
Douglas Gregor5e461192013-06-07 22:56:11 +00001668 return PrevInSystem && NewInSystem;
Argyrios Kyrtzidis3a9c42c2013-03-27 01:25:34 +00001669}
1670
Richard Smith49f906a2014-03-01 00:08:04 +00001671void ASTReader::removeOverriddenMacros(IdentifierInfo *II,
1672 AmbiguousMacros &Ambig,
1673 llvm::ArrayRef<SubmoduleID> Overrides) {
1674 for (unsigned OI = 0, ON = Overrides.size(); OI != ON; ++OI) {
1675 SubmoduleID OwnerID = Overrides[OI];
Argyrios Kyrtzidiseb663da2013-03-22 21:12:57 +00001676
Richard Smith49f906a2014-03-01 00:08:04 +00001677 // If this macro is not yet visible, remove it from the hidden names list.
1678 Module *Owner = getSubmodule(OwnerID);
1679 HiddenNames &Hidden = HiddenNamesMap[Owner];
1680 HiddenMacrosMap::iterator HI = Hidden.HiddenMacros.find(II);
1681 if (HI != Hidden.HiddenMacros.end()) {
1682 removeOverriddenMacros(II, Ambig, HI->second->getOverriddenSubmodules());
1683 Hidden.HiddenMacros.erase(HI);
1684 }
1685
1686 // If this macro is already in our list of conflicts, remove it from there.
Richard Smithbb29e512014-03-06 00:33:23 +00001687 Ambig.erase(
1688 std::remove_if(Ambig.begin(), Ambig.end(), [&](DefMacroDirective *MD) {
1689 return MD->getInfo()->getOwningModuleID() == OwnerID;
1690 }),
1691 Ambig.end());
Richard Smith49f906a2014-03-01 00:08:04 +00001692 }
1693}
1694
1695ASTReader::AmbiguousMacros *
1696ASTReader::removeOverriddenMacros(IdentifierInfo *II,
1697 llvm::ArrayRef<SubmoduleID> Overrides) {
Argyrios Kyrtzidiseb663da2013-03-22 21:12:57 +00001698 MacroDirective *Prev = PP.getMacroDirective(II);
Richard Smith49f906a2014-03-01 00:08:04 +00001699 if (!Prev && Overrides.empty())
1700 return 0;
1701
1702 DefMacroDirective *PrevDef = Prev ? Prev->getDefinition().getDirective() : 0;
1703 if (PrevDef && PrevDef->isAmbiguous()) {
1704 // We had a prior ambiguity. Check whether we resolve it (or make it worse).
1705 AmbiguousMacros &Ambig = AmbiguousMacroDefs[II];
1706 Ambig.push_back(PrevDef);
1707
1708 removeOverriddenMacros(II, Ambig, Overrides);
1709
1710 if (!Ambig.empty())
1711 return &Ambig;
1712
1713 AmbiguousMacroDefs.erase(II);
1714 } else {
1715 // There's no ambiguity yet. Maybe we're introducing one.
1716 llvm::SmallVector<DefMacroDirective*, 1> Ambig;
1717 if (PrevDef)
1718 Ambig.push_back(PrevDef);
1719
1720 removeOverriddenMacros(II, Ambig, Overrides);
1721
1722 if (!Ambig.empty()) {
1723 AmbiguousMacros &Result = AmbiguousMacroDefs[II];
1724 Result.swap(Ambig);
1725 return &Result;
Argyrios Kyrtzidisb6210df2013-03-26 17:17:01 +00001726 }
Argyrios Kyrtzidiseb663da2013-03-22 21:12:57 +00001727 }
Richard Smith49f906a2014-03-01 00:08:04 +00001728
1729 // We ended up with no ambiguity.
1730 return 0;
1731}
1732
1733void ASTReader::installImportedMacro(IdentifierInfo *II, ModuleMacroInfo *MMI,
1734 Module *Owner) {
1735 assert(II && Owner);
1736
1737 SourceLocation ImportLoc = Owner->MacroVisibilityLoc;
1738 if (ImportLoc.isInvalid()) {
1739 // FIXME: If we made macros from this module visible but didn't provide a
1740 // source location for the import, we don't have a location for the macro.
1741 // Use the location at which the containing module file was first imported
1742 // for now.
1743 ImportLoc = MMI->F->DirectImportLoc;
1744 }
1745
1746 llvm::SmallVectorImpl<DefMacroDirective*> *Prev =
1747 removeOverriddenMacros(II, MMI->getOverriddenSubmodules());
1748
1749
1750 // Create a synthetic macro definition corresponding to the import (or null
1751 // if this was an undefinition of the macro).
1752 DefMacroDirective *MD = MMI->import(PP, ImportLoc);
1753
1754 // If there's no ambiguity, just install the macro.
1755 if (!Prev) {
1756 if (MD)
1757 PP.appendMacroDirective(II, MD);
1758 else
1759 PP.appendMacroDirective(II, PP.AllocateUndefMacroDirective(ImportLoc));
1760 return;
1761 }
1762 assert(!Prev->empty());
1763
1764 if (!MD) {
1765 // We imported a #undef that didn't remove all prior definitions. The most
1766 // recent prior definition remains, and we install it in the place of the
1767 // imported directive.
1768 MacroInfo *NewMI = Prev->back()->getInfo();
1769 Prev->pop_back();
1770 MD = PP.AllocateDefMacroDirective(NewMI, ImportLoc, /*Imported*/true);
1771 }
1772
1773 // We're introducing a macro definition that creates or adds to an ambiguity.
1774 // We can resolve that ambiguity if this macro is token-for-token identical to
1775 // all of the existing definitions.
1776 MacroInfo *NewMI = MD->getInfo();
1777 assert(NewMI && "macro definition with no MacroInfo?");
1778 while (!Prev->empty()) {
1779 MacroInfo *PrevMI = Prev->back()->getInfo();
1780 assert(PrevMI && "macro definition with no MacroInfo?");
1781
1782 // Before marking the macros as ambiguous, check if this is a case where
1783 // both macros are in system headers. If so, we trust that the system
1784 // did not get it wrong. This also handles cases where Clang's own
1785 // headers have a different spelling of certain system macros:
1786 // #define LONG_MAX __LONG_MAX__ (clang's limits.h)
1787 // #define LONG_MAX 0x7fffffffffffffffL (system's limits.h)
1788 //
1789 // FIXME: Remove the defined-in-system-headers check. clang's limits.h
1790 // overrides the system limits.h's macros, so there's no conflict here.
1791 if (NewMI != PrevMI &&
1792 !PrevMI->isIdenticalTo(*NewMI, PP, /*Syntactically=*/true) &&
1793 !areDefinedInSystemModules(PrevMI, NewMI, Owner, *this))
1794 break;
1795
1796 // The previous definition is the same as this one (or both are defined in
1797 // system modules so we can assume they're equivalent); we don't need to
1798 // track it any more.
1799 Prev->pop_back();
1800 }
1801
1802 if (!Prev->empty())
1803 MD->setAmbiguous(true);
1804
Argyrios Kyrtzidisb6210df2013-03-26 17:17:01 +00001805 PP.appendMacroDirective(II, MD);
Argyrios Kyrtzidiseb663da2013-03-22 21:12:57 +00001806}
1807
Argyrios Kyrtzidis61c3d872013-03-01 03:26:04 +00001808InputFile ASTReader::getInputFile(ModuleFile &F, unsigned ID, bool Complain) {
Guy Benyei11169dd2012-12-18 14:30:41 +00001809 // If this ID is bogus, just return an empty input file.
1810 if (ID == 0 || ID > F.InputFilesLoaded.size())
1811 return InputFile();
1812
1813 // If we've already loaded this input file, return it.
Argyrios Kyrtzidis61c3d872013-03-01 03:26:04 +00001814 if (F.InputFilesLoaded[ID-1].getFile())
Guy Benyei11169dd2012-12-18 14:30:41 +00001815 return F.InputFilesLoaded[ID-1];
1816
Argyrios Kyrtzidis9308f0a2014-01-08 19:13:34 +00001817 if (F.InputFilesLoaded[ID-1].isNotFound())
1818 return InputFile();
1819
Guy Benyei11169dd2012-12-18 14:30:41 +00001820 // Go find this input file.
Chris Lattner7fb3bef2013-01-20 00:56:42 +00001821 BitstreamCursor &Cursor = F.InputFilesCursor;
Guy Benyei11169dd2012-12-18 14:30:41 +00001822 SavedStreamPosition SavedPosition(Cursor);
1823 Cursor.JumpToBit(F.InputFileOffsets[ID-1]);
1824
1825 unsigned Code = Cursor.ReadCode();
1826 RecordData Record;
Chris Lattner0e6c9402013-01-20 02:38:54 +00001827 StringRef Blob;
1828 switch ((InputFileRecordTypes)Cursor.readRecord(Code, Record, &Blob)) {
Guy Benyei11169dd2012-12-18 14:30:41 +00001829 case INPUT_FILE: {
1830 unsigned StoredID = Record[0];
1831 assert(ID == StoredID && "Bogus stored ID or offset");
1832 (void)StoredID;
1833 off_t StoredSize = (off_t)Record[1];
1834 time_t StoredTime = (time_t)Record[2];
1835 bool Overridden = (bool)Record[3];
1836
1837 // Get the file entry for this input file.
Chris Lattner0e6c9402013-01-20 02:38:54 +00001838 StringRef OrigFilename = Blob;
Guy Benyei11169dd2012-12-18 14:30:41 +00001839 std::string Filename = OrigFilename;
1840 MaybeAddSystemRootToFilename(F, Filename);
1841 const FileEntry *File
1842 = Overridden? FileMgr.getVirtualFile(Filename, StoredSize, StoredTime)
1843 : FileMgr.getFile(Filename, /*OpenFile=*/false);
1844
1845 // If we didn't find the file, resolve it relative to the
1846 // original directory from which this AST file was created.
1847 if (File == 0 && !F.OriginalDir.empty() && !CurrentDir.empty() &&
1848 F.OriginalDir != CurrentDir) {
1849 std::string Resolved = resolveFileRelativeToOriginalDir(Filename,
1850 F.OriginalDir,
1851 CurrentDir);
1852 if (!Resolved.empty())
1853 File = FileMgr.getFile(Resolved);
1854 }
1855
1856 // For an overridden file, create a virtual file with the stored
1857 // size/timestamp.
1858 if (Overridden && File == 0) {
1859 File = FileMgr.getVirtualFile(Filename, StoredSize, StoredTime);
1860 }
1861
1862 if (File == 0) {
1863 if (Complain) {
1864 std::string ErrorStr = "could not find file '";
1865 ErrorStr += Filename;
1866 ErrorStr += "' referenced by AST file";
1867 Error(ErrorStr.c_str());
1868 }
Argyrios Kyrtzidis9308f0a2014-01-08 19:13:34 +00001869 // Record that we didn't find the file.
1870 F.InputFilesLoaded[ID-1] = InputFile::getNotFound();
Guy Benyei11169dd2012-12-18 14:30:41 +00001871 return InputFile();
1872 }
Argyrios Kyrtzidis61c3d872013-03-01 03:26:04 +00001873
Guy Benyei11169dd2012-12-18 14:30:41 +00001874 // Check if there was a request to override the contents of the file
1875 // that was part of the precompiled header. Overridding such a file
1876 // can lead to problems when lexing using the source locations from the
1877 // PCH.
1878 SourceManager &SM = getSourceManager();
1879 if (!Overridden && SM.isFileOverridden(File)) {
Argyrios Kyrtzidis61c3d872013-03-01 03:26:04 +00001880 if (Complain)
1881 Error(diag::err_fe_pch_file_overridden, Filename);
Guy Benyei11169dd2012-12-18 14:30:41 +00001882 // After emitting the diagnostic, recover by disabling the override so
1883 // that the original file will be used.
1884 SM.disableFileContentsOverride(File);
1885 // The FileEntry is a virtual file entry with the size of the contents
1886 // that would override the original contents. Set it to the original's
1887 // size/time.
1888 FileMgr.modifyFileEntry(const_cast<FileEntry*>(File),
1889 StoredSize, StoredTime);
1890 }
1891
Argyrios Kyrtzidis61c3d872013-03-01 03:26:04 +00001892 bool IsOutOfDate = false;
Guy Benyei11169dd2012-12-18 14:30:41 +00001893
Argyrios Kyrtzidis61c3d872013-03-01 03:26:04 +00001894 // For an overridden file, there is nothing to validate.
1895 if (!Overridden && (StoredSize != File->getSize()
Guy Benyei11169dd2012-12-18 14:30:41 +00001896#if !defined(LLVM_ON_WIN32)
1897 // In our regression testing, the Windows file system seems to
1898 // have inconsistent modification times that sometimes
1899 // erroneously trigger this error-handling path.
1900 || StoredTime != File->getModificationTime()
1901#endif
1902 )) {
Douglas Gregor7029ce12013-03-19 00:28:20 +00001903 if (Complain) {
Ben Langmuire82630d2014-01-17 00:19:09 +00001904 // Build a list of the PCH imports that got us here (in reverse).
1905 SmallVector<ModuleFile *, 4> ImportStack(1, &F);
1906 while (ImportStack.back()->ImportedBy.size() > 0)
1907 ImportStack.push_back(ImportStack.back()->ImportedBy[0]);
1908
1909 // The top-level PCH is stale.
1910 StringRef TopLevelPCHName(ImportStack.back()->FileName);
1911 Error(diag::err_fe_pch_file_modified, Filename, TopLevelPCHName);
1912
1913 // Print the import stack.
1914 if (ImportStack.size() > 1 && !Diags.isDiagnosticInFlight()) {
1915 Diag(diag::note_pch_required_by)
1916 << Filename << ImportStack[0]->FileName;
1917 for (unsigned I = 1; I < ImportStack.size(); ++I)
1918 Diag(diag::note_pch_required_by)
1919 << ImportStack[I-1]->FileName << ImportStack[I]->FileName;
Douglas Gregor940e8052013-05-10 22:15:13 +00001920 }
Ben Langmuire82630d2014-01-17 00:19:09 +00001921
1922 if (!Diags.isDiagnosticInFlight())
1923 Diag(diag::note_pch_rebuild_required) << TopLevelPCHName;
Douglas Gregor7029ce12013-03-19 00:28:20 +00001924 }
1925
Argyrios Kyrtzidis61c3d872013-03-01 03:26:04 +00001926 IsOutOfDate = true;
Guy Benyei11169dd2012-12-18 14:30:41 +00001927 }
1928
Argyrios Kyrtzidis61c3d872013-03-01 03:26:04 +00001929 InputFile IF = InputFile(File, Overridden, IsOutOfDate);
1930
1931 // Note that we've loaded this input file.
1932 F.InputFilesLoaded[ID-1] = IF;
1933 return IF;
Guy Benyei11169dd2012-12-18 14:30:41 +00001934 }
1935 }
1936
1937 return InputFile();
1938}
1939
1940const FileEntry *ASTReader::getFileEntry(StringRef filenameStrRef) {
1941 ModuleFile &M = ModuleMgr.getPrimaryModule();
1942 std::string Filename = filenameStrRef;
1943 MaybeAddSystemRootToFilename(M, Filename);
1944 const FileEntry *File = FileMgr.getFile(Filename);
1945 if (File == 0 && !M.OriginalDir.empty() && !CurrentDir.empty() &&
1946 M.OriginalDir != CurrentDir) {
1947 std::string resolved = resolveFileRelativeToOriginalDir(Filename,
1948 M.OriginalDir,
1949 CurrentDir);
1950 if (!resolved.empty())
1951 File = FileMgr.getFile(resolved);
1952 }
1953
1954 return File;
1955}
1956
1957/// \brief If we are loading a relocatable PCH file, and the filename is
1958/// not an absolute path, add the system root to the beginning of the file
1959/// name.
1960void ASTReader::MaybeAddSystemRootToFilename(ModuleFile &M,
1961 std::string &Filename) {
1962 // If this is not a relocatable PCH file, there's nothing to do.
1963 if (!M.RelocatablePCH)
1964 return;
1965
1966 if (Filename.empty() || llvm::sys::path::is_absolute(Filename))
1967 return;
1968
1969 if (isysroot.empty()) {
1970 // If no system root was given, default to '/'
1971 Filename.insert(Filename.begin(), '/');
1972 return;
1973 }
1974
1975 unsigned Length = isysroot.size();
1976 if (isysroot[Length - 1] != '/')
1977 Filename.insert(Filename.begin(), '/');
1978
1979 Filename.insert(Filename.begin(), isysroot.begin(), isysroot.end());
1980}
1981
1982ASTReader::ASTReadResult
1983ASTReader::ReadControlBlock(ModuleFile &F,
Dmitri Gribenkof8579502013-01-12 19:30:44 +00001984 SmallVectorImpl<ImportedModule> &Loaded,
Guy Benyei11169dd2012-12-18 14:30:41 +00001985 unsigned ClientLoadCapabilities) {
Chris Lattner7fb3bef2013-01-20 00:56:42 +00001986 BitstreamCursor &Stream = F.Stream;
Guy Benyei11169dd2012-12-18 14:30:41 +00001987
1988 if (Stream.EnterSubBlock(CONTROL_BLOCK_ID)) {
1989 Error("malformed block record in AST file");
1990 return Failure;
1991 }
1992
1993 // Read all of the records and blocks in the control block.
1994 RecordData Record;
Chris Lattnere7b154b2013-01-19 21:39:22 +00001995 while (1) {
1996 llvm::BitstreamEntry Entry = Stream.advance();
1997
1998 switch (Entry.Kind) {
1999 case llvm::BitstreamEntry::Error:
2000 Error("malformed block record in AST file");
2001 return Failure;
Dmitri Gribenkof430da42014-02-12 10:33:14 +00002002 case llvm::BitstreamEntry::EndBlock: {
2003 // Validate input files.
2004 const HeaderSearchOptions &HSOpts =
2005 PP.getHeaderSearchInfo().getHeaderSearchOpts();
2006 if (!DisableValidation &&
2007 (!HSOpts.ModulesValidateOncePerBuildSession ||
2008 F.InputFilesValidationTimestamp <= HSOpts.BuildSessionTimestamp)) {
Guy Benyei11169dd2012-12-18 14:30:41 +00002009 bool Complain = (ClientLoadCapabilities & ARR_OutOfDate) == 0;
Ben Langmuir3d4417c2014-02-07 17:31:11 +00002010 // All user input files reside at the index range [0, Record[1]), and
2011 // system input files reside at [Record[1], Record[0]).
Argyrios Kyrtzidis7d238572013-03-06 18:12:50 +00002012 // Record is the one from INPUT_FILE_OFFSETS.
Dmitri Gribenkof430da42014-02-12 10:33:14 +00002013 //
2014 // If we are reading a module, we will create a verification timestamp,
2015 // so we verify all input files. Otherwise, verify only user input
2016 // files.
Ben Langmuir3d4417c2014-02-07 17:31:11 +00002017 unsigned NumInputs = Record[0];
2018 unsigned NumUserInputs = Record[1];
Dmitri Gribenkof430da42014-02-12 10:33:14 +00002019 unsigned N = ValidateSystemInputs ||
2020 (HSOpts.ModulesValidateOncePerBuildSession &&
2021 F.Kind == MK_Module)
2022 ? NumInputs
2023 : NumUserInputs;
Ben Langmuir3d4417c2014-02-07 17:31:11 +00002024 for (unsigned I = 0; I < N; ++I) {
Argyrios Kyrtzidis61c3d872013-03-01 03:26:04 +00002025 InputFile IF = getInputFile(F, I+1, Complain);
2026 if (!IF.getFile() || IF.isOutOfDate())
Guy Benyei11169dd2012-12-18 14:30:41 +00002027 return OutOfDate;
Argyrios Kyrtzidis61c3d872013-03-01 03:26:04 +00002028 }
Guy Benyei11169dd2012-12-18 14:30:41 +00002029 }
Guy Benyei11169dd2012-12-18 14:30:41 +00002030 return Success;
Dmitri Gribenkof430da42014-02-12 10:33:14 +00002031 }
2032
Chris Lattnere7b154b2013-01-19 21:39:22 +00002033 case llvm::BitstreamEntry::SubBlock:
2034 switch (Entry.ID) {
Guy Benyei11169dd2012-12-18 14:30:41 +00002035 case INPUT_FILES_BLOCK_ID:
2036 F.InputFilesCursor = Stream;
2037 if (Stream.SkipBlock() || // Skip with the main cursor
2038 // Read the abbreviations
2039 ReadBlockAbbrevs(F.InputFilesCursor, INPUT_FILES_BLOCK_ID)) {
2040 Error("malformed block record in AST file");
2041 return Failure;
2042 }
2043 continue;
Chris Lattnere7b154b2013-01-19 21:39:22 +00002044
Guy Benyei11169dd2012-12-18 14:30:41 +00002045 default:
Chris Lattnere7b154b2013-01-19 21:39:22 +00002046 if (Stream.SkipBlock()) {
2047 Error("malformed block record in AST file");
2048 return Failure;
2049 }
2050 continue;
Guy Benyei11169dd2012-12-18 14:30:41 +00002051 }
Chris Lattnere7b154b2013-01-19 21:39:22 +00002052
2053 case llvm::BitstreamEntry::Record:
2054 // The interesting case.
2055 break;
Guy Benyei11169dd2012-12-18 14:30:41 +00002056 }
2057
2058 // Read and process a record.
2059 Record.clear();
Chris Lattner0e6c9402013-01-20 02:38:54 +00002060 StringRef Blob;
2061 switch ((ControlRecordTypes)Stream.readRecord(Entry.ID, Record, &Blob)) {
Guy Benyei11169dd2012-12-18 14:30:41 +00002062 case METADATA: {
2063 if (Record[0] != VERSION_MAJOR && !DisableValidation) {
2064 if ((ClientLoadCapabilities & ARR_VersionMismatch) == 0)
Dmitri Gribenko2228cd32014-02-11 15:40:09 +00002065 Diag(Record[0] < VERSION_MAJOR? diag::err_pch_version_too_old
2066 : diag::err_pch_version_too_new);
Guy Benyei11169dd2012-12-18 14:30:41 +00002067 return VersionMismatch;
2068 }
2069
2070 bool hasErrors = Record[5];
2071 if (hasErrors && !DisableValidation && !AllowASTWithCompilerErrors) {
2072 Diag(diag::err_pch_with_compiler_errors);
2073 return HadErrors;
2074 }
2075
2076 F.RelocatablePCH = Record[4];
2077
2078 const std::string &CurBranch = getClangFullRepositoryVersion();
Chris Lattner0e6c9402013-01-20 02:38:54 +00002079 StringRef ASTBranch = Blob;
Guy Benyei11169dd2012-12-18 14:30:41 +00002080 if (StringRef(CurBranch) != ASTBranch && !DisableValidation) {
2081 if ((ClientLoadCapabilities & ARR_VersionMismatch) == 0)
Dmitri Gribenko2228cd32014-02-11 15:40:09 +00002082 Diag(diag::err_pch_different_branch) << ASTBranch << CurBranch;
Guy Benyei11169dd2012-12-18 14:30:41 +00002083 return VersionMismatch;
2084 }
2085 break;
2086 }
2087
2088 case IMPORTS: {
2089 // Load each of the imported PCH files.
2090 unsigned Idx = 0, N = Record.size();
2091 while (Idx < N) {
2092 // Read information about the AST file.
2093 ModuleKind ImportedKind = (ModuleKind)Record[Idx++];
2094 // The import location will be the local one for now; we will adjust
2095 // all import locations of module imports after the global source
2096 // location info are setup.
2097 SourceLocation ImportLoc =
2098 SourceLocation::getFromRawEncoding(Record[Idx++]);
Douglas Gregor7029ce12013-03-19 00:28:20 +00002099 off_t StoredSize = (off_t)Record[Idx++];
2100 time_t StoredModTime = (time_t)Record[Idx++];
Guy Benyei11169dd2012-12-18 14:30:41 +00002101 unsigned Length = Record[Idx++];
2102 SmallString<128> ImportedFile(Record.begin() + Idx,
2103 Record.begin() + Idx + Length);
2104 Idx += Length;
2105
2106 // Load the AST file.
2107 switch(ReadASTCore(ImportedFile, ImportedKind, ImportLoc, &F, Loaded,
Douglas Gregor7029ce12013-03-19 00:28:20 +00002108 StoredSize, StoredModTime,
Guy Benyei11169dd2012-12-18 14:30:41 +00002109 ClientLoadCapabilities)) {
2110 case Failure: return Failure;
2111 // If we have to ignore the dependency, we'll have to ignore this too.
Douglas Gregor2f1806e2013-03-19 00:38:50 +00002112 case Missing:
Guy Benyei11169dd2012-12-18 14:30:41 +00002113 case OutOfDate: return OutOfDate;
2114 case VersionMismatch: return VersionMismatch;
2115 case ConfigurationMismatch: return ConfigurationMismatch;
2116 case HadErrors: return HadErrors;
2117 case Success: break;
2118 }
2119 }
2120 break;
2121 }
2122
2123 case LANGUAGE_OPTIONS: {
2124 bool Complain = (ClientLoadCapabilities & ARR_ConfigurationMismatch) == 0;
2125 if (Listener && &F == *ModuleMgr.begin() &&
2126 ParseLanguageOptions(Record, Complain, *Listener) &&
Ben Langmuir2cb4a782014-02-05 22:21:15 +00002127 !DisableValidation && !AllowConfigurationMismatch)
Guy Benyei11169dd2012-12-18 14:30:41 +00002128 return ConfigurationMismatch;
2129 break;
2130 }
2131
2132 case TARGET_OPTIONS: {
2133 bool Complain = (ClientLoadCapabilities & ARR_ConfigurationMismatch)==0;
2134 if (Listener && &F == *ModuleMgr.begin() &&
2135 ParseTargetOptions(Record, Complain, *Listener) &&
Ben Langmuir2cb4a782014-02-05 22:21:15 +00002136 !DisableValidation && !AllowConfigurationMismatch)
Guy Benyei11169dd2012-12-18 14:30:41 +00002137 return ConfigurationMismatch;
2138 break;
2139 }
2140
2141 case DIAGNOSTIC_OPTIONS: {
2142 bool Complain = (ClientLoadCapabilities & ARR_ConfigurationMismatch)==0;
2143 if (Listener && &F == *ModuleMgr.begin() &&
2144 ParseDiagnosticOptions(Record, Complain, *Listener) &&
Ben Langmuir2cb4a782014-02-05 22:21:15 +00002145 !DisableValidation && !AllowConfigurationMismatch)
Guy Benyei11169dd2012-12-18 14:30:41 +00002146 return ConfigurationMismatch;
2147 break;
2148 }
2149
2150 case FILE_SYSTEM_OPTIONS: {
2151 bool Complain = (ClientLoadCapabilities & ARR_ConfigurationMismatch)==0;
2152 if (Listener && &F == *ModuleMgr.begin() &&
2153 ParseFileSystemOptions(Record, Complain, *Listener) &&
Ben Langmuir2cb4a782014-02-05 22:21:15 +00002154 !DisableValidation && !AllowConfigurationMismatch)
Guy Benyei11169dd2012-12-18 14:30:41 +00002155 return ConfigurationMismatch;
2156 break;
2157 }
2158
2159 case HEADER_SEARCH_OPTIONS: {
2160 bool Complain = (ClientLoadCapabilities & ARR_ConfigurationMismatch)==0;
2161 if (Listener && &F == *ModuleMgr.begin() &&
2162 ParseHeaderSearchOptions(Record, Complain, *Listener) &&
Ben Langmuir2cb4a782014-02-05 22:21:15 +00002163 !DisableValidation && !AllowConfigurationMismatch)
Guy Benyei11169dd2012-12-18 14:30:41 +00002164 return ConfigurationMismatch;
2165 break;
2166 }
2167
2168 case PREPROCESSOR_OPTIONS: {
2169 bool Complain = (ClientLoadCapabilities & ARR_ConfigurationMismatch)==0;
2170 if (Listener && &F == *ModuleMgr.begin() &&
2171 ParsePreprocessorOptions(Record, Complain, *Listener,
2172 SuggestedPredefines) &&
Ben Langmuir2cb4a782014-02-05 22:21:15 +00002173 !DisableValidation && !AllowConfigurationMismatch)
Guy Benyei11169dd2012-12-18 14:30:41 +00002174 return ConfigurationMismatch;
2175 break;
2176 }
2177
2178 case ORIGINAL_FILE:
2179 F.OriginalSourceFileID = FileID::get(Record[0]);
Chris Lattner0e6c9402013-01-20 02:38:54 +00002180 F.ActualOriginalSourceFileName = Blob;
Guy Benyei11169dd2012-12-18 14:30:41 +00002181 F.OriginalSourceFileName = F.ActualOriginalSourceFileName;
2182 MaybeAddSystemRootToFilename(F, F.OriginalSourceFileName);
2183 break;
2184
2185 case ORIGINAL_FILE_ID:
2186 F.OriginalSourceFileID = FileID::get(Record[0]);
2187 break;
2188
2189 case ORIGINAL_PCH_DIR:
Chris Lattner0e6c9402013-01-20 02:38:54 +00002190 F.OriginalDir = Blob;
Guy Benyei11169dd2012-12-18 14:30:41 +00002191 break;
2192
2193 case INPUT_FILE_OFFSETS:
Chris Lattner0e6c9402013-01-20 02:38:54 +00002194 F.InputFileOffsets = (const uint32_t *)Blob.data();
Guy Benyei11169dd2012-12-18 14:30:41 +00002195 F.InputFilesLoaded.resize(Record[0]);
2196 break;
2197 }
2198 }
Guy Benyei11169dd2012-12-18 14:30:41 +00002199}
2200
2201bool ASTReader::ReadASTBlock(ModuleFile &F) {
Chris Lattner7fb3bef2013-01-20 00:56:42 +00002202 BitstreamCursor &Stream = F.Stream;
Guy Benyei11169dd2012-12-18 14:30:41 +00002203
2204 if (Stream.EnterSubBlock(AST_BLOCK_ID)) {
2205 Error("malformed block record in AST file");
2206 return true;
2207 }
2208
2209 // Read all of the records and blocks for the AST file.
2210 RecordData Record;
Chris Lattnere7b154b2013-01-19 21:39:22 +00002211 while (1) {
2212 llvm::BitstreamEntry Entry = Stream.advance();
2213
2214 switch (Entry.Kind) {
2215 case llvm::BitstreamEntry::Error:
2216 Error("error at end of module block in AST file");
2217 return true;
2218 case llvm::BitstreamEntry::EndBlock: {
Richard Smithc0fbba72013-04-03 22:49:41 +00002219 // Outside of C++, we do not store a lookup map for the translation unit.
2220 // Instead, mark it as needing a lookup map to be built if this module
2221 // contains any declarations lexically within it (which it always does!).
2222 // This usually has no cost, since we very rarely need the lookup map for
2223 // the translation unit outside C++.
Guy Benyei11169dd2012-12-18 14:30:41 +00002224 DeclContext *DC = Context.getTranslationUnitDecl();
Richard Smithc0fbba72013-04-03 22:49:41 +00002225 if (DC->hasExternalLexicalStorage() &&
2226 !getContext().getLangOpts().CPlusPlus)
Guy Benyei11169dd2012-12-18 14:30:41 +00002227 DC->setMustBuildLookupTable();
Chris Lattnere7b154b2013-01-19 21:39:22 +00002228
Guy Benyei11169dd2012-12-18 14:30:41 +00002229 return false;
2230 }
Chris Lattnere7b154b2013-01-19 21:39:22 +00002231 case llvm::BitstreamEntry::SubBlock:
2232 switch (Entry.ID) {
Guy Benyei11169dd2012-12-18 14:30:41 +00002233 case DECLTYPES_BLOCK_ID:
2234 // We lazily load the decls block, but we want to set up the
2235 // DeclsCursor cursor to point into it. Clone our current bitcode
2236 // cursor to it, enter the block and read the abbrevs in that block.
2237 // With the main cursor, we just skip over it.
2238 F.DeclsCursor = Stream;
2239 if (Stream.SkipBlock() || // Skip with the main cursor.
2240 // Read the abbrevs.
2241 ReadBlockAbbrevs(F.DeclsCursor, DECLTYPES_BLOCK_ID)) {
2242 Error("malformed block record in AST file");
2243 return true;
2244 }
2245 break;
Chris Lattnere7b154b2013-01-19 21:39:22 +00002246
Guy Benyei11169dd2012-12-18 14:30:41 +00002247 case DECL_UPDATES_BLOCK_ID:
2248 if (Stream.SkipBlock()) {
2249 Error("malformed block record in AST file");
2250 return true;
2251 }
2252 break;
Chris Lattnere7b154b2013-01-19 21:39:22 +00002253
Guy Benyei11169dd2012-12-18 14:30:41 +00002254 case PREPROCESSOR_BLOCK_ID:
2255 F.MacroCursor = Stream;
2256 if (!PP.getExternalSource())
2257 PP.setExternalSource(this);
Chris Lattnere7b154b2013-01-19 21:39:22 +00002258
Guy Benyei11169dd2012-12-18 14:30:41 +00002259 if (Stream.SkipBlock() ||
2260 ReadBlockAbbrevs(F.MacroCursor, PREPROCESSOR_BLOCK_ID)) {
2261 Error("malformed block record in AST file");
2262 return true;
2263 }
2264 F.MacroStartOffset = F.MacroCursor.GetCurrentBitNo();
2265 break;
Chris Lattnere7b154b2013-01-19 21:39:22 +00002266
Guy Benyei11169dd2012-12-18 14:30:41 +00002267 case PREPROCESSOR_DETAIL_BLOCK_ID:
2268 F.PreprocessorDetailCursor = Stream;
2269 if (Stream.SkipBlock() ||
Chris Lattnere7b154b2013-01-19 21:39:22 +00002270 ReadBlockAbbrevs(F.PreprocessorDetailCursor,
Guy Benyei11169dd2012-12-18 14:30:41 +00002271 PREPROCESSOR_DETAIL_BLOCK_ID)) {
Chris Lattnere7b154b2013-01-19 21:39:22 +00002272 Error("malformed preprocessor detail record in AST file");
2273 return true;
2274 }
Guy Benyei11169dd2012-12-18 14:30:41 +00002275 F.PreprocessorDetailStartOffset
Chris Lattnere7b154b2013-01-19 21:39:22 +00002276 = F.PreprocessorDetailCursor.GetCurrentBitNo();
2277
Guy Benyei11169dd2012-12-18 14:30:41 +00002278 if (!PP.getPreprocessingRecord())
2279 PP.createPreprocessingRecord();
2280 if (!PP.getPreprocessingRecord()->getExternalSource())
2281 PP.getPreprocessingRecord()->SetExternalSource(*this);
2282 break;
2283
2284 case SOURCE_MANAGER_BLOCK_ID:
2285 if (ReadSourceManagerBlock(F))
2286 return true;
2287 break;
Chris Lattnere7b154b2013-01-19 21:39:22 +00002288
Guy Benyei11169dd2012-12-18 14:30:41 +00002289 case SUBMODULE_BLOCK_ID:
2290 if (ReadSubmoduleBlock(F))
2291 return true;
2292 break;
Chris Lattnere7b154b2013-01-19 21:39:22 +00002293
Guy Benyei11169dd2012-12-18 14:30:41 +00002294 case COMMENTS_BLOCK_ID: {
Chris Lattner7fb3bef2013-01-20 00:56:42 +00002295 BitstreamCursor C = Stream;
Guy Benyei11169dd2012-12-18 14:30:41 +00002296 if (Stream.SkipBlock() ||
2297 ReadBlockAbbrevs(C, COMMENTS_BLOCK_ID)) {
2298 Error("malformed comments block in AST file");
2299 return true;
2300 }
2301 CommentsCursors.push_back(std::make_pair(C, &F));
2302 break;
2303 }
Chris Lattnere7b154b2013-01-19 21:39:22 +00002304
Guy Benyei11169dd2012-12-18 14:30:41 +00002305 default:
Chris Lattnere7b154b2013-01-19 21:39:22 +00002306 if (Stream.SkipBlock()) {
2307 Error("malformed block record in AST file");
2308 return true;
2309 }
2310 break;
Guy Benyei11169dd2012-12-18 14:30:41 +00002311 }
2312 continue;
Chris Lattnere7b154b2013-01-19 21:39:22 +00002313
2314 case llvm::BitstreamEntry::Record:
2315 // The interesting case.
2316 break;
Guy Benyei11169dd2012-12-18 14:30:41 +00002317 }
2318
2319 // Read and process a record.
2320 Record.clear();
Chris Lattner0e6c9402013-01-20 02:38:54 +00002321 StringRef Blob;
2322 switch ((ASTRecordTypes)Stream.readRecord(Entry.ID, Record, &Blob)) {
Guy Benyei11169dd2012-12-18 14:30:41 +00002323 default: // Default behavior: ignore.
2324 break;
2325
2326 case TYPE_OFFSET: {
2327 if (F.LocalNumTypes != 0) {
2328 Error("duplicate TYPE_OFFSET record in AST file");
2329 return true;
2330 }
Chris Lattner0e6c9402013-01-20 02:38:54 +00002331 F.TypeOffsets = (const uint32_t *)Blob.data();
Guy Benyei11169dd2012-12-18 14:30:41 +00002332 F.LocalNumTypes = Record[0];
2333 unsigned LocalBaseTypeIndex = Record[1];
2334 F.BaseTypeIndex = getTotalNumTypes();
2335
2336 if (F.LocalNumTypes > 0) {
2337 // Introduce the global -> local mapping for types within this module.
2338 GlobalTypeMap.insert(std::make_pair(getTotalNumTypes(), &F));
2339
2340 // Introduce the local -> global mapping for types within this module.
2341 F.TypeRemap.insertOrReplace(
2342 std::make_pair(LocalBaseTypeIndex,
2343 F.BaseTypeIndex - LocalBaseTypeIndex));
2344
2345 TypesLoaded.resize(TypesLoaded.size() + F.LocalNumTypes);
2346 }
2347 break;
2348 }
2349
2350 case DECL_OFFSET: {
2351 if (F.LocalNumDecls != 0) {
2352 Error("duplicate DECL_OFFSET record in AST file");
2353 return true;
2354 }
Chris Lattner0e6c9402013-01-20 02:38:54 +00002355 F.DeclOffsets = (const DeclOffset *)Blob.data();
Guy Benyei11169dd2012-12-18 14:30:41 +00002356 F.LocalNumDecls = Record[0];
2357 unsigned LocalBaseDeclID = Record[1];
2358 F.BaseDeclID = getTotalNumDecls();
2359
2360 if (F.LocalNumDecls > 0) {
2361 // Introduce the global -> local mapping for declarations within this
2362 // module.
2363 GlobalDeclMap.insert(
2364 std::make_pair(getTotalNumDecls() + NUM_PREDEF_DECL_IDS, &F));
2365
2366 // Introduce the local -> global mapping for declarations within this
2367 // module.
2368 F.DeclRemap.insertOrReplace(
2369 std::make_pair(LocalBaseDeclID, F.BaseDeclID - LocalBaseDeclID));
2370
2371 // Introduce the global -> local mapping for declarations within this
2372 // module.
2373 F.GlobalToLocalDeclIDs[&F] = LocalBaseDeclID;
2374
2375 DeclsLoaded.resize(DeclsLoaded.size() + F.LocalNumDecls);
2376 }
2377 break;
2378 }
2379
2380 case TU_UPDATE_LEXICAL: {
2381 DeclContext *TU = Context.getTranslationUnitDecl();
2382 DeclContextInfo &Info = F.DeclContextInfos[TU];
Chris Lattner0e6c9402013-01-20 02:38:54 +00002383 Info.LexicalDecls = reinterpret_cast<const KindDeclIDPair *>(Blob.data());
Guy Benyei11169dd2012-12-18 14:30:41 +00002384 Info.NumLexicalDecls
Chris Lattner0e6c9402013-01-20 02:38:54 +00002385 = static_cast<unsigned int>(Blob.size() / sizeof(KindDeclIDPair));
Guy Benyei11169dd2012-12-18 14:30:41 +00002386 TU->setHasExternalLexicalStorage(true);
2387 break;
2388 }
2389
2390 case UPDATE_VISIBLE: {
2391 unsigned Idx = 0;
2392 serialization::DeclID ID = ReadDeclID(F, Record, Idx);
2393 ASTDeclContextNameLookupTable *Table =
2394 ASTDeclContextNameLookupTable::Create(
Chris Lattner0e6c9402013-01-20 02:38:54 +00002395 (const unsigned char *)Blob.data() + Record[Idx++],
2396 (const unsigned char *)Blob.data(),
Guy Benyei11169dd2012-12-18 14:30:41 +00002397 ASTDeclContextNameLookupTrait(*this, F));
2398 if (ID == PREDEF_DECL_TRANSLATION_UNIT_ID) { // Is it the TU?
2399 DeclContext *TU = Context.getTranslationUnitDecl();
2400 F.DeclContextInfos[TU].NameLookupTableData = Table;
2401 TU->setHasExternalVisibleStorage(true);
2402 } else
2403 PendingVisibleUpdates[ID].push_back(std::make_pair(Table, &F));
2404 break;
2405 }
2406
2407 case IDENTIFIER_TABLE:
Chris Lattner0e6c9402013-01-20 02:38:54 +00002408 F.IdentifierTableData = Blob.data();
Guy Benyei11169dd2012-12-18 14:30:41 +00002409 if (Record[0]) {
2410 F.IdentifierLookupTable
2411 = ASTIdentifierLookupTable::Create(
2412 (const unsigned char *)F.IdentifierTableData + Record[0],
2413 (const unsigned char *)F.IdentifierTableData,
2414 ASTIdentifierLookupTrait(*this, F));
2415
2416 PP.getIdentifierTable().setExternalIdentifierLookup(this);
2417 }
2418 break;
2419
2420 case IDENTIFIER_OFFSET: {
2421 if (F.LocalNumIdentifiers != 0) {
2422 Error("duplicate IDENTIFIER_OFFSET record in AST file");
2423 return true;
2424 }
Chris Lattner0e6c9402013-01-20 02:38:54 +00002425 F.IdentifierOffsets = (const uint32_t *)Blob.data();
Guy Benyei11169dd2012-12-18 14:30:41 +00002426 F.LocalNumIdentifiers = Record[0];
2427 unsigned LocalBaseIdentifierID = Record[1];
2428 F.BaseIdentifierID = getTotalNumIdentifiers();
2429
2430 if (F.LocalNumIdentifiers > 0) {
2431 // Introduce the global -> local mapping for identifiers within this
2432 // module.
2433 GlobalIdentifierMap.insert(std::make_pair(getTotalNumIdentifiers() + 1,
2434 &F));
2435
2436 // Introduce the local -> global mapping for identifiers within this
2437 // module.
2438 F.IdentifierRemap.insertOrReplace(
2439 std::make_pair(LocalBaseIdentifierID,
2440 F.BaseIdentifierID - LocalBaseIdentifierID));
2441
2442 IdentifiersLoaded.resize(IdentifiersLoaded.size()
2443 + F.LocalNumIdentifiers);
2444 }
2445 break;
2446 }
2447
Ben Langmuir332aafe2014-01-31 01:06:56 +00002448 case EAGERLY_DESERIALIZED_DECLS:
Guy Benyei11169dd2012-12-18 14:30:41 +00002449 for (unsigned I = 0, N = Record.size(); I != N; ++I)
Ben Langmuir332aafe2014-01-31 01:06:56 +00002450 EagerlyDeserializedDecls.push_back(getGlobalDeclID(F, Record[I]));
Guy Benyei11169dd2012-12-18 14:30:41 +00002451 break;
2452
2453 case SPECIAL_TYPES:
Douglas Gregor44180f82013-02-01 23:45:03 +00002454 if (SpecialTypes.empty()) {
2455 for (unsigned I = 0, N = Record.size(); I != N; ++I)
2456 SpecialTypes.push_back(getGlobalTypeID(F, Record[I]));
2457 break;
2458 }
2459
2460 if (SpecialTypes.size() != Record.size()) {
2461 Error("invalid special-types record");
2462 return true;
2463 }
2464
2465 for (unsigned I = 0, N = Record.size(); I != N; ++I) {
2466 serialization::TypeID ID = getGlobalTypeID(F, Record[I]);
2467 if (!SpecialTypes[I])
2468 SpecialTypes[I] = ID;
2469 // FIXME: If ID && SpecialTypes[I] != ID, do we need a separate
2470 // merge step?
2471 }
Guy Benyei11169dd2012-12-18 14:30:41 +00002472 break;
2473
2474 case STATISTICS:
2475 TotalNumStatements += Record[0];
2476 TotalNumMacros += Record[1];
2477 TotalLexicalDeclContexts += Record[2];
2478 TotalVisibleDeclContexts += Record[3];
2479 break;
2480
2481 case UNUSED_FILESCOPED_DECLS:
2482 for (unsigned I = 0, N = Record.size(); I != N; ++I)
2483 UnusedFileScopedDecls.push_back(getGlobalDeclID(F, Record[I]));
2484 break;
2485
2486 case DELEGATING_CTORS:
2487 for (unsigned I = 0, N = Record.size(); I != N; ++I)
2488 DelegatingCtorDecls.push_back(getGlobalDeclID(F, Record[I]));
2489 break;
2490
2491 case WEAK_UNDECLARED_IDENTIFIERS:
2492 if (Record.size() % 4 != 0) {
2493 Error("invalid weak identifiers record");
2494 return true;
2495 }
2496
2497 // FIXME: Ignore weak undeclared identifiers from non-original PCH
2498 // files. This isn't the way to do it :)
2499 WeakUndeclaredIdentifiers.clear();
2500
2501 // Translate the weak, undeclared identifiers into global IDs.
2502 for (unsigned I = 0, N = Record.size(); I < N; /* in loop */) {
2503 WeakUndeclaredIdentifiers.push_back(
2504 getGlobalIdentifierID(F, Record[I++]));
2505 WeakUndeclaredIdentifiers.push_back(
2506 getGlobalIdentifierID(F, Record[I++]));
2507 WeakUndeclaredIdentifiers.push_back(
2508 ReadSourceLocation(F, Record, I).getRawEncoding());
2509 WeakUndeclaredIdentifiers.push_back(Record[I++]);
2510 }
2511 break;
2512
Richard Smith78165b52013-01-10 23:43:47 +00002513 case LOCALLY_SCOPED_EXTERN_C_DECLS:
Guy Benyei11169dd2012-12-18 14:30:41 +00002514 for (unsigned I = 0, N = Record.size(); I != N; ++I)
Richard Smith78165b52013-01-10 23:43:47 +00002515 LocallyScopedExternCDecls.push_back(getGlobalDeclID(F, Record[I]));
Guy Benyei11169dd2012-12-18 14:30:41 +00002516 break;
2517
2518 case SELECTOR_OFFSETS: {
Chris Lattner0e6c9402013-01-20 02:38:54 +00002519 F.SelectorOffsets = (const uint32_t *)Blob.data();
Guy Benyei11169dd2012-12-18 14:30:41 +00002520 F.LocalNumSelectors = Record[0];
2521 unsigned LocalBaseSelectorID = Record[1];
2522 F.BaseSelectorID = getTotalNumSelectors();
2523
2524 if (F.LocalNumSelectors > 0) {
2525 // Introduce the global -> local mapping for selectors within this
2526 // module.
2527 GlobalSelectorMap.insert(std::make_pair(getTotalNumSelectors()+1, &F));
2528
2529 // Introduce the local -> global mapping for selectors within this
2530 // module.
2531 F.SelectorRemap.insertOrReplace(
2532 std::make_pair(LocalBaseSelectorID,
2533 F.BaseSelectorID - LocalBaseSelectorID));
2534
2535 SelectorsLoaded.resize(SelectorsLoaded.size() + F.LocalNumSelectors);
2536 }
2537 break;
2538 }
2539
2540 case METHOD_POOL:
Chris Lattner0e6c9402013-01-20 02:38:54 +00002541 F.SelectorLookupTableData = (const unsigned char *)Blob.data();
Guy Benyei11169dd2012-12-18 14:30:41 +00002542 if (Record[0])
2543 F.SelectorLookupTable
2544 = ASTSelectorLookupTable::Create(
2545 F.SelectorLookupTableData + Record[0],
2546 F.SelectorLookupTableData,
2547 ASTSelectorLookupTrait(*this, F));
2548 TotalNumMethodPoolEntries += Record[1];
2549 break;
2550
2551 case REFERENCED_SELECTOR_POOL:
2552 if (!Record.empty()) {
2553 for (unsigned Idx = 0, N = Record.size() - 1; Idx < N; /* in loop */) {
2554 ReferencedSelectorsData.push_back(getGlobalSelectorID(F,
2555 Record[Idx++]));
2556 ReferencedSelectorsData.push_back(ReadSourceLocation(F, Record, Idx).
2557 getRawEncoding());
2558 }
2559 }
2560 break;
2561
2562 case PP_COUNTER_VALUE:
2563 if (!Record.empty() && Listener)
2564 Listener->ReadCounter(F, Record[0]);
2565 break;
2566
2567 case FILE_SORTED_DECLS:
Chris Lattner0e6c9402013-01-20 02:38:54 +00002568 F.FileSortedDecls = (const DeclID *)Blob.data();
Guy Benyei11169dd2012-12-18 14:30:41 +00002569 F.NumFileSortedDecls = Record[0];
2570 break;
2571
2572 case SOURCE_LOCATION_OFFSETS: {
Chris Lattner0e6c9402013-01-20 02:38:54 +00002573 F.SLocEntryOffsets = (const uint32_t *)Blob.data();
Guy Benyei11169dd2012-12-18 14:30:41 +00002574 F.LocalNumSLocEntries = Record[0];
2575 unsigned SLocSpaceSize = Record[1];
Benjamin Kramer867ea1d2014-03-02 13:01:17 +00002576 std::tie(F.SLocEntryBaseID, F.SLocEntryBaseOffset) =
Guy Benyei11169dd2012-12-18 14:30:41 +00002577 SourceMgr.AllocateLoadedSLocEntries(F.LocalNumSLocEntries,
2578 SLocSpaceSize);
2579 // Make our entry in the range map. BaseID is negative and growing, so
2580 // we invert it. Because we invert it, though, we need the other end of
2581 // the range.
2582 unsigned RangeStart =
2583 unsigned(-F.SLocEntryBaseID) - F.LocalNumSLocEntries + 1;
2584 GlobalSLocEntryMap.insert(std::make_pair(RangeStart, &F));
2585 F.FirstLoc = SourceLocation::getFromRawEncoding(F.SLocEntryBaseOffset);
2586
2587 // SLocEntryBaseOffset is lower than MaxLoadedOffset and decreasing.
2588 assert((F.SLocEntryBaseOffset & (1U << 31U)) == 0);
2589 GlobalSLocOffsetMap.insert(
2590 std::make_pair(SourceManager::MaxLoadedOffset - F.SLocEntryBaseOffset
2591 - SLocSpaceSize,&F));
2592
2593 // Initialize the remapping table.
2594 // Invalid stays invalid.
2595 F.SLocRemap.insert(std::make_pair(0U, 0));
2596 // This module. Base was 2 when being compiled.
2597 F.SLocRemap.insert(std::make_pair(2U,
2598 static_cast<int>(F.SLocEntryBaseOffset - 2)));
2599
2600 TotalNumSLocEntries += F.LocalNumSLocEntries;
2601 break;
2602 }
2603
2604 case MODULE_OFFSET_MAP: {
2605 // Additional remapping information.
Chris Lattner0e6c9402013-01-20 02:38:54 +00002606 const unsigned char *Data = (const unsigned char*)Blob.data();
2607 const unsigned char *DataEnd = Data + Blob.size();
Guy Benyei11169dd2012-12-18 14:30:41 +00002608
2609 // Continuous range maps we may be updating in our module.
2610 ContinuousRangeMap<uint32_t, int, 2>::Builder SLocRemap(F.SLocRemap);
2611 ContinuousRangeMap<uint32_t, int, 2>::Builder
2612 IdentifierRemap(F.IdentifierRemap);
2613 ContinuousRangeMap<uint32_t, int, 2>::Builder
2614 MacroRemap(F.MacroRemap);
2615 ContinuousRangeMap<uint32_t, int, 2>::Builder
2616 PreprocessedEntityRemap(F.PreprocessedEntityRemap);
2617 ContinuousRangeMap<uint32_t, int, 2>::Builder
2618 SubmoduleRemap(F.SubmoduleRemap);
2619 ContinuousRangeMap<uint32_t, int, 2>::Builder
2620 SelectorRemap(F.SelectorRemap);
2621 ContinuousRangeMap<uint32_t, int, 2>::Builder DeclRemap(F.DeclRemap);
2622 ContinuousRangeMap<uint32_t, int, 2>::Builder TypeRemap(F.TypeRemap);
2623
2624 while(Data < DataEnd) {
2625 uint16_t Len = io::ReadUnalignedLE16(Data);
2626 StringRef Name = StringRef((const char*)Data, Len);
2627 Data += Len;
2628 ModuleFile *OM = ModuleMgr.lookup(Name);
2629 if (!OM) {
2630 Error("SourceLocation remap refers to unknown module");
2631 return true;
2632 }
2633
2634 uint32_t SLocOffset = io::ReadUnalignedLE32(Data);
2635 uint32_t IdentifierIDOffset = io::ReadUnalignedLE32(Data);
2636 uint32_t MacroIDOffset = io::ReadUnalignedLE32(Data);
2637 uint32_t PreprocessedEntityIDOffset = io::ReadUnalignedLE32(Data);
2638 uint32_t SubmoduleIDOffset = io::ReadUnalignedLE32(Data);
2639 uint32_t SelectorIDOffset = io::ReadUnalignedLE32(Data);
2640 uint32_t DeclIDOffset = io::ReadUnalignedLE32(Data);
2641 uint32_t TypeIndexOffset = io::ReadUnalignedLE32(Data);
2642
2643 // Source location offset is mapped to OM->SLocEntryBaseOffset.
2644 SLocRemap.insert(std::make_pair(SLocOffset,
2645 static_cast<int>(OM->SLocEntryBaseOffset - SLocOffset)));
2646 IdentifierRemap.insert(
2647 std::make_pair(IdentifierIDOffset,
2648 OM->BaseIdentifierID - IdentifierIDOffset));
2649 MacroRemap.insert(std::make_pair(MacroIDOffset,
2650 OM->BaseMacroID - MacroIDOffset));
2651 PreprocessedEntityRemap.insert(
2652 std::make_pair(PreprocessedEntityIDOffset,
2653 OM->BasePreprocessedEntityID - PreprocessedEntityIDOffset));
2654 SubmoduleRemap.insert(std::make_pair(SubmoduleIDOffset,
2655 OM->BaseSubmoduleID - SubmoduleIDOffset));
2656 SelectorRemap.insert(std::make_pair(SelectorIDOffset,
2657 OM->BaseSelectorID - SelectorIDOffset));
2658 DeclRemap.insert(std::make_pair(DeclIDOffset,
2659 OM->BaseDeclID - DeclIDOffset));
2660
2661 TypeRemap.insert(std::make_pair(TypeIndexOffset,
2662 OM->BaseTypeIndex - TypeIndexOffset));
2663
2664 // Global -> local mappings.
2665 F.GlobalToLocalDeclIDs[OM] = DeclIDOffset;
2666 }
2667 break;
2668 }
2669
2670 case SOURCE_MANAGER_LINE_TABLE:
2671 if (ParseLineTable(F, Record))
2672 return true;
2673 break;
2674
2675 case SOURCE_LOCATION_PRELOADS: {
2676 // Need to transform from the local view (1-based IDs) to the global view,
2677 // which is based off F.SLocEntryBaseID.
2678 if (!F.PreloadSLocEntries.empty()) {
2679 Error("Multiple SOURCE_LOCATION_PRELOADS records in AST file");
2680 return true;
2681 }
2682
2683 F.PreloadSLocEntries.swap(Record);
2684 break;
2685 }
2686
2687 case EXT_VECTOR_DECLS:
2688 for (unsigned I = 0, N = Record.size(); I != N; ++I)
2689 ExtVectorDecls.push_back(getGlobalDeclID(F, Record[I]));
2690 break;
2691
2692 case VTABLE_USES:
2693 if (Record.size() % 3 != 0) {
2694 Error("Invalid VTABLE_USES record");
2695 return true;
2696 }
2697
2698 // Later tables overwrite earlier ones.
2699 // FIXME: Modules will have some trouble with this. This is clearly not
2700 // the right way to do this.
2701 VTableUses.clear();
2702
2703 for (unsigned Idx = 0, N = Record.size(); Idx != N; /* In loop */) {
2704 VTableUses.push_back(getGlobalDeclID(F, Record[Idx++]));
2705 VTableUses.push_back(
2706 ReadSourceLocation(F, Record, Idx).getRawEncoding());
2707 VTableUses.push_back(Record[Idx++]);
2708 }
2709 break;
2710
2711 case DYNAMIC_CLASSES:
2712 for (unsigned I = 0, N = Record.size(); I != N; ++I)
2713 DynamicClasses.push_back(getGlobalDeclID(F, Record[I]));
2714 break;
2715
2716 case PENDING_IMPLICIT_INSTANTIATIONS:
2717 if (PendingInstantiations.size() % 2 != 0) {
2718 Error("Invalid existing PendingInstantiations");
2719 return true;
2720 }
2721
2722 if (Record.size() % 2 != 0) {
2723 Error("Invalid PENDING_IMPLICIT_INSTANTIATIONS block");
2724 return true;
2725 }
2726
2727 for (unsigned I = 0, N = Record.size(); I != N; /* in loop */) {
2728 PendingInstantiations.push_back(getGlobalDeclID(F, Record[I++]));
2729 PendingInstantiations.push_back(
2730 ReadSourceLocation(F, Record, I).getRawEncoding());
2731 }
2732 break;
2733
2734 case SEMA_DECL_REFS:
Richard Smith3d8e97e2013-10-18 06:54:39 +00002735 if (Record.size() != 2) {
2736 Error("Invalid SEMA_DECL_REFS block");
2737 return true;
2738 }
Guy Benyei11169dd2012-12-18 14:30:41 +00002739 for (unsigned I = 0, N = Record.size(); I != N; ++I)
2740 SemaDeclRefs.push_back(getGlobalDeclID(F, Record[I]));
2741 break;
2742
2743 case PPD_ENTITIES_OFFSETS: {
Chris Lattner0e6c9402013-01-20 02:38:54 +00002744 F.PreprocessedEntityOffsets = (const PPEntityOffset *)Blob.data();
2745 assert(Blob.size() % sizeof(PPEntityOffset) == 0);
2746 F.NumPreprocessedEntities = Blob.size() / sizeof(PPEntityOffset);
Guy Benyei11169dd2012-12-18 14:30:41 +00002747
2748 unsigned LocalBasePreprocessedEntityID = Record[0];
2749
2750 unsigned StartingID;
2751 if (!PP.getPreprocessingRecord())
2752 PP.createPreprocessingRecord();
2753 if (!PP.getPreprocessingRecord()->getExternalSource())
2754 PP.getPreprocessingRecord()->SetExternalSource(*this);
2755 StartingID
2756 = PP.getPreprocessingRecord()
2757 ->allocateLoadedEntities(F.NumPreprocessedEntities);
2758 F.BasePreprocessedEntityID = StartingID;
2759
2760 if (F.NumPreprocessedEntities > 0) {
2761 // Introduce the global -> local mapping for preprocessed entities in
2762 // this module.
2763 GlobalPreprocessedEntityMap.insert(std::make_pair(StartingID, &F));
2764
2765 // Introduce the local -> global mapping for preprocessed entities in
2766 // this module.
2767 F.PreprocessedEntityRemap.insertOrReplace(
2768 std::make_pair(LocalBasePreprocessedEntityID,
2769 F.BasePreprocessedEntityID - LocalBasePreprocessedEntityID));
2770 }
2771
2772 break;
2773 }
2774
2775 case DECL_UPDATE_OFFSETS: {
2776 if (Record.size() % 2 != 0) {
2777 Error("invalid DECL_UPDATE_OFFSETS block in AST file");
2778 return true;
2779 }
2780 for (unsigned I = 0, N = Record.size(); I != N; I += 2)
2781 DeclUpdateOffsets[getGlobalDeclID(F, Record[I])]
2782 .push_back(std::make_pair(&F, Record[I+1]));
2783 break;
2784 }
2785
2786 case DECL_REPLACEMENTS: {
2787 if (Record.size() % 3 != 0) {
2788 Error("invalid DECL_REPLACEMENTS block in AST file");
2789 return true;
2790 }
2791 for (unsigned I = 0, N = Record.size(); I != N; I += 3)
2792 ReplacedDecls[getGlobalDeclID(F, Record[I])]
2793 = ReplacedDeclInfo(&F, Record[I+1], Record[I+2]);
2794 break;
2795 }
2796
2797 case OBJC_CATEGORIES_MAP: {
2798 if (F.LocalNumObjCCategoriesInMap != 0) {
2799 Error("duplicate OBJC_CATEGORIES_MAP record in AST file");
2800 return true;
2801 }
2802
2803 F.LocalNumObjCCategoriesInMap = Record[0];
Chris Lattner0e6c9402013-01-20 02:38:54 +00002804 F.ObjCCategoriesMap = (const ObjCCategoriesInfo *)Blob.data();
Guy Benyei11169dd2012-12-18 14:30:41 +00002805 break;
2806 }
2807
2808 case OBJC_CATEGORIES:
2809 F.ObjCCategories.swap(Record);
2810 break;
2811
2812 case CXX_BASE_SPECIFIER_OFFSETS: {
2813 if (F.LocalNumCXXBaseSpecifiers != 0) {
2814 Error("duplicate CXX_BASE_SPECIFIER_OFFSETS record in AST file");
2815 return true;
2816 }
2817
2818 F.LocalNumCXXBaseSpecifiers = Record[0];
Chris Lattner0e6c9402013-01-20 02:38:54 +00002819 F.CXXBaseSpecifiersOffsets = (const uint32_t *)Blob.data();
Guy Benyei11169dd2012-12-18 14:30:41 +00002820 NumCXXBaseSpecifiersLoaded += F.LocalNumCXXBaseSpecifiers;
2821 break;
2822 }
2823
2824 case DIAG_PRAGMA_MAPPINGS:
2825 if (F.PragmaDiagMappings.empty())
2826 F.PragmaDiagMappings.swap(Record);
2827 else
2828 F.PragmaDiagMappings.insert(F.PragmaDiagMappings.end(),
2829 Record.begin(), Record.end());
2830 break;
2831
2832 case CUDA_SPECIAL_DECL_REFS:
2833 // Later tables overwrite earlier ones.
2834 // FIXME: Modules will have trouble with this.
2835 CUDASpecialDeclRefs.clear();
2836 for (unsigned I = 0, N = Record.size(); I != N; ++I)
2837 CUDASpecialDeclRefs.push_back(getGlobalDeclID(F, Record[I]));
2838 break;
2839
2840 case HEADER_SEARCH_TABLE: {
Chris Lattner0e6c9402013-01-20 02:38:54 +00002841 F.HeaderFileInfoTableData = Blob.data();
Guy Benyei11169dd2012-12-18 14:30:41 +00002842 F.LocalNumHeaderFileInfos = Record[1];
Guy Benyei11169dd2012-12-18 14:30:41 +00002843 if (Record[0]) {
2844 F.HeaderFileInfoTable
2845 = HeaderFileInfoLookupTable::Create(
2846 (const unsigned char *)F.HeaderFileInfoTableData + Record[0],
2847 (const unsigned char *)F.HeaderFileInfoTableData,
2848 HeaderFileInfoTrait(*this, F,
2849 &PP.getHeaderSearchInfo(),
Chris Lattner0e6c9402013-01-20 02:38:54 +00002850 Blob.data() + Record[2]));
Guy Benyei11169dd2012-12-18 14:30:41 +00002851
2852 PP.getHeaderSearchInfo().SetExternalSource(this);
2853 if (!PP.getHeaderSearchInfo().getExternalLookup())
2854 PP.getHeaderSearchInfo().SetExternalLookup(this);
2855 }
2856 break;
2857 }
2858
2859 case FP_PRAGMA_OPTIONS:
2860 // Later tables overwrite earlier ones.
2861 FPPragmaOptions.swap(Record);
2862 break;
2863
2864 case OPENCL_EXTENSIONS:
2865 // Later tables overwrite earlier ones.
2866 OpenCLExtensions.swap(Record);
2867 break;
2868
2869 case TENTATIVE_DEFINITIONS:
2870 for (unsigned I = 0, N = Record.size(); I != N; ++I)
2871 TentativeDefinitions.push_back(getGlobalDeclID(F, Record[I]));
2872 break;
2873
2874 case KNOWN_NAMESPACES:
2875 for (unsigned I = 0, N = Record.size(); I != N; ++I)
2876 KnownNamespaces.push_back(getGlobalDeclID(F, Record[I]));
2877 break;
Nick Lewycky8334af82013-01-26 00:35:08 +00002878
Nick Lewycky9c7eb1d2013-02-01 08:13:20 +00002879 case UNDEFINED_BUT_USED:
2880 if (UndefinedButUsed.size() % 2 != 0) {
2881 Error("Invalid existing UndefinedButUsed");
Nick Lewycky8334af82013-01-26 00:35:08 +00002882 return true;
2883 }
2884
2885 if (Record.size() % 2 != 0) {
Nick Lewycky9c7eb1d2013-02-01 08:13:20 +00002886 Error("invalid undefined-but-used record");
Nick Lewycky8334af82013-01-26 00:35:08 +00002887 return true;
2888 }
2889 for (unsigned I = 0, N = Record.size(); I != N; /* in loop */) {
Nick Lewycky9c7eb1d2013-02-01 08:13:20 +00002890 UndefinedButUsed.push_back(getGlobalDeclID(F, Record[I++]));
2891 UndefinedButUsed.push_back(
Nick Lewycky8334af82013-01-26 00:35:08 +00002892 ReadSourceLocation(F, Record, I).getRawEncoding());
2893 }
2894 break;
2895
Guy Benyei11169dd2012-12-18 14:30:41 +00002896 case IMPORTED_MODULES: {
2897 if (F.Kind != MK_Module) {
2898 // If we aren't loading a module (which has its own exports), make
2899 // all of the imported modules visible.
2900 // FIXME: Deal with macros-only imports.
2901 for (unsigned I = 0, N = Record.size(); I != N; ++I) {
2902 if (unsigned GlobalID = getGlobalSubmoduleID(F, Record[I]))
2903 ImportedModules.push_back(GlobalID);
2904 }
2905 }
2906 break;
2907 }
2908
2909 case LOCAL_REDECLARATIONS: {
2910 F.RedeclarationChains.swap(Record);
2911 break;
2912 }
2913
2914 case LOCAL_REDECLARATIONS_MAP: {
2915 if (F.LocalNumRedeclarationsInMap != 0) {
2916 Error("duplicate LOCAL_REDECLARATIONS_MAP record in AST file");
2917 return true;
2918 }
2919
2920 F.LocalNumRedeclarationsInMap = Record[0];
Chris Lattner0e6c9402013-01-20 02:38:54 +00002921 F.RedeclarationsMap = (const LocalRedeclarationsInfo *)Blob.data();
Guy Benyei11169dd2012-12-18 14:30:41 +00002922 break;
2923 }
2924
2925 case MERGED_DECLARATIONS: {
2926 for (unsigned Idx = 0; Idx < Record.size(); /* increment in loop */) {
2927 GlobalDeclID CanonID = getGlobalDeclID(F, Record[Idx++]);
2928 SmallVectorImpl<GlobalDeclID> &Decls = StoredMergedDecls[CanonID];
2929 for (unsigned N = Record[Idx++]; N > 0; --N)
2930 Decls.push_back(getGlobalDeclID(F, Record[Idx++]));
2931 }
2932 break;
2933 }
2934
2935 case MACRO_OFFSET: {
2936 if (F.LocalNumMacros != 0) {
2937 Error("duplicate MACRO_OFFSET record in AST file");
2938 return true;
2939 }
Chris Lattner0e6c9402013-01-20 02:38:54 +00002940 F.MacroOffsets = (const uint32_t *)Blob.data();
Guy Benyei11169dd2012-12-18 14:30:41 +00002941 F.LocalNumMacros = Record[0];
2942 unsigned LocalBaseMacroID = Record[1];
2943 F.BaseMacroID = getTotalNumMacros();
2944
2945 if (F.LocalNumMacros > 0) {
2946 // Introduce the global -> local mapping for macros within this module.
2947 GlobalMacroMap.insert(std::make_pair(getTotalNumMacros() + 1, &F));
2948
2949 // Introduce the local -> global mapping for macros within this module.
2950 F.MacroRemap.insertOrReplace(
2951 std::make_pair(LocalBaseMacroID,
2952 F.BaseMacroID - LocalBaseMacroID));
2953
2954 MacrosLoaded.resize(MacrosLoaded.size() + F.LocalNumMacros);
2955 }
2956 break;
2957 }
2958
Argyrios Kyrtzidiseb663da2013-03-22 21:12:57 +00002959 case MACRO_TABLE: {
2960 // FIXME: Not used yet.
Guy Benyei11169dd2012-12-18 14:30:41 +00002961 break;
2962 }
Richard Smithe40f2ba2013-08-07 21:41:30 +00002963
2964 case LATE_PARSED_TEMPLATE: {
2965 LateParsedTemplates.append(Record.begin(), Record.end());
2966 break;
2967 }
Guy Benyei11169dd2012-12-18 14:30:41 +00002968 }
2969 }
Guy Benyei11169dd2012-12-18 14:30:41 +00002970}
2971
Douglas Gregorc1489562013-02-12 23:36:21 +00002972/// \brief Move the given method to the back of the global list of methods.
2973static void moveMethodToBackOfGlobalList(Sema &S, ObjCMethodDecl *Method) {
2974 // Find the entry for this selector in the method pool.
2975 Sema::GlobalMethodPool::iterator Known
2976 = S.MethodPool.find(Method->getSelector());
2977 if (Known == S.MethodPool.end())
2978 return;
2979
2980 // Retrieve the appropriate method list.
2981 ObjCMethodList &Start = Method->isInstanceMethod()? Known->second.first
2982 : Known->second.second;
2983 bool Found = false;
Argyrios Kyrtzidisd3da6e02013-04-17 00:08:58 +00002984 for (ObjCMethodList *List = &Start; List; List = List->getNext()) {
Douglas Gregorc1489562013-02-12 23:36:21 +00002985 if (!Found) {
2986 if (List->Method == Method) {
2987 Found = true;
2988 } else {
2989 // Keep searching.
2990 continue;
2991 }
2992 }
2993
Argyrios Kyrtzidisd3da6e02013-04-17 00:08:58 +00002994 if (List->getNext())
2995 List->Method = List->getNext()->Method;
Douglas Gregorc1489562013-02-12 23:36:21 +00002996 else
2997 List->Method = Method;
2998 }
2999}
3000
Argyrios Kyrtzidis3a9c42c2013-03-27 01:25:34 +00003001void ASTReader::makeNamesVisible(const HiddenNames &Names, Module *Owner) {
Richard Smith49f906a2014-03-01 00:08:04 +00003002 for (unsigned I = 0, N = Names.HiddenDecls.size(); I != N; ++I) {
3003 Decl *D = Names.HiddenDecls[I];
3004 bool wasHidden = D->Hidden;
3005 D->Hidden = false;
Guy Benyei11169dd2012-12-18 14:30:41 +00003006
Richard Smith49f906a2014-03-01 00:08:04 +00003007 if (wasHidden && SemaObj) {
3008 if (ObjCMethodDecl *Method = dyn_cast<ObjCMethodDecl>(D)) {
3009 moveMethodToBackOfGlobalList(*SemaObj, Method);
Douglas Gregorc1489562013-02-12 23:36:21 +00003010 }
Guy Benyei11169dd2012-12-18 14:30:41 +00003011 }
3012 }
Richard Smith49f906a2014-03-01 00:08:04 +00003013
3014 for (HiddenMacrosMap::const_iterator I = Names.HiddenMacros.begin(),
3015 E = Names.HiddenMacros.end();
3016 I != E; ++I)
3017 installImportedMacro(I->first, I->second, Owner);
Guy Benyei11169dd2012-12-18 14:30:41 +00003018}
3019
Richard Smith49f906a2014-03-01 00:08:04 +00003020void ASTReader::makeModuleVisible(Module *Mod,
Argyrios Kyrtzidis125df052013-02-01 16:36:12 +00003021 Module::NameVisibilityKind NameVisibility,
Douglas Gregorfb912652013-03-20 21:10:35 +00003022 SourceLocation ImportLoc,
3023 bool Complain) {
Guy Benyei11169dd2012-12-18 14:30:41 +00003024 llvm::SmallPtrSet<Module *, 4> Visited;
Dmitri Gribenkof8579502013-01-12 19:30:44 +00003025 SmallVector<Module *, 4> Stack;
Robert Wilhelm25284cc2013-08-23 16:11:15 +00003026 Stack.push_back(Mod);
Guy Benyei11169dd2012-12-18 14:30:41 +00003027 while (!Stack.empty()) {
Robert Wilhelm25284cc2013-08-23 16:11:15 +00003028 Mod = Stack.pop_back_val();
Guy Benyei11169dd2012-12-18 14:30:41 +00003029
3030 if (NameVisibility <= Mod->NameVisibility) {
Robert Wilhelm25284cc2013-08-23 16:11:15 +00003031 // This module already has this level of visibility (or greater), so
Guy Benyei11169dd2012-12-18 14:30:41 +00003032 // there is nothing more to do.
3033 continue;
3034 }
Richard Smith49f906a2014-03-01 00:08:04 +00003035
Guy Benyei11169dd2012-12-18 14:30:41 +00003036 if (!Mod->isAvailable()) {
3037 // Modules that aren't available cannot be made visible.
3038 continue;
3039 }
3040
3041 // Update the module's name visibility.
Richard Smith49f906a2014-03-01 00:08:04 +00003042 if (NameVisibility >= Module::MacrosVisible &&
3043 Mod->NameVisibility < Module::MacrosVisible)
3044 Mod->MacroVisibilityLoc = ImportLoc;
Guy Benyei11169dd2012-12-18 14:30:41 +00003045 Mod->NameVisibility = NameVisibility;
Richard Smith49f906a2014-03-01 00:08:04 +00003046
Guy Benyei11169dd2012-12-18 14:30:41 +00003047 // If we've already deserialized any names from this module,
3048 // mark them as visible.
3049 HiddenNamesMapType::iterator Hidden = HiddenNamesMap.find(Mod);
3050 if (Hidden != HiddenNamesMap.end()) {
Argyrios Kyrtzidis3a9c42c2013-03-27 01:25:34 +00003051 makeNamesVisible(Hidden->second, Hidden->first);
Guy Benyei11169dd2012-12-18 14:30:41 +00003052 HiddenNamesMap.erase(Hidden);
3053 }
Dmitri Gribenkoe9bcf5b2013-11-04 21:51:33 +00003054
Guy Benyei11169dd2012-12-18 14:30:41 +00003055 // Push any exported modules onto the stack to be marked as visible.
Argyrios Kyrtzidis8739f7b2013-02-19 19:34:40 +00003056 SmallVector<Module *, 16> Exports;
3057 Mod->getExportedModules(Exports);
3058 for (SmallVectorImpl<Module *>::iterator
3059 I = Exports.begin(), E = Exports.end(); I != E; ++I) {
3060 Module *Exported = *I;
3061 if (Visited.insert(Exported))
3062 Stack.push_back(Exported);
Guy Benyei11169dd2012-12-18 14:30:41 +00003063 }
Douglas Gregorfb912652013-03-20 21:10:35 +00003064
3065 // Detect any conflicts.
3066 if (Complain) {
3067 assert(ImportLoc.isValid() && "Missing import location");
3068 for (unsigned I = 0, N = Mod->Conflicts.size(); I != N; ++I) {
3069 if (Mod->Conflicts[I].Other->NameVisibility >= NameVisibility) {
3070 Diag(ImportLoc, diag::warn_module_conflict)
3071 << Mod->getFullModuleName()
3072 << Mod->Conflicts[I].Other->getFullModuleName()
3073 << Mod->Conflicts[I].Message;
3074 // FIXME: Need note where the other module was imported.
3075 }
3076 }
3077 }
Guy Benyei11169dd2012-12-18 14:30:41 +00003078 }
3079}
3080
Douglas Gregore060e572013-01-25 01:03:03 +00003081bool ASTReader::loadGlobalIndex() {
3082 if (GlobalIndex)
3083 return false;
3084
3085 if (TriedLoadingGlobalIndex || !UseGlobalIndex ||
3086 !Context.getLangOpts().Modules)
3087 return true;
3088
3089 // Try to load the global index.
3090 TriedLoadingGlobalIndex = true;
3091 StringRef ModuleCachePath
3092 = getPreprocessor().getHeaderSearchInfo().getModuleCachePath();
3093 std::pair<GlobalModuleIndex *, GlobalModuleIndex::ErrorCode> Result
Douglas Gregor7029ce12013-03-19 00:28:20 +00003094 = GlobalModuleIndex::readIndex(ModuleCachePath);
Douglas Gregore060e572013-01-25 01:03:03 +00003095 if (!Result.first)
3096 return true;
3097
3098 GlobalIndex.reset(Result.first);
Douglas Gregor7211ac12013-01-25 23:32:03 +00003099 ModuleMgr.setGlobalIndex(GlobalIndex.get());
Douglas Gregore060e572013-01-25 01:03:03 +00003100 return false;
3101}
3102
3103bool ASTReader::isGlobalIndexUnavailable() const {
3104 return Context.getLangOpts().Modules && UseGlobalIndex &&
3105 !hasGlobalIndex() && TriedLoadingGlobalIndex;
3106}
3107
Dmitri Gribenkof430da42014-02-12 10:33:14 +00003108static void updateModuleTimestamp(ModuleFile &MF) {
3109 // Overwrite the timestamp file contents so that file's mtime changes.
3110 std::string TimestampFilename = MF.getTimestampFilename();
3111 std::string ErrorInfo;
Rafael Espindola04a13be2014-02-24 15:06:52 +00003112 llvm::raw_fd_ostream OS(TimestampFilename.c_str(), ErrorInfo,
Rafael Espindola4fbd3732014-02-24 18:20:21 +00003113 llvm::sys::fs::F_Text);
Dmitri Gribenkof430da42014-02-12 10:33:14 +00003114 if (!ErrorInfo.empty())
3115 return;
3116 OS << "Timestamp file\n";
3117}
3118
Guy Benyei11169dd2012-12-18 14:30:41 +00003119ASTReader::ASTReadResult ASTReader::ReadAST(const std::string &FileName,
3120 ModuleKind Type,
3121 SourceLocation ImportLoc,
3122 unsigned ClientLoadCapabilities) {
Argyrios Kyrtzidisdc9fdaf2013-05-24 05:44:08 +00003123 llvm::SaveAndRestore<SourceLocation>
3124 SetCurImportLocRAII(CurrentImportLoc, ImportLoc);
3125
Guy Benyei11169dd2012-12-18 14:30:41 +00003126 // Bump the generation number.
3127 unsigned PreviousGeneration = CurrentGeneration++;
3128
3129 unsigned NumModules = ModuleMgr.size();
Dmitri Gribenkof8579502013-01-12 19:30:44 +00003130 SmallVector<ImportedModule, 4> Loaded;
Guy Benyei11169dd2012-12-18 14:30:41 +00003131 switch(ASTReadResult ReadResult = ReadASTCore(FileName, Type, ImportLoc,
3132 /*ImportedBy=*/0, Loaded,
Douglas Gregor7029ce12013-03-19 00:28:20 +00003133 0, 0,
Guy Benyei11169dd2012-12-18 14:30:41 +00003134 ClientLoadCapabilities)) {
3135 case Failure:
Douglas Gregor7029ce12013-03-19 00:28:20 +00003136 case Missing:
Guy Benyei11169dd2012-12-18 14:30:41 +00003137 case OutOfDate:
3138 case VersionMismatch:
3139 case ConfigurationMismatch:
3140 case HadErrors:
Douglas Gregor7029ce12013-03-19 00:28:20 +00003141 ModuleMgr.removeModules(ModuleMgr.begin() + NumModules, ModuleMgr.end(),
3142 Context.getLangOpts().Modules
3143 ? &PP.getHeaderSearchInfo().getModuleMap()
3144 : 0);
Douglas Gregore060e572013-01-25 01:03:03 +00003145
3146 // If we find that any modules are unusable, the global index is going
3147 // to be out-of-date. Just remove it.
3148 GlobalIndex.reset();
Douglas Gregor7211ac12013-01-25 23:32:03 +00003149 ModuleMgr.setGlobalIndex(0);
Guy Benyei11169dd2012-12-18 14:30:41 +00003150 return ReadResult;
3151
3152 case Success:
3153 break;
3154 }
3155
3156 // Here comes stuff that we only do once the entire chain is loaded.
3157
3158 // Load the AST blocks of all of the modules that we loaded.
Dmitri Gribenkof8579502013-01-12 19:30:44 +00003159 for (SmallVectorImpl<ImportedModule>::iterator M = Loaded.begin(),
3160 MEnd = Loaded.end();
Guy Benyei11169dd2012-12-18 14:30:41 +00003161 M != MEnd; ++M) {
3162 ModuleFile &F = *M->Mod;
3163
3164 // Read the AST block.
3165 if (ReadASTBlock(F))
3166 return Failure;
3167
3168 // Once read, set the ModuleFile bit base offset and update the size in
3169 // bits of all files we've seen.
3170 F.GlobalBitOffset = TotalModulesSizeInBits;
3171 TotalModulesSizeInBits += F.SizeInBits;
3172 GlobalBitOffsetsMap.insert(std::make_pair(F.GlobalBitOffset, &F));
3173
3174 // Preload SLocEntries.
3175 for (unsigned I = 0, N = F.PreloadSLocEntries.size(); I != N; ++I) {
3176 int Index = int(F.PreloadSLocEntries[I] - 1) + F.SLocEntryBaseID;
3177 // Load it through the SourceManager and don't call ReadSLocEntry()
3178 // directly because the entry may have already been loaded in which case
3179 // calling ReadSLocEntry() directly would trigger an assertion in
3180 // SourceManager.
3181 SourceMgr.getLoadedSLocEntryByID(Index);
3182 }
3183 }
3184
Douglas Gregor603cd862013-03-22 18:50:14 +00003185 // Setup the import locations and notify the module manager that we've
3186 // committed to these module files.
Dmitri Gribenkof8579502013-01-12 19:30:44 +00003187 for (SmallVectorImpl<ImportedModule>::iterator M = Loaded.begin(),
3188 MEnd = Loaded.end();
Guy Benyei11169dd2012-12-18 14:30:41 +00003189 M != MEnd; ++M) {
3190 ModuleFile &F = *M->Mod;
Douglas Gregor603cd862013-03-22 18:50:14 +00003191
3192 ModuleMgr.moduleFileAccepted(&F);
3193
3194 // Set the import location.
Argyrios Kyrtzidis71c1af82013-02-01 16:36:14 +00003195 F.DirectImportLoc = ImportLoc;
Guy Benyei11169dd2012-12-18 14:30:41 +00003196 if (!M->ImportedBy)
3197 F.ImportLoc = M->ImportLoc;
3198 else
3199 F.ImportLoc = ReadSourceLocation(*M->ImportedBy,
3200 M->ImportLoc.getRawEncoding());
3201 }
3202
3203 // Mark all of the identifiers in the identifier table as being out of date,
3204 // so that various accessors know to check the loaded modules when the
3205 // identifier is used.
3206 for (IdentifierTable::iterator Id = PP.getIdentifierTable().begin(),
3207 IdEnd = PP.getIdentifierTable().end();
3208 Id != IdEnd; ++Id)
3209 Id->second->setOutOfDate(true);
3210
3211 // Resolve any unresolved module exports.
Douglas Gregorfb912652013-03-20 21:10:35 +00003212 for (unsigned I = 0, N = UnresolvedModuleRefs.size(); I != N; ++I) {
3213 UnresolvedModuleRef &Unresolved = UnresolvedModuleRefs[I];
Guy Benyei11169dd2012-12-18 14:30:41 +00003214 SubmoduleID GlobalID = getGlobalSubmoduleID(*Unresolved.File,Unresolved.ID);
3215 Module *ResolvedMod = getSubmodule(GlobalID);
Douglas Gregorfb912652013-03-20 21:10:35 +00003216
3217 switch (Unresolved.Kind) {
3218 case UnresolvedModuleRef::Conflict:
3219 if (ResolvedMod) {
3220 Module::Conflict Conflict;
3221 Conflict.Other = ResolvedMod;
3222 Conflict.Message = Unresolved.String.str();
3223 Unresolved.Mod->Conflicts.push_back(Conflict);
3224 }
3225 continue;
3226
3227 case UnresolvedModuleRef::Import:
Guy Benyei11169dd2012-12-18 14:30:41 +00003228 if (ResolvedMod)
3229 Unresolved.Mod->Imports.push_back(ResolvedMod);
3230 continue;
Guy Benyei11169dd2012-12-18 14:30:41 +00003231
Douglas Gregorfb912652013-03-20 21:10:35 +00003232 case UnresolvedModuleRef::Export:
3233 if (ResolvedMod || Unresolved.IsWildcard)
3234 Unresolved.Mod->Exports.push_back(
3235 Module::ExportDecl(ResolvedMod, Unresolved.IsWildcard));
3236 continue;
3237 }
Guy Benyei11169dd2012-12-18 14:30:41 +00003238 }
Douglas Gregorfb912652013-03-20 21:10:35 +00003239 UnresolvedModuleRefs.clear();
Daniel Jasperba7f2f72013-09-24 09:14:14 +00003240
3241 // FIXME: How do we load the 'use'd modules? They may not be submodules.
3242 // Might be unnecessary as use declarations are only used to build the
3243 // module itself.
Guy Benyei11169dd2012-12-18 14:30:41 +00003244
3245 InitializeContext();
3246
Richard Smith3d8e97e2013-10-18 06:54:39 +00003247 if (SemaObj)
3248 UpdateSema();
3249
Guy Benyei11169dd2012-12-18 14:30:41 +00003250 if (DeserializationListener)
3251 DeserializationListener->ReaderInitialized(this);
3252
3253 ModuleFile &PrimaryModule = ModuleMgr.getPrimaryModule();
3254 if (!PrimaryModule.OriginalSourceFileID.isInvalid()) {
3255 PrimaryModule.OriginalSourceFileID
3256 = FileID::get(PrimaryModule.SLocEntryBaseID
3257 + PrimaryModule.OriginalSourceFileID.getOpaqueValue() - 1);
3258
3259 // If this AST file is a precompiled preamble, then set the
3260 // preamble file ID of the source manager to the file source file
3261 // from which the preamble was built.
3262 if (Type == MK_Preamble) {
3263 SourceMgr.setPreambleFileID(PrimaryModule.OriginalSourceFileID);
3264 } else if (Type == MK_MainFile) {
3265 SourceMgr.setMainFileID(PrimaryModule.OriginalSourceFileID);
3266 }
3267 }
3268
3269 // For any Objective-C class definitions we have already loaded, make sure
3270 // that we load any additional categories.
3271 for (unsigned I = 0, N = ObjCClassesLoaded.size(); I != N; ++I) {
3272 loadObjCCategories(ObjCClassesLoaded[I]->getGlobalID(),
3273 ObjCClassesLoaded[I],
3274 PreviousGeneration);
3275 }
Douglas Gregore060e572013-01-25 01:03:03 +00003276
Dmitri Gribenkof430da42014-02-12 10:33:14 +00003277 if (PP.getHeaderSearchInfo()
3278 .getHeaderSearchOpts()
3279 .ModulesValidateOncePerBuildSession) {
3280 // Now we are certain that the module and all modules it depends on are
3281 // up to date. Create or update timestamp files for modules that are
3282 // located in the module cache (not for PCH files that could be anywhere
3283 // in the filesystem).
3284 for (unsigned I = 0, N = Loaded.size(); I != N; ++I) {
3285 ImportedModule &M = Loaded[I];
3286 if (M.Mod->Kind == MK_Module) {
3287 updateModuleTimestamp(*M.Mod);
3288 }
3289 }
3290 }
3291
Guy Benyei11169dd2012-12-18 14:30:41 +00003292 return Success;
3293}
3294
3295ASTReader::ASTReadResult
3296ASTReader::ReadASTCore(StringRef FileName,
3297 ModuleKind Type,
3298 SourceLocation ImportLoc,
3299 ModuleFile *ImportedBy,
Dmitri Gribenkof8579502013-01-12 19:30:44 +00003300 SmallVectorImpl<ImportedModule> &Loaded,
Douglas Gregor7029ce12013-03-19 00:28:20 +00003301 off_t ExpectedSize, time_t ExpectedModTime,
Guy Benyei11169dd2012-12-18 14:30:41 +00003302 unsigned ClientLoadCapabilities) {
3303 ModuleFile *M;
Guy Benyei11169dd2012-12-18 14:30:41 +00003304 std::string ErrorStr;
Douglas Gregor7029ce12013-03-19 00:28:20 +00003305 ModuleManager::AddModuleResult AddResult
3306 = ModuleMgr.addModule(FileName, Type, ImportLoc, ImportedBy,
3307 CurrentGeneration, ExpectedSize, ExpectedModTime,
3308 M, ErrorStr);
Guy Benyei11169dd2012-12-18 14:30:41 +00003309
Douglas Gregor7029ce12013-03-19 00:28:20 +00003310 switch (AddResult) {
3311 case ModuleManager::AlreadyLoaded:
3312 return Success;
3313
3314 case ModuleManager::NewlyLoaded:
3315 // Load module file below.
3316 break;
3317
3318 case ModuleManager::Missing:
3319 // The module file was missing; if the client handle handle, that, return
3320 // it.
3321 if (ClientLoadCapabilities & ARR_Missing)
3322 return Missing;
3323
3324 // Otherwise, return an error.
3325 {
3326 std::string Msg = "Unable to load module \"" + FileName.str() + "\": "
3327 + ErrorStr;
3328 Error(Msg);
3329 }
3330 return Failure;
3331
3332 case ModuleManager::OutOfDate:
3333 // We couldn't load the module file because it is out-of-date. If the
3334 // client can handle out-of-date, return it.
3335 if (ClientLoadCapabilities & ARR_OutOfDate)
3336 return OutOfDate;
3337
3338 // Otherwise, return an error.
3339 {
3340 std::string Msg = "Unable to load module \"" + FileName.str() + "\": "
3341 + ErrorStr;
3342 Error(Msg);
3343 }
Guy Benyei11169dd2012-12-18 14:30:41 +00003344 return Failure;
3345 }
3346
Douglas Gregor7029ce12013-03-19 00:28:20 +00003347 assert(M && "Missing module file");
Guy Benyei11169dd2012-12-18 14:30:41 +00003348
3349 // FIXME: This seems rather a hack. Should CurrentDir be part of the
3350 // module?
3351 if (FileName != "-") {
3352 CurrentDir = llvm::sys::path::parent_path(FileName);
3353 if (CurrentDir.empty()) CurrentDir = ".";
3354 }
3355
3356 ModuleFile &F = *M;
Chris Lattner7fb3bef2013-01-20 00:56:42 +00003357 BitstreamCursor &Stream = F.Stream;
Guy Benyei11169dd2012-12-18 14:30:41 +00003358 Stream.init(F.StreamFile);
3359 F.SizeInBits = F.Buffer->getBufferSize() * 8;
3360
3361 // Sniff for the signature.
3362 if (Stream.Read(8) != 'C' ||
3363 Stream.Read(8) != 'P' ||
3364 Stream.Read(8) != 'C' ||
3365 Stream.Read(8) != 'H') {
3366 Diag(diag::err_not_a_pch_file) << FileName;
3367 return Failure;
3368 }
3369
3370 // This is used for compatibility with older PCH formats.
3371 bool HaveReadControlBlock = false;
3372
Chris Lattnerefa77172013-01-20 00:00:22 +00003373 while (1) {
3374 llvm::BitstreamEntry Entry = Stream.advance();
3375
3376 switch (Entry.Kind) {
3377 case llvm::BitstreamEntry::Error:
3378 case llvm::BitstreamEntry::EndBlock:
3379 case llvm::BitstreamEntry::Record:
Guy Benyei11169dd2012-12-18 14:30:41 +00003380 Error("invalid record at top-level of AST file");
3381 return Failure;
Chris Lattnerefa77172013-01-20 00:00:22 +00003382
3383 case llvm::BitstreamEntry::SubBlock:
3384 break;
Guy Benyei11169dd2012-12-18 14:30:41 +00003385 }
3386
Guy Benyei11169dd2012-12-18 14:30:41 +00003387 // We only know the control subblock ID.
Chris Lattnerefa77172013-01-20 00:00:22 +00003388 switch (Entry.ID) {
Guy Benyei11169dd2012-12-18 14:30:41 +00003389 case llvm::bitc::BLOCKINFO_BLOCK_ID:
3390 if (Stream.ReadBlockInfoBlock()) {
3391 Error("malformed BlockInfoBlock in AST file");
3392 return Failure;
3393 }
3394 break;
3395 case CONTROL_BLOCK_ID:
3396 HaveReadControlBlock = true;
3397 switch (ReadControlBlock(F, Loaded, ClientLoadCapabilities)) {
3398 case Success:
3399 break;
3400
3401 case Failure: return Failure;
Douglas Gregor7029ce12013-03-19 00:28:20 +00003402 case Missing: return Missing;
Guy Benyei11169dd2012-12-18 14:30:41 +00003403 case OutOfDate: return OutOfDate;
3404 case VersionMismatch: return VersionMismatch;
3405 case ConfigurationMismatch: return ConfigurationMismatch;
3406 case HadErrors: return HadErrors;
3407 }
3408 break;
3409 case AST_BLOCK_ID:
3410 if (!HaveReadControlBlock) {
3411 if ((ClientLoadCapabilities & ARR_VersionMismatch) == 0)
Dmitri Gribenko2228cd32014-02-11 15:40:09 +00003412 Diag(diag::err_pch_version_too_old);
Guy Benyei11169dd2012-12-18 14:30:41 +00003413 return VersionMismatch;
3414 }
3415
3416 // Record that we've loaded this module.
3417 Loaded.push_back(ImportedModule(M, ImportedBy, ImportLoc));
3418 return Success;
3419
3420 default:
3421 if (Stream.SkipBlock()) {
3422 Error("malformed block record in AST file");
3423 return Failure;
3424 }
3425 break;
3426 }
3427 }
3428
3429 return Success;
3430}
3431
3432void ASTReader::InitializeContext() {
3433 // If there's a listener, notify them that we "read" the translation unit.
3434 if (DeserializationListener)
3435 DeserializationListener->DeclRead(PREDEF_DECL_TRANSLATION_UNIT_ID,
3436 Context.getTranslationUnitDecl());
3437
3438 // Make sure we load the declaration update records for the translation unit,
3439 // if there are any.
3440 loadDeclUpdateRecords(PREDEF_DECL_TRANSLATION_UNIT_ID,
3441 Context.getTranslationUnitDecl());
3442
3443 // FIXME: Find a better way to deal with collisions between these
3444 // built-in types. Right now, we just ignore the problem.
3445
3446 // Load the special types.
3447 if (SpecialTypes.size() >= NumSpecialTypeIDs) {
3448 if (unsigned String = SpecialTypes[SPECIAL_TYPE_CF_CONSTANT_STRING]) {
3449 if (!Context.CFConstantStringTypeDecl)
3450 Context.setCFConstantStringType(GetType(String));
3451 }
3452
3453 if (unsigned File = SpecialTypes[SPECIAL_TYPE_FILE]) {
3454 QualType FileType = GetType(File);
3455 if (FileType.isNull()) {
3456 Error("FILE type is NULL");
3457 return;
3458 }
3459
3460 if (!Context.FILEDecl) {
3461 if (const TypedefType *Typedef = FileType->getAs<TypedefType>())
3462 Context.setFILEDecl(Typedef->getDecl());
3463 else {
3464 const TagType *Tag = FileType->getAs<TagType>();
3465 if (!Tag) {
3466 Error("Invalid FILE type in AST file");
3467 return;
3468 }
3469 Context.setFILEDecl(Tag->getDecl());
3470 }
3471 }
3472 }
3473
3474 if (unsigned Jmp_buf = SpecialTypes[SPECIAL_TYPE_JMP_BUF]) {
3475 QualType Jmp_bufType = GetType(Jmp_buf);
3476 if (Jmp_bufType.isNull()) {
3477 Error("jmp_buf type is NULL");
3478 return;
3479 }
3480
3481 if (!Context.jmp_bufDecl) {
3482 if (const TypedefType *Typedef = Jmp_bufType->getAs<TypedefType>())
3483 Context.setjmp_bufDecl(Typedef->getDecl());
3484 else {
3485 const TagType *Tag = Jmp_bufType->getAs<TagType>();
3486 if (!Tag) {
3487 Error("Invalid jmp_buf type in AST file");
3488 return;
3489 }
3490 Context.setjmp_bufDecl(Tag->getDecl());
3491 }
3492 }
3493 }
3494
3495 if (unsigned Sigjmp_buf = SpecialTypes[SPECIAL_TYPE_SIGJMP_BUF]) {
3496 QualType Sigjmp_bufType = GetType(Sigjmp_buf);
3497 if (Sigjmp_bufType.isNull()) {
3498 Error("sigjmp_buf type is NULL");
3499 return;
3500 }
3501
3502 if (!Context.sigjmp_bufDecl) {
3503 if (const TypedefType *Typedef = Sigjmp_bufType->getAs<TypedefType>())
3504 Context.setsigjmp_bufDecl(Typedef->getDecl());
3505 else {
3506 const TagType *Tag = Sigjmp_bufType->getAs<TagType>();
3507 assert(Tag && "Invalid sigjmp_buf type in AST file");
3508 Context.setsigjmp_bufDecl(Tag->getDecl());
3509 }
3510 }
3511 }
3512
3513 if (unsigned ObjCIdRedef
3514 = SpecialTypes[SPECIAL_TYPE_OBJC_ID_REDEFINITION]) {
3515 if (Context.ObjCIdRedefinitionType.isNull())
3516 Context.ObjCIdRedefinitionType = GetType(ObjCIdRedef);
3517 }
3518
3519 if (unsigned ObjCClassRedef
3520 = SpecialTypes[SPECIAL_TYPE_OBJC_CLASS_REDEFINITION]) {
3521 if (Context.ObjCClassRedefinitionType.isNull())
3522 Context.ObjCClassRedefinitionType = GetType(ObjCClassRedef);
3523 }
3524
3525 if (unsigned ObjCSelRedef
3526 = SpecialTypes[SPECIAL_TYPE_OBJC_SEL_REDEFINITION]) {
3527 if (Context.ObjCSelRedefinitionType.isNull())
3528 Context.ObjCSelRedefinitionType = GetType(ObjCSelRedef);
3529 }
3530
3531 if (unsigned Ucontext_t = SpecialTypes[SPECIAL_TYPE_UCONTEXT_T]) {
3532 QualType Ucontext_tType = GetType(Ucontext_t);
3533 if (Ucontext_tType.isNull()) {
3534 Error("ucontext_t type is NULL");
3535 return;
3536 }
3537
3538 if (!Context.ucontext_tDecl) {
3539 if (const TypedefType *Typedef = Ucontext_tType->getAs<TypedefType>())
3540 Context.setucontext_tDecl(Typedef->getDecl());
3541 else {
3542 const TagType *Tag = Ucontext_tType->getAs<TagType>();
3543 assert(Tag && "Invalid ucontext_t type in AST file");
3544 Context.setucontext_tDecl(Tag->getDecl());
3545 }
3546 }
3547 }
3548 }
3549
3550 ReadPragmaDiagnosticMappings(Context.getDiagnostics());
3551
3552 // If there were any CUDA special declarations, deserialize them.
3553 if (!CUDASpecialDeclRefs.empty()) {
3554 assert(CUDASpecialDeclRefs.size() == 1 && "More decl refs than expected!");
3555 Context.setcudaConfigureCallDecl(
3556 cast<FunctionDecl>(GetDecl(CUDASpecialDeclRefs[0])));
3557 }
3558
3559 // Re-export any modules that were imported by a non-module AST file.
3560 for (unsigned I = 0, N = ImportedModules.size(); I != N; ++I) {
3561 if (Module *Imported = getSubmodule(ImportedModules[I]))
Argyrios Kyrtzidis125df052013-02-01 16:36:12 +00003562 makeModuleVisible(Imported, Module::AllVisible,
Douglas Gregorfb912652013-03-20 21:10:35 +00003563 /*ImportLoc=*/SourceLocation(),
3564 /*Complain=*/false);
Guy Benyei11169dd2012-12-18 14:30:41 +00003565 }
3566 ImportedModules.clear();
3567}
3568
3569void ASTReader::finalizeForWriting() {
3570 for (HiddenNamesMapType::iterator Hidden = HiddenNamesMap.begin(),
3571 HiddenEnd = HiddenNamesMap.end();
3572 Hidden != HiddenEnd; ++Hidden) {
Argyrios Kyrtzidis3a9c42c2013-03-27 01:25:34 +00003573 makeNamesVisible(Hidden->second, Hidden->first);
Guy Benyei11169dd2012-12-18 14:30:41 +00003574 }
3575 HiddenNamesMap.clear();
3576}
3577
Argyrios Kyrtzidisc4cd2c42013-05-06 19:23:40 +00003578/// \brief Given a cursor at the start of an AST file, scan ahead and drop the
3579/// cursor into the start of the given block ID, returning false on success and
3580/// true on failure.
3581static bool SkipCursorToBlock(BitstreamCursor &Cursor, unsigned BlockID) {
Chris Lattner7fb3bef2013-01-20 00:56:42 +00003582 while (1) {
3583 llvm::BitstreamEntry Entry = Cursor.advance();
3584 switch (Entry.Kind) {
3585 case llvm::BitstreamEntry::Error:
3586 case llvm::BitstreamEntry::EndBlock:
3587 return true;
3588
3589 case llvm::BitstreamEntry::Record:
3590 // Ignore top-level records.
3591 Cursor.skipRecord(Entry.ID);
3592 break;
3593
3594 case llvm::BitstreamEntry::SubBlock:
Argyrios Kyrtzidisc4cd2c42013-05-06 19:23:40 +00003595 if (Entry.ID == BlockID) {
3596 if (Cursor.EnterSubBlock(BlockID))
Chris Lattner7fb3bef2013-01-20 00:56:42 +00003597 return true;
3598 // Found it!
3599 return false;
3600 }
3601
3602 if (Cursor.SkipBlock())
3603 return true;
3604 }
3605 }
3606}
3607
Guy Benyei11169dd2012-12-18 14:30:41 +00003608/// \brief Retrieve the name of the original source file name
3609/// directly from the AST file, without actually loading the AST
3610/// file.
3611std::string ASTReader::getOriginalSourceFile(const std::string &ASTFileName,
3612 FileManager &FileMgr,
3613 DiagnosticsEngine &Diags) {
3614 // Open the AST file.
3615 std::string ErrStr;
3616 OwningPtr<llvm::MemoryBuffer> Buffer;
3617 Buffer.reset(FileMgr.getBufferForFile(ASTFileName, &ErrStr));
3618 if (!Buffer) {
3619 Diags.Report(diag::err_fe_unable_to_read_pch_file) << ASTFileName << ErrStr;
3620 return std::string();
3621 }
3622
3623 // Initialize the stream
3624 llvm::BitstreamReader StreamFile;
Chris Lattner7fb3bef2013-01-20 00:56:42 +00003625 BitstreamCursor Stream;
Guy Benyei11169dd2012-12-18 14:30:41 +00003626 StreamFile.init((const unsigned char *)Buffer->getBufferStart(),
3627 (const unsigned char *)Buffer->getBufferEnd());
3628 Stream.init(StreamFile);
3629
3630 // Sniff for the signature.
3631 if (Stream.Read(8) != 'C' ||
3632 Stream.Read(8) != 'P' ||
3633 Stream.Read(8) != 'C' ||
3634 Stream.Read(8) != 'H') {
3635 Diags.Report(diag::err_fe_not_a_pch_file) << ASTFileName;
3636 return std::string();
3637 }
Chris Lattner7fb3bef2013-01-20 00:56:42 +00003638
Chris Lattnere7b154b2013-01-19 21:39:22 +00003639 // Scan for the CONTROL_BLOCK_ID block.
Argyrios Kyrtzidisc4cd2c42013-05-06 19:23:40 +00003640 if (SkipCursorToBlock(Stream, CONTROL_BLOCK_ID)) {
Chris Lattner7fb3bef2013-01-20 00:56:42 +00003641 Diags.Report(diag::err_fe_pch_malformed_block) << ASTFileName;
3642 return std::string();
Chris Lattnere7b154b2013-01-19 21:39:22 +00003643 }
Guy Benyei11169dd2012-12-18 14:30:41 +00003644
Chris Lattner7fb3bef2013-01-20 00:56:42 +00003645 // Scan for ORIGINAL_FILE inside the control block.
3646 RecordData Record;
Chris Lattnere7b154b2013-01-19 21:39:22 +00003647 while (1) {
Chris Lattner7fb3bef2013-01-20 00:56:42 +00003648 llvm::BitstreamEntry Entry = Stream.advanceSkippingSubblocks();
Chris Lattnere7b154b2013-01-19 21:39:22 +00003649 if (Entry.Kind == llvm::BitstreamEntry::EndBlock)
3650 return std::string();
3651
3652 if (Entry.Kind != llvm::BitstreamEntry::Record) {
3653 Diags.Report(diag::err_fe_pch_malformed_block) << ASTFileName;
3654 return std::string();
Guy Benyei11169dd2012-12-18 14:30:41 +00003655 }
Chris Lattnere7b154b2013-01-19 21:39:22 +00003656
Guy Benyei11169dd2012-12-18 14:30:41 +00003657 Record.clear();
Chris Lattner0e6c9402013-01-20 02:38:54 +00003658 StringRef Blob;
3659 if (Stream.readRecord(Entry.ID, Record, &Blob) == ORIGINAL_FILE)
3660 return Blob.str();
Guy Benyei11169dd2012-12-18 14:30:41 +00003661 }
Guy Benyei11169dd2012-12-18 14:30:41 +00003662}
3663
3664namespace {
3665 class SimplePCHValidator : public ASTReaderListener {
3666 const LangOptions &ExistingLangOpts;
3667 const TargetOptions &ExistingTargetOpts;
3668 const PreprocessorOptions &ExistingPPOpts;
3669 FileManager &FileMgr;
3670
3671 public:
3672 SimplePCHValidator(const LangOptions &ExistingLangOpts,
3673 const TargetOptions &ExistingTargetOpts,
3674 const PreprocessorOptions &ExistingPPOpts,
3675 FileManager &FileMgr)
3676 : ExistingLangOpts(ExistingLangOpts),
3677 ExistingTargetOpts(ExistingTargetOpts),
3678 ExistingPPOpts(ExistingPPOpts),
3679 FileMgr(FileMgr)
3680 {
3681 }
3682
3683 virtual bool ReadLanguageOptions(const LangOptions &LangOpts,
3684 bool Complain) {
3685 return checkLanguageOptions(ExistingLangOpts, LangOpts, 0);
3686 }
3687 virtual bool ReadTargetOptions(const TargetOptions &TargetOpts,
3688 bool Complain) {
3689 return checkTargetOptions(ExistingTargetOpts, TargetOpts, 0);
3690 }
3691 virtual bool ReadPreprocessorOptions(const PreprocessorOptions &PPOpts,
3692 bool Complain,
3693 std::string &SuggestedPredefines) {
3694 return checkPreprocessorOptions(ExistingPPOpts, PPOpts, 0, FileMgr,
Argyrios Kyrtzidisd3afa0c2013-04-26 21:33:40 +00003695 SuggestedPredefines, ExistingLangOpts);
Guy Benyei11169dd2012-12-18 14:30:41 +00003696 }
3697 };
3698}
3699
3700bool ASTReader::readASTFileControlBlock(StringRef Filename,
3701 FileManager &FileMgr,
3702 ASTReaderListener &Listener) {
3703 // Open the AST file.
3704 std::string ErrStr;
3705 OwningPtr<llvm::MemoryBuffer> Buffer;
3706 Buffer.reset(FileMgr.getBufferForFile(Filename, &ErrStr));
3707 if (!Buffer) {
3708 return true;
3709 }
3710
3711 // Initialize the stream
3712 llvm::BitstreamReader StreamFile;
Chris Lattner7fb3bef2013-01-20 00:56:42 +00003713 BitstreamCursor Stream;
Guy Benyei11169dd2012-12-18 14:30:41 +00003714 StreamFile.init((const unsigned char *)Buffer->getBufferStart(),
3715 (const unsigned char *)Buffer->getBufferEnd());
3716 Stream.init(StreamFile);
3717
3718 // Sniff for the signature.
3719 if (Stream.Read(8) != 'C' ||
3720 Stream.Read(8) != 'P' ||
3721 Stream.Read(8) != 'C' ||
3722 Stream.Read(8) != 'H') {
3723 return true;
3724 }
3725
Chris Lattner7fb3bef2013-01-20 00:56:42 +00003726 // Scan for the CONTROL_BLOCK_ID block.
Argyrios Kyrtzidisc4cd2c42013-05-06 19:23:40 +00003727 if (SkipCursorToBlock(Stream, CONTROL_BLOCK_ID))
Chris Lattner7fb3bef2013-01-20 00:56:42 +00003728 return true;
Argyrios Kyrtzidisc4cd2c42013-05-06 19:23:40 +00003729
3730 bool NeedsInputFiles = Listener.needsInputFileVisitation();
3731 BitstreamCursor InputFilesCursor;
3732 if (NeedsInputFiles) {
3733 InputFilesCursor = Stream;
3734 if (SkipCursorToBlock(InputFilesCursor, INPUT_FILES_BLOCK_ID))
3735 return true;
3736
3737 // Read the abbreviations
3738 while (true) {
3739 uint64_t Offset = InputFilesCursor.GetCurrentBitNo();
3740 unsigned Code = InputFilesCursor.ReadCode();
3741
3742 // We expect all abbrevs to be at the start of the block.
3743 if (Code != llvm::bitc::DEFINE_ABBREV) {
3744 InputFilesCursor.JumpToBit(Offset);
3745 break;
3746 }
3747 InputFilesCursor.ReadAbbrevRecord();
3748 }
3749 }
Chris Lattner7fb3bef2013-01-20 00:56:42 +00003750
3751 // Scan for ORIGINAL_FILE inside the control block.
Guy Benyei11169dd2012-12-18 14:30:41 +00003752 RecordData Record;
Chris Lattner7fb3bef2013-01-20 00:56:42 +00003753 while (1) {
3754 llvm::BitstreamEntry Entry = Stream.advanceSkippingSubblocks();
3755 if (Entry.Kind == llvm::BitstreamEntry::EndBlock)
3756 return false;
3757
3758 if (Entry.Kind != llvm::BitstreamEntry::Record)
3759 return true;
3760
Guy Benyei11169dd2012-12-18 14:30:41 +00003761 Record.clear();
Chris Lattner0e6c9402013-01-20 02:38:54 +00003762 StringRef Blob;
3763 unsigned RecCode = Stream.readRecord(Entry.ID, Record, &Blob);
Chris Lattner7fb3bef2013-01-20 00:56:42 +00003764 switch ((ControlRecordTypes)RecCode) {
3765 case METADATA: {
3766 if (Record[0] != VERSION_MAJOR)
3767 return true;
Guy Benyei11169dd2012-12-18 14:30:41 +00003768
Douglas Gregorbf7fc9c2013-03-27 16:47:18 +00003769 if (Listener.ReadFullVersionInformation(Blob))
Chris Lattner7fb3bef2013-01-20 00:56:42 +00003770 return true;
Douglas Gregorbf7fc9c2013-03-27 16:47:18 +00003771
Chris Lattner7fb3bef2013-01-20 00:56:42 +00003772 break;
3773 }
3774 case LANGUAGE_OPTIONS:
3775 if (ParseLanguageOptions(Record, false, Listener))
3776 return true;
3777 break;
Guy Benyei11169dd2012-12-18 14:30:41 +00003778
Chris Lattner7fb3bef2013-01-20 00:56:42 +00003779 case TARGET_OPTIONS:
3780 if (ParseTargetOptions(Record, false, Listener))
3781 return true;
3782 break;
Guy Benyei11169dd2012-12-18 14:30:41 +00003783
Chris Lattner7fb3bef2013-01-20 00:56:42 +00003784 case DIAGNOSTIC_OPTIONS:
3785 if (ParseDiagnosticOptions(Record, false, Listener))
3786 return true;
3787 break;
Guy Benyei11169dd2012-12-18 14:30:41 +00003788
Chris Lattner7fb3bef2013-01-20 00:56:42 +00003789 case FILE_SYSTEM_OPTIONS:
3790 if (ParseFileSystemOptions(Record, false, Listener))
3791 return true;
3792 break;
Guy Benyei11169dd2012-12-18 14:30:41 +00003793
Chris Lattner7fb3bef2013-01-20 00:56:42 +00003794 case HEADER_SEARCH_OPTIONS:
3795 if (ParseHeaderSearchOptions(Record, false, Listener))
3796 return true;
3797 break;
Guy Benyei11169dd2012-12-18 14:30:41 +00003798
Chris Lattner7fb3bef2013-01-20 00:56:42 +00003799 case PREPROCESSOR_OPTIONS: {
3800 std::string IgnoredSuggestedPredefines;
3801 if (ParsePreprocessorOptions(Record, false, Listener,
3802 IgnoredSuggestedPredefines))
3803 return true;
3804 break;
3805 }
Guy Benyei11169dd2012-12-18 14:30:41 +00003806
Argyrios Kyrtzidisc4cd2c42013-05-06 19:23:40 +00003807 case INPUT_FILE_OFFSETS: {
3808 if (!NeedsInputFiles)
3809 break;
3810
3811 unsigned NumInputFiles = Record[0];
3812 unsigned NumUserFiles = Record[1];
3813 const uint32_t *InputFileOffs = (const uint32_t *)Blob.data();
3814 for (unsigned I = 0; I != NumInputFiles; ++I) {
3815 // Go find this input file.
3816 bool isSystemFile = I >= NumUserFiles;
3817 BitstreamCursor &Cursor = InputFilesCursor;
3818 SavedStreamPosition SavedPosition(Cursor);
3819 Cursor.JumpToBit(InputFileOffs[I]);
3820
3821 unsigned Code = Cursor.ReadCode();
3822 RecordData Record;
3823 StringRef Blob;
3824 bool shouldContinue = false;
3825 switch ((InputFileRecordTypes)Cursor.readRecord(Code, Record, &Blob)) {
3826 case INPUT_FILE:
3827 shouldContinue = Listener.visitInputFile(Blob, isSystemFile);
3828 break;
3829 }
3830 if (!shouldContinue)
3831 break;
3832 }
3833 break;
3834 }
3835
Chris Lattner7fb3bef2013-01-20 00:56:42 +00003836 default:
3837 // No other validation to perform.
3838 break;
Guy Benyei11169dd2012-12-18 14:30:41 +00003839 }
3840 }
Guy Benyei11169dd2012-12-18 14:30:41 +00003841}
3842
3843
3844bool ASTReader::isAcceptableASTFile(StringRef Filename,
3845 FileManager &FileMgr,
3846 const LangOptions &LangOpts,
3847 const TargetOptions &TargetOpts,
3848 const PreprocessorOptions &PPOpts) {
3849 SimplePCHValidator validator(LangOpts, TargetOpts, PPOpts, FileMgr);
3850 return !readASTFileControlBlock(Filename, FileMgr, validator);
3851}
3852
3853bool ASTReader::ReadSubmoduleBlock(ModuleFile &F) {
3854 // Enter the submodule block.
3855 if (F.Stream.EnterSubBlock(SUBMODULE_BLOCK_ID)) {
3856 Error("malformed submodule block record in AST file");
3857 return true;
3858 }
3859
3860 ModuleMap &ModMap = PP.getHeaderSearchInfo().getModuleMap();
3861 bool First = true;
3862 Module *CurrentModule = 0;
3863 RecordData Record;
3864 while (true) {
Chris Lattner7fb3bef2013-01-20 00:56:42 +00003865 llvm::BitstreamEntry Entry = F.Stream.advanceSkippingSubblocks();
3866
3867 switch (Entry.Kind) {
3868 case llvm::BitstreamEntry::SubBlock: // Handled for us already.
3869 case llvm::BitstreamEntry::Error:
3870 Error("malformed block record in AST file");
3871 return true;
3872 case llvm::BitstreamEntry::EndBlock:
Guy Benyei11169dd2012-12-18 14:30:41 +00003873 return false;
Chris Lattner7fb3bef2013-01-20 00:56:42 +00003874 case llvm::BitstreamEntry::Record:
3875 // The interesting case.
3876 break;
Guy Benyei11169dd2012-12-18 14:30:41 +00003877 }
Chris Lattner7fb3bef2013-01-20 00:56:42 +00003878
Guy Benyei11169dd2012-12-18 14:30:41 +00003879 // Read a record.
Chris Lattner0e6c9402013-01-20 02:38:54 +00003880 StringRef Blob;
Guy Benyei11169dd2012-12-18 14:30:41 +00003881 Record.clear();
Chris Lattner0e6c9402013-01-20 02:38:54 +00003882 switch (F.Stream.readRecord(Entry.ID, Record, &Blob)) {
Guy Benyei11169dd2012-12-18 14:30:41 +00003883 default: // Default behavior: ignore.
3884 break;
3885
3886 case SUBMODULE_DEFINITION: {
3887 if (First) {
3888 Error("missing submodule metadata record at beginning of block");
3889 return true;
3890 }
3891
Douglas Gregor8d932422013-03-20 03:59:18 +00003892 if (Record.size() < 8) {
Guy Benyei11169dd2012-12-18 14:30:41 +00003893 Error("malformed module definition");
3894 return true;
3895 }
3896
Chris Lattner0e6c9402013-01-20 02:38:54 +00003897 StringRef Name = Blob;
Guy Benyei11169dd2012-12-18 14:30:41 +00003898 SubmoduleID GlobalID = getGlobalSubmoduleID(F, Record[0]);
3899 SubmoduleID Parent = getGlobalSubmoduleID(F, Record[1]);
3900 bool IsFramework = Record[2];
3901 bool IsExplicit = Record[3];
3902 bool IsSystem = Record[4];
3903 bool InferSubmodules = Record[5];
3904 bool InferExplicitSubmodules = Record[6];
3905 bool InferExportWildcard = Record[7];
Douglas Gregor8d932422013-03-20 03:59:18 +00003906 bool ConfigMacrosExhaustive = Record[8];
3907
Guy Benyei11169dd2012-12-18 14:30:41 +00003908 Module *ParentModule = 0;
3909 if (Parent)
3910 ParentModule = getSubmodule(Parent);
3911
3912 // Retrieve this (sub)module from the module map, creating it if
3913 // necessary.
3914 CurrentModule = ModMap.findOrCreateModule(Name, ParentModule,
3915 IsFramework,
3916 IsExplicit).first;
3917 SubmoduleID GlobalIndex = GlobalID - NUM_PREDEF_SUBMODULE_IDS;
3918 if (GlobalIndex >= SubmodulesLoaded.size() ||
3919 SubmodulesLoaded[GlobalIndex]) {
3920 Error("too many submodules");
3921 return true;
3922 }
Douglas Gregor8a114ab2013-02-06 22:40:31 +00003923
Douglas Gregor7029ce12013-03-19 00:28:20 +00003924 if (!ParentModule) {
3925 if (const FileEntry *CurFile = CurrentModule->getASTFile()) {
3926 if (CurFile != F.File) {
3927 if (!Diags.isDiagnosticInFlight()) {
3928 Diag(diag::err_module_file_conflict)
3929 << CurrentModule->getTopLevelModuleName()
3930 << CurFile->getName()
3931 << F.File->getName();
3932 }
3933 return true;
Douglas Gregor8a114ab2013-02-06 22:40:31 +00003934 }
Douglas Gregor8a114ab2013-02-06 22:40:31 +00003935 }
Douglas Gregor7029ce12013-03-19 00:28:20 +00003936
3937 CurrentModule->setASTFile(F.File);
Douglas Gregor8a114ab2013-02-06 22:40:31 +00003938 }
Douglas Gregor7029ce12013-03-19 00:28:20 +00003939
Guy Benyei11169dd2012-12-18 14:30:41 +00003940 CurrentModule->IsFromModuleFile = true;
3941 CurrentModule->IsSystem = IsSystem || CurrentModule->IsSystem;
3942 CurrentModule->InferSubmodules = InferSubmodules;
3943 CurrentModule->InferExplicitSubmodules = InferExplicitSubmodules;
3944 CurrentModule->InferExportWildcard = InferExportWildcard;
Douglas Gregor8d932422013-03-20 03:59:18 +00003945 CurrentModule->ConfigMacrosExhaustive = ConfigMacrosExhaustive;
Guy Benyei11169dd2012-12-18 14:30:41 +00003946 if (DeserializationListener)
3947 DeserializationListener->ModuleRead(GlobalID, CurrentModule);
3948
3949 SubmodulesLoaded[GlobalIndex] = CurrentModule;
Douglas Gregor6ddfca92013-01-14 17:21:00 +00003950
Douglas Gregorfb912652013-03-20 21:10:35 +00003951 // Clear out data that will be replaced by what is the module file.
Douglas Gregor6ddfca92013-01-14 17:21:00 +00003952 CurrentModule->LinkLibraries.clear();
Douglas Gregor8d932422013-03-20 03:59:18 +00003953 CurrentModule->ConfigMacros.clear();
Douglas Gregorfb912652013-03-20 21:10:35 +00003954 CurrentModule->UnresolvedConflicts.clear();
3955 CurrentModule->Conflicts.clear();
Guy Benyei11169dd2012-12-18 14:30:41 +00003956 break;
3957 }
3958
3959 case SUBMODULE_UMBRELLA_HEADER: {
3960 if (First) {
3961 Error("missing submodule metadata record at beginning of block");
3962 return true;
3963 }
3964
3965 if (!CurrentModule)
3966 break;
3967
Chris Lattner0e6c9402013-01-20 02:38:54 +00003968 if (const FileEntry *Umbrella = PP.getFileManager().getFile(Blob)) {
Guy Benyei11169dd2012-12-18 14:30:41 +00003969 if (!CurrentModule->getUmbrellaHeader())
3970 ModMap.setUmbrellaHeader(CurrentModule, Umbrella);
3971 else if (CurrentModule->getUmbrellaHeader() != Umbrella) {
3972 Error("mismatched umbrella headers in submodule");
3973 return true;
3974 }
3975 }
3976 break;
3977 }
3978
3979 case SUBMODULE_HEADER: {
3980 if (First) {
3981 Error("missing submodule metadata record at beginning of block");
3982 return true;
3983 }
3984
3985 if (!CurrentModule)
3986 break;
3987
Argyrios Kyrtzidisb146baa2013-03-13 21:13:51 +00003988 // We lazily associate headers with their modules via the HeaderInfoTable.
3989 // FIXME: Re-evaluate this section; maybe only store InputFile IDs instead
3990 // of complete filenames or remove it entirely.
Guy Benyei11169dd2012-12-18 14:30:41 +00003991 break;
3992 }
3993
3994 case SUBMODULE_EXCLUDED_HEADER: {
3995 if (First) {
3996 Error("missing submodule metadata record at beginning of block");
3997 return true;
3998 }
3999
4000 if (!CurrentModule)
4001 break;
4002
Argyrios Kyrtzidisb146baa2013-03-13 21:13:51 +00004003 // We lazily associate headers with their modules via the HeaderInfoTable.
4004 // FIXME: Re-evaluate this section; maybe only store InputFile IDs instead
4005 // of complete filenames or remove it entirely.
Guy Benyei11169dd2012-12-18 14:30:41 +00004006 break;
4007 }
4008
Lawrence Crowlb53e5482013-06-20 21:14:14 +00004009 case SUBMODULE_PRIVATE_HEADER: {
4010 if (First) {
4011 Error("missing submodule metadata record at beginning of block");
4012 return true;
4013 }
4014
4015 if (!CurrentModule)
4016 break;
4017
4018 // We lazily associate headers with their modules via the HeaderInfoTable.
4019 // FIXME: Re-evaluate this section; maybe only store InputFile IDs instead
4020 // of complete filenames or remove it entirely.
4021 break;
4022 }
4023
Guy Benyei11169dd2012-12-18 14:30:41 +00004024 case SUBMODULE_TOPHEADER: {
4025 if (First) {
4026 Error("missing submodule metadata record at beginning of block");
4027 return true;
4028 }
4029
4030 if (!CurrentModule)
4031 break;
4032
Argyrios Kyrtzidis3c5305c2013-03-13 21:13:43 +00004033 CurrentModule->addTopHeaderFilename(Blob);
Guy Benyei11169dd2012-12-18 14:30:41 +00004034 break;
4035 }
4036
4037 case SUBMODULE_UMBRELLA_DIR: {
4038 if (First) {
4039 Error("missing submodule metadata record at beginning of block");
4040 return true;
4041 }
4042
4043 if (!CurrentModule)
4044 break;
4045
Guy Benyei11169dd2012-12-18 14:30:41 +00004046 if (const DirectoryEntry *Umbrella
Chris Lattner0e6c9402013-01-20 02:38:54 +00004047 = PP.getFileManager().getDirectory(Blob)) {
Guy Benyei11169dd2012-12-18 14:30:41 +00004048 if (!CurrentModule->getUmbrellaDir())
4049 ModMap.setUmbrellaDir(CurrentModule, Umbrella);
4050 else if (CurrentModule->getUmbrellaDir() != Umbrella) {
4051 Error("mismatched umbrella directories in submodule");
4052 return true;
4053 }
4054 }
4055 break;
4056 }
4057
4058 case SUBMODULE_METADATA: {
4059 if (!First) {
4060 Error("submodule metadata record not at beginning of block");
4061 return true;
4062 }
4063 First = false;
4064
4065 F.BaseSubmoduleID = getTotalNumSubmodules();
4066 F.LocalNumSubmodules = Record[0];
4067 unsigned LocalBaseSubmoduleID = Record[1];
4068 if (F.LocalNumSubmodules > 0) {
4069 // Introduce the global -> local mapping for submodules within this
4070 // module.
4071 GlobalSubmoduleMap.insert(std::make_pair(getTotalNumSubmodules()+1,&F));
4072
4073 // Introduce the local -> global mapping for submodules within this
4074 // module.
4075 F.SubmoduleRemap.insertOrReplace(
4076 std::make_pair(LocalBaseSubmoduleID,
4077 F.BaseSubmoduleID - LocalBaseSubmoduleID));
4078
4079 SubmodulesLoaded.resize(SubmodulesLoaded.size() + F.LocalNumSubmodules);
4080 }
4081 break;
4082 }
4083
4084 case SUBMODULE_IMPORTS: {
4085 if (First) {
4086 Error("missing submodule metadata record at beginning of block");
4087 return true;
4088 }
4089
4090 if (!CurrentModule)
4091 break;
4092
4093 for (unsigned Idx = 0; Idx != Record.size(); ++Idx) {
Douglas Gregorfb912652013-03-20 21:10:35 +00004094 UnresolvedModuleRef Unresolved;
Guy Benyei11169dd2012-12-18 14:30:41 +00004095 Unresolved.File = &F;
4096 Unresolved.Mod = CurrentModule;
4097 Unresolved.ID = Record[Idx];
Douglas Gregorfb912652013-03-20 21:10:35 +00004098 Unresolved.Kind = UnresolvedModuleRef::Import;
Guy Benyei11169dd2012-12-18 14:30:41 +00004099 Unresolved.IsWildcard = false;
Douglas Gregorfb912652013-03-20 21:10:35 +00004100 UnresolvedModuleRefs.push_back(Unresolved);
Guy Benyei11169dd2012-12-18 14:30:41 +00004101 }
4102 break;
4103 }
4104
4105 case SUBMODULE_EXPORTS: {
4106 if (First) {
4107 Error("missing submodule metadata record at beginning of block");
4108 return true;
4109 }
4110
4111 if (!CurrentModule)
4112 break;
4113
4114 for (unsigned Idx = 0; Idx + 1 < Record.size(); Idx += 2) {
Douglas Gregorfb912652013-03-20 21:10:35 +00004115 UnresolvedModuleRef Unresolved;
Guy Benyei11169dd2012-12-18 14:30:41 +00004116 Unresolved.File = &F;
4117 Unresolved.Mod = CurrentModule;
4118 Unresolved.ID = Record[Idx];
Douglas Gregorfb912652013-03-20 21:10:35 +00004119 Unresolved.Kind = UnresolvedModuleRef::Export;
Guy Benyei11169dd2012-12-18 14:30:41 +00004120 Unresolved.IsWildcard = Record[Idx + 1];
Douglas Gregorfb912652013-03-20 21:10:35 +00004121 UnresolvedModuleRefs.push_back(Unresolved);
Guy Benyei11169dd2012-12-18 14:30:41 +00004122 }
4123
4124 // Once we've loaded the set of exports, there's no reason to keep
4125 // the parsed, unresolved exports around.
4126 CurrentModule->UnresolvedExports.clear();
4127 break;
4128 }
4129 case SUBMODULE_REQUIRES: {
4130 if (First) {
4131 Error("missing submodule metadata record at beginning of block");
4132 return true;
4133 }
4134
4135 if (!CurrentModule)
4136 break;
4137
Richard Smitha3feee22013-10-28 22:18:19 +00004138 CurrentModule->addRequirement(Blob, Record[0], Context.getLangOpts(),
Guy Benyei11169dd2012-12-18 14:30:41 +00004139 Context.getTargetInfo());
4140 break;
4141 }
Douglas Gregor6ddfca92013-01-14 17:21:00 +00004142
4143 case SUBMODULE_LINK_LIBRARY:
4144 if (First) {
4145 Error("missing submodule metadata record at beginning of block");
4146 return true;
4147 }
4148
4149 if (!CurrentModule)
4150 break;
4151
4152 CurrentModule->LinkLibraries.push_back(
Chris Lattner0e6c9402013-01-20 02:38:54 +00004153 Module::LinkLibrary(Blob, Record[0]));
Douglas Gregor6ddfca92013-01-14 17:21:00 +00004154 break;
Douglas Gregor35b13ec2013-03-20 00:22:05 +00004155
4156 case SUBMODULE_CONFIG_MACRO:
4157 if (First) {
4158 Error("missing submodule metadata record at beginning of block");
4159 return true;
4160 }
4161
4162 if (!CurrentModule)
4163 break;
4164
4165 CurrentModule->ConfigMacros.push_back(Blob.str());
4166 break;
Douglas Gregorfb912652013-03-20 21:10:35 +00004167
4168 case SUBMODULE_CONFLICT: {
4169 if (First) {
4170 Error("missing submodule metadata record at beginning of block");
4171 return true;
4172 }
4173
4174 if (!CurrentModule)
4175 break;
4176
4177 UnresolvedModuleRef Unresolved;
4178 Unresolved.File = &F;
4179 Unresolved.Mod = CurrentModule;
4180 Unresolved.ID = Record[0];
4181 Unresolved.Kind = UnresolvedModuleRef::Conflict;
4182 Unresolved.IsWildcard = false;
4183 Unresolved.String = Blob;
4184 UnresolvedModuleRefs.push_back(Unresolved);
4185 break;
4186 }
Guy Benyei11169dd2012-12-18 14:30:41 +00004187 }
4188 }
4189}
4190
4191/// \brief Parse the record that corresponds to a LangOptions data
4192/// structure.
4193///
4194/// This routine parses the language options from the AST file and then gives
4195/// them to the AST listener if one is set.
4196///
4197/// \returns true if the listener deems the file unacceptable, false otherwise.
4198bool ASTReader::ParseLanguageOptions(const RecordData &Record,
4199 bool Complain,
4200 ASTReaderListener &Listener) {
4201 LangOptions LangOpts;
4202 unsigned Idx = 0;
4203#define LANGOPT(Name, Bits, Default, Description) \
4204 LangOpts.Name = Record[Idx++];
4205#define ENUM_LANGOPT(Name, Type, Bits, Default, Description) \
4206 LangOpts.set##Name(static_cast<LangOptions::Type>(Record[Idx++]));
4207#include "clang/Basic/LangOptions.def"
Will Dietzf54319c2013-01-18 11:30:38 +00004208#define SANITIZER(NAME, ID) LangOpts.Sanitize.ID = Record[Idx++];
4209#include "clang/Basic/Sanitizers.def"
Guy Benyei11169dd2012-12-18 14:30:41 +00004210
4211 ObjCRuntime::Kind runtimeKind = (ObjCRuntime::Kind) Record[Idx++];
4212 VersionTuple runtimeVersion = ReadVersionTuple(Record, Idx);
4213 LangOpts.ObjCRuntime = ObjCRuntime(runtimeKind, runtimeVersion);
4214
4215 unsigned Length = Record[Idx++];
4216 LangOpts.CurrentModule.assign(Record.begin() + Idx,
4217 Record.begin() + Idx + Length);
Dmitri Gribenkoacf2e782013-02-22 14:21:27 +00004218
4219 Idx += Length;
4220
4221 // Comment options.
4222 for (unsigned N = Record[Idx++]; N; --N) {
4223 LangOpts.CommentOpts.BlockCommandNames.push_back(
4224 ReadString(Record, Idx));
4225 }
Dmitri Gribenkoa7d16ce2013-04-10 15:35:17 +00004226 LangOpts.CommentOpts.ParseAllComments = Record[Idx++];
Dmitri Gribenkoacf2e782013-02-22 14:21:27 +00004227
Guy Benyei11169dd2012-12-18 14:30:41 +00004228 return Listener.ReadLanguageOptions(LangOpts, Complain);
4229}
4230
4231bool ASTReader::ParseTargetOptions(const RecordData &Record,
4232 bool Complain,
4233 ASTReaderListener &Listener) {
4234 unsigned Idx = 0;
4235 TargetOptions TargetOpts;
4236 TargetOpts.Triple = ReadString(Record, Idx);
4237 TargetOpts.CPU = ReadString(Record, Idx);
4238 TargetOpts.ABI = ReadString(Record, Idx);
Guy Benyei11169dd2012-12-18 14:30:41 +00004239 TargetOpts.LinkerVersion = ReadString(Record, Idx);
4240 for (unsigned N = Record[Idx++]; N; --N) {
4241 TargetOpts.FeaturesAsWritten.push_back(ReadString(Record, Idx));
4242 }
4243 for (unsigned N = Record[Idx++]; N; --N) {
4244 TargetOpts.Features.push_back(ReadString(Record, Idx));
4245 }
4246
4247 return Listener.ReadTargetOptions(TargetOpts, Complain);
4248}
4249
4250bool ASTReader::ParseDiagnosticOptions(const RecordData &Record, bool Complain,
4251 ASTReaderListener &Listener) {
4252 DiagnosticOptions DiagOpts;
4253 unsigned Idx = 0;
4254#define DIAGOPT(Name, Bits, Default) DiagOpts.Name = Record[Idx++];
4255#define ENUM_DIAGOPT(Name, Type, Bits, Default) \
4256 DiagOpts.set##Name(static_cast<Type>(Record[Idx++]));
4257#include "clang/Basic/DiagnosticOptions.def"
4258
4259 for (unsigned N = Record[Idx++]; N; --N) {
4260 DiagOpts.Warnings.push_back(ReadString(Record, Idx));
4261 }
4262
4263 return Listener.ReadDiagnosticOptions(DiagOpts, Complain);
4264}
4265
4266bool ASTReader::ParseFileSystemOptions(const RecordData &Record, bool Complain,
4267 ASTReaderListener &Listener) {
4268 FileSystemOptions FSOpts;
4269 unsigned Idx = 0;
4270 FSOpts.WorkingDir = ReadString(Record, Idx);
4271 return Listener.ReadFileSystemOptions(FSOpts, Complain);
4272}
4273
4274bool ASTReader::ParseHeaderSearchOptions(const RecordData &Record,
4275 bool Complain,
4276 ASTReaderListener &Listener) {
4277 HeaderSearchOptions HSOpts;
4278 unsigned Idx = 0;
4279 HSOpts.Sysroot = ReadString(Record, Idx);
4280
4281 // Include entries.
4282 for (unsigned N = Record[Idx++]; N; --N) {
4283 std::string Path = ReadString(Record, Idx);
4284 frontend::IncludeDirGroup Group
4285 = static_cast<frontend::IncludeDirGroup>(Record[Idx++]);
Guy Benyei11169dd2012-12-18 14:30:41 +00004286 bool IsFramework = Record[Idx++];
4287 bool IgnoreSysRoot = Record[Idx++];
Guy Benyei11169dd2012-12-18 14:30:41 +00004288 HSOpts.UserEntries.push_back(
Daniel Dunbar53681732013-01-30 00:34:26 +00004289 HeaderSearchOptions::Entry(Path, Group, IsFramework, IgnoreSysRoot));
Guy Benyei11169dd2012-12-18 14:30:41 +00004290 }
4291
4292 // System header prefixes.
4293 for (unsigned N = Record[Idx++]; N; --N) {
4294 std::string Prefix = ReadString(Record, Idx);
4295 bool IsSystemHeader = Record[Idx++];
4296 HSOpts.SystemHeaderPrefixes.push_back(
4297 HeaderSearchOptions::SystemHeaderPrefix(Prefix, IsSystemHeader));
4298 }
4299
4300 HSOpts.ResourceDir = ReadString(Record, Idx);
4301 HSOpts.ModuleCachePath = ReadString(Record, Idx);
Argyrios Kyrtzidis1594c152014-03-03 08:12:05 +00004302 HSOpts.ModuleUserBuildPath = ReadString(Record, Idx);
Guy Benyei11169dd2012-12-18 14:30:41 +00004303 HSOpts.DisableModuleHash = Record[Idx++];
4304 HSOpts.UseBuiltinIncludes = Record[Idx++];
4305 HSOpts.UseStandardSystemIncludes = Record[Idx++];
4306 HSOpts.UseStandardCXXIncludes = Record[Idx++];
4307 HSOpts.UseLibcxx = Record[Idx++];
4308
4309 return Listener.ReadHeaderSearchOptions(HSOpts, Complain);
4310}
4311
4312bool ASTReader::ParsePreprocessorOptions(const RecordData &Record,
4313 bool Complain,
4314 ASTReaderListener &Listener,
4315 std::string &SuggestedPredefines) {
4316 PreprocessorOptions PPOpts;
4317 unsigned Idx = 0;
4318
4319 // Macro definitions/undefs
4320 for (unsigned N = Record[Idx++]; N; --N) {
4321 std::string Macro = ReadString(Record, Idx);
4322 bool IsUndef = Record[Idx++];
4323 PPOpts.Macros.push_back(std::make_pair(Macro, IsUndef));
4324 }
4325
4326 // Includes
4327 for (unsigned N = Record[Idx++]; N; --N) {
4328 PPOpts.Includes.push_back(ReadString(Record, Idx));
4329 }
4330
4331 // Macro Includes
4332 for (unsigned N = Record[Idx++]; N; --N) {
4333 PPOpts.MacroIncludes.push_back(ReadString(Record, Idx));
4334 }
4335
4336 PPOpts.UsePredefines = Record[Idx++];
Argyrios Kyrtzidisd3afa0c2013-04-26 21:33:40 +00004337 PPOpts.DetailedRecord = Record[Idx++];
Guy Benyei11169dd2012-12-18 14:30:41 +00004338 PPOpts.ImplicitPCHInclude = ReadString(Record, Idx);
4339 PPOpts.ImplicitPTHInclude = ReadString(Record, Idx);
4340 PPOpts.ObjCXXARCStandardLibrary =
4341 static_cast<ObjCXXARCStandardLibraryKind>(Record[Idx++]);
4342 SuggestedPredefines.clear();
4343 return Listener.ReadPreprocessorOptions(PPOpts, Complain,
4344 SuggestedPredefines);
4345}
4346
4347std::pair<ModuleFile *, unsigned>
4348ASTReader::getModulePreprocessedEntity(unsigned GlobalIndex) {
4349 GlobalPreprocessedEntityMapType::iterator
4350 I = GlobalPreprocessedEntityMap.find(GlobalIndex);
4351 assert(I != GlobalPreprocessedEntityMap.end() &&
4352 "Corrupted global preprocessed entity map");
4353 ModuleFile *M = I->second;
4354 unsigned LocalIndex = GlobalIndex - M->BasePreprocessedEntityID;
4355 return std::make_pair(M, LocalIndex);
4356}
4357
4358std::pair<PreprocessingRecord::iterator, PreprocessingRecord::iterator>
4359ASTReader::getModulePreprocessedEntities(ModuleFile &Mod) const {
4360 if (PreprocessingRecord *PPRec = PP.getPreprocessingRecord())
4361 return PPRec->getIteratorsForLoadedRange(Mod.BasePreprocessedEntityID,
4362 Mod.NumPreprocessedEntities);
4363
4364 return std::make_pair(PreprocessingRecord::iterator(),
4365 PreprocessingRecord::iterator());
4366}
4367
4368std::pair<ASTReader::ModuleDeclIterator, ASTReader::ModuleDeclIterator>
4369ASTReader::getModuleFileLevelDecls(ModuleFile &Mod) {
4370 return std::make_pair(ModuleDeclIterator(this, &Mod, Mod.FileSortedDecls),
4371 ModuleDeclIterator(this, &Mod,
4372 Mod.FileSortedDecls + Mod.NumFileSortedDecls));
4373}
4374
4375PreprocessedEntity *ASTReader::ReadPreprocessedEntity(unsigned Index) {
4376 PreprocessedEntityID PPID = Index+1;
4377 std::pair<ModuleFile *, unsigned> PPInfo = getModulePreprocessedEntity(Index);
4378 ModuleFile &M = *PPInfo.first;
4379 unsigned LocalIndex = PPInfo.second;
4380 const PPEntityOffset &PPOffs = M.PreprocessedEntityOffsets[LocalIndex];
4381
Guy Benyei11169dd2012-12-18 14:30:41 +00004382 if (!PP.getPreprocessingRecord()) {
4383 Error("no preprocessing record");
4384 return 0;
4385 }
4386
Chris Lattner7fb3bef2013-01-20 00:56:42 +00004387 SavedStreamPosition SavedPosition(M.PreprocessorDetailCursor);
4388 M.PreprocessorDetailCursor.JumpToBit(PPOffs.BitOffset);
4389
4390 llvm::BitstreamEntry Entry =
4391 M.PreprocessorDetailCursor.advance(BitstreamCursor::AF_DontPopBlockAtEnd);
4392 if (Entry.Kind != llvm::BitstreamEntry::Record)
4393 return 0;
4394
Guy Benyei11169dd2012-12-18 14:30:41 +00004395 // Read the record.
4396 SourceRange Range(ReadSourceLocation(M, PPOffs.Begin),
4397 ReadSourceLocation(M, PPOffs.End));
4398 PreprocessingRecord &PPRec = *PP.getPreprocessingRecord();
Chris Lattner0e6c9402013-01-20 02:38:54 +00004399 StringRef Blob;
Guy Benyei11169dd2012-12-18 14:30:41 +00004400 RecordData Record;
4401 PreprocessorDetailRecordTypes RecType =
Chris Lattner0e6c9402013-01-20 02:38:54 +00004402 (PreprocessorDetailRecordTypes)M.PreprocessorDetailCursor.readRecord(
4403 Entry.ID, Record, &Blob);
Guy Benyei11169dd2012-12-18 14:30:41 +00004404 switch (RecType) {
4405 case PPD_MACRO_EXPANSION: {
4406 bool isBuiltin = Record[0];
4407 IdentifierInfo *Name = 0;
4408 MacroDefinition *Def = 0;
4409 if (isBuiltin)
4410 Name = getLocalIdentifier(M, Record[1]);
4411 else {
4412 PreprocessedEntityID
4413 GlobalID = getGlobalPreprocessedEntityID(M, Record[1]);
4414 Def =cast<MacroDefinition>(PPRec.getLoadedPreprocessedEntity(GlobalID-1));
4415 }
4416
4417 MacroExpansion *ME;
4418 if (isBuiltin)
4419 ME = new (PPRec) MacroExpansion(Name, Range);
4420 else
4421 ME = new (PPRec) MacroExpansion(Def, Range);
4422
4423 return ME;
4424 }
4425
4426 case PPD_MACRO_DEFINITION: {
4427 // Decode the identifier info and then check again; if the macro is
4428 // still defined and associated with the identifier,
4429 IdentifierInfo *II = getLocalIdentifier(M, Record[0]);
4430 MacroDefinition *MD
4431 = new (PPRec) MacroDefinition(II, Range);
4432
4433 if (DeserializationListener)
4434 DeserializationListener->MacroDefinitionRead(PPID, MD);
4435
4436 return MD;
4437 }
4438
4439 case PPD_INCLUSION_DIRECTIVE: {
Chris Lattner0e6c9402013-01-20 02:38:54 +00004440 const char *FullFileNameStart = Blob.data() + Record[0];
4441 StringRef FullFileName(FullFileNameStart, Blob.size() - Record[0]);
Guy Benyei11169dd2012-12-18 14:30:41 +00004442 const FileEntry *File = 0;
4443 if (!FullFileName.empty())
4444 File = PP.getFileManager().getFile(FullFileName);
4445
4446 // FIXME: Stable encoding
4447 InclusionDirective::InclusionKind Kind
4448 = static_cast<InclusionDirective::InclusionKind>(Record[2]);
4449 InclusionDirective *ID
4450 = new (PPRec) InclusionDirective(PPRec, Kind,
Chris Lattner0e6c9402013-01-20 02:38:54 +00004451 StringRef(Blob.data(), Record[0]),
Guy Benyei11169dd2012-12-18 14:30:41 +00004452 Record[1], Record[3],
4453 File,
4454 Range);
4455 return ID;
4456 }
4457 }
4458
4459 llvm_unreachable("Invalid PreprocessorDetailRecordTypes");
4460}
4461
4462/// \brief \arg SLocMapI points at a chunk of a module that contains no
4463/// preprocessed entities or the entities it contains are not the ones we are
4464/// looking for. Find the next module that contains entities and return the ID
4465/// of the first entry.
4466PreprocessedEntityID ASTReader::findNextPreprocessedEntity(
4467 GlobalSLocOffsetMapType::const_iterator SLocMapI) const {
4468 ++SLocMapI;
4469 for (GlobalSLocOffsetMapType::const_iterator
4470 EndI = GlobalSLocOffsetMap.end(); SLocMapI != EndI; ++SLocMapI) {
4471 ModuleFile &M = *SLocMapI->second;
4472 if (M.NumPreprocessedEntities)
4473 return M.BasePreprocessedEntityID;
4474 }
4475
4476 return getTotalNumPreprocessedEntities();
4477}
4478
4479namespace {
4480
4481template <unsigned PPEntityOffset::*PPLoc>
4482struct PPEntityComp {
4483 const ASTReader &Reader;
4484 ModuleFile &M;
4485
4486 PPEntityComp(const ASTReader &Reader, ModuleFile &M) : Reader(Reader), M(M) { }
4487
4488 bool operator()(const PPEntityOffset &L, const PPEntityOffset &R) const {
4489 SourceLocation LHS = getLoc(L);
4490 SourceLocation RHS = getLoc(R);
4491 return Reader.getSourceManager().isBeforeInTranslationUnit(LHS, RHS);
4492 }
4493
4494 bool operator()(const PPEntityOffset &L, SourceLocation RHS) const {
4495 SourceLocation LHS = getLoc(L);
4496 return Reader.getSourceManager().isBeforeInTranslationUnit(LHS, RHS);
4497 }
4498
4499 bool operator()(SourceLocation LHS, const PPEntityOffset &R) const {
4500 SourceLocation RHS = getLoc(R);
4501 return Reader.getSourceManager().isBeforeInTranslationUnit(LHS, RHS);
4502 }
4503
4504 SourceLocation getLoc(const PPEntityOffset &PPE) const {
4505 return Reader.ReadSourceLocation(M, PPE.*PPLoc);
4506 }
4507};
4508
4509}
4510
4511/// \brief Returns the first preprocessed entity ID that ends after \arg BLoc.
4512PreprocessedEntityID
4513ASTReader::findBeginPreprocessedEntity(SourceLocation BLoc) const {
4514 if (SourceMgr.isLocalSourceLocation(BLoc))
4515 return getTotalNumPreprocessedEntities();
4516
4517 GlobalSLocOffsetMapType::const_iterator
4518 SLocMapI = GlobalSLocOffsetMap.find(SourceManager::MaxLoadedOffset -
Argyrios Kyrtzidis503c83a2013-03-08 02:32:34 +00004519 BLoc.getOffset() - 1);
Guy Benyei11169dd2012-12-18 14:30:41 +00004520 assert(SLocMapI != GlobalSLocOffsetMap.end() &&
4521 "Corrupted global sloc offset map");
4522
4523 if (SLocMapI->second->NumPreprocessedEntities == 0)
4524 return findNextPreprocessedEntity(SLocMapI);
4525
4526 ModuleFile &M = *SLocMapI->second;
4527 typedef const PPEntityOffset *pp_iterator;
4528 pp_iterator pp_begin = M.PreprocessedEntityOffsets;
4529 pp_iterator pp_end = pp_begin + M.NumPreprocessedEntities;
4530
4531 size_t Count = M.NumPreprocessedEntities;
4532 size_t Half;
4533 pp_iterator First = pp_begin;
4534 pp_iterator PPI;
4535
4536 // Do a binary search manually instead of using std::lower_bound because
4537 // The end locations of entities may be unordered (when a macro expansion
4538 // is inside another macro argument), but for this case it is not important
4539 // whether we get the first macro expansion or its containing macro.
4540 while (Count > 0) {
4541 Half = Count/2;
4542 PPI = First;
4543 std::advance(PPI, Half);
4544 if (SourceMgr.isBeforeInTranslationUnit(ReadSourceLocation(M, PPI->End),
4545 BLoc)){
4546 First = PPI;
4547 ++First;
4548 Count = Count - Half - 1;
4549 } else
4550 Count = Half;
4551 }
4552
4553 if (PPI == pp_end)
4554 return findNextPreprocessedEntity(SLocMapI);
4555
4556 return M.BasePreprocessedEntityID + (PPI - pp_begin);
4557}
4558
4559/// \brief Returns the first preprocessed entity ID that begins after \arg ELoc.
4560PreprocessedEntityID
4561ASTReader::findEndPreprocessedEntity(SourceLocation ELoc) const {
4562 if (SourceMgr.isLocalSourceLocation(ELoc))
4563 return getTotalNumPreprocessedEntities();
4564
4565 GlobalSLocOffsetMapType::const_iterator
4566 SLocMapI = GlobalSLocOffsetMap.find(SourceManager::MaxLoadedOffset -
Argyrios Kyrtzidis503c83a2013-03-08 02:32:34 +00004567 ELoc.getOffset() - 1);
Guy Benyei11169dd2012-12-18 14:30:41 +00004568 assert(SLocMapI != GlobalSLocOffsetMap.end() &&
4569 "Corrupted global sloc offset map");
4570
4571 if (SLocMapI->second->NumPreprocessedEntities == 0)
4572 return findNextPreprocessedEntity(SLocMapI);
4573
4574 ModuleFile &M = *SLocMapI->second;
4575 typedef const PPEntityOffset *pp_iterator;
4576 pp_iterator pp_begin = M.PreprocessedEntityOffsets;
4577 pp_iterator pp_end = pp_begin + M.NumPreprocessedEntities;
4578 pp_iterator PPI =
4579 std::upper_bound(pp_begin, pp_end, ELoc,
4580 PPEntityComp<&PPEntityOffset::Begin>(*this, M));
4581
4582 if (PPI == pp_end)
4583 return findNextPreprocessedEntity(SLocMapI);
4584
4585 return M.BasePreprocessedEntityID + (PPI - pp_begin);
4586}
4587
4588/// \brief Returns a pair of [Begin, End) indices of preallocated
4589/// preprocessed entities that \arg Range encompasses.
4590std::pair<unsigned, unsigned>
4591 ASTReader::findPreprocessedEntitiesInRange(SourceRange Range) {
4592 if (Range.isInvalid())
4593 return std::make_pair(0,0);
4594 assert(!SourceMgr.isBeforeInTranslationUnit(Range.getEnd(),Range.getBegin()));
4595
4596 PreprocessedEntityID BeginID = findBeginPreprocessedEntity(Range.getBegin());
4597 PreprocessedEntityID EndID = findEndPreprocessedEntity(Range.getEnd());
4598 return std::make_pair(BeginID, EndID);
4599}
4600
4601/// \brief Optionally returns true or false if the preallocated preprocessed
4602/// entity with index \arg Index came from file \arg FID.
David Blaikie05785d12013-02-20 22:23:23 +00004603Optional<bool> ASTReader::isPreprocessedEntityInFileID(unsigned Index,
Guy Benyei11169dd2012-12-18 14:30:41 +00004604 FileID FID) {
4605 if (FID.isInvalid())
4606 return false;
4607
4608 std::pair<ModuleFile *, unsigned> PPInfo = getModulePreprocessedEntity(Index);
4609 ModuleFile &M = *PPInfo.first;
4610 unsigned LocalIndex = PPInfo.second;
4611 const PPEntityOffset &PPOffs = M.PreprocessedEntityOffsets[LocalIndex];
4612
4613 SourceLocation Loc = ReadSourceLocation(M, PPOffs.Begin);
4614 if (Loc.isInvalid())
4615 return false;
4616
4617 if (SourceMgr.isInFileID(SourceMgr.getFileLoc(Loc), FID))
4618 return true;
4619 else
4620 return false;
4621}
4622
4623namespace {
4624 /// \brief Visitor used to search for information about a header file.
4625 class HeaderFileInfoVisitor {
Guy Benyei11169dd2012-12-18 14:30:41 +00004626 const FileEntry *FE;
4627
David Blaikie05785d12013-02-20 22:23:23 +00004628 Optional<HeaderFileInfo> HFI;
Guy Benyei11169dd2012-12-18 14:30:41 +00004629
4630 public:
Argyrios Kyrtzidis61a38962013-03-06 18:12:44 +00004631 explicit HeaderFileInfoVisitor(const FileEntry *FE)
4632 : FE(FE) { }
Guy Benyei11169dd2012-12-18 14:30:41 +00004633
4634 static bool visit(ModuleFile &M, void *UserData) {
4635 HeaderFileInfoVisitor *This
4636 = static_cast<HeaderFileInfoVisitor *>(UserData);
4637
Guy Benyei11169dd2012-12-18 14:30:41 +00004638 HeaderFileInfoLookupTable *Table
4639 = static_cast<HeaderFileInfoLookupTable *>(M.HeaderFileInfoTable);
4640 if (!Table)
4641 return false;
4642
4643 // Look in the on-disk hash table for an entry for this file name.
Argyrios Kyrtzidis5c2a3452013-03-06 18:12:47 +00004644 HeaderFileInfoLookupTable::iterator Pos = Table->find(This->FE);
Guy Benyei11169dd2012-12-18 14:30:41 +00004645 if (Pos == Table->end())
4646 return false;
4647
4648 This->HFI = *Pos;
4649 return true;
4650 }
4651
David Blaikie05785d12013-02-20 22:23:23 +00004652 Optional<HeaderFileInfo> getHeaderFileInfo() const { return HFI; }
Guy Benyei11169dd2012-12-18 14:30:41 +00004653 };
4654}
4655
4656HeaderFileInfo ASTReader::GetHeaderFileInfo(const FileEntry *FE) {
Argyrios Kyrtzidis61a38962013-03-06 18:12:44 +00004657 HeaderFileInfoVisitor Visitor(FE);
Guy Benyei11169dd2012-12-18 14:30:41 +00004658 ModuleMgr.visit(&HeaderFileInfoVisitor::visit, &Visitor);
Argyrios Kyrtzidis1054bbf2013-05-08 23:46:55 +00004659 if (Optional<HeaderFileInfo> HFI = Visitor.getHeaderFileInfo())
Guy Benyei11169dd2012-12-18 14:30:41 +00004660 return *HFI;
Guy Benyei11169dd2012-12-18 14:30:41 +00004661
4662 return HeaderFileInfo();
4663}
4664
4665void ASTReader::ReadPragmaDiagnosticMappings(DiagnosticsEngine &Diag) {
4666 // FIXME: Make it work properly with modules.
Dmitri Gribenkof8579502013-01-12 19:30:44 +00004667 SmallVector<DiagnosticsEngine::DiagState *, 32> DiagStates;
Guy Benyei11169dd2012-12-18 14:30:41 +00004668 for (ModuleIterator I = ModuleMgr.begin(), E = ModuleMgr.end(); I != E; ++I) {
4669 ModuleFile &F = *(*I);
4670 unsigned Idx = 0;
4671 DiagStates.clear();
4672 assert(!Diag.DiagStates.empty());
4673 DiagStates.push_back(&Diag.DiagStates.front()); // the command-line one.
4674 while (Idx < F.PragmaDiagMappings.size()) {
4675 SourceLocation Loc = ReadSourceLocation(F, F.PragmaDiagMappings[Idx++]);
4676 unsigned DiagStateID = F.PragmaDiagMappings[Idx++];
4677 if (DiagStateID != 0) {
4678 Diag.DiagStatePoints.push_back(
4679 DiagnosticsEngine::DiagStatePoint(DiagStates[DiagStateID-1],
4680 FullSourceLoc(Loc, SourceMgr)));
4681 continue;
4682 }
4683
4684 assert(DiagStateID == 0);
4685 // A new DiagState was created here.
4686 Diag.DiagStates.push_back(*Diag.GetCurDiagState());
4687 DiagnosticsEngine::DiagState *NewState = &Diag.DiagStates.back();
4688 DiagStates.push_back(NewState);
4689 Diag.DiagStatePoints.push_back(
4690 DiagnosticsEngine::DiagStatePoint(NewState,
4691 FullSourceLoc(Loc, SourceMgr)));
4692 while (1) {
4693 assert(Idx < F.PragmaDiagMappings.size() &&
4694 "Invalid data, didn't find '-1' marking end of diag/map pairs");
4695 if (Idx >= F.PragmaDiagMappings.size()) {
4696 break; // Something is messed up but at least avoid infinite loop in
4697 // release build.
4698 }
4699 unsigned DiagID = F.PragmaDiagMappings[Idx++];
4700 if (DiagID == (unsigned)-1) {
4701 break; // no more diag/map pairs for this location.
4702 }
4703 diag::Mapping Map = (diag::Mapping)F.PragmaDiagMappings[Idx++];
4704 DiagnosticMappingInfo MappingInfo = Diag.makeMappingInfo(Map, Loc);
4705 Diag.GetCurDiagState()->setMappingInfo(DiagID, MappingInfo);
4706 }
4707 }
4708 }
4709}
4710
4711/// \brief Get the correct cursor and offset for loading a type.
4712ASTReader::RecordLocation ASTReader::TypeCursorForIndex(unsigned Index) {
4713 GlobalTypeMapType::iterator I = GlobalTypeMap.find(Index);
4714 assert(I != GlobalTypeMap.end() && "Corrupted global type map");
4715 ModuleFile *M = I->second;
4716 return RecordLocation(M, M->TypeOffsets[Index - M->BaseTypeIndex]);
4717}
4718
4719/// \brief Read and return the type with the given index..
4720///
4721/// The index is the type ID, shifted and minus the number of predefs. This
4722/// routine actually reads the record corresponding to the type at the given
4723/// location. It is a helper routine for GetType, which deals with reading type
4724/// IDs.
4725QualType ASTReader::readTypeRecord(unsigned Index) {
4726 RecordLocation Loc = TypeCursorForIndex(Index);
Chris Lattner7fb3bef2013-01-20 00:56:42 +00004727 BitstreamCursor &DeclsCursor = Loc.F->DeclsCursor;
Guy Benyei11169dd2012-12-18 14:30:41 +00004728
4729 // Keep track of where we are in the stream, then jump back there
4730 // after reading this type.
4731 SavedStreamPosition SavedPosition(DeclsCursor);
4732
4733 ReadingKindTracker ReadingKind(Read_Type, *this);
4734
4735 // Note that we are loading a type record.
4736 Deserializing AType(this);
4737
4738 unsigned Idx = 0;
4739 DeclsCursor.JumpToBit(Loc.Offset);
4740 RecordData Record;
4741 unsigned Code = DeclsCursor.ReadCode();
Chris Lattner0e6c9402013-01-20 02:38:54 +00004742 switch ((TypeCode)DeclsCursor.readRecord(Code, Record)) {
Guy Benyei11169dd2012-12-18 14:30:41 +00004743 case TYPE_EXT_QUAL: {
4744 if (Record.size() != 2) {
4745 Error("Incorrect encoding of extended qualifier type");
4746 return QualType();
4747 }
4748 QualType Base = readType(*Loc.F, Record, Idx);
4749 Qualifiers Quals = Qualifiers::fromOpaqueValue(Record[Idx++]);
4750 return Context.getQualifiedType(Base, Quals);
4751 }
4752
4753 case TYPE_COMPLEX: {
4754 if (Record.size() != 1) {
4755 Error("Incorrect encoding of complex type");
4756 return QualType();
4757 }
4758 QualType ElemType = readType(*Loc.F, Record, Idx);
4759 return Context.getComplexType(ElemType);
4760 }
4761
4762 case TYPE_POINTER: {
4763 if (Record.size() != 1) {
4764 Error("Incorrect encoding of pointer type");
4765 return QualType();
4766 }
4767 QualType PointeeType = readType(*Loc.F, Record, Idx);
4768 return Context.getPointerType(PointeeType);
4769 }
4770
Reid Kleckner8a365022013-06-24 17:51:48 +00004771 case TYPE_DECAYED: {
4772 if (Record.size() != 1) {
4773 Error("Incorrect encoding of decayed type");
4774 return QualType();
4775 }
4776 QualType OriginalType = readType(*Loc.F, Record, Idx);
4777 QualType DT = Context.getAdjustedParameterType(OriginalType);
4778 if (!isa<DecayedType>(DT))
4779 Error("Decayed type does not decay");
4780 return DT;
4781 }
4782
Reid Kleckner0503a872013-12-05 01:23:43 +00004783 case TYPE_ADJUSTED: {
4784 if (Record.size() != 2) {
4785 Error("Incorrect encoding of adjusted type");
4786 return QualType();
4787 }
4788 QualType OriginalTy = readType(*Loc.F, Record, Idx);
4789 QualType AdjustedTy = readType(*Loc.F, Record, Idx);
4790 return Context.getAdjustedType(OriginalTy, AdjustedTy);
4791 }
4792
Guy Benyei11169dd2012-12-18 14:30:41 +00004793 case TYPE_BLOCK_POINTER: {
4794 if (Record.size() != 1) {
4795 Error("Incorrect encoding of block pointer type");
4796 return QualType();
4797 }
4798 QualType PointeeType = readType(*Loc.F, Record, Idx);
4799 return Context.getBlockPointerType(PointeeType);
4800 }
4801
4802 case TYPE_LVALUE_REFERENCE: {
4803 if (Record.size() != 2) {
4804 Error("Incorrect encoding of lvalue reference type");
4805 return QualType();
4806 }
4807 QualType PointeeType = readType(*Loc.F, Record, Idx);
4808 return Context.getLValueReferenceType(PointeeType, Record[1]);
4809 }
4810
4811 case TYPE_RVALUE_REFERENCE: {
4812 if (Record.size() != 1) {
4813 Error("Incorrect encoding of rvalue reference type");
4814 return QualType();
4815 }
4816 QualType PointeeType = readType(*Loc.F, Record, Idx);
4817 return Context.getRValueReferenceType(PointeeType);
4818 }
4819
4820 case TYPE_MEMBER_POINTER: {
4821 if (Record.size() != 2) {
4822 Error("Incorrect encoding of member pointer type");
4823 return QualType();
4824 }
4825 QualType PointeeType = readType(*Loc.F, Record, Idx);
4826 QualType ClassType = readType(*Loc.F, Record, Idx);
4827 if (PointeeType.isNull() || ClassType.isNull())
4828 return QualType();
4829
4830 return Context.getMemberPointerType(PointeeType, ClassType.getTypePtr());
4831 }
4832
4833 case TYPE_CONSTANT_ARRAY: {
4834 QualType ElementType = readType(*Loc.F, Record, Idx);
4835 ArrayType::ArraySizeModifier ASM = (ArrayType::ArraySizeModifier)Record[1];
4836 unsigned IndexTypeQuals = Record[2];
4837 unsigned Idx = 3;
4838 llvm::APInt Size = ReadAPInt(Record, Idx);
4839 return Context.getConstantArrayType(ElementType, Size,
4840 ASM, IndexTypeQuals);
4841 }
4842
4843 case TYPE_INCOMPLETE_ARRAY: {
4844 QualType ElementType = readType(*Loc.F, Record, Idx);
4845 ArrayType::ArraySizeModifier ASM = (ArrayType::ArraySizeModifier)Record[1];
4846 unsigned IndexTypeQuals = Record[2];
4847 return Context.getIncompleteArrayType(ElementType, ASM, IndexTypeQuals);
4848 }
4849
4850 case TYPE_VARIABLE_ARRAY: {
4851 QualType ElementType = readType(*Loc.F, Record, Idx);
4852 ArrayType::ArraySizeModifier ASM = (ArrayType::ArraySizeModifier)Record[1];
4853 unsigned IndexTypeQuals = Record[2];
4854 SourceLocation LBLoc = ReadSourceLocation(*Loc.F, Record[3]);
4855 SourceLocation RBLoc = ReadSourceLocation(*Loc.F, Record[4]);
4856 return Context.getVariableArrayType(ElementType, ReadExpr(*Loc.F),
4857 ASM, IndexTypeQuals,
4858 SourceRange(LBLoc, RBLoc));
4859 }
4860
4861 case TYPE_VECTOR: {
4862 if (Record.size() != 3) {
4863 Error("incorrect encoding of vector type in AST file");
4864 return QualType();
4865 }
4866
4867 QualType ElementType = readType(*Loc.F, Record, Idx);
4868 unsigned NumElements = Record[1];
4869 unsigned VecKind = Record[2];
4870 return Context.getVectorType(ElementType, NumElements,
4871 (VectorType::VectorKind)VecKind);
4872 }
4873
4874 case TYPE_EXT_VECTOR: {
4875 if (Record.size() != 3) {
4876 Error("incorrect encoding of extended vector type in AST file");
4877 return QualType();
4878 }
4879
4880 QualType ElementType = readType(*Loc.F, Record, Idx);
4881 unsigned NumElements = Record[1];
4882 return Context.getExtVectorType(ElementType, NumElements);
4883 }
4884
4885 case TYPE_FUNCTION_NO_PROTO: {
4886 if (Record.size() != 6) {
4887 Error("incorrect encoding of no-proto function type");
4888 return QualType();
4889 }
4890 QualType ResultType = readType(*Loc.F, Record, Idx);
4891 FunctionType::ExtInfo Info(Record[1], Record[2], Record[3],
4892 (CallingConv)Record[4], Record[5]);
4893 return Context.getFunctionNoProtoType(ResultType, Info);
4894 }
4895
4896 case TYPE_FUNCTION_PROTO: {
4897 QualType ResultType = readType(*Loc.F, Record, Idx);
4898
4899 FunctionProtoType::ExtProtoInfo EPI;
4900 EPI.ExtInfo = FunctionType::ExtInfo(/*noreturn*/ Record[1],
4901 /*hasregparm*/ Record[2],
4902 /*regparm*/ Record[3],
4903 static_cast<CallingConv>(Record[4]),
4904 /*produces*/ Record[5]);
4905
4906 unsigned Idx = 6;
4907 unsigned NumParams = Record[Idx++];
4908 SmallVector<QualType, 16> ParamTypes;
4909 for (unsigned I = 0; I != NumParams; ++I)
4910 ParamTypes.push_back(readType(*Loc.F, Record, Idx));
4911
4912 EPI.Variadic = Record[Idx++];
4913 EPI.HasTrailingReturn = Record[Idx++];
4914 EPI.TypeQuals = Record[Idx++];
4915 EPI.RefQualifier = static_cast<RefQualifierKind>(Record[Idx++]);
4916 ExceptionSpecificationType EST =
4917 static_cast<ExceptionSpecificationType>(Record[Idx++]);
4918 EPI.ExceptionSpecType = EST;
4919 SmallVector<QualType, 2> Exceptions;
4920 if (EST == EST_Dynamic) {
4921 EPI.NumExceptions = Record[Idx++];
4922 for (unsigned I = 0; I != EPI.NumExceptions; ++I)
4923 Exceptions.push_back(readType(*Loc.F, Record, Idx));
4924 EPI.Exceptions = Exceptions.data();
4925 } else if (EST == EST_ComputedNoexcept) {
4926 EPI.NoexceptExpr = ReadExpr(*Loc.F);
4927 } else if (EST == EST_Uninstantiated) {
4928 EPI.ExceptionSpecDecl = ReadDeclAs<FunctionDecl>(*Loc.F, Record, Idx);
4929 EPI.ExceptionSpecTemplate = ReadDeclAs<FunctionDecl>(*Loc.F, Record, Idx);
4930 } else if (EST == EST_Unevaluated) {
4931 EPI.ExceptionSpecDecl = ReadDeclAs<FunctionDecl>(*Loc.F, Record, Idx);
4932 }
Jordan Rose5c382722013-03-08 21:51:21 +00004933 return Context.getFunctionType(ResultType, ParamTypes, EPI);
Guy Benyei11169dd2012-12-18 14:30:41 +00004934 }
4935
4936 case TYPE_UNRESOLVED_USING: {
4937 unsigned Idx = 0;
4938 return Context.getTypeDeclType(
4939 ReadDeclAs<UnresolvedUsingTypenameDecl>(*Loc.F, Record, Idx));
4940 }
4941
4942 case TYPE_TYPEDEF: {
4943 if (Record.size() != 2) {
4944 Error("incorrect encoding of typedef type");
4945 return QualType();
4946 }
4947 unsigned Idx = 0;
4948 TypedefNameDecl *Decl = ReadDeclAs<TypedefNameDecl>(*Loc.F, Record, Idx);
4949 QualType Canonical = readType(*Loc.F, Record, Idx);
4950 if (!Canonical.isNull())
4951 Canonical = Context.getCanonicalType(Canonical);
4952 return Context.getTypedefType(Decl, Canonical);
4953 }
4954
4955 case TYPE_TYPEOF_EXPR:
4956 return Context.getTypeOfExprType(ReadExpr(*Loc.F));
4957
4958 case TYPE_TYPEOF: {
4959 if (Record.size() != 1) {
4960 Error("incorrect encoding of typeof(type) in AST file");
4961 return QualType();
4962 }
4963 QualType UnderlyingType = readType(*Loc.F, Record, Idx);
4964 return Context.getTypeOfType(UnderlyingType);
4965 }
4966
4967 case TYPE_DECLTYPE: {
4968 QualType UnderlyingType = readType(*Loc.F, Record, Idx);
4969 return Context.getDecltypeType(ReadExpr(*Loc.F), UnderlyingType);
4970 }
4971
4972 case TYPE_UNARY_TRANSFORM: {
4973 QualType BaseType = readType(*Loc.F, Record, Idx);
4974 QualType UnderlyingType = readType(*Loc.F, Record, Idx);
4975 UnaryTransformType::UTTKind UKind = (UnaryTransformType::UTTKind)Record[2];
4976 return Context.getUnaryTransformType(BaseType, UnderlyingType, UKind);
4977 }
4978
Richard Smith74aeef52013-04-26 16:15:35 +00004979 case TYPE_AUTO: {
4980 QualType Deduced = readType(*Loc.F, Record, Idx);
4981 bool IsDecltypeAuto = Record[Idx++];
Richard Smith27d807c2013-04-30 13:56:41 +00004982 bool IsDependent = Deduced.isNull() ? Record[Idx++] : false;
Manuel Klimek2fdbea22013-08-22 12:12:24 +00004983 return Context.getAutoType(Deduced, IsDecltypeAuto, IsDependent);
Richard Smith74aeef52013-04-26 16:15:35 +00004984 }
Guy Benyei11169dd2012-12-18 14:30:41 +00004985
4986 case TYPE_RECORD: {
4987 if (Record.size() != 2) {
4988 Error("incorrect encoding of record type");
4989 return QualType();
4990 }
4991 unsigned Idx = 0;
4992 bool IsDependent = Record[Idx++];
4993 RecordDecl *RD = ReadDeclAs<RecordDecl>(*Loc.F, Record, Idx);
4994 RD = cast_or_null<RecordDecl>(RD->getCanonicalDecl());
4995 QualType T = Context.getRecordType(RD);
4996 const_cast<Type*>(T.getTypePtr())->setDependent(IsDependent);
4997 return T;
4998 }
4999
5000 case TYPE_ENUM: {
5001 if (Record.size() != 2) {
5002 Error("incorrect encoding of enum type");
5003 return QualType();
5004 }
5005 unsigned Idx = 0;
5006 bool IsDependent = Record[Idx++];
5007 QualType T
5008 = Context.getEnumType(ReadDeclAs<EnumDecl>(*Loc.F, Record, Idx));
5009 const_cast<Type*>(T.getTypePtr())->setDependent(IsDependent);
5010 return T;
5011 }
5012
5013 case TYPE_ATTRIBUTED: {
5014 if (Record.size() != 3) {
5015 Error("incorrect encoding of attributed type");
5016 return QualType();
5017 }
5018 QualType modifiedType = readType(*Loc.F, Record, Idx);
5019 QualType equivalentType = readType(*Loc.F, Record, Idx);
5020 AttributedType::Kind kind = static_cast<AttributedType::Kind>(Record[2]);
5021 return Context.getAttributedType(kind, modifiedType, equivalentType);
5022 }
5023
5024 case TYPE_PAREN: {
5025 if (Record.size() != 1) {
5026 Error("incorrect encoding of paren type");
5027 return QualType();
5028 }
5029 QualType InnerType = readType(*Loc.F, Record, Idx);
5030 return Context.getParenType(InnerType);
5031 }
5032
5033 case TYPE_PACK_EXPANSION: {
5034 if (Record.size() != 2) {
5035 Error("incorrect encoding of pack expansion type");
5036 return QualType();
5037 }
5038 QualType Pattern = readType(*Loc.F, Record, Idx);
5039 if (Pattern.isNull())
5040 return QualType();
David Blaikie05785d12013-02-20 22:23:23 +00005041 Optional<unsigned> NumExpansions;
Guy Benyei11169dd2012-12-18 14:30:41 +00005042 if (Record[1])
5043 NumExpansions = Record[1] - 1;
5044 return Context.getPackExpansionType(Pattern, NumExpansions);
5045 }
5046
5047 case TYPE_ELABORATED: {
5048 unsigned Idx = 0;
5049 ElaboratedTypeKeyword Keyword = (ElaboratedTypeKeyword)Record[Idx++];
5050 NestedNameSpecifier *NNS = ReadNestedNameSpecifier(*Loc.F, Record, Idx);
5051 QualType NamedType = readType(*Loc.F, Record, Idx);
5052 return Context.getElaboratedType(Keyword, NNS, NamedType);
5053 }
5054
5055 case TYPE_OBJC_INTERFACE: {
5056 unsigned Idx = 0;
5057 ObjCInterfaceDecl *ItfD
5058 = ReadDeclAs<ObjCInterfaceDecl>(*Loc.F, Record, Idx);
5059 return Context.getObjCInterfaceType(ItfD->getCanonicalDecl());
5060 }
5061
5062 case TYPE_OBJC_OBJECT: {
5063 unsigned Idx = 0;
5064 QualType Base = readType(*Loc.F, Record, Idx);
5065 unsigned NumProtos = Record[Idx++];
5066 SmallVector<ObjCProtocolDecl*, 4> Protos;
5067 for (unsigned I = 0; I != NumProtos; ++I)
5068 Protos.push_back(ReadDeclAs<ObjCProtocolDecl>(*Loc.F, Record, Idx));
5069 return Context.getObjCObjectType(Base, Protos.data(), NumProtos);
5070 }
5071
5072 case TYPE_OBJC_OBJECT_POINTER: {
5073 unsigned Idx = 0;
5074 QualType Pointee = readType(*Loc.F, Record, Idx);
5075 return Context.getObjCObjectPointerType(Pointee);
5076 }
5077
5078 case TYPE_SUBST_TEMPLATE_TYPE_PARM: {
5079 unsigned Idx = 0;
5080 QualType Parm = readType(*Loc.F, Record, Idx);
5081 QualType Replacement = readType(*Loc.F, Record, Idx);
5082 return
5083 Context.getSubstTemplateTypeParmType(cast<TemplateTypeParmType>(Parm),
5084 Replacement);
5085 }
5086
5087 case TYPE_SUBST_TEMPLATE_TYPE_PARM_PACK: {
5088 unsigned Idx = 0;
5089 QualType Parm = readType(*Loc.F, Record, Idx);
5090 TemplateArgument ArgPack = ReadTemplateArgument(*Loc.F, Record, Idx);
5091 return Context.getSubstTemplateTypeParmPackType(
5092 cast<TemplateTypeParmType>(Parm),
5093 ArgPack);
5094 }
5095
5096 case TYPE_INJECTED_CLASS_NAME: {
5097 CXXRecordDecl *D = ReadDeclAs<CXXRecordDecl>(*Loc.F, Record, Idx);
5098 QualType TST = readType(*Loc.F, Record, Idx); // probably derivable
5099 // FIXME: ASTContext::getInjectedClassNameType is not currently suitable
5100 // for AST reading, too much interdependencies.
5101 return
5102 QualType(new (Context, TypeAlignment) InjectedClassNameType(D, TST), 0);
5103 }
5104
5105 case TYPE_TEMPLATE_TYPE_PARM: {
5106 unsigned Idx = 0;
5107 unsigned Depth = Record[Idx++];
5108 unsigned Index = Record[Idx++];
5109 bool Pack = Record[Idx++];
5110 TemplateTypeParmDecl *D
5111 = ReadDeclAs<TemplateTypeParmDecl>(*Loc.F, Record, Idx);
5112 return Context.getTemplateTypeParmType(Depth, Index, Pack, D);
5113 }
5114
5115 case TYPE_DEPENDENT_NAME: {
5116 unsigned Idx = 0;
5117 ElaboratedTypeKeyword Keyword = (ElaboratedTypeKeyword)Record[Idx++];
5118 NestedNameSpecifier *NNS = ReadNestedNameSpecifier(*Loc.F, Record, Idx);
5119 const IdentifierInfo *Name = this->GetIdentifierInfo(*Loc.F, Record, Idx);
5120 QualType Canon = readType(*Loc.F, Record, Idx);
5121 if (!Canon.isNull())
5122 Canon = Context.getCanonicalType(Canon);
5123 return Context.getDependentNameType(Keyword, NNS, Name, Canon);
5124 }
5125
5126 case TYPE_DEPENDENT_TEMPLATE_SPECIALIZATION: {
5127 unsigned Idx = 0;
5128 ElaboratedTypeKeyword Keyword = (ElaboratedTypeKeyword)Record[Idx++];
5129 NestedNameSpecifier *NNS = ReadNestedNameSpecifier(*Loc.F, Record, Idx);
5130 const IdentifierInfo *Name = this->GetIdentifierInfo(*Loc.F, Record, Idx);
5131 unsigned NumArgs = Record[Idx++];
5132 SmallVector<TemplateArgument, 8> Args;
5133 Args.reserve(NumArgs);
5134 while (NumArgs--)
5135 Args.push_back(ReadTemplateArgument(*Loc.F, Record, Idx));
5136 return Context.getDependentTemplateSpecializationType(Keyword, NNS, Name,
5137 Args.size(), Args.data());
5138 }
5139
5140 case TYPE_DEPENDENT_SIZED_ARRAY: {
5141 unsigned Idx = 0;
5142
5143 // ArrayType
5144 QualType ElementType = readType(*Loc.F, Record, Idx);
5145 ArrayType::ArraySizeModifier ASM
5146 = (ArrayType::ArraySizeModifier)Record[Idx++];
5147 unsigned IndexTypeQuals = Record[Idx++];
5148
5149 // DependentSizedArrayType
5150 Expr *NumElts = ReadExpr(*Loc.F);
5151 SourceRange Brackets = ReadSourceRange(*Loc.F, Record, Idx);
5152
5153 return Context.getDependentSizedArrayType(ElementType, NumElts, ASM,
5154 IndexTypeQuals, Brackets);
5155 }
5156
5157 case TYPE_TEMPLATE_SPECIALIZATION: {
5158 unsigned Idx = 0;
5159 bool IsDependent = Record[Idx++];
5160 TemplateName Name = ReadTemplateName(*Loc.F, Record, Idx);
5161 SmallVector<TemplateArgument, 8> Args;
5162 ReadTemplateArgumentList(Args, *Loc.F, Record, Idx);
5163 QualType Underlying = readType(*Loc.F, Record, Idx);
5164 QualType T;
5165 if (Underlying.isNull())
5166 T = Context.getCanonicalTemplateSpecializationType(Name, Args.data(),
5167 Args.size());
5168 else
5169 T = Context.getTemplateSpecializationType(Name, Args.data(),
5170 Args.size(), Underlying);
5171 const_cast<Type*>(T.getTypePtr())->setDependent(IsDependent);
5172 return T;
5173 }
5174
5175 case TYPE_ATOMIC: {
5176 if (Record.size() != 1) {
5177 Error("Incorrect encoding of atomic type");
5178 return QualType();
5179 }
5180 QualType ValueType = readType(*Loc.F, Record, Idx);
5181 return Context.getAtomicType(ValueType);
5182 }
5183 }
5184 llvm_unreachable("Invalid TypeCode!");
5185}
5186
5187class clang::TypeLocReader : public TypeLocVisitor<TypeLocReader> {
5188 ASTReader &Reader;
5189 ModuleFile &F;
5190 const ASTReader::RecordData &Record;
5191 unsigned &Idx;
5192
5193 SourceLocation ReadSourceLocation(const ASTReader::RecordData &R,
5194 unsigned &I) {
5195 return Reader.ReadSourceLocation(F, R, I);
5196 }
5197
5198 template<typename T>
5199 T *ReadDeclAs(const ASTReader::RecordData &Record, unsigned &Idx) {
5200 return Reader.ReadDeclAs<T>(F, Record, Idx);
5201 }
5202
5203public:
5204 TypeLocReader(ASTReader &Reader, ModuleFile &F,
5205 const ASTReader::RecordData &Record, unsigned &Idx)
5206 : Reader(Reader), F(F), Record(Record), Idx(Idx)
5207 { }
5208
5209 // We want compile-time assurance that we've enumerated all of
5210 // these, so unfortunately we have to declare them first, then
5211 // define them out-of-line.
5212#define ABSTRACT_TYPELOC(CLASS, PARENT)
5213#define TYPELOC(CLASS, PARENT) \
5214 void Visit##CLASS##TypeLoc(CLASS##TypeLoc TyLoc);
5215#include "clang/AST/TypeLocNodes.def"
5216
5217 void VisitFunctionTypeLoc(FunctionTypeLoc);
5218 void VisitArrayTypeLoc(ArrayTypeLoc);
5219};
5220
5221void TypeLocReader::VisitQualifiedTypeLoc(QualifiedTypeLoc TL) {
5222 // nothing to do
5223}
5224void TypeLocReader::VisitBuiltinTypeLoc(BuiltinTypeLoc TL) {
5225 TL.setBuiltinLoc(ReadSourceLocation(Record, Idx));
5226 if (TL.needsExtraLocalData()) {
5227 TL.setWrittenTypeSpec(static_cast<DeclSpec::TST>(Record[Idx++]));
5228 TL.setWrittenSignSpec(static_cast<DeclSpec::TSS>(Record[Idx++]));
5229 TL.setWrittenWidthSpec(static_cast<DeclSpec::TSW>(Record[Idx++]));
5230 TL.setModeAttr(Record[Idx++]);
5231 }
5232}
5233void TypeLocReader::VisitComplexTypeLoc(ComplexTypeLoc TL) {
5234 TL.setNameLoc(ReadSourceLocation(Record, Idx));
5235}
5236void TypeLocReader::VisitPointerTypeLoc(PointerTypeLoc TL) {
5237 TL.setStarLoc(ReadSourceLocation(Record, Idx));
5238}
Reid Kleckner8a365022013-06-24 17:51:48 +00005239void TypeLocReader::VisitDecayedTypeLoc(DecayedTypeLoc TL) {
5240 // nothing to do
5241}
Reid Kleckner0503a872013-12-05 01:23:43 +00005242void TypeLocReader::VisitAdjustedTypeLoc(AdjustedTypeLoc TL) {
5243 // nothing to do
5244}
Guy Benyei11169dd2012-12-18 14:30:41 +00005245void TypeLocReader::VisitBlockPointerTypeLoc(BlockPointerTypeLoc TL) {
5246 TL.setCaretLoc(ReadSourceLocation(Record, Idx));
5247}
5248void TypeLocReader::VisitLValueReferenceTypeLoc(LValueReferenceTypeLoc TL) {
5249 TL.setAmpLoc(ReadSourceLocation(Record, Idx));
5250}
5251void TypeLocReader::VisitRValueReferenceTypeLoc(RValueReferenceTypeLoc TL) {
5252 TL.setAmpAmpLoc(ReadSourceLocation(Record, Idx));
5253}
5254void TypeLocReader::VisitMemberPointerTypeLoc(MemberPointerTypeLoc TL) {
5255 TL.setStarLoc(ReadSourceLocation(Record, Idx));
5256 TL.setClassTInfo(Reader.GetTypeSourceInfo(F, Record, Idx));
5257}
5258void TypeLocReader::VisitArrayTypeLoc(ArrayTypeLoc TL) {
5259 TL.setLBracketLoc(ReadSourceLocation(Record, Idx));
5260 TL.setRBracketLoc(ReadSourceLocation(Record, Idx));
5261 if (Record[Idx++])
5262 TL.setSizeExpr(Reader.ReadExpr(F));
5263 else
5264 TL.setSizeExpr(0);
5265}
5266void TypeLocReader::VisitConstantArrayTypeLoc(ConstantArrayTypeLoc TL) {
5267 VisitArrayTypeLoc(TL);
5268}
5269void TypeLocReader::VisitIncompleteArrayTypeLoc(IncompleteArrayTypeLoc TL) {
5270 VisitArrayTypeLoc(TL);
5271}
5272void TypeLocReader::VisitVariableArrayTypeLoc(VariableArrayTypeLoc TL) {
5273 VisitArrayTypeLoc(TL);
5274}
5275void TypeLocReader::VisitDependentSizedArrayTypeLoc(
5276 DependentSizedArrayTypeLoc TL) {
5277 VisitArrayTypeLoc(TL);
5278}
5279void TypeLocReader::VisitDependentSizedExtVectorTypeLoc(
5280 DependentSizedExtVectorTypeLoc TL) {
5281 TL.setNameLoc(ReadSourceLocation(Record, Idx));
5282}
5283void TypeLocReader::VisitVectorTypeLoc(VectorTypeLoc TL) {
5284 TL.setNameLoc(ReadSourceLocation(Record, Idx));
5285}
5286void TypeLocReader::VisitExtVectorTypeLoc(ExtVectorTypeLoc TL) {
5287 TL.setNameLoc(ReadSourceLocation(Record, Idx));
5288}
5289void TypeLocReader::VisitFunctionTypeLoc(FunctionTypeLoc TL) {
5290 TL.setLocalRangeBegin(ReadSourceLocation(Record, Idx));
5291 TL.setLParenLoc(ReadSourceLocation(Record, Idx));
5292 TL.setRParenLoc(ReadSourceLocation(Record, Idx));
5293 TL.setLocalRangeEnd(ReadSourceLocation(Record, Idx));
Alp Tokerb3fd5cf2014-01-21 00:32:38 +00005294 for (unsigned i = 0, e = TL.getNumParams(); i != e; ++i) {
5295 TL.setParam(i, ReadDeclAs<ParmVarDecl>(Record, Idx));
Guy Benyei11169dd2012-12-18 14:30:41 +00005296 }
5297}
5298void TypeLocReader::VisitFunctionProtoTypeLoc(FunctionProtoTypeLoc TL) {
5299 VisitFunctionTypeLoc(TL);
5300}
5301void TypeLocReader::VisitFunctionNoProtoTypeLoc(FunctionNoProtoTypeLoc TL) {
5302 VisitFunctionTypeLoc(TL);
5303}
5304void TypeLocReader::VisitUnresolvedUsingTypeLoc(UnresolvedUsingTypeLoc TL) {
5305 TL.setNameLoc(ReadSourceLocation(Record, Idx));
5306}
5307void TypeLocReader::VisitTypedefTypeLoc(TypedefTypeLoc TL) {
5308 TL.setNameLoc(ReadSourceLocation(Record, Idx));
5309}
5310void TypeLocReader::VisitTypeOfExprTypeLoc(TypeOfExprTypeLoc TL) {
5311 TL.setTypeofLoc(ReadSourceLocation(Record, Idx));
5312 TL.setLParenLoc(ReadSourceLocation(Record, Idx));
5313 TL.setRParenLoc(ReadSourceLocation(Record, Idx));
5314}
5315void TypeLocReader::VisitTypeOfTypeLoc(TypeOfTypeLoc TL) {
5316 TL.setTypeofLoc(ReadSourceLocation(Record, Idx));
5317 TL.setLParenLoc(ReadSourceLocation(Record, Idx));
5318 TL.setRParenLoc(ReadSourceLocation(Record, Idx));
5319 TL.setUnderlyingTInfo(Reader.GetTypeSourceInfo(F, Record, Idx));
5320}
5321void TypeLocReader::VisitDecltypeTypeLoc(DecltypeTypeLoc TL) {
5322 TL.setNameLoc(ReadSourceLocation(Record, Idx));
5323}
5324void TypeLocReader::VisitUnaryTransformTypeLoc(UnaryTransformTypeLoc TL) {
5325 TL.setKWLoc(ReadSourceLocation(Record, Idx));
5326 TL.setLParenLoc(ReadSourceLocation(Record, Idx));
5327 TL.setRParenLoc(ReadSourceLocation(Record, Idx));
5328 TL.setUnderlyingTInfo(Reader.GetTypeSourceInfo(F, Record, Idx));
5329}
5330void TypeLocReader::VisitAutoTypeLoc(AutoTypeLoc TL) {
5331 TL.setNameLoc(ReadSourceLocation(Record, Idx));
5332}
5333void TypeLocReader::VisitRecordTypeLoc(RecordTypeLoc TL) {
5334 TL.setNameLoc(ReadSourceLocation(Record, Idx));
5335}
5336void TypeLocReader::VisitEnumTypeLoc(EnumTypeLoc TL) {
5337 TL.setNameLoc(ReadSourceLocation(Record, Idx));
5338}
5339void TypeLocReader::VisitAttributedTypeLoc(AttributedTypeLoc TL) {
5340 TL.setAttrNameLoc(ReadSourceLocation(Record, Idx));
5341 if (TL.hasAttrOperand()) {
5342 SourceRange range;
5343 range.setBegin(ReadSourceLocation(Record, Idx));
5344 range.setEnd(ReadSourceLocation(Record, Idx));
5345 TL.setAttrOperandParensRange(range);
5346 }
5347 if (TL.hasAttrExprOperand()) {
5348 if (Record[Idx++])
5349 TL.setAttrExprOperand(Reader.ReadExpr(F));
5350 else
5351 TL.setAttrExprOperand(0);
5352 } else if (TL.hasAttrEnumOperand())
5353 TL.setAttrEnumOperandLoc(ReadSourceLocation(Record, Idx));
5354}
5355void TypeLocReader::VisitTemplateTypeParmTypeLoc(TemplateTypeParmTypeLoc TL) {
5356 TL.setNameLoc(ReadSourceLocation(Record, Idx));
5357}
5358void TypeLocReader::VisitSubstTemplateTypeParmTypeLoc(
5359 SubstTemplateTypeParmTypeLoc TL) {
5360 TL.setNameLoc(ReadSourceLocation(Record, Idx));
5361}
5362void TypeLocReader::VisitSubstTemplateTypeParmPackTypeLoc(
5363 SubstTemplateTypeParmPackTypeLoc TL) {
5364 TL.setNameLoc(ReadSourceLocation(Record, Idx));
5365}
5366void TypeLocReader::VisitTemplateSpecializationTypeLoc(
5367 TemplateSpecializationTypeLoc TL) {
5368 TL.setTemplateKeywordLoc(ReadSourceLocation(Record, Idx));
5369 TL.setTemplateNameLoc(ReadSourceLocation(Record, Idx));
5370 TL.setLAngleLoc(ReadSourceLocation(Record, Idx));
5371 TL.setRAngleLoc(ReadSourceLocation(Record, Idx));
5372 for (unsigned i = 0, e = TL.getNumArgs(); i != e; ++i)
5373 TL.setArgLocInfo(i,
5374 Reader.GetTemplateArgumentLocInfo(F,
5375 TL.getTypePtr()->getArg(i).getKind(),
5376 Record, Idx));
5377}
5378void TypeLocReader::VisitParenTypeLoc(ParenTypeLoc TL) {
5379 TL.setLParenLoc(ReadSourceLocation(Record, Idx));
5380 TL.setRParenLoc(ReadSourceLocation(Record, Idx));
5381}
5382void TypeLocReader::VisitElaboratedTypeLoc(ElaboratedTypeLoc TL) {
5383 TL.setElaboratedKeywordLoc(ReadSourceLocation(Record, Idx));
5384 TL.setQualifierLoc(Reader.ReadNestedNameSpecifierLoc(F, Record, Idx));
5385}
5386void TypeLocReader::VisitInjectedClassNameTypeLoc(InjectedClassNameTypeLoc TL) {
5387 TL.setNameLoc(ReadSourceLocation(Record, Idx));
5388}
5389void TypeLocReader::VisitDependentNameTypeLoc(DependentNameTypeLoc TL) {
5390 TL.setElaboratedKeywordLoc(ReadSourceLocation(Record, Idx));
5391 TL.setQualifierLoc(Reader.ReadNestedNameSpecifierLoc(F, Record, Idx));
5392 TL.setNameLoc(ReadSourceLocation(Record, Idx));
5393}
5394void TypeLocReader::VisitDependentTemplateSpecializationTypeLoc(
5395 DependentTemplateSpecializationTypeLoc TL) {
5396 TL.setElaboratedKeywordLoc(ReadSourceLocation(Record, Idx));
5397 TL.setQualifierLoc(Reader.ReadNestedNameSpecifierLoc(F, Record, Idx));
5398 TL.setTemplateKeywordLoc(ReadSourceLocation(Record, Idx));
5399 TL.setTemplateNameLoc(ReadSourceLocation(Record, Idx));
5400 TL.setLAngleLoc(ReadSourceLocation(Record, Idx));
5401 TL.setRAngleLoc(ReadSourceLocation(Record, Idx));
5402 for (unsigned I = 0, E = TL.getNumArgs(); I != E; ++I)
5403 TL.setArgLocInfo(I,
5404 Reader.GetTemplateArgumentLocInfo(F,
5405 TL.getTypePtr()->getArg(I).getKind(),
5406 Record, Idx));
5407}
5408void TypeLocReader::VisitPackExpansionTypeLoc(PackExpansionTypeLoc TL) {
5409 TL.setEllipsisLoc(ReadSourceLocation(Record, Idx));
5410}
5411void TypeLocReader::VisitObjCInterfaceTypeLoc(ObjCInterfaceTypeLoc TL) {
5412 TL.setNameLoc(ReadSourceLocation(Record, Idx));
5413}
5414void TypeLocReader::VisitObjCObjectTypeLoc(ObjCObjectTypeLoc TL) {
5415 TL.setHasBaseTypeAsWritten(Record[Idx++]);
5416 TL.setLAngleLoc(ReadSourceLocation(Record, Idx));
5417 TL.setRAngleLoc(ReadSourceLocation(Record, Idx));
5418 for (unsigned i = 0, e = TL.getNumProtocols(); i != e; ++i)
5419 TL.setProtocolLoc(i, ReadSourceLocation(Record, Idx));
5420}
5421void TypeLocReader::VisitObjCObjectPointerTypeLoc(ObjCObjectPointerTypeLoc TL) {
5422 TL.setStarLoc(ReadSourceLocation(Record, Idx));
5423}
5424void TypeLocReader::VisitAtomicTypeLoc(AtomicTypeLoc TL) {
5425 TL.setKWLoc(ReadSourceLocation(Record, Idx));
5426 TL.setLParenLoc(ReadSourceLocation(Record, Idx));
5427 TL.setRParenLoc(ReadSourceLocation(Record, Idx));
5428}
5429
5430TypeSourceInfo *ASTReader::GetTypeSourceInfo(ModuleFile &F,
5431 const RecordData &Record,
5432 unsigned &Idx) {
5433 QualType InfoTy = readType(F, Record, Idx);
5434 if (InfoTy.isNull())
5435 return 0;
5436
5437 TypeSourceInfo *TInfo = getContext().CreateTypeSourceInfo(InfoTy);
5438 TypeLocReader TLR(*this, F, Record, Idx);
5439 for (TypeLoc TL = TInfo->getTypeLoc(); !TL.isNull(); TL = TL.getNextTypeLoc())
5440 TLR.Visit(TL);
5441 return TInfo;
5442}
5443
5444QualType ASTReader::GetType(TypeID ID) {
5445 unsigned FastQuals = ID & Qualifiers::FastMask;
5446 unsigned Index = ID >> Qualifiers::FastWidth;
5447
5448 if (Index < NUM_PREDEF_TYPE_IDS) {
5449 QualType T;
5450 switch ((PredefinedTypeIDs)Index) {
5451 case PREDEF_TYPE_NULL_ID: return QualType();
5452 case PREDEF_TYPE_VOID_ID: T = Context.VoidTy; break;
5453 case PREDEF_TYPE_BOOL_ID: T = Context.BoolTy; break;
5454
5455 case PREDEF_TYPE_CHAR_U_ID:
5456 case PREDEF_TYPE_CHAR_S_ID:
5457 // FIXME: Check that the signedness of CharTy is correct!
5458 T = Context.CharTy;
5459 break;
5460
5461 case PREDEF_TYPE_UCHAR_ID: T = Context.UnsignedCharTy; break;
5462 case PREDEF_TYPE_USHORT_ID: T = Context.UnsignedShortTy; break;
5463 case PREDEF_TYPE_UINT_ID: T = Context.UnsignedIntTy; break;
5464 case PREDEF_TYPE_ULONG_ID: T = Context.UnsignedLongTy; break;
5465 case PREDEF_TYPE_ULONGLONG_ID: T = Context.UnsignedLongLongTy; break;
5466 case PREDEF_TYPE_UINT128_ID: T = Context.UnsignedInt128Ty; break;
5467 case PREDEF_TYPE_SCHAR_ID: T = Context.SignedCharTy; break;
5468 case PREDEF_TYPE_WCHAR_ID: T = Context.WCharTy; break;
5469 case PREDEF_TYPE_SHORT_ID: T = Context.ShortTy; break;
5470 case PREDEF_TYPE_INT_ID: T = Context.IntTy; break;
5471 case PREDEF_TYPE_LONG_ID: T = Context.LongTy; break;
5472 case PREDEF_TYPE_LONGLONG_ID: T = Context.LongLongTy; break;
5473 case PREDEF_TYPE_INT128_ID: T = Context.Int128Ty; break;
5474 case PREDEF_TYPE_HALF_ID: T = Context.HalfTy; break;
5475 case PREDEF_TYPE_FLOAT_ID: T = Context.FloatTy; break;
5476 case PREDEF_TYPE_DOUBLE_ID: T = Context.DoubleTy; break;
5477 case PREDEF_TYPE_LONGDOUBLE_ID: T = Context.LongDoubleTy; break;
5478 case PREDEF_TYPE_OVERLOAD_ID: T = Context.OverloadTy; break;
5479 case PREDEF_TYPE_BOUND_MEMBER: T = Context.BoundMemberTy; break;
5480 case PREDEF_TYPE_PSEUDO_OBJECT: T = Context.PseudoObjectTy; break;
5481 case PREDEF_TYPE_DEPENDENT_ID: T = Context.DependentTy; break;
5482 case PREDEF_TYPE_UNKNOWN_ANY: T = Context.UnknownAnyTy; break;
5483 case PREDEF_TYPE_NULLPTR_ID: T = Context.NullPtrTy; break;
5484 case PREDEF_TYPE_CHAR16_ID: T = Context.Char16Ty; break;
5485 case PREDEF_TYPE_CHAR32_ID: T = Context.Char32Ty; break;
5486 case PREDEF_TYPE_OBJC_ID: T = Context.ObjCBuiltinIdTy; break;
5487 case PREDEF_TYPE_OBJC_CLASS: T = Context.ObjCBuiltinClassTy; break;
5488 case PREDEF_TYPE_OBJC_SEL: T = Context.ObjCBuiltinSelTy; break;
Guy Benyeid8a08ea2012-12-18 14:38:23 +00005489 case PREDEF_TYPE_IMAGE1D_ID: T = Context.OCLImage1dTy; break;
5490 case PREDEF_TYPE_IMAGE1D_ARR_ID: T = Context.OCLImage1dArrayTy; break;
5491 case PREDEF_TYPE_IMAGE1D_BUFF_ID: T = Context.OCLImage1dBufferTy; break;
5492 case PREDEF_TYPE_IMAGE2D_ID: T = Context.OCLImage2dTy; break;
5493 case PREDEF_TYPE_IMAGE2D_ARR_ID: T = Context.OCLImage2dArrayTy; break;
5494 case PREDEF_TYPE_IMAGE3D_ID: T = Context.OCLImage3dTy; break;
Guy Benyei61054192013-02-07 10:55:47 +00005495 case PREDEF_TYPE_SAMPLER_ID: T = Context.OCLSamplerTy; break;
Guy Benyei1b4fb3e2013-01-20 12:31:11 +00005496 case PREDEF_TYPE_EVENT_ID: T = Context.OCLEventTy; break;
Guy Benyei11169dd2012-12-18 14:30:41 +00005497 case PREDEF_TYPE_AUTO_DEDUCT: T = Context.getAutoDeductType(); break;
5498
5499 case PREDEF_TYPE_AUTO_RREF_DEDUCT:
5500 T = Context.getAutoRRefDeductType();
5501 break;
5502
5503 case PREDEF_TYPE_ARC_UNBRIDGED_CAST:
5504 T = Context.ARCUnbridgedCastTy;
5505 break;
5506
5507 case PREDEF_TYPE_VA_LIST_TAG:
5508 T = Context.getVaListTagType();
5509 break;
5510
5511 case PREDEF_TYPE_BUILTIN_FN:
5512 T = Context.BuiltinFnTy;
5513 break;
5514 }
5515
5516 assert(!T.isNull() && "Unknown predefined type");
5517 return T.withFastQualifiers(FastQuals);
5518 }
5519
5520 Index -= NUM_PREDEF_TYPE_IDS;
5521 assert(Index < TypesLoaded.size() && "Type index out-of-range");
5522 if (TypesLoaded[Index].isNull()) {
5523 TypesLoaded[Index] = readTypeRecord(Index);
5524 if (TypesLoaded[Index].isNull())
5525 return QualType();
5526
5527 TypesLoaded[Index]->setFromAST();
5528 if (DeserializationListener)
5529 DeserializationListener->TypeRead(TypeIdx::fromTypeID(ID),
5530 TypesLoaded[Index]);
5531 }
5532
5533 return TypesLoaded[Index].withFastQualifiers(FastQuals);
5534}
5535
5536QualType ASTReader::getLocalType(ModuleFile &F, unsigned LocalID) {
5537 return GetType(getGlobalTypeID(F, LocalID));
5538}
5539
5540serialization::TypeID
5541ASTReader::getGlobalTypeID(ModuleFile &F, unsigned LocalID) const {
5542 unsigned FastQuals = LocalID & Qualifiers::FastMask;
5543 unsigned LocalIndex = LocalID >> Qualifiers::FastWidth;
5544
5545 if (LocalIndex < NUM_PREDEF_TYPE_IDS)
5546 return LocalID;
5547
5548 ContinuousRangeMap<uint32_t, int, 2>::iterator I
5549 = F.TypeRemap.find(LocalIndex - NUM_PREDEF_TYPE_IDS);
5550 assert(I != F.TypeRemap.end() && "Invalid index into type index remap");
5551
5552 unsigned GlobalIndex = LocalIndex + I->second;
5553 return (GlobalIndex << Qualifiers::FastWidth) | FastQuals;
5554}
5555
5556TemplateArgumentLocInfo
5557ASTReader::GetTemplateArgumentLocInfo(ModuleFile &F,
5558 TemplateArgument::ArgKind Kind,
5559 const RecordData &Record,
5560 unsigned &Index) {
5561 switch (Kind) {
5562 case TemplateArgument::Expression:
5563 return ReadExpr(F);
5564 case TemplateArgument::Type:
5565 return GetTypeSourceInfo(F, Record, Index);
5566 case TemplateArgument::Template: {
5567 NestedNameSpecifierLoc QualifierLoc = ReadNestedNameSpecifierLoc(F, Record,
5568 Index);
5569 SourceLocation TemplateNameLoc = ReadSourceLocation(F, Record, Index);
5570 return TemplateArgumentLocInfo(QualifierLoc, TemplateNameLoc,
5571 SourceLocation());
5572 }
5573 case TemplateArgument::TemplateExpansion: {
5574 NestedNameSpecifierLoc QualifierLoc = ReadNestedNameSpecifierLoc(F, Record,
5575 Index);
5576 SourceLocation TemplateNameLoc = ReadSourceLocation(F, Record, Index);
5577 SourceLocation EllipsisLoc = ReadSourceLocation(F, Record, Index);
5578 return TemplateArgumentLocInfo(QualifierLoc, TemplateNameLoc,
5579 EllipsisLoc);
5580 }
5581 case TemplateArgument::Null:
5582 case TemplateArgument::Integral:
5583 case TemplateArgument::Declaration:
5584 case TemplateArgument::NullPtr:
5585 case TemplateArgument::Pack:
5586 // FIXME: Is this right?
5587 return TemplateArgumentLocInfo();
5588 }
5589 llvm_unreachable("unexpected template argument loc");
5590}
5591
5592TemplateArgumentLoc
5593ASTReader::ReadTemplateArgumentLoc(ModuleFile &F,
5594 const RecordData &Record, unsigned &Index) {
5595 TemplateArgument Arg = ReadTemplateArgument(F, Record, Index);
5596
5597 if (Arg.getKind() == TemplateArgument::Expression) {
5598 if (Record[Index++]) // bool InfoHasSameExpr.
5599 return TemplateArgumentLoc(Arg, TemplateArgumentLocInfo(Arg.getAsExpr()));
5600 }
5601 return TemplateArgumentLoc(Arg, GetTemplateArgumentLocInfo(F, Arg.getKind(),
5602 Record, Index));
5603}
5604
Enea Zaffanella6dbe1872013-08-10 07:24:53 +00005605const ASTTemplateArgumentListInfo*
5606ASTReader::ReadASTTemplateArgumentListInfo(ModuleFile &F,
5607 const RecordData &Record,
5608 unsigned &Index) {
5609 SourceLocation LAngleLoc = ReadSourceLocation(F, Record, Index);
5610 SourceLocation RAngleLoc = ReadSourceLocation(F, Record, Index);
5611 unsigned NumArgsAsWritten = Record[Index++];
5612 TemplateArgumentListInfo TemplArgsInfo(LAngleLoc, RAngleLoc);
5613 for (unsigned i = 0; i != NumArgsAsWritten; ++i)
5614 TemplArgsInfo.addArgument(ReadTemplateArgumentLoc(F, Record, Index));
5615 return ASTTemplateArgumentListInfo::Create(getContext(), TemplArgsInfo);
5616}
5617
Guy Benyei11169dd2012-12-18 14:30:41 +00005618Decl *ASTReader::GetExternalDecl(uint32_t ID) {
5619 return GetDecl(ID);
5620}
5621
5622uint64_t ASTReader::readCXXBaseSpecifiers(ModuleFile &M, const RecordData &Record,
5623 unsigned &Idx){
5624 if (Idx >= Record.size())
5625 return 0;
5626
5627 unsigned LocalID = Record[Idx++];
5628 return getGlobalBitOffset(M, M.CXXBaseSpecifiersOffsets[LocalID - 1]);
5629}
5630
5631CXXBaseSpecifier *ASTReader::GetExternalCXXBaseSpecifiers(uint64_t Offset) {
5632 RecordLocation Loc = getLocalBitOffset(Offset);
Chris Lattner7fb3bef2013-01-20 00:56:42 +00005633 BitstreamCursor &Cursor = Loc.F->DeclsCursor;
Guy Benyei11169dd2012-12-18 14:30:41 +00005634 SavedStreamPosition SavedPosition(Cursor);
5635 Cursor.JumpToBit(Loc.Offset);
5636 ReadingKindTracker ReadingKind(Read_Decl, *this);
5637 RecordData Record;
5638 unsigned Code = Cursor.ReadCode();
Chris Lattner0e6c9402013-01-20 02:38:54 +00005639 unsigned RecCode = Cursor.readRecord(Code, Record);
Guy Benyei11169dd2012-12-18 14:30:41 +00005640 if (RecCode != DECL_CXX_BASE_SPECIFIERS) {
5641 Error("Malformed AST file: missing C++ base specifiers");
5642 return 0;
5643 }
5644
5645 unsigned Idx = 0;
5646 unsigned NumBases = Record[Idx++];
5647 void *Mem = Context.Allocate(sizeof(CXXBaseSpecifier) * NumBases);
5648 CXXBaseSpecifier *Bases = new (Mem) CXXBaseSpecifier [NumBases];
5649 for (unsigned I = 0; I != NumBases; ++I)
5650 Bases[I] = ReadCXXBaseSpecifier(*Loc.F, Record, Idx);
5651 return Bases;
5652}
5653
5654serialization::DeclID
5655ASTReader::getGlobalDeclID(ModuleFile &F, LocalDeclID LocalID) const {
5656 if (LocalID < NUM_PREDEF_DECL_IDS)
5657 return LocalID;
5658
5659 ContinuousRangeMap<uint32_t, int, 2>::iterator I
5660 = F.DeclRemap.find(LocalID - NUM_PREDEF_DECL_IDS);
5661 assert(I != F.DeclRemap.end() && "Invalid index into decl index remap");
5662
5663 return LocalID + I->second;
5664}
5665
5666bool ASTReader::isDeclIDFromModule(serialization::GlobalDeclID ID,
5667 ModuleFile &M) const {
5668 GlobalDeclMapType::const_iterator I = GlobalDeclMap.find(ID);
5669 assert(I != GlobalDeclMap.end() && "Corrupted global declaration map");
5670 return &M == I->second;
5671}
5672
Douglas Gregor9f782892013-01-21 15:25:38 +00005673ModuleFile *ASTReader::getOwningModuleFile(const Decl *D) {
Guy Benyei11169dd2012-12-18 14:30:41 +00005674 if (!D->isFromASTFile())
5675 return 0;
5676 GlobalDeclMapType::const_iterator I = GlobalDeclMap.find(D->getGlobalID());
5677 assert(I != GlobalDeclMap.end() && "Corrupted global declaration map");
5678 return I->second;
5679}
5680
5681SourceLocation ASTReader::getSourceLocationForDeclID(GlobalDeclID ID) {
5682 if (ID < NUM_PREDEF_DECL_IDS)
5683 return SourceLocation();
5684
5685 unsigned Index = ID - NUM_PREDEF_DECL_IDS;
5686
5687 if (Index > DeclsLoaded.size()) {
5688 Error("declaration ID out-of-range for AST file");
5689 return SourceLocation();
5690 }
5691
5692 if (Decl *D = DeclsLoaded[Index])
5693 return D->getLocation();
5694
5695 unsigned RawLocation = 0;
5696 RecordLocation Rec = DeclCursorForID(ID, RawLocation);
5697 return ReadSourceLocation(*Rec.F, RawLocation);
5698}
5699
5700Decl *ASTReader::GetDecl(DeclID ID) {
5701 if (ID < NUM_PREDEF_DECL_IDS) {
5702 switch ((PredefinedDeclIDs)ID) {
5703 case PREDEF_DECL_NULL_ID:
5704 return 0;
5705
5706 case PREDEF_DECL_TRANSLATION_UNIT_ID:
5707 return Context.getTranslationUnitDecl();
5708
5709 case PREDEF_DECL_OBJC_ID_ID:
5710 return Context.getObjCIdDecl();
5711
5712 case PREDEF_DECL_OBJC_SEL_ID:
5713 return Context.getObjCSelDecl();
5714
5715 case PREDEF_DECL_OBJC_CLASS_ID:
5716 return Context.getObjCClassDecl();
5717
5718 case PREDEF_DECL_OBJC_PROTOCOL_ID:
5719 return Context.getObjCProtocolDecl();
5720
5721 case PREDEF_DECL_INT_128_ID:
5722 return Context.getInt128Decl();
5723
5724 case PREDEF_DECL_UNSIGNED_INT_128_ID:
5725 return Context.getUInt128Decl();
5726
5727 case PREDEF_DECL_OBJC_INSTANCETYPE_ID:
5728 return Context.getObjCInstanceTypeDecl();
5729
5730 case PREDEF_DECL_BUILTIN_VA_LIST_ID:
5731 return Context.getBuiltinVaListDecl();
5732 }
5733 }
5734
5735 unsigned Index = ID - NUM_PREDEF_DECL_IDS;
5736
5737 if (Index >= DeclsLoaded.size()) {
5738 assert(0 && "declaration ID out-of-range for AST file");
5739 Error("declaration ID out-of-range for AST file");
5740 return 0;
5741 }
5742
5743 if (!DeclsLoaded[Index]) {
5744 ReadDeclRecord(ID);
5745 if (DeserializationListener)
5746 DeserializationListener->DeclRead(ID, DeclsLoaded[Index]);
5747 }
5748
5749 return DeclsLoaded[Index];
5750}
5751
5752DeclID ASTReader::mapGlobalIDToModuleFileGlobalID(ModuleFile &M,
5753 DeclID GlobalID) {
5754 if (GlobalID < NUM_PREDEF_DECL_IDS)
5755 return GlobalID;
5756
5757 GlobalDeclMapType::const_iterator I = GlobalDeclMap.find(GlobalID);
5758 assert(I != GlobalDeclMap.end() && "Corrupted global declaration map");
5759 ModuleFile *Owner = I->second;
5760
5761 llvm::DenseMap<ModuleFile *, serialization::DeclID>::iterator Pos
5762 = M.GlobalToLocalDeclIDs.find(Owner);
5763 if (Pos == M.GlobalToLocalDeclIDs.end())
5764 return 0;
5765
5766 return GlobalID - Owner->BaseDeclID + Pos->second;
5767}
5768
5769serialization::DeclID ASTReader::ReadDeclID(ModuleFile &F,
5770 const RecordData &Record,
5771 unsigned &Idx) {
5772 if (Idx >= Record.size()) {
5773 Error("Corrupted AST file");
5774 return 0;
5775 }
5776
5777 return getGlobalDeclID(F, Record[Idx++]);
5778}
5779
5780/// \brief Resolve the offset of a statement into a statement.
5781///
5782/// This operation will read a new statement from the external
5783/// source each time it is called, and is meant to be used via a
5784/// LazyOffsetPtr (which is used by Decls for the body of functions, etc).
5785Stmt *ASTReader::GetExternalDeclStmt(uint64_t Offset) {
5786 // Switch case IDs are per Decl.
5787 ClearSwitchCaseIDs();
5788
5789 // Offset here is a global offset across the entire chain.
5790 RecordLocation Loc = getLocalBitOffset(Offset);
5791 Loc.F->DeclsCursor.JumpToBit(Loc.Offset);
5792 return ReadStmtFromStream(*Loc.F);
5793}
5794
5795namespace {
5796 class FindExternalLexicalDeclsVisitor {
5797 ASTReader &Reader;
5798 const DeclContext *DC;
5799 bool (*isKindWeWant)(Decl::Kind);
5800
5801 SmallVectorImpl<Decl*> &Decls;
5802 bool PredefsVisited[NUM_PREDEF_DECL_IDS];
5803
5804 public:
5805 FindExternalLexicalDeclsVisitor(ASTReader &Reader, const DeclContext *DC,
5806 bool (*isKindWeWant)(Decl::Kind),
5807 SmallVectorImpl<Decl*> &Decls)
5808 : Reader(Reader), DC(DC), isKindWeWant(isKindWeWant), Decls(Decls)
5809 {
5810 for (unsigned I = 0; I != NUM_PREDEF_DECL_IDS; ++I)
5811 PredefsVisited[I] = false;
5812 }
5813
5814 static bool visit(ModuleFile &M, bool Preorder, void *UserData) {
5815 if (Preorder)
5816 return false;
5817
5818 FindExternalLexicalDeclsVisitor *This
5819 = static_cast<FindExternalLexicalDeclsVisitor *>(UserData);
5820
5821 ModuleFile::DeclContextInfosMap::iterator Info
5822 = M.DeclContextInfos.find(This->DC);
5823 if (Info == M.DeclContextInfos.end() || !Info->second.LexicalDecls)
5824 return false;
5825
5826 // Load all of the declaration IDs
5827 for (const KindDeclIDPair *ID = Info->second.LexicalDecls,
5828 *IDE = ID + Info->second.NumLexicalDecls;
5829 ID != IDE; ++ID) {
5830 if (This->isKindWeWant && !This->isKindWeWant((Decl::Kind)ID->first))
5831 continue;
5832
5833 // Don't add predefined declarations to the lexical context more
5834 // than once.
5835 if (ID->second < NUM_PREDEF_DECL_IDS) {
5836 if (This->PredefsVisited[ID->second])
5837 continue;
5838
5839 This->PredefsVisited[ID->second] = true;
5840 }
5841
5842 if (Decl *D = This->Reader.GetLocalDecl(M, ID->second)) {
5843 if (!This->DC->isDeclInLexicalTraversal(D))
5844 This->Decls.push_back(D);
5845 }
5846 }
5847
5848 return false;
5849 }
5850 };
5851}
5852
5853ExternalLoadResult ASTReader::FindExternalLexicalDecls(const DeclContext *DC,
5854 bool (*isKindWeWant)(Decl::Kind),
5855 SmallVectorImpl<Decl*> &Decls) {
5856 // There might be lexical decls in multiple modules, for the TU at
5857 // least. Walk all of the modules in the order they were loaded.
5858 FindExternalLexicalDeclsVisitor Visitor(*this, DC, isKindWeWant, Decls);
5859 ModuleMgr.visitDepthFirst(&FindExternalLexicalDeclsVisitor::visit, &Visitor);
5860 ++NumLexicalDeclContextsRead;
5861 return ELR_Success;
5862}
5863
5864namespace {
5865
5866class DeclIDComp {
5867 ASTReader &Reader;
5868 ModuleFile &Mod;
5869
5870public:
5871 DeclIDComp(ASTReader &Reader, ModuleFile &M) : Reader(Reader), Mod(M) {}
5872
5873 bool operator()(LocalDeclID L, LocalDeclID R) const {
5874 SourceLocation LHS = getLocation(L);
5875 SourceLocation RHS = getLocation(R);
5876 return Reader.getSourceManager().isBeforeInTranslationUnit(LHS, RHS);
5877 }
5878
5879 bool operator()(SourceLocation LHS, LocalDeclID R) const {
5880 SourceLocation RHS = getLocation(R);
5881 return Reader.getSourceManager().isBeforeInTranslationUnit(LHS, RHS);
5882 }
5883
5884 bool operator()(LocalDeclID L, SourceLocation RHS) const {
5885 SourceLocation LHS = getLocation(L);
5886 return Reader.getSourceManager().isBeforeInTranslationUnit(LHS, RHS);
5887 }
5888
5889 SourceLocation getLocation(LocalDeclID ID) const {
5890 return Reader.getSourceManager().getFileLoc(
5891 Reader.getSourceLocationForDeclID(Reader.getGlobalDeclID(Mod, ID)));
5892 }
5893};
5894
5895}
5896
5897void ASTReader::FindFileRegionDecls(FileID File,
5898 unsigned Offset, unsigned Length,
5899 SmallVectorImpl<Decl *> &Decls) {
5900 SourceManager &SM = getSourceManager();
5901
5902 llvm::DenseMap<FileID, FileDeclsInfo>::iterator I = FileDeclIDs.find(File);
5903 if (I == FileDeclIDs.end())
5904 return;
5905
5906 FileDeclsInfo &DInfo = I->second;
5907 if (DInfo.Decls.empty())
5908 return;
5909
5910 SourceLocation
5911 BeginLoc = SM.getLocForStartOfFile(File).getLocWithOffset(Offset);
5912 SourceLocation EndLoc = BeginLoc.getLocWithOffset(Length);
5913
5914 DeclIDComp DIDComp(*this, *DInfo.Mod);
5915 ArrayRef<serialization::LocalDeclID>::iterator
5916 BeginIt = std::lower_bound(DInfo.Decls.begin(), DInfo.Decls.end(),
5917 BeginLoc, DIDComp);
5918 if (BeginIt != DInfo.Decls.begin())
5919 --BeginIt;
5920
5921 // If we are pointing at a top-level decl inside an objc container, we need
5922 // to backtrack until we find it otherwise we will fail to report that the
5923 // region overlaps with an objc container.
5924 while (BeginIt != DInfo.Decls.begin() &&
5925 GetDecl(getGlobalDeclID(*DInfo.Mod, *BeginIt))
5926 ->isTopLevelDeclInObjCContainer())
5927 --BeginIt;
5928
5929 ArrayRef<serialization::LocalDeclID>::iterator
5930 EndIt = std::upper_bound(DInfo.Decls.begin(), DInfo.Decls.end(),
5931 EndLoc, DIDComp);
5932 if (EndIt != DInfo.Decls.end())
5933 ++EndIt;
5934
5935 for (ArrayRef<serialization::LocalDeclID>::iterator
5936 DIt = BeginIt; DIt != EndIt; ++DIt)
5937 Decls.push_back(GetDecl(getGlobalDeclID(*DInfo.Mod, *DIt)));
5938}
5939
5940namespace {
5941 /// \brief ModuleFile visitor used to perform name lookup into a
5942 /// declaration context.
5943 class DeclContextNameLookupVisitor {
5944 ASTReader &Reader;
Dmitri Gribenkof8579502013-01-12 19:30:44 +00005945 SmallVectorImpl<const DeclContext *> &Contexts;
Guy Benyei11169dd2012-12-18 14:30:41 +00005946 DeclarationName Name;
5947 SmallVectorImpl<NamedDecl *> &Decls;
5948
5949 public:
5950 DeclContextNameLookupVisitor(ASTReader &Reader,
5951 SmallVectorImpl<const DeclContext *> &Contexts,
5952 DeclarationName Name,
5953 SmallVectorImpl<NamedDecl *> &Decls)
5954 : Reader(Reader), Contexts(Contexts), Name(Name), Decls(Decls) { }
5955
5956 static bool visit(ModuleFile &M, void *UserData) {
5957 DeclContextNameLookupVisitor *This
5958 = static_cast<DeclContextNameLookupVisitor *>(UserData);
5959
5960 // Check whether we have any visible declaration information for
5961 // this context in this module.
5962 ModuleFile::DeclContextInfosMap::iterator Info;
5963 bool FoundInfo = false;
5964 for (unsigned I = 0, N = This->Contexts.size(); I != N; ++I) {
5965 Info = M.DeclContextInfos.find(This->Contexts[I]);
5966 if (Info != M.DeclContextInfos.end() &&
5967 Info->second.NameLookupTableData) {
5968 FoundInfo = true;
5969 break;
5970 }
5971 }
5972
5973 if (!FoundInfo)
5974 return false;
5975
5976 // Look for this name within this module.
5977 ASTDeclContextNameLookupTable *LookupTable =
5978 Info->second.NameLookupTableData;
5979 ASTDeclContextNameLookupTable::iterator Pos
5980 = LookupTable->find(This->Name);
5981 if (Pos == LookupTable->end())
5982 return false;
5983
5984 bool FoundAnything = false;
5985 ASTDeclContextNameLookupTrait::data_type Data = *Pos;
5986 for (; Data.first != Data.second; ++Data.first) {
5987 NamedDecl *ND = This->Reader.GetLocalDeclAs<NamedDecl>(M, *Data.first);
5988 if (!ND)
5989 continue;
5990
5991 if (ND->getDeclName() != This->Name) {
5992 // A name might be null because the decl's redeclarable part is
5993 // currently read before reading its name. The lookup is triggered by
5994 // building that decl (likely indirectly), and so it is later in the
5995 // sense of "already existing" and can be ignored here.
5996 continue;
5997 }
5998
5999 // Record this declaration.
6000 FoundAnything = true;
6001 This->Decls.push_back(ND);
6002 }
6003
6004 return FoundAnything;
6005 }
6006 };
6007}
6008
Douglas Gregor9f782892013-01-21 15:25:38 +00006009/// \brief Retrieve the "definitive" module file for the definition of the
6010/// given declaration context, if there is one.
6011///
6012/// The "definitive" module file is the only place where we need to look to
6013/// find information about the declarations within the given declaration
6014/// context. For example, C++ and Objective-C classes, C structs/unions, and
6015/// Objective-C protocols, categories, and extensions are all defined in a
6016/// single place in the source code, so they have definitive module files
6017/// associated with them. C++ namespaces, on the other hand, can have
6018/// definitions in multiple different module files.
6019///
6020/// Note: this needs to be kept in sync with ASTWriter::AddedVisibleDecl's
6021/// NDEBUG checking.
6022static ModuleFile *getDefinitiveModuleFileFor(const DeclContext *DC,
6023 ASTReader &Reader) {
Douglas Gregor7a6e2002013-01-22 17:08:30 +00006024 if (const DeclContext *DefDC = getDefinitiveDeclContext(DC))
6025 return Reader.getOwningModuleFile(cast<Decl>(DefDC));
Douglas Gregor9f782892013-01-21 15:25:38 +00006026
6027 return 0;
6028}
6029
Richard Smith9ce12e32013-02-07 03:30:24 +00006030bool
Guy Benyei11169dd2012-12-18 14:30:41 +00006031ASTReader::FindExternalVisibleDeclsByName(const DeclContext *DC,
6032 DeclarationName Name) {
6033 assert(DC->hasExternalVisibleStorage() &&
6034 "DeclContext has no visible decls in storage");
6035 if (!Name)
Richard Smith9ce12e32013-02-07 03:30:24 +00006036 return false;
Guy Benyei11169dd2012-12-18 14:30:41 +00006037
6038 SmallVector<NamedDecl *, 64> Decls;
6039
6040 // Compute the declaration contexts we need to look into. Multiple such
6041 // declaration contexts occur when two declaration contexts from disjoint
6042 // modules get merged, e.g., when two namespaces with the same name are
6043 // independently defined in separate modules.
6044 SmallVector<const DeclContext *, 2> Contexts;
6045 Contexts.push_back(DC);
6046
6047 if (DC->isNamespace()) {
6048 MergedDeclsMap::iterator Merged
6049 = MergedDecls.find(const_cast<Decl *>(cast<Decl>(DC)));
6050 if (Merged != MergedDecls.end()) {
6051 for (unsigned I = 0, N = Merged->second.size(); I != N; ++I)
6052 Contexts.push_back(cast<DeclContext>(GetDecl(Merged->second[I])));
6053 }
6054 }
6055
6056 DeclContextNameLookupVisitor Visitor(*this, Contexts, Name, Decls);
Douglas Gregor9f782892013-01-21 15:25:38 +00006057
6058 // If we can definitively determine which module file to look into,
6059 // only look there. Otherwise, look in all module files.
6060 ModuleFile *Definitive;
6061 if (Contexts.size() == 1 &&
6062 (Definitive = getDefinitiveModuleFileFor(DC, *this))) {
6063 DeclContextNameLookupVisitor::visit(*Definitive, &Visitor);
6064 } else {
6065 ModuleMgr.visit(&DeclContextNameLookupVisitor::visit, &Visitor);
6066 }
Guy Benyei11169dd2012-12-18 14:30:41 +00006067 ++NumVisibleDeclContextsRead;
6068 SetExternalVisibleDeclsForName(DC, Name, Decls);
Richard Smith9ce12e32013-02-07 03:30:24 +00006069 return !Decls.empty();
Guy Benyei11169dd2012-12-18 14:30:41 +00006070}
6071
6072namespace {
6073 /// \brief ModuleFile visitor used to retrieve all visible names in a
6074 /// declaration context.
6075 class DeclContextAllNamesVisitor {
6076 ASTReader &Reader;
Dmitri Gribenkof8579502013-01-12 19:30:44 +00006077 SmallVectorImpl<const DeclContext *> &Contexts;
Craig Topper3598eb72013-07-05 04:43:31 +00006078 DeclsMap &Decls;
Argyrios Kyrtzidis2810e9d2012-12-19 22:21:18 +00006079 bool VisitAll;
Guy Benyei11169dd2012-12-18 14:30:41 +00006080
6081 public:
6082 DeclContextAllNamesVisitor(ASTReader &Reader,
6083 SmallVectorImpl<const DeclContext *> &Contexts,
Craig Topper3598eb72013-07-05 04:43:31 +00006084 DeclsMap &Decls, bool VisitAll)
Argyrios Kyrtzidis2810e9d2012-12-19 22:21:18 +00006085 : Reader(Reader), Contexts(Contexts), Decls(Decls), VisitAll(VisitAll) { }
Guy Benyei11169dd2012-12-18 14:30:41 +00006086
6087 static bool visit(ModuleFile &M, void *UserData) {
6088 DeclContextAllNamesVisitor *This
6089 = static_cast<DeclContextAllNamesVisitor *>(UserData);
6090
6091 // Check whether we have any visible declaration information for
6092 // this context in this module.
6093 ModuleFile::DeclContextInfosMap::iterator Info;
6094 bool FoundInfo = false;
6095 for (unsigned I = 0, N = This->Contexts.size(); I != N; ++I) {
6096 Info = M.DeclContextInfos.find(This->Contexts[I]);
6097 if (Info != M.DeclContextInfos.end() &&
6098 Info->second.NameLookupTableData) {
6099 FoundInfo = true;
6100 break;
6101 }
6102 }
6103
6104 if (!FoundInfo)
6105 return false;
6106
6107 ASTDeclContextNameLookupTable *LookupTable =
6108 Info->second.NameLookupTableData;
6109 bool FoundAnything = false;
6110 for (ASTDeclContextNameLookupTable::data_iterator
Douglas Gregor5e306b12013-01-23 22:38:11 +00006111 I = LookupTable->data_begin(), E = LookupTable->data_end();
6112 I != E;
6113 ++I) {
Guy Benyei11169dd2012-12-18 14:30:41 +00006114 ASTDeclContextNameLookupTrait::data_type Data = *I;
6115 for (; Data.first != Data.second; ++Data.first) {
6116 NamedDecl *ND = This->Reader.GetLocalDeclAs<NamedDecl>(M,
6117 *Data.first);
6118 if (!ND)
6119 continue;
6120
6121 // Record this declaration.
6122 FoundAnything = true;
6123 This->Decls[ND->getDeclName()].push_back(ND);
6124 }
6125 }
6126
Argyrios Kyrtzidis2810e9d2012-12-19 22:21:18 +00006127 return FoundAnything && !This->VisitAll;
Guy Benyei11169dd2012-12-18 14:30:41 +00006128 }
6129 };
6130}
6131
6132void ASTReader::completeVisibleDeclsMap(const DeclContext *DC) {
6133 if (!DC->hasExternalVisibleStorage())
6134 return;
Craig Topper79be4cd2013-07-05 04:33:53 +00006135 DeclsMap Decls;
Guy Benyei11169dd2012-12-18 14:30:41 +00006136
6137 // Compute the declaration contexts we need to look into. Multiple such
6138 // declaration contexts occur when two declaration contexts from disjoint
6139 // modules get merged, e.g., when two namespaces with the same name are
6140 // independently defined in separate modules.
6141 SmallVector<const DeclContext *, 2> Contexts;
6142 Contexts.push_back(DC);
6143
6144 if (DC->isNamespace()) {
6145 MergedDeclsMap::iterator Merged
6146 = MergedDecls.find(const_cast<Decl *>(cast<Decl>(DC)));
6147 if (Merged != MergedDecls.end()) {
6148 for (unsigned I = 0, N = Merged->second.size(); I != N; ++I)
6149 Contexts.push_back(cast<DeclContext>(GetDecl(Merged->second[I])));
6150 }
6151 }
6152
Argyrios Kyrtzidis2810e9d2012-12-19 22:21:18 +00006153 DeclContextAllNamesVisitor Visitor(*this, Contexts, Decls,
6154 /*VisitAll=*/DC->isFileContext());
Guy Benyei11169dd2012-12-18 14:30:41 +00006155 ModuleMgr.visit(&DeclContextAllNamesVisitor::visit, &Visitor);
6156 ++NumVisibleDeclContextsRead;
6157
Craig Topper79be4cd2013-07-05 04:33:53 +00006158 for (DeclsMap::iterator I = Decls.begin(), E = Decls.end(); I != E; ++I) {
Guy Benyei11169dd2012-12-18 14:30:41 +00006159 SetExternalVisibleDeclsForName(DC, I->first, I->second);
6160 }
6161 const_cast<DeclContext *>(DC)->setHasExternalVisibleStorage(false);
6162}
6163
6164/// \brief Under non-PCH compilation the consumer receives the objc methods
6165/// before receiving the implementation, and codegen depends on this.
6166/// We simulate this by deserializing and passing to consumer the methods of the
6167/// implementation before passing the deserialized implementation decl.
6168static void PassObjCImplDeclToConsumer(ObjCImplDecl *ImplD,
6169 ASTConsumer *Consumer) {
6170 assert(ImplD && Consumer);
6171
6172 for (ObjCImplDecl::method_iterator
6173 I = ImplD->meth_begin(), E = ImplD->meth_end(); I != E; ++I)
6174 Consumer->HandleInterestingDecl(DeclGroupRef(*I));
6175
6176 Consumer->HandleInterestingDecl(DeclGroupRef(ImplD));
6177}
6178
6179void ASTReader::PassInterestingDeclsToConsumer() {
6180 assert(Consumer);
6181 while (!InterestingDecls.empty()) {
6182 Decl *D = InterestingDecls.front();
6183 InterestingDecls.pop_front();
6184
6185 PassInterestingDeclToConsumer(D);
6186 }
6187}
6188
6189void ASTReader::PassInterestingDeclToConsumer(Decl *D) {
6190 if (ObjCImplDecl *ImplD = dyn_cast<ObjCImplDecl>(D))
6191 PassObjCImplDeclToConsumer(ImplD, Consumer);
6192 else
6193 Consumer->HandleInterestingDecl(DeclGroupRef(D));
6194}
6195
6196void ASTReader::StartTranslationUnit(ASTConsumer *Consumer) {
6197 this->Consumer = Consumer;
6198
6199 if (!Consumer)
6200 return;
6201
Ben Langmuir332aafe2014-01-31 01:06:56 +00006202 for (unsigned I = 0, N = EagerlyDeserializedDecls.size(); I != N; ++I) {
Guy Benyei11169dd2012-12-18 14:30:41 +00006203 // Force deserialization of this decl, which will cause it to be queued for
6204 // passing to the consumer.
Ben Langmuir332aafe2014-01-31 01:06:56 +00006205 GetDecl(EagerlyDeserializedDecls[I]);
Guy Benyei11169dd2012-12-18 14:30:41 +00006206 }
Ben Langmuir332aafe2014-01-31 01:06:56 +00006207 EagerlyDeserializedDecls.clear();
Guy Benyei11169dd2012-12-18 14:30:41 +00006208
6209 PassInterestingDeclsToConsumer();
6210}
6211
6212void ASTReader::PrintStats() {
6213 std::fprintf(stderr, "*** AST File Statistics:\n");
6214
6215 unsigned NumTypesLoaded
6216 = TypesLoaded.size() - std::count(TypesLoaded.begin(), TypesLoaded.end(),
6217 QualType());
6218 unsigned NumDeclsLoaded
6219 = DeclsLoaded.size() - std::count(DeclsLoaded.begin(), DeclsLoaded.end(),
6220 (Decl *)0);
6221 unsigned NumIdentifiersLoaded
6222 = IdentifiersLoaded.size() - std::count(IdentifiersLoaded.begin(),
6223 IdentifiersLoaded.end(),
6224 (IdentifierInfo *)0);
6225 unsigned NumMacrosLoaded
6226 = MacrosLoaded.size() - std::count(MacrosLoaded.begin(),
6227 MacrosLoaded.end(),
Argyrios Kyrtzidiseb663da2013-03-22 21:12:57 +00006228 (MacroInfo *)0);
Guy Benyei11169dd2012-12-18 14:30:41 +00006229 unsigned NumSelectorsLoaded
6230 = SelectorsLoaded.size() - std::count(SelectorsLoaded.begin(),
6231 SelectorsLoaded.end(),
6232 Selector());
6233
6234 if (unsigned TotalNumSLocEntries = getTotalNumSLocs())
6235 std::fprintf(stderr, " %u/%u source location entries read (%f%%)\n",
6236 NumSLocEntriesRead, TotalNumSLocEntries,
6237 ((float)NumSLocEntriesRead/TotalNumSLocEntries * 100));
6238 if (!TypesLoaded.empty())
6239 std::fprintf(stderr, " %u/%u types read (%f%%)\n",
6240 NumTypesLoaded, (unsigned)TypesLoaded.size(),
6241 ((float)NumTypesLoaded/TypesLoaded.size() * 100));
6242 if (!DeclsLoaded.empty())
6243 std::fprintf(stderr, " %u/%u declarations read (%f%%)\n",
6244 NumDeclsLoaded, (unsigned)DeclsLoaded.size(),
6245 ((float)NumDeclsLoaded/DeclsLoaded.size() * 100));
6246 if (!IdentifiersLoaded.empty())
6247 std::fprintf(stderr, " %u/%u identifiers read (%f%%)\n",
6248 NumIdentifiersLoaded, (unsigned)IdentifiersLoaded.size(),
6249 ((float)NumIdentifiersLoaded/IdentifiersLoaded.size() * 100));
6250 if (!MacrosLoaded.empty())
6251 std::fprintf(stderr, " %u/%u macros read (%f%%)\n",
6252 NumMacrosLoaded, (unsigned)MacrosLoaded.size(),
6253 ((float)NumMacrosLoaded/MacrosLoaded.size() * 100));
6254 if (!SelectorsLoaded.empty())
6255 std::fprintf(stderr, " %u/%u selectors read (%f%%)\n",
6256 NumSelectorsLoaded, (unsigned)SelectorsLoaded.size(),
6257 ((float)NumSelectorsLoaded/SelectorsLoaded.size() * 100));
6258 if (TotalNumStatements)
6259 std::fprintf(stderr, " %u/%u statements read (%f%%)\n",
6260 NumStatementsRead, TotalNumStatements,
6261 ((float)NumStatementsRead/TotalNumStatements * 100));
6262 if (TotalNumMacros)
6263 std::fprintf(stderr, " %u/%u macros read (%f%%)\n",
6264 NumMacrosRead, TotalNumMacros,
6265 ((float)NumMacrosRead/TotalNumMacros * 100));
6266 if (TotalLexicalDeclContexts)
6267 std::fprintf(stderr, " %u/%u lexical declcontexts read (%f%%)\n",
6268 NumLexicalDeclContextsRead, TotalLexicalDeclContexts,
6269 ((float)NumLexicalDeclContextsRead/TotalLexicalDeclContexts
6270 * 100));
6271 if (TotalVisibleDeclContexts)
6272 std::fprintf(stderr, " %u/%u visible declcontexts read (%f%%)\n",
6273 NumVisibleDeclContextsRead, TotalVisibleDeclContexts,
6274 ((float)NumVisibleDeclContextsRead/TotalVisibleDeclContexts
6275 * 100));
6276 if (TotalNumMethodPoolEntries) {
6277 std::fprintf(stderr, " %u/%u method pool entries read (%f%%)\n",
6278 NumMethodPoolEntriesRead, TotalNumMethodPoolEntries,
6279 ((float)NumMethodPoolEntriesRead/TotalNumMethodPoolEntries
6280 * 100));
Guy Benyei11169dd2012-12-18 14:30:41 +00006281 }
Douglas Gregorad2f7a52013-01-28 17:54:36 +00006282 if (NumMethodPoolLookups) {
6283 std::fprintf(stderr, " %u/%u method pool lookups succeeded (%f%%)\n",
6284 NumMethodPoolHits, NumMethodPoolLookups,
6285 ((float)NumMethodPoolHits/NumMethodPoolLookups * 100.0));
6286 }
6287 if (NumMethodPoolTableLookups) {
6288 std::fprintf(stderr, " %u/%u method pool table lookups succeeded (%f%%)\n",
6289 NumMethodPoolTableHits, NumMethodPoolTableLookups,
6290 ((float)NumMethodPoolTableHits/NumMethodPoolTableLookups
6291 * 100.0));
6292 }
6293
Douglas Gregor00a50f72013-01-25 00:38:33 +00006294 if (NumIdentifierLookupHits) {
6295 std::fprintf(stderr,
6296 " %u / %u identifier table lookups succeeded (%f%%)\n",
6297 NumIdentifierLookupHits, NumIdentifierLookups,
6298 (double)NumIdentifierLookupHits*100.0/NumIdentifierLookups);
6299 }
6300
Douglas Gregore060e572013-01-25 01:03:03 +00006301 if (GlobalIndex) {
6302 std::fprintf(stderr, "\n");
6303 GlobalIndex->printStats();
6304 }
6305
Guy Benyei11169dd2012-12-18 14:30:41 +00006306 std::fprintf(stderr, "\n");
6307 dump();
6308 std::fprintf(stderr, "\n");
6309}
6310
6311template<typename Key, typename ModuleFile, unsigned InitialCapacity>
6312static void
6313dumpModuleIDMap(StringRef Name,
6314 const ContinuousRangeMap<Key, ModuleFile *,
6315 InitialCapacity> &Map) {
6316 if (Map.begin() == Map.end())
6317 return;
6318
6319 typedef ContinuousRangeMap<Key, ModuleFile *, InitialCapacity> MapType;
6320 llvm::errs() << Name << ":\n";
6321 for (typename MapType::const_iterator I = Map.begin(), IEnd = Map.end();
6322 I != IEnd; ++I) {
6323 llvm::errs() << " " << I->first << " -> " << I->second->FileName
6324 << "\n";
6325 }
6326}
6327
6328void ASTReader::dump() {
6329 llvm::errs() << "*** PCH/ModuleFile Remappings:\n";
6330 dumpModuleIDMap("Global bit offset map", GlobalBitOffsetsMap);
6331 dumpModuleIDMap("Global source location entry map", GlobalSLocEntryMap);
6332 dumpModuleIDMap("Global type map", GlobalTypeMap);
6333 dumpModuleIDMap("Global declaration map", GlobalDeclMap);
6334 dumpModuleIDMap("Global identifier map", GlobalIdentifierMap);
6335 dumpModuleIDMap("Global macro map", GlobalMacroMap);
6336 dumpModuleIDMap("Global submodule map", GlobalSubmoduleMap);
6337 dumpModuleIDMap("Global selector map", GlobalSelectorMap);
6338 dumpModuleIDMap("Global preprocessed entity map",
6339 GlobalPreprocessedEntityMap);
6340
6341 llvm::errs() << "\n*** PCH/Modules Loaded:";
6342 for (ModuleManager::ModuleConstIterator M = ModuleMgr.begin(),
6343 MEnd = ModuleMgr.end();
6344 M != MEnd; ++M)
6345 (*M)->dump();
6346}
6347
6348/// Return the amount of memory used by memory buffers, breaking down
6349/// by heap-backed versus mmap'ed memory.
6350void ASTReader::getMemoryBufferSizes(MemoryBufferSizes &sizes) const {
6351 for (ModuleConstIterator I = ModuleMgr.begin(),
6352 E = ModuleMgr.end(); I != E; ++I) {
6353 if (llvm::MemoryBuffer *buf = (*I)->Buffer.get()) {
6354 size_t bytes = buf->getBufferSize();
6355 switch (buf->getBufferKind()) {
6356 case llvm::MemoryBuffer::MemoryBuffer_Malloc:
6357 sizes.malloc_bytes += bytes;
6358 break;
6359 case llvm::MemoryBuffer::MemoryBuffer_MMap:
6360 sizes.mmap_bytes += bytes;
6361 break;
6362 }
6363 }
6364 }
6365}
6366
6367void ASTReader::InitializeSema(Sema &S) {
6368 SemaObj = &S;
6369 S.addExternalSource(this);
6370
6371 // Makes sure any declarations that were deserialized "too early"
6372 // still get added to the identifier's declaration chains.
6373 for (unsigned I = 0, N = PreloadedDecls.size(); I != N; ++I) {
Argyrios Kyrtzidise5edbf92013-04-26 21:33:35 +00006374 pushExternalDeclIntoScope(PreloadedDecls[I],
6375 PreloadedDecls[I]->getDeclName());
Guy Benyei11169dd2012-12-18 14:30:41 +00006376 }
6377 PreloadedDecls.clear();
6378
Richard Smith3d8e97e2013-10-18 06:54:39 +00006379 // FIXME: What happens if these are changed by a module import?
Guy Benyei11169dd2012-12-18 14:30:41 +00006380 if (!FPPragmaOptions.empty()) {
6381 assert(FPPragmaOptions.size() == 1 && "Wrong number of FP_PRAGMA_OPTIONS");
6382 SemaObj->FPFeatures.fp_contract = FPPragmaOptions[0];
6383 }
6384
Richard Smith3d8e97e2013-10-18 06:54:39 +00006385 // FIXME: What happens if these are changed by a module import?
Guy Benyei11169dd2012-12-18 14:30:41 +00006386 if (!OpenCLExtensions.empty()) {
6387 unsigned I = 0;
6388#define OPENCLEXT(nm) SemaObj->OpenCLFeatures.nm = OpenCLExtensions[I++];
6389#include "clang/Basic/OpenCLExtensions.def"
6390
6391 assert(OpenCLExtensions.size() == I && "Wrong number of OPENCL_EXTENSIONS");
6392 }
Richard Smith3d8e97e2013-10-18 06:54:39 +00006393
6394 UpdateSema();
6395}
6396
6397void ASTReader::UpdateSema() {
6398 assert(SemaObj && "no Sema to update");
6399
6400 // Load the offsets of the declarations that Sema references.
6401 // They will be lazily deserialized when needed.
6402 if (!SemaDeclRefs.empty()) {
6403 assert(SemaDeclRefs.size() % 2 == 0);
6404 for (unsigned I = 0; I != SemaDeclRefs.size(); I += 2) {
6405 if (!SemaObj->StdNamespace)
6406 SemaObj->StdNamespace = SemaDeclRefs[I];
6407 if (!SemaObj->StdBadAlloc)
6408 SemaObj->StdBadAlloc = SemaDeclRefs[I+1];
6409 }
6410 SemaDeclRefs.clear();
6411 }
Guy Benyei11169dd2012-12-18 14:30:41 +00006412}
6413
6414IdentifierInfo* ASTReader::get(const char *NameStart, const char *NameEnd) {
6415 // Note that we are loading an identifier.
6416 Deserializing AnIdentifier(this);
Douglas Gregore060e572013-01-25 01:03:03 +00006417 StringRef Name(NameStart, NameEnd - NameStart);
6418
6419 // If there is a global index, look there first to determine which modules
6420 // provably do not have any results for this identifier.
Douglas Gregor7211ac12013-01-25 23:32:03 +00006421 GlobalModuleIndex::HitSet Hits;
6422 GlobalModuleIndex::HitSet *HitsPtr = 0;
Douglas Gregore060e572013-01-25 01:03:03 +00006423 if (!loadGlobalIndex()) {
Douglas Gregor7211ac12013-01-25 23:32:03 +00006424 if (GlobalIndex->lookupIdentifier(Name, Hits)) {
6425 HitsPtr = &Hits;
Douglas Gregore060e572013-01-25 01:03:03 +00006426 }
6427 }
Douglas Gregor7211ac12013-01-25 23:32:03 +00006428 IdentifierLookupVisitor Visitor(Name, /*PriorGeneration=*/0,
Douglas Gregor00a50f72013-01-25 00:38:33 +00006429 NumIdentifierLookups,
6430 NumIdentifierLookupHits);
Douglas Gregor7211ac12013-01-25 23:32:03 +00006431 ModuleMgr.visit(IdentifierLookupVisitor::visit, &Visitor, HitsPtr);
Guy Benyei11169dd2012-12-18 14:30:41 +00006432 IdentifierInfo *II = Visitor.getIdentifierInfo();
6433 markIdentifierUpToDate(II);
6434 return II;
6435}
6436
6437namespace clang {
6438 /// \brief An identifier-lookup iterator that enumerates all of the
6439 /// identifiers stored within a set of AST files.
6440 class ASTIdentifierIterator : public IdentifierIterator {
6441 /// \brief The AST reader whose identifiers are being enumerated.
6442 const ASTReader &Reader;
6443
6444 /// \brief The current index into the chain of AST files stored in
6445 /// the AST reader.
6446 unsigned Index;
6447
6448 /// \brief The current position within the identifier lookup table
6449 /// of the current AST file.
6450 ASTIdentifierLookupTable::key_iterator Current;
6451
6452 /// \brief The end position within the identifier lookup table of
6453 /// the current AST file.
6454 ASTIdentifierLookupTable::key_iterator End;
6455
6456 public:
6457 explicit ASTIdentifierIterator(const ASTReader &Reader);
6458
6459 virtual StringRef Next();
6460 };
6461}
6462
6463ASTIdentifierIterator::ASTIdentifierIterator(const ASTReader &Reader)
6464 : Reader(Reader), Index(Reader.ModuleMgr.size() - 1) {
6465 ASTIdentifierLookupTable *IdTable
6466 = (ASTIdentifierLookupTable *)Reader.ModuleMgr[Index].IdentifierLookupTable;
6467 Current = IdTable->key_begin();
6468 End = IdTable->key_end();
6469}
6470
6471StringRef ASTIdentifierIterator::Next() {
6472 while (Current == End) {
6473 // If we have exhausted all of our AST files, we're done.
6474 if (Index == 0)
6475 return StringRef();
6476
6477 --Index;
6478 ASTIdentifierLookupTable *IdTable
6479 = (ASTIdentifierLookupTable *)Reader.ModuleMgr[Index].
6480 IdentifierLookupTable;
6481 Current = IdTable->key_begin();
6482 End = IdTable->key_end();
6483 }
6484
6485 // We have any identifiers remaining in the current AST file; return
6486 // the next one.
Douglas Gregorbfd73d72013-01-23 18:53:14 +00006487 StringRef Result = *Current;
Guy Benyei11169dd2012-12-18 14:30:41 +00006488 ++Current;
Douglas Gregorbfd73d72013-01-23 18:53:14 +00006489 return Result;
Guy Benyei11169dd2012-12-18 14:30:41 +00006490}
6491
Argyrios Kyrtzidis9aca3c62013-04-17 22:10:55 +00006492IdentifierIterator *ASTReader::getIdentifiers() {
6493 if (!loadGlobalIndex())
6494 return GlobalIndex->createIdentifierIterator();
6495
Guy Benyei11169dd2012-12-18 14:30:41 +00006496 return new ASTIdentifierIterator(*this);
6497}
6498
6499namespace clang { namespace serialization {
6500 class ReadMethodPoolVisitor {
6501 ASTReader &Reader;
6502 Selector Sel;
6503 unsigned PriorGeneration;
Argyrios Kyrtzidisd3da6e02013-04-17 00:08:58 +00006504 unsigned InstanceBits;
6505 unsigned FactoryBits;
Dmitri Gribenkof8579502013-01-12 19:30:44 +00006506 SmallVector<ObjCMethodDecl *, 4> InstanceMethods;
6507 SmallVector<ObjCMethodDecl *, 4> FactoryMethods;
Guy Benyei11169dd2012-12-18 14:30:41 +00006508
6509 public:
6510 ReadMethodPoolVisitor(ASTReader &Reader, Selector Sel,
6511 unsigned PriorGeneration)
Argyrios Kyrtzidisd3da6e02013-04-17 00:08:58 +00006512 : Reader(Reader), Sel(Sel), PriorGeneration(PriorGeneration),
6513 InstanceBits(0), FactoryBits(0) { }
Guy Benyei11169dd2012-12-18 14:30:41 +00006514
6515 static bool visit(ModuleFile &M, void *UserData) {
6516 ReadMethodPoolVisitor *This
6517 = static_cast<ReadMethodPoolVisitor *>(UserData);
6518
6519 if (!M.SelectorLookupTable)
6520 return false;
6521
6522 // If we've already searched this module file, skip it now.
6523 if (M.Generation <= This->PriorGeneration)
6524 return true;
6525
Douglas Gregorad2f7a52013-01-28 17:54:36 +00006526 ++This->Reader.NumMethodPoolTableLookups;
Guy Benyei11169dd2012-12-18 14:30:41 +00006527 ASTSelectorLookupTable *PoolTable
6528 = (ASTSelectorLookupTable*)M.SelectorLookupTable;
6529 ASTSelectorLookupTable::iterator Pos = PoolTable->find(This->Sel);
6530 if (Pos == PoolTable->end())
6531 return false;
Douglas Gregorad2f7a52013-01-28 17:54:36 +00006532
6533 ++This->Reader.NumMethodPoolTableHits;
Guy Benyei11169dd2012-12-18 14:30:41 +00006534 ++This->Reader.NumSelectorsRead;
6535 // FIXME: Not quite happy with the statistics here. We probably should
6536 // disable this tracking when called via LoadSelector.
6537 // Also, should entries without methods count as misses?
6538 ++This->Reader.NumMethodPoolEntriesRead;
6539 ASTSelectorLookupTrait::data_type Data = *Pos;
6540 if (This->Reader.DeserializationListener)
6541 This->Reader.DeserializationListener->SelectorRead(Data.ID,
6542 This->Sel);
6543
6544 This->InstanceMethods.append(Data.Instance.begin(), Data.Instance.end());
6545 This->FactoryMethods.append(Data.Factory.begin(), Data.Factory.end());
Argyrios Kyrtzidisd3da6e02013-04-17 00:08:58 +00006546 This->InstanceBits = Data.InstanceBits;
6547 This->FactoryBits = Data.FactoryBits;
Guy Benyei11169dd2012-12-18 14:30:41 +00006548 return true;
6549 }
6550
6551 /// \brief Retrieve the instance methods found by this visitor.
6552 ArrayRef<ObjCMethodDecl *> getInstanceMethods() const {
6553 return InstanceMethods;
6554 }
6555
6556 /// \brief Retrieve the instance methods found by this visitor.
6557 ArrayRef<ObjCMethodDecl *> getFactoryMethods() const {
6558 return FactoryMethods;
6559 }
Argyrios Kyrtzidisd3da6e02013-04-17 00:08:58 +00006560
6561 unsigned getInstanceBits() const { return InstanceBits; }
6562 unsigned getFactoryBits() const { return FactoryBits; }
Guy Benyei11169dd2012-12-18 14:30:41 +00006563 };
6564} } // end namespace clang::serialization
6565
6566/// \brief Add the given set of methods to the method list.
6567static void addMethodsToPool(Sema &S, ArrayRef<ObjCMethodDecl *> Methods,
6568 ObjCMethodList &List) {
6569 for (unsigned I = 0, N = Methods.size(); I != N; ++I) {
6570 S.addMethodToGlobalList(&List, Methods[I]);
6571 }
6572}
6573
6574void ASTReader::ReadMethodPool(Selector Sel) {
6575 // Get the selector generation and update it to the current generation.
6576 unsigned &Generation = SelectorGeneration[Sel];
6577 unsigned PriorGeneration = Generation;
6578 Generation = CurrentGeneration;
6579
6580 // Search for methods defined with this selector.
Douglas Gregorad2f7a52013-01-28 17:54:36 +00006581 ++NumMethodPoolLookups;
Guy Benyei11169dd2012-12-18 14:30:41 +00006582 ReadMethodPoolVisitor Visitor(*this, Sel, PriorGeneration);
6583 ModuleMgr.visit(&ReadMethodPoolVisitor::visit, &Visitor);
6584
6585 if (Visitor.getInstanceMethods().empty() &&
Douglas Gregorad2f7a52013-01-28 17:54:36 +00006586 Visitor.getFactoryMethods().empty())
Guy Benyei11169dd2012-12-18 14:30:41 +00006587 return;
Douglas Gregorad2f7a52013-01-28 17:54:36 +00006588
6589 ++NumMethodPoolHits;
6590
Guy Benyei11169dd2012-12-18 14:30:41 +00006591 if (!getSema())
6592 return;
6593
6594 Sema &S = *getSema();
6595 Sema::GlobalMethodPool::iterator Pos
6596 = S.MethodPool.insert(std::make_pair(Sel, Sema::GlobalMethods())).first;
6597
6598 addMethodsToPool(S, Visitor.getInstanceMethods(), Pos->second.first);
6599 addMethodsToPool(S, Visitor.getFactoryMethods(), Pos->second.second);
Argyrios Kyrtzidisd3da6e02013-04-17 00:08:58 +00006600 Pos->second.first.setBits(Visitor.getInstanceBits());
6601 Pos->second.second.setBits(Visitor.getFactoryBits());
Guy Benyei11169dd2012-12-18 14:30:41 +00006602}
6603
6604void ASTReader::ReadKnownNamespaces(
6605 SmallVectorImpl<NamespaceDecl *> &Namespaces) {
6606 Namespaces.clear();
6607
6608 for (unsigned I = 0, N = KnownNamespaces.size(); I != N; ++I) {
6609 if (NamespaceDecl *Namespace
6610 = dyn_cast_or_null<NamespaceDecl>(GetDecl(KnownNamespaces[I])))
6611 Namespaces.push_back(Namespace);
6612 }
6613}
6614
Nick Lewycky9c7eb1d2013-02-01 08:13:20 +00006615void ASTReader::ReadUndefinedButUsed(
Nick Lewyckyf0f56162013-01-31 03:23:57 +00006616 llvm::DenseMap<NamedDecl*, SourceLocation> &Undefined) {
Nick Lewycky9c7eb1d2013-02-01 08:13:20 +00006617 for (unsigned Idx = 0, N = UndefinedButUsed.size(); Idx != N;) {
6618 NamedDecl *D = cast<NamedDecl>(GetDecl(UndefinedButUsed[Idx++]));
Nick Lewycky8334af82013-01-26 00:35:08 +00006619 SourceLocation Loc =
Nick Lewycky9c7eb1d2013-02-01 08:13:20 +00006620 SourceLocation::getFromRawEncoding(UndefinedButUsed[Idx++]);
Nick Lewycky8334af82013-01-26 00:35:08 +00006621 Undefined.insert(std::make_pair(D, Loc));
6622 }
6623}
Nick Lewycky8334af82013-01-26 00:35:08 +00006624
Guy Benyei11169dd2012-12-18 14:30:41 +00006625void ASTReader::ReadTentativeDefinitions(
6626 SmallVectorImpl<VarDecl *> &TentativeDefs) {
6627 for (unsigned I = 0, N = TentativeDefinitions.size(); I != N; ++I) {
6628 VarDecl *Var = dyn_cast_or_null<VarDecl>(GetDecl(TentativeDefinitions[I]));
6629 if (Var)
6630 TentativeDefs.push_back(Var);
6631 }
6632 TentativeDefinitions.clear();
6633}
6634
6635void ASTReader::ReadUnusedFileScopedDecls(
6636 SmallVectorImpl<const DeclaratorDecl *> &Decls) {
6637 for (unsigned I = 0, N = UnusedFileScopedDecls.size(); I != N; ++I) {
6638 DeclaratorDecl *D
6639 = dyn_cast_or_null<DeclaratorDecl>(GetDecl(UnusedFileScopedDecls[I]));
6640 if (D)
6641 Decls.push_back(D);
6642 }
6643 UnusedFileScopedDecls.clear();
6644}
6645
6646void ASTReader::ReadDelegatingConstructors(
6647 SmallVectorImpl<CXXConstructorDecl *> &Decls) {
6648 for (unsigned I = 0, N = DelegatingCtorDecls.size(); I != N; ++I) {
6649 CXXConstructorDecl *D
6650 = dyn_cast_or_null<CXXConstructorDecl>(GetDecl(DelegatingCtorDecls[I]));
6651 if (D)
6652 Decls.push_back(D);
6653 }
6654 DelegatingCtorDecls.clear();
6655}
6656
6657void ASTReader::ReadExtVectorDecls(SmallVectorImpl<TypedefNameDecl *> &Decls) {
6658 for (unsigned I = 0, N = ExtVectorDecls.size(); I != N; ++I) {
6659 TypedefNameDecl *D
6660 = dyn_cast_or_null<TypedefNameDecl>(GetDecl(ExtVectorDecls[I]));
6661 if (D)
6662 Decls.push_back(D);
6663 }
6664 ExtVectorDecls.clear();
6665}
6666
6667void ASTReader::ReadDynamicClasses(SmallVectorImpl<CXXRecordDecl *> &Decls) {
6668 for (unsigned I = 0, N = DynamicClasses.size(); I != N; ++I) {
6669 CXXRecordDecl *D
6670 = dyn_cast_or_null<CXXRecordDecl>(GetDecl(DynamicClasses[I]));
6671 if (D)
6672 Decls.push_back(D);
6673 }
6674 DynamicClasses.clear();
6675}
6676
6677void
Richard Smith78165b52013-01-10 23:43:47 +00006678ASTReader::ReadLocallyScopedExternCDecls(SmallVectorImpl<NamedDecl *> &Decls) {
6679 for (unsigned I = 0, N = LocallyScopedExternCDecls.size(); I != N; ++I) {
6680 NamedDecl *D
6681 = dyn_cast_or_null<NamedDecl>(GetDecl(LocallyScopedExternCDecls[I]));
Guy Benyei11169dd2012-12-18 14:30:41 +00006682 if (D)
6683 Decls.push_back(D);
6684 }
Richard Smith78165b52013-01-10 23:43:47 +00006685 LocallyScopedExternCDecls.clear();
Guy Benyei11169dd2012-12-18 14:30:41 +00006686}
6687
6688void ASTReader::ReadReferencedSelectors(
6689 SmallVectorImpl<std::pair<Selector, SourceLocation> > &Sels) {
6690 if (ReferencedSelectorsData.empty())
6691 return;
6692
6693 // If there are @selector references added them to its pool. This is for
6694 // implementation of -Wselector.
6695 unsigned int DataSize = ReferencedSelectorsData.size()-1;
6696 unsigned I = 0;
6697 while (I < DataSize) {
6698 Selector Sel = DecodeSelector(ReferencedSelectorsData[I++]);
6699 SourceLocation SelLoc
6700 = SourceLocation::getFromRawEncoding(ReferencedSelectorsData[I++]);
6701 Sels.push_back(std::make_pair(Sel, SelLoc));
6702 }
6703 ReferencedSelectorsData.clear();
6704}
6705
6706void ASTReader::ReadWeakUndeclaredIdentifiers(
6707 SmallVectorImpl<std::pair<IdentifierInfo *, WeakInfo> > &WeakIDs) {
6708 if (WeakUndeclaredIdentifiers.empty())
6709 return;
6710
6711 for (unsigned I = 0, N = WeakUndeclaredIdentifiers.size(); I < N; /*none*/) {
6712 IdentifierInfo *WeakId
6713 = DecodeIdentifierInfo(WeakUndeclaredIdentifiers[I++]);
6714 IdentifierInfo *AliasId
6715 = DecodeIdentifierInfo(WeakUndeclaredIdentifiers[I++]);
6716 SourceLocation Loc
6717 = SourceLocation::getFromRawEncoding(WeakUndeclaredIdentifiers[I++]);
6718 bool Used = WeakUndeclaredIdentifiers[I++];
6719 WeakInfo WI(AliasId, Loc);
6720 WI.setUsed(Used);
6721 WeakIDs.push_back(std::make_pair(WeakId, WI));
6722 }
6723 WeakUndeclaredIdentifiers.clear();
6724}
6725
6726void ASTReader::ReadUsedVTables(SmallVectorImpl<ExternalVTableUse> &VTables) {
6727 for (unsigned Idx = 0, N = VTableUses.size(); Idx < N; /* In loop */) {
6728 ExternalVTableUse VT;
6729 VT.Record = dyn_cast_or_null<CXXRecordDecl>(GetDecl(VTableUses[Idx++]));
6730 VT.Location = SourceLocation::getFromRawEncoding(VTableUses[Idx++]);
6731 VT.DefinitionRequired = VTableUses[Idx++];
6732 VTables.push_back(VT);
6733 }
6734
6735 VTableUses.clear();
6736}
6737
6738void ASTReader::ReadPendingInstantiations(
6739 SmallVectorImpl<std::pair<ValueDecl *, SourceLocation> > &Pending) {
6740 for (unsigned Idx = 0, N = PendingInstantiations.size(); Idx < N;) {
6741 ValueDecl *D = cast<ValueDecl>(GetDecl(PendingInstantiations[Idx++]));
6742 SourceLocation Loc
6743 = SourceLocation::getFromRawEncoding(PendingInstantiations[Idx++]);
6744
6745 Pending.push_back(std::make_pair(D, Loc));
6746 }
6747 PendingInstantiations.clear();
6748}
6749
Richard Smithe40f2ba2013-08-07 21:41:30 +00006750void ASTReader::ReadLateParsedTemplates(
6751 llvm::DenseMap<const FunctionDecl *, LateParsedTemplate *> &LPTMap) {
6752 for (unsigned Idx = 0, N = LateParsedTemplates.size(); Idx < N;
6753 /* In loop */) {
6754 FunctionDecl *FD = cast<FunctionDecl>(GetDecl(LateParsedTemplates[Idx++]));
6755
6756 LateParsedTemplate *LT = new LateParsedTemplate;
6757 LT->D = GetDecl(LateParsedTemplates[Idx++]);
6758
6759 ModuleFile *F = getOwningModuleFile(LT->D);
6760 assert(F && "No module");
6761
6762 unsigned TokN = LateParsedTemplates[Idx++];
6763 LT->Toks.reserve(TokN);
6764 for (unsigned T = 0; T < TokN; ++T)
6765 LT->Toks.push_back(ReadToken(*F, LateParsedTemplates, Idx));
6766
6767 LPTMap[FD] = LT;
6768 }
6769
6770 LateParsedTemplates.clear();
6771}
6772
Guy Benyei11169dd2012-12-18 14:30:41 +00006773void ASTReader::LoadSelector(Selector Sel) {
6774 // It would be complicated to avoid reading the methods anyway. So don't.
6775 ReadMethodPool(Sel);
6776}
6777
6778void ASTReader::SetIdentifierInfo(IdentifierID ID, IdentifierInfo *II) {
6779 assert(ID && "Non-zero identifier ID required");
6780 assert(ID <= IdentifiersLoaded.size() && "identifier ID out of range");
6781 IdentifiersLoaded[ID - 1] = II;
6782 if (DeserializationListener)
6783 DeserializationListener->IdentifierRead(ID, II);
6784}
6785
6786/// \brief Set the globally-visible declarations associated with the given
6787/// identifier.
6788///
6789/// If the AST reader is currently in a state where the given declaration IDs
6790/// cannot safely be resolved, they are queued until it is safe to resolve
6791/// them.
6792///
6793/// \param II an IdentifierInfo that refers to one or more globally-visible
6794/// declarations.
6795///
6796/// \param DeclIDs the set of declaration IDs with the name @p II that are
6797/// visible at global scope.
6798///
Douglas Gregor6168bd22013-02-18 15:53:43 +00006799/// \param Decls if non-null, this vector will be populated with the set of
6800/// deserialized declarations. These declarations will not be pushed into
6801/// scope.
Guy Benyei11169dd2012-12-18 14:30:41 +00006802void
6803ASTReader::SetGloballyVisibleDecls(IdentifierInfo *II,
6804 const SmallVectorImpl<uint32_t> &DeclIDs,
Douglas Gregor6168bd22013-02-18 15:53:43 +00006805 SmallVectorImpl<Decl *> *Decls) {
6806 if (NumCurrentElementsDeserializing && !Decls) {
6807 PendingIdentifierInfos[II].append(DeclIDs.begin(), DeclIDs.end());
Guy Benyei11169dd2012-12-18 14:30:41 +00006808 return;
6809 }
6810
6811 for (unsigned I = 0, N = DeclIDs.size(); I != N; ++I) {
6812 NamedDecl *D = cast<NamedDecl>(GetDecl(DeclIDs[I]));
6813 if (SemaObj) {
Douglas Gregor6168bd22013-02-18 15:53:43 +00006814 // If we're simply supposed to record the declarations, do so now.
6815 if (Decls) {
6816 Decls->push_back(D);
6817 continue;
6818 }
6819
Guy Benyei11169dd2012-12-18 14:30:41 +00006820 // Introduce this declaration into the translation-unit scope
6821 // and add it to the declaration chain for this identifier, so
6822 // that (unqualified) name lookup will find it.
Argyrios Kyrtzidise5edbf92013-04-26 21:33:35 +00006823 pushExternalDeclIntoScope(D, II);
Guy Benyei11169dd2012-12-18 14:30:41 +00006824 } else {
6825 // Queue this declaration so that it will be added to the
6826 // translation unit scope and identifier's declaration chain
6827 // once a Sema object is known.
6828 PreloadedDecls.push_back(D);
6829 }
6830 }
6831}
6832
Douglas Gregorc8a992f2013-01-21 16:52:34 +00006833IdentifierInfo *ASTReader::DecodeIdentifierInfo(IdentifierID ID) {
Guy Benyei11169dd2012-12-18 14:30:41 +00006834 if (ID == 0)
6835 return 0;
6836
6837 if (IdentifiersLoaded.empty()) {
6838 Error("no identifier table in AST file");
6839 return 0;
6840 }
6841
6842 ID -= 1;
6843 if (!IdentifiersLoaded[ID]) {
6844 GlobalIdentifierMapType::iterator I = GlobalIdentifierMap.find(ID + 1);
6845 assert(I != GlobalIdentifierMap.end() && "Corrupted global identifier map");
6846 ModuleFile *M = I->second;
6847 unsigned Index = ID - M->BaseIdentifierID;
6848 const char *Str = M->IdentifierTableData + M->IdentifierOffsets[Index];
6849
6850 // All of the strings in the AST file are preceded by a 16-bit length.
6851 // Extract that 16-bit length to avoid having to execute strlen().
6852 // NOTE: 'StrLenPtr' is an 'unsigned char*' so that we load bytes as
6853 // unsigned integers. This is important to avoid integer overflow when
6854 // we cast them to 'unsigned'.
6855 const unsigned char *StrLenPtr = (const unsigned char*) Str - 2;
6856 unsigned StrLen = (((unsigned) StrLenPtr[0])
6857 | (((unsigned) StrLenPtr[1]) << 8)) - 1;
Douglas Gregorc8a992f2013-01-21 16:52:34 +00006858 IdentifiersLoaded[ID]
6859 = &PP.getIdentifierTable().get(StringRef(Str, StrLen));
Guy Benyei11169dd2012-12-18 14:30:41 +00006860 if (DeserializationListener)
6861 DeserializationListener->IdentifierRead(ID + 1, IdentifiersLoaded[ID]);
6862 }
6863
6864 return IdentifiersLoaded[ID];
6865}
6866
Douglas Gregorc8a992f2013-01-21 16:52:34 +00006867IdentifierInfo *ASTReader::getLocalIdentifier(ModuleFile &M, unsigned LocalID) {
6868 return DecodeIdentifierInfo(getGlobalIdentifierID(M, LocalID));
Guy Benyei11169dd2012-12-18 14:30:41 +00006869}
6870
6871IdentifierID ASTReader::getGlobalIdentifierID(ModuleFile &M, unsigned LocalID) {
6872 if (LocalID < NUM_PREDEF_IDENT_IDS)
6873 return LocalID;
6874
6875 ContinuousRangeMap<uint32_t, int, 2>::iterator I
6876 = M.IdentifierRemap.find(LocalID - NUM_PREDEF_IDENT_IDS);
6877 assert(I != M.IdentifierRemap.end()
6878 && "Invalid index into identifier index remap");
6879
6880 return LocalID + I->second;
6881}
6882
Argyrios Kyrtzidiseb663da2013-03-22 21:12:57 +00006883MacroInfo *ASTReader::getMacro(MacroID ID) {
Guy Benyei11169dd2012-12-18 14:30:41 +00006884 if (ID == 0)
6885 return 0;
6886
6887 if (MacrosLoaded.empty()) {
6888 Error("no macro table in AST file");
6889 return 0;
6890 }
6891
6892 ID -= NUM_PREDEF_MACRO_IDS;
6893 if (!MacrosLoaded[ID]) {
6894 GlobalMacroMapType::iterator I
6895 = GlobalMacroMap.find(ID + NUM_PREDEF_MACRO_IDS);
6896 assert(I != GlobalMacroMap.end() && "Corrupted global macro map");
6897 ModuleFile *M = I->second;
6898 unsigned Index = ID - M->BaseMacroID;
Argyrios Kyrtzidiseb663da2013-03-22 21:12:57 +00006899 MacrosLoaded[ID] = ReadMacroRecord(*M, M->MacroOffsets[Index]);
6900
6901 if (DeserializationListener)
6902 DeserializationListener->MacroRead(ID + NUM_PREDEF_MACRO_IDS,
6903 MacrosLoaded[ID]);
Guy Benyei11169dd2012-12-18 14:30:41 +00006904 }
6905
6906 return MacrosLoaded[ID];
6907}
6908
6909MacroID ASTReader::getGlobalMacroID(ModuleFile &M, unsigned LocalID) {
6910 if (LocalID < NUM_PREDEF_MACRO_IDS)
6911 return LocalID;
6912
6913 ContinuousRangeMap<uint32_t, int, 2>::iterator I
6914 = M.MacroRemap.find(LocalID - NUM_PREDEF_MACRO_IDS);
6915 assert(I != M.MacroRemap.end() && "Invalid index into macro index remap");
6916
6917 return LocalID + I->second;
6918}
6919
6920serialization::SubmoduleID
6921ASTReader::getGlobalSubmoduleID(ModuleFile &M, unsigned LocalID) {
6922 if (LocalID < NUM_PREDEF_SUBMODULE_IDS)
6923 return LocalID;
6924
6925 ContinuousRangeMap<uint32_t, int, 2>::iterator I
6926 = M.SubmoduleRemap.find(LocalID - NUM_PREDEF_SUBMODULE_IDS);
6927 assert(I != M.SubmoduleRemap.end()
6928 && "Invalid index into submodule index remap");
6929
6930 return LocalID + I->second;
6931}
6932
6933Module *ASTReader::getSubmodule(SubmoduleID GlobalID) {
6934 if (GlobalID < NUM_PREDEF_SUBMODULE_IDS) {
6935 assert(GlobalID == 0 && "Unhandled global submodule ID");
6936 return 0;
6937 }
6938
6939 if (GlobalID > SubmodulesLoaded.size()) {
6940 Error("submodule ID out of range in AST file");
6941 return 0;
6942 }
6943
6944 return SubmodulesLoaded[GlobalID - NUM_PREDEF_SUBMODULE_IDS];
6945}
Douglas Gregorc147b0b2013-01-12 01:29:50 +00006946
6947Module *ASTReader::getModule(unsigned ID) {
6948 return getSubmodule(ID);
6949}
6950
Guy Benyei11169dd2012-12-18 14:30:41 +00006951Selector ASTReader::getLocalSelector(ModuleFile &M, unsigned LocalID) {
6952 return DecodeSelector(getGlobalSelectorID(M, LocalID));
6953}
6954
6955Selector ASTReader::DecodeSelector(serialization::SelectorID ID) {
6956 if (ID == 0)
6957 return Selector();
6958
6959 if (ID > SelectorsLoaded.size()) {
6960 Error("selector ID out of range in AST file");
6961 return Selector();
6962 }
6963
6964 if (SelectorsLoaded[ID - 1].getAsOpaquePtr() == 0) {
6965 // Load this selector from the selector table.
6966 GlobalSelectorMapType::iterator I = GlobalSelectorMap.find(ID);
6967 assert(I != GlobalSelectorMap.end() && "Corrupted global selector map");
6968 ModuleFile &M = *I->second;
6969 ASTSelectorLookupTrait Trait(*this, M);
6970 unsigned Idx = ID - M.BaseSelectorID - NUM_PREDEF_SELECTOR_IDS;
6971 SelectorsLoaded[ID - 1] =
6972 Trait.ReadKey(M.SelectorLookupTableData + M.SelectorOffsets[Idx], 0);
6973 if (DeserializationListener)
6974 DeserializationListener->SelectorRead(ID, SelectorsLoaded[ID - 1]);
6975 }
6976
6977 return SelectorsLoaded[ID - 1];
6978}
6979
6980Selector ASTReader::GetExternalSelector(serialization::SelectorID ID) {
6981 return DecodeSelector(ID);
6982}
6983
6984uint32_t ASTReader::GetNumExternalSelectors() {
6985 // ID 0 (the null selector) is considered an external selector.
6986 return getTotalNumSelectors() + 1;
6987}
6988
6989serialization::SelectorID
6990ASTReader::getGlobalSelectorID(ModuleFile &M, unsigned LocalID) const {
6991 if (LocalID < NUM_PREDEF_SELECTOR_IDS)
6992 return LocalID;
6993
6994 ContinuousRangeMap<uint32_t, int, 2>::iterator I
6995 = M.SelectorRemap.find(LocalID - NUM_PREDEF_SELECTOR_IDS);
6996 assert(I != M.SelectorRemap.end()
6997 && "Invalid index into selector index remap");
6998
6999 return LocalID + I->second;
7000}
7001
7002DeclarationName
7003ASTReader::ReadDeclarationName(ModuleFile &F,
7004 const RecordData &Record, unsigned &Idx) {
7005 DeclarationName::NameKind Kind = (DeclarationName::NameKind)Record[Idx++];
7006 switch (Kind) {
7007 case DeclarationName::Identifier:
Douglas Gregorc8a992f2013-01-21 16:52:34 +00007008 return DeclarationName(GetIdentifierInfo(F, Record, Idx));
Guy Benyei11169dd2012-12-18 14:30:41 +00007009
7010 case DeclarationName::ObjCZeroArgSelector:
7011 case DeclarationName::ObjCOneArgSelector:
7012 case DeclarationName::ObjCMultiArgSelector:
7013 return DeclarationName(ReadSelector(F, Record, Idx));
7014
7015 case DeclarationName::CXXConstructorName:
7016 return Context.DeclarationNames.getCXXConstructorName(
7017 Context.getCanonicalType(readType(F, Record, Idx)));
7018
7019 case DeclarationName::CXXDestructorName:
7020 return Context.DeclarationNames.getCXXDestructorName(
7021 Context.getCanonicalType(readType(F, Record, Idx)));
7022
7023 case DeclarationName::CXXConversionFunctionName:
7024 return Context.DeclarationNames.getCXXConversionFunctionName(
7025 Context.getCanonicalType(readType(F, Record, Idx)));
7026
7027 case DeclarationName::CXXOperatorName:
7028 return Context.DeclarationNames.getCXXOperatorName(
7029 (OverloadedOperatorKind)Record[Idx++]);
7030
7031 case DeclarationName::CXXLiteralOperatorName:
7032 return Context.DeclarationNames.getCXXLiteralOperatorName(
7033 GetIdentifierInfo(F, Record, Idx));
7034
7035 case DeclarationName::CXXUsingDirective:
7036 return DeclarationName::getUsingDirectiveName();
7037 }
7038
7039 llvm_unreachable("Invalid NameKind!");
7040}
7041
7042void ASTReader::ReadDeclarationNameLoc(ModuleFile &F,
7043 DeclarationNameLoc &DNLoc,
7044 DeclarationName Name,
7045 const RecordData &Record, unsigned &Idx) {
7046 switch (Name.getNameKind()) {
7047 case DeclarationName::CXXConstructorName:
7048 case DeclarationName::CXXDestructorName:
7049 case DeclarationName::CXXConversionFunctionName:
7050 DNLoc.NamedType.TInfo = GetTypeSourceInfo(F, Record, Idx);
7051 break;
7052
7053 case DeclarationName::CXXOperatorName:
7054 DNLoc.CXXOperatorName.BeginOpNameLoc
7055 = ReadSourceLocation(F, Record, Idx).getRawEncoding();
7056 DNLoc.CXXOperatorName.EndOpNameLoc
7057 = ReadSourceLocation(F, Record, Idx).getRawEncoding();
7058 break;
7059
7060 case DeclarationName::CXXLiteralOperatorName:
7061 DNLoc.CXXLiteralOperatorName.OpNameLoc
7062 = ReadSourceLocation(F, Record, Idx).getRawEncoding();
7063 break;
7064
7065 case DeclarationName::Identifier:
7066 case DeclarationName::ObjCZeroArgSelector:
7067 case DeclarationName::ObjCOneArgSelector:
7068 case DeclarationName::ObjCMultiArgSelector:
7069 case DeclarationName::CXXUsingDirective:
7070 break;
7071 }
7072}
7073
7074void ASTReader::ReadDeclarationNameInfo(ModuleFile &F,
7075 DeclarationNameInfo &NameInfo,
7076 const RecordData &Record, unsigned &Idx) {
7077 NameInfo.setName(ReadDeclarationName(F, Record, Idx));
7078 NameInfo.setLoc(ReadSourceLocation(F, Record, Idx));
7079 DeclarationNameLoc DNLoc;
7080 ReadDeclarationNameLoc(F, DNLoc, NameInfo.getName(), Record, Idx);
7081 NameInfo.setInfo(DNLoc);
7082}
7083
7084void ASTReader::ReadQualifierInfo(ModuleFile &F, QualifierInfo &Info,
7085 const RecordData &Record, unsigned &Idx) {
7086 Info.QualifierLoc = ReadNestedNameSpecifierLoc(F, Record, Idx);
7087 unsigned NumTPLists = Record[Idx++];
7088 Info.NumTemplParamLists = NumTPLists;
7089 if (NumTPLists) {
7090 Info.TemplParamLists = new (Context) TemplateParameterList*[NumTPLists];
7091 for (unsigned i=0; i != NumTPLists; ++i)
7092 Info.TemplParamLists[i] = ReadTemplateParameterList(F, Record, Idx);
7093 }
7094}
7095
7096TemplateName
7097ASTReader::ReadTemplateName(ModuleFile &F, const RecordData &Record,
7098 unsigned &Idx) {
7099 TemplateName::NameKind Kind = (TemplateName::NameKind)Record[Idx++];
7100 switch (Kind) {
7101 case TemplateName::Template:
7102 return TemplateName(ReadDeclAs<TemplateDecl>(F, Record, Idx));
7103
7104 case TemplateName::OverloadedTemplate: {
7105 unsigned size = Record[Idx++];
7106 UnresolvedSet<8> Decls;
7107 while (size--)
7108 Decls.addDecl(ReadDeclAs<NamedDecl>(F, Record, Idx));
7109
7110 return Context.getOverloadedTemplateName(Decls.begin(), Decls.end());
7111 }
7112
7113 case TemplateName::QualifiedTemplate: {
7114 NestedNameSpecifier *NNS = ReadNestedNameSpecifier(F, Record, Idx);
7115 bool hasTemplKeyword = Record[Idx++];
7116 TemplateDecl *Template = ReadDeclAs<TemplateDecl>(F, Record, Idx);
7117 return Context.getQualifiedTemplateName(NNS, hasTemplKeyword, Template);
7118 }
7119
7120 case TemplateName::DependentTemplate: {
7121 NestedNameSpecifier *NNS = ReadNestedNameSpecifier(F, Record, Idx);
7122 if (Record[Idx++]) // isIdentifier
7123 return Context.getDependentTemplateName(NNS,
7124 GetIdentifierInfo(F, Record,
7125 Idx));
7126 return Context.getDependentTemplateName(NNS,
7127 (OverloadedOperatorKind)Record[Idx++]);
7128 }
7129
7130 case TemplateName::SubstTemplateTemplateParm: {
7131 TemplateTemplateParmDecl *param
7132 = ReadDeclAs<TemplateTemplateParmDecl>(F, Record, Idx);
7133 if (!param) return TemplateName();
7134 TemplateName replacement = ReadTemplateName(F, Record, Idx);
7135 return Context.getSubstTemplateTemplateParm(param, replacement);
7136 }
7137
7138 case TemplateName::SubstTemplateTemplateParmPack: {
7139 TemplateTemplateParmDecl *Param
7140 = ReadDeclAs<TemplateTemplateParmDecl>(F, Record, Idx);
7141 if (!Param)
7142 return TemplateName();
7143
7144 TemplateArgument ArgPack = ReadTemplateArgument(F, Record, Idx);
7145 if (ArgPack.getKind() != TemplateArgument::Pack)
7146 return TemplateName();
7147
7148 return Context.getSubstTemplateTemplateParmPack(Param, ArgPack);
7149 }
7150 }
7151
7152 llvm_unreachable("Unhandled template name kind!");
7153}
7154
7155TemplateArgument
7156ASTReader::ReadTemplateArgument(ModuleFile &F,
7157 const RecordData &Record, unsigned &Idx) {
7158 TemplateArgument::ArgKind Kind = (TemplateArgument::ArgKind)Record[Idx++];
7159 switch (Kind) {
7160 case TemplateArgument::Null:
7161 return TemplateArgument();
7162 case TemplateArgument::Type:
7163 return TemplateArgument(readType(F, Record, Idx));
7164 case TemplateArgument::Declaration: {
7165 ValueDecl *D = ReadDeclAs<ValueDecl>(F, Record, Idx);
7166 bool ForReferenceParam = Record[Idx++];
7167 return TemplateArgument(D, ForReferenceParam);
7168 }
7169 case TemplateArgument::NullPtr:
7170 return TemplateArgument(readType(F, Record, Idx), /*isNullPtr*/true);
7171 case TemplateArgument::Integral: {
7172 llvm::APSInt Value = ReadAPSInt(Record, Idx);
7173 QualType T = readType(F, Record, Idx);
7174 return TemplateArgument(Context, Value, T);
7175 }
7176 case TemplateArgument::Template:
7177 return TemplateArgument(ReadTemplateName(F, Record, Idx));
7178 case TemplateArgument::TemplateExpansion: {
7179 TemplateName Name = ReadTemplateName(F, Record, Idx);
David Blaikie05785d12013-02-20 22:23:23 +00007180 Optional<unsigned> NumTemplateExpansions;
Guy Benyei11169dd2012-12-18 14:30:41 +00007181 if (unsigned NumExpansions = Record[Idx++])
7182 NumTemplateExpansions = NumExpansions - 1;
7183 return TemplateArgument(Name, NumTemplateExpansions);
7184 }
7185 case TemplateArgument::Expression:
7186 return TemplateArgument(ReadExpr(F));
7187 case TemplateArgument::Pack: {
7188 unsigned NumArgs = Record[Idx++];
7189 TemplateArgument *Args = new (Context) TemplateArgument[NumArgs];
7190 for (unsigned I = 0; I != NumArgs; ++I)
7191 Args[I] = ReadTemplateArgument(F, Record, Idx);
7192 return TemplateArgument(Args, NumArgs);
7193 }
7194 }
7195
7196 llvm_unreachable("Unhandled template argument kind!");
7197}
7198
7199TemplateParameterList *
7200ASTReader::ReadTemplateParameterList(ModuleFile &F,
7201 const RecordData &Record, unsigned &Idx) {
7202 SourceLocation TemplateLoc = ReadSourceLocation(F, Record, Idx);
7203 SourceLocation LAngleLoc = ReadSourceLocation(F, Record, Idx);
7204 SourceLocation RAngleLoc = ReadSourceLocation(F, Record, Idx);
7205
7206 unsigned NumParams = Record[Idx++];
7207 SmallVector<NamedDecl *, 16> Params;
7208 Params.reserve(NumParams);
7209 while (NumParams--)
7210 Params.push_back(ReadDeclAs<NamedDecl>(F, Record, Idx));
7211
7212 TemplateParameterList* TemplateParams =
7213 TemplateParameterList::Create(Context, TemplateLoc, LAngleLoc,
7214 Params.data(), Params.size(), RAngleLoc);
7215 return TemplateParams;
7216}
7217
7218void
7219ASTReader::
Craig Topper5603df42013-07-05 19:34:19 +00007220ReadTemplateArgumentList(SmallVectorImpl<TemplateArgument> &TemplArgs,
Guy Benyei11169dd2012-12-18 14:30:41 +00007221 ModuleFile &F, const RecordData &Record,
7222 unsigned &Idx) {
7223 unsigned NumTemplateArgs = Record[Idx++];
7224 TemplArgs.reserve(NumTemplateArgs);
7225 while (NumTemplateArgs--)
7226 TemplArgs.push_back(ReadTemplateArgument(F, Record, Idx));
7227}
7228
7229/// \brief Read a UnresolvedSet structure.
Richard Smitha4ba74c2013-08-30 04:46:40 +00007230void ASTReader::ReadUnresolvedSet(ModuleFile &F, LazyASTUnresolvedSet &Set,
Guy Benyei11169dd2012-12-18 14:30:41 +00007231 const RecordData &Record, unsigned &Idx) {
7232 unsigned NumDecls = Record[Idx++];
7233 Set.reserve(Context, NumDecls);
7234 while (NumDecls--) {
Richard Smitha4ba74c2013-08-30 04:46:40 +00007235 DeclID ID = ReadDeclID(F, Record, Idx);
Guy Benyei11169dd2012-12-18 14:30:41 +00007236 AccessSpecifier AS = (AccessSpecifier)Record[Idx++];
Richard Smitha4ba74c2013-08-30 04:46:40 +00007237 Set.addLazyDecl(Context, ID, AS);
Guy Benyei11169dd2012-12-18 14:30:41 +00007238 }
7239}
7240
7241CXXBaseSpecifier
7242ASTReader::ReadCXXBaseSpecifier(ModuleFile &F,
7243 const RecordData &Record, unsigned &Idx) {
7244 bool isVirtual = static_cast<bool>(Record[Idx++]);
7245 bool isBaseOfClass = static_cast<bool>(Record[Idx++]);
7246 AccessSpecifier AS = static_cast<AccessSpecifier>(Record[Idx++]);
7247 bool inheritConstructors = static_cast<bool>(Record[Idx++]);
7248 TypeSourceInfo *TInfo = GetTypeSourceInfo(F, Record, Idx);
7249 SourceRange Range = ReadSourceRange(F, Record, Idx);
7250 SourceLocation EllipsisLoc = ReadSourceLocation(F, Record, Idx);
7251 CXXBaseSpecifier Result(Range, isVirtual, isBaseOfClass, AS, TInfo,
7252 EllipsisLoc);
7253 Result.setInheritConstructors(inheritConstructors);
7254 return Result;
7255}
7256
7257std::pair<CXXCtorInitializer **, unsigned>
7258ASTReader::ReadCXXCtorInitializers(ModuleFile &F, const RecordData &Record,
7259 unsigned &Idx) {
7260 CXXCtorInitializer **CtorInitializers = 0;
7261 unsigned NumInitializers = Record[Idx++];
7262 if (NumInitializers) {
7263 CtorInitializers
7264 = new (Context) CXXCtorInitializer*[NumInitializers];
7265 for (unsigned i=0; i != NumInitializers; ++i) {
7266 TypeSourceInfo *TInfo = 0;
7267 bool IsBaseVirtual = false;
7268 FieldDecl *Member = 0;
7269 IndirectFieldDecl *IndirectMember = 0;
7270
7271 CtorInitializerType Type = (CtorInitializerType)Record[Idx++];
7272 switch (Type) {
7273 case CTOR_INITIALIZER_BASE:
7274 TInfo = GetTypeSourceInfo(F, Record, Idx);
7275 IsBaseVirtual = Record[Idx++];
7276 break;
7277
7278 case CTOR_INITIALIZER_DELEGATING:
7279 TInfo = GetTypeSourceInfo(F, Record, Idx);
7280 break;
7281
7282 case CTOR_INITIALIZER_MEMBER:
7283 Member = ReadDeclAs<FieldDecl>(F, Record, Idx);
7284 break;
7285
7286 case CTOR_INITIALIZER_INDIRECT_MEMBER:
7287 IndirectMember = ReadDeclAs<IndirectFieldDecl>(F, Record, Idx);
7288 break;
7289 }
7290
7291 SourceLocation MemberOrEllipsisLoc = ReadSourceLocation(F, Record, Idx);
7292 Expr *Init = ReadExpr(F);
7293 SourceLocation LParenLoc = ReadSourceLocation(F, Record, Idx);
7294 SourceLocation RParenLoc = ReadSourceLocation(F, Record, Idx);
7295 bool IsWritten = Record[Idx++];
7296 unsigned SourceOrderOrNumArrayIndices;
7297 SmallVector<VarDecl *, 8> Indices;
7298 if (IsWritten) {
7299 SourceOrderOrNumArrayIndices = Record[Idx++];
7300 } else {
7301 SourceOrderOrNumArrayIndices = Record[Idx++];
7302 Indices.reserve(SourceOrderOrNumArrayIndices);
7303 for (unsigned i=0; i != SourceOrderOrNumArrayIndices; ++i)
7304 Indices.push_back(ReadDeclAs<VarDecl>(F, Record, Idx));
7305 }
7306
7307 CXXCtorInitializer *BOMInit;
7308 if (Type == CTOR_INITIALIZER_BASE) {
7309 BOMInit = new (Context) CXXCtorInitializer(Context, TInfo, IsBaseVirtual,
7310 LParenLoc, Init, RParenLoc,
7311 MemberOrEllipsisLoc);
7312 } else if (Type == CTOR_INITIALIZER_DELEGATING) {
7313 BOMInit = new (Context) CXXCtorInitializer(Context, TInfo, LParenLoc,
7314 Init, RParenLoc);
7315 } else if (IsWritten) {
7316 if (Member)
7317 BOMInit = new (Context) CXXCtorInitializer(Context, Member, MemberOrEllipsisLoc,
7318 LParenLoc, Init, RParenLoc);
7319 else
7320 BOMInit = new (Context) CXXCtorInitializer(Context, IndirectMember,
7321 MemberOrEllipsisLoc, LParenLoc,
7322 Init, RParenLoc);
7323 } else {
Argyrios Kyrtzidis794671d2013-05-30 23:59:46 +00007324 if (IndirectMember) {
7325 assert(Indices.empty() && "Indirect field improperly initialized");
7326 BOMInit = new (Context) CXXCtorInitializer(Context, IndirectMember,
7327 MemberOrEllipsisLoc, LParenLoc,
7328 Init, RParenLoc);
7329 } else {
7330 BOMInit = CXXCtorInitializer::Create(Context, Member, MemberOrEllipsisLoc,
7331 LParenLoc, Init, RParenLoc,
7332 Indices.data(), Indices.size());
7333 }
Guy Benyei11169dd2012-12-18 14:30:41 +00007334 }
7335
7336 if (IsWritten)
7337 BOMInit->setSourceOrder(SourceOrderOrNumArrayIndices);
7338 CtorInitializers[i] = BOMInit;
7339 }
7340 }
7341
7342 return std::make_pair(CtorInitializers, NumInitializers);
7343}
7344
7345NestedNameSpecifier *
7346ASTReader::ReadNestedNameSpecifier(ModuleFile &F,
7347 const RecordData &Record, unsigned &Idx) {
7348 unsigned N = Record[Idx++];
7349 NestedNameSpecifier *NNS = 0, *Prev = 0;
7350 for (unsigned I = 0; I != N; ++I) {
7351 NestedNameSpecifier::SpecifierKind Kind
7352 = (NestedNameSpecifier::SpecifierKind)Record[Idx++];
7353 switch (Kind) {
7354 case NestedNameSpecifier::Identifier: {
7355 IdentifierInfo *II = GetIdentifierInfo(F, Record, Idx);
7356 NNS = NestedNameSpecifier::Create(Context, Prev, II);
7357 break;
7358 }
7359
7360 case NestedNameSpecifier::Namespace: {
7361 NamespaceDecl *NS = ReadDeclAs<NamespaceDecl>(F, Record, Idx);
7362 NNS = NestedNameSpecifier::Create(Context, Prev, NS);
7363 break;
7364 }
7365
7366 case NestedNameSpecifier::NamespaceAlias: {
7367 NamespaceAliasDecl *Alias =ReadDeclAs<NamespaceAliasDecl>(F, Record, Idx);
7368 NNS = NestedNameSpecifier::Create(Context, Prev, Alias);
7369 break;
7370 }
7371
7372 case NestedNameSpecifier::TypeSpec:
7373 case NestedNameSpecifier::TypeSpecWithTemplate: {
7374 const Type *T = readType(F, Record, Idx).getTypePtrOrNull();
7375 if (!T)
7376 return 0;
7377
7378 bool Template = Record[Idx++];
7379 NNS = NestedNameSpecifier::Create(Context, Prev, Template, T);
7380 break;
7381 }
7382
7383 case NestedNameSpecifier::Global: {
7384 NNS = NestedNameSpecifier::GlobalSpecifier(Context);
7385 // No associated value, and there can't be a prefix.
7386 break;
7387 }
7388 }
7389 Prev = NNS;
7390 }
7391 return NNS;
7392}
7393
7394NestedNameSpecifierLoc
7395ASTReader::ReadNestedNameSpecifierLoc(ModuleFile &F, const RecordData &Record,
7396 unsigned &Idx) {
7397 unsigned N = Record[Idx++];
7398 NestedNameSpecifierLocBuilder Builder;
7399 for (unsigned I = 0; I != N; ++I) {
7400 NestedNameSpecifier::SpecifierKind Kind
7401 = (NestedNameSpecifier::SpecifierKind)Record[Idx++];
7402 switch (Kind) {
7403 case NestedNameSpecifier::Identifier: {
7404 IdentifierInfo *II = GetIdentifierInfo(F, Record, Idx);
7405 SourceRange Range = ReadSourceRange(F, Record, Idx);
7406 Builder.Extend(Context, II, Range.getBegin(), Range.getEnd());
7407 break;
7408 }
7409
7410 case NestedNameSpecifier::Namespace: {
7411 NamespaceDecl *NS = ReadDeclAs<NamespaceDecl>(F, Record, Idx);
7412 SourceRange Range = ReadSourceRange(F, Record, Idx);
7413 Builder.Extend(Context, NS, Range.getBegin(), Range.getEnd());
7414 break;
7415 }
7416
7417 case NestedNameSpecifier::NamespaceAlias: {
7418 NamespaceAliasDecl *Alias =ReadDeclAs<NamespaceAliasDecl>(F, Record, Idx);
7419 SourceRange Range = ReadSourceRange(F, Record, Idx);
7420 Builder.Extend(Context, Alias, Range.getBegin(), Range.getEnd());
7421 break;
7422 }
7423
7424 case NestedNameSpecifier::TypeSpec:
7425 case NestedNameSpecifier::TypeSpecWithTemplate: {
7426 bool Template = Record[Idx++];
7427 TypeSourceInfo *T = GetTypeSourceInfo(F, Record, Idx);
7428 if (!T)
7429 return NestedNameSpecifierLoc();
7430 SourceLocation ColonColonLoc = ReadSourceLocation(F, Record, Idx);
7431
7432 // FIXME: 'template' keyword location not saved anywhere, so we fake it.
7433 Builder.Extend(Context,
7434 Template? T->getTypeLoc().getBeginLoc() : SourceLocation(),
7435 T->getTypeLoc(), ColonColonLoc);
7436 break;
7437 }
7438
7439 case NestedNameSpecifier::Global: {
7440 SourceLocation ColonColonLoc = ReadSourceLocation(F, Record, Idx);
7441 Builder.MakeGlobal(Context, ColonColonLoc);
7442 break;
7443 }
7444 }
7445 }
7446
7447 return Builder.getWithLocInContext(Context);
7448}
7449
7450SourceRange
7451ASTReader::ReadSourceRange(ModuleFile &F, const RecordData &Record,
7452 unsigned &Idx) {
7453 SourceLocation beg = ReadSourceLocation(F, Record, Idx);
7454 SourceLocation end = ReadSourceLocation(F, Record, Idx);
7455 return SourceRange(beg, end);
7456}
7457
7458/// \brief Read an integral value
7459llvm::APInt ASTReader::ReadAPInt(const RecordData &Record, unsigned &Idx) {
7460 unsigned BitWidth = Record[Idx++];
7461 unsigned NumWords = llvm::APInt::getNumWords(BitWidth);
7462 llvm::APInt Result(BitWidth, NumWords, &Record[Idx]);
7463 Idx += NumWords;
7464 return Result;
7465}
7466
7467/// \brief Read a signed integral value
7468llvm::APSInt ASTReader::ReadAPSInt(const RecordData &Record, unsigned &Idx) {
7469 bool isUnsigned = Record[Idx++];
7470 return llvm::APSInt(ReadAPInt(Record, Idx), isUnsigned);
7471}
7472
7473/// \brief Read a floating-point value
Tim Northover178723a2013-01-22 09:46:51 +00007474llvm::APFloat ASTReader::ReadAPFloat(const RecordData &Record,
7475 const llvm::fltSemantics &Sem,
7476 unsigned &Idx) {
7477 return llvm::APFloat(Sem, ReadAPInt(Record, Idx));
Guy Benyei11169dd2012-12-18 14:30:41 +00007478}
7479
7480// \brief Read a string
7481std::string ASTReader::ReadString(const RecordData &Record, unsigned &Idx) {
7482 unsigned Len = Record[Idx++];
7483 std::string Result(Record.data() + Idx, Record.data() + Idx + Len);
7484 Idx += Len;
7485 return Result;
7486}
7487
7488VersionTuple ASTReader::ReadVersionTuple(const RecordData &Record,
7489 unsigned &Idx) {
7490 unsigned Major = Record[Idx++];
7491 unsigned Minor = Record[Idx++];
7492 unsigned Subminor = Record[Idx++];
7493 if (Minor == 0)
7494 return VersionTuple(Major);
7495 if (Subminor == 0)
7496 return VersionTuple(Major, Minor - 1);
7497 return VersionTuple(Major, Minor - 1, Subminor - 1);
7498}
7499
7500CXXTemporary *ASTReader::ReadCXXTemporary(ModuleFile &F,
7501 const RecordData &Record,
7502 unsigned &Idx) {
7503 CXXDestructorDecl *Decl = ReadDeclAs<CXXDestructorDecl>(F, Record, Idx);
7504 return CXXTemporary::Create(Context, Decl);
7505}
7506
7507DiagnosticBuilder ASTReader::Diag(unsigned DiagID) {
Argyrios Kyrtzidisdc9fdaf2013-05-24 05:44:08 +00007508 return Diag(CurrentImportLoc, DiagID);
Guy Benyei11169dd2012-12-18 14:30:41 +00007509}
7510
7511DiagnosticBuilder ASTReader::Diag(SourceLocation Loc, unsigned DiagID) {
7512 return Diags.Report(Loc, DiagID);
7513}
7514
7515/// \brief Retrieve the identifier table associated with the
7516/// preprocessor.
7517IdentifierTable &ASTReader::getIdentifierTable() {
7518 return PP.getIdentifierTable();
7519}
7520
7521/// \brief Record that the given ID maps to the given switch-case
7522/// statement.
7523void ASTReader::RecordSwitchCaseID(SwitchCase *SC, unsigned ID) {
7524 assert((*CurrSwitchCaseStmts)[ID] == 0 &&
7525 "Already have a SwitchCase with this ID");
7526 (*CurrSwitchCaseStmts)[ID] = SC;
7527}
7528
7529/// \brief Retrieve the switch-case statement with the given ID.
7530SwitchCase *ASTReader::getSwitchCaseWithID(unsigned ID) {
7531 assert((*CurrSwitchCaseStmts)[ID] != 0 && "No SwitchCase with this ID");
7532 return (*CurrSwitchCaseStmts)[ID];
7533}
7534
7535void ASTReader::ClearSwitchCaseIDs() {
7536 CurrSwitchCaseStmts->clear();
7537}
7538
7539void ASTReader::ReadComments() {
7540 std::vector<RawComment *> Comments;
Chris Lattner7fb3bef2013-01-20 00:56:42 +00007541 for (SmallVectorImpl<std::pair<BitstreamCursor,
Guy Benyei11169dd2012-12-18 14:30:41 +00007542 serialization::ModuleFile *> >::iterator
7543 I = CommentsCursors.begin(),
7544 E = CommentsCursors.end();
7545 I != E; ++I) {
Chris Lattner7fb3bef2013-01-20 00:56:42 +00007546 BitstreamCursor &Cursor = I->first;
Guy Benyei11169dd2012-12-18 14:30:41 +00007547 serialization::ModuleFile &F = *I->second;
7548 SavedStreamPosition SavedPosition(Cursor);
7549
7550 RecordData Record;
7551 while (true) {
Chris Lattner7fb3bef2013-01-20 00:56:42 +00007552 llvm::BitstreamEntry Entry =
7553 Cursor.advanceSkippingSubblocks(BitstreamCursor::AF_DontPopBlockAtEnd);
7554
7555 switch (Entry.Kind) {
7556 case llvm::BitstreamEntry::SubBlock: // Handled for us already.
7557 case llvm::BitstreamEntry::Error:
7558 Error("malformed block record in AST file");
7559 return;
7560 case llvm::BitstreamEntry::EndBlock:
7561 goto NextCursor;
7562 case llvm::BitstreamEntry::Record:
7563 // The interesting case.
Guy Benyei11169dd2012-12-18 14:30:41 +00007564 break;
Guy Benyei11169dd2012-12-18 14:30:41 +00007565 }
7566
7567 // Read a record.
7568 Record.clear();
Chris Lattner0e6c9402013-01-20 02:38:54 +00007569 switch ((CommentRecordTypes)Cursor.readRecord(Entry.ID, Record)) {
Guy Benyei11169dd2012-12-18 14:30:41 +00007570 case COMMENTS_RAW_COMMENT: {
7571 unsigned Idx = 0;
7572 SourceRange SR = ReadSourceRange(F, Record, Idx);
7573 RawComment::CommentKind Kind =
7574 (RawComment::CommentKind) Record[Idx++];
7575 bool IsTrailingComment = Record[Idx++];
7576 bool IsAlmostTrailingComment = Record[Idx++];
Dmitri Gribenkoa7d16ce2013-04-10 15:35:17 +00007577 Comments.push_back(new (Context) RawComment(
7578 SR, Kind, IsTrailingComment, IsAlmostTrailingComment,
7579 Context.getLangOpts().CommentOpts.ParseAllComments));
Guy Benyei11169dd2012-12-18 14:30:41 +00007580 break;
7581 }
7582 }
7583 }
Chris Lattner7fb3bef2013-01-20 00:56:42 +00007584 NextCursor:;
Guy Benyei11169dd2012-12-18 14:30:41 +00007585 }
7586 Context.Comments.addCommentsToFront(Comments);
7587}
7588
7589void ASTReader::finishPendingActions() {
7590 while (!PendingIdentifierInfos.empty() || !PendingDeclChains.empty() ||
Richard Smith2b9e3e32013-10-18 06:05:18 +00007591 !PendingMacroIDs.empty() || !PendingDeclContextInfos.empty() ||
7592 !PendingOdrMergeChecks.empty()) {
Guy Benyei11169dd2012-12-18 14:30:41 +00007593 // If any identifiers with corresponding top-level declarations have
7594 // been loaded, load those declarations now.
Craig Topper79be4cd2013-07-05 04:33:53 +00007595 typedef llvm::DenseMap<IdentifierInfo *, SmallVector<Decl *, 2> >
7596 TopLevelDeclsMap;
7597 TopLevelDeclsMap TopLevelDecls;
7598
Guy Benyei11169dd2012-12-18 14:30:41 +00007599 while (!PendingIdentifierInfos.empty()) {
Douglas Gregor6168bd22013-02-18 15:53:43 +00007600 // FIXME: std::move
7601 IdentifierInfo *II = PendingIdentifierInfos.back().first;
7602 SmallVector<uint32_t, 4> DeclIDs = PendingIdentifierInfos.back().second;
Douglas Gregorcb15f082013-02-19 18:26:28 +00007603 PendingIdentifierInfos.pop_back();
Douglas Gregor6168bd22013-02-18 15:53:43 +00007604
7605 SetGloballyVisibleDecls(II, DeclIDs, &TopLevelDecls[II]);
Guy Benyei11169dd2012-12-18 14:30:41 +00007606 }
7607
7608 // Load pending declaration chains.
7609 for (unsigned I = 0; I != PendingDeclChains.size(); ++I) {
7610 loadPendingDeclChain(PendingDeclChains[I]);
7611 PendingDeclChainsKnown.erase(PendingDeclChains[I]);
7612 }
7613 PendingDeclChains.clear();
7614
Douglas Gregor6168bd22013-02-18 15:53:43 +00007615 // Make the most recent of the top-level declarations visible.
Craig Topper79be4cd2013-07-05 04:33:53 +00007616 for (TopLevelDeclsMap::iterator TLD = TopLevelDecls.begin(),
7617 TLDEnd = TopLevelDecls.end(); TLD != TLDEnd; ++TLD) {
Douglas Gregor6168bd22013-02-18 15:53:43 +00007618 IdentifierInfo *II = TLD->first;
7619 for (unsigned I = 0, N = TLD->second.size(); I != N; ++I) {
Argyrios Kyrtzidise5edbf92013-04-26 21:33:35 +00007620 pushExternalDeclIntoScope(cast<NamedDecl>(TLD->second[I]), II);
Douglas Gregor6168bd22013-02-18 15:53:43 +00007621 }
7622 }
7623
Guy Benyei11169dd2012-12-18 14:30:41 +00007624 // Load any pending macro definitions.
7625 for (unsigned I = 0; I != PendingMacroIDs.size(); ++I) {
Argyrios Kyrtzidiseb663da2013-03-22 21:12:57 +00007626 IdentifierInfo *II = PendingMacroIDs.begin()[I].first;
7627 SmallVector<PendingMacroInfo, 2> GlobalIDs;
7628 GlobalIDs.swap(PendingMacroIDs.begin()[I].second);
7629 // Initialize the macro history from chained-PCHs ahead of module imports.
Richard Smith49f906a2014-03-01 00:08:04 +00007630 for (unsigned IDIdx = 0, NumIDs = GlobalIDs.size(); IDIdx != NumIDs;
Argyrios Kyrtzidis719736c2013-01-19 03:14:56 +00007631 ++IDIdx) {
Argyrios Kyrtzidiseb663da2013-03-22 21:12:57 +00007632 const PendingMacroInfo &Info = GlobalIDs[IDIdx];
7633 if (Info.M->Kind != MK_Module)
7634 resolvePendingMacro(II, Info);
7635 }
7636 // Handle module imports.
Richard Smith49f906a2014-03-01 00:08:04 +00007637 for (unsigned IDIdx = 0, NumIDs = GlobalIDs.size(); IDIdx != NumIDs;
Argyrios Kyrtzidiseb663da2013-03-22 21:12:57 +00007638 ++IDIdx) {
7639 const PendingMacroInfo &Info = GlobalIDs[IDIdx];
7640 if (Info.M->Kind == MK_Module)
7641 resolvePendingMacro(II, Info);
Guy Benyei11169dd2012-12-18 14:30:41 +00007642 }
7643 }
7644 PendingMacroIDs.clear();
Argyrios Kyrtzidis83a6e3b2013-02-16 00:48:59 +00007645
7646 // Wire up the DeclContexts for Decls that we delayed setting until
7647 // recursive loading is completed.
7648 while (!PendingDeclContextInfos.empty()) {
7649 PendingDeclContextInfo Info = PendingDeclContextInfos.front();
7650 PendingDeclContextInfos.pop_front();
7651 DeclContext *SemaDC = cast<DeclContext>(GetDecl(Info.SemaDC));
7652 DeclContext *LexicalDC = cast<DeclContext>(GetDecl(Info.LexicalDC));
7653 Info.D->setDeclContextsImpl(SemaDC, LexicalDC, getContext());
7654 }
Richard Smith2b9e3e32013-10-18 06:05:18 +00007655
7656 // For each declaration from a merged context, check that the canonical
7657 // definition of that context also contains a declaration of the same
7658 // entity.
7659 while (!PendingOdrMergeChecks.empty()) {
7660 NamedDecl *D = PendingOdrMergeChecks.pop_back_val();
7661
7662 // FIXME: Skip over implicit declarations for now. This matters for things
7663 // like implicitly-declared special member functions. This isn't entirely
7664 // correct; we can end up with multiple unmerged declarations of the same
7665 // implicit entity.
7666 if (D->isImplicit())
7667 continue;
7668
7669 DeclContext *CanonDef = D->getDeclContext();
7670 DeclContext::lookup_result R = CanonDef->lookup(D->getDeclName());
7671
7672 bool Found = false;
7673 const Decl *DCanon = D->getCanonicalDecl();
7674
7675 llvm::SmallVector<const NamedDecl*, 4> Candidates;
7676 for (DeclContext::lookup_iterator I = R.begin(), E = R.end();
7677 !Found && I != E; ++I) {
7678 for (Decl::redecl_iterator RI = (*I)->redecls_begin(),
7679 RE = (*I)->redecls_end();
7680 RI != RE; ++RI) {
7681 if ((*RI)->getLexicalDeclContext() == CanonDef) {
7682 // This declaration is present in the canonical definition. If it's
7683 // in the same redecl chain, it's the one we're looking for.
7684 if ((*RI)->getCanonicalDecl() == DCanon)
7685 Found = true;
7686 else
7687 Candidates.push_back(cast<NamedDecl>(*RI));
7688 break;
7689 }
7690 }
7691 }
7692
7693 if (!Found) {
7694 D->setInvalidDecl();
7695
7696 Module *CanonDefModule = cast<Decl>(CanonDef)->getOwningModule();
7697 Diag(D->getLocation(), diag::err_module_odr_violation_missing_decl)
7698 << D << D->getOwningModule()->getFullModuleName()
7699 << CanonDef << !CanonDefModule
7700 << (CanonDefModule ? CanonDefModule->getFullModuleName() : "");
7701
7702 if (Candidates.empty())
7703 Diag(cast<Decl>(CanonDef)->getLocation(),
7704 diag::note_module_odr_violation_no_possible_decls) << D;
7705 else {
7706 for (unsigned I = 0, N = Candidates.size(); I != N; ++I)
7707 Diag(Candidates[I]->getLocation(),
7708 diag::note_module_odr_violation_possible_decl)
7709 << Candidates[I];
7710 }
7711 }
7712 }
Guy Benyei11169dd2012-12-18 14:30:41 +00007713 }
7714
7715 // If we deserialized any C++ or Objective-C class definitions, any
7716 // Objective-C protocol definitions, or any redeclarable templates, make sure
7717 // that all redeclarations point to the definitions. Note that this can only
7718 // happen now, after the redeclaration chains have been fully wired.
7719 for (llvm::SmallPtrSet<Decl *, 4>::iterator D = PendingDefinitions.begin(),
7720 DEnd = PendingDefinitions.end();
7721 D != DEnd; ++D) {
7722 if (TagDecl *TD = dyn_cast<TagDecl>(*D)) {
7723 if (const TagType *TagT = dyn_cast<TagType>(TD->TypeForDecl)) {
7724 // Make sure that the TagType points at the definition.
7725 const_cast<TagType*>(TagT)->decl = TD;
7726 }
7727
7728 if (CXXRecordDecl *RD = dyn_cast<CXXRecordDecl>(*D)) {
7729 for (CXXRecordDecl::redecl_iterator R = RD->redecls_begin(),
7730 REnd = RD->redecls_end();
7731 R != REnd; ++R)
7732 cast<CXXRecordDecl>(*R)->DefinitionData = RD->DefinitionData;
7733
7734 }
7735
7736 continue;
7737 }
7738
7739 if (ObjCInterfaceDecl *ID = dyn_cast<ObjCInterfaceDecl>(*D)) {
7740 // Make sure that the ObjCInterfaceType points at the definition.
7741 const_cast<ObjCInterfaceType *>(cast<ObjCInterfaceType>(ID->TypeForDecl))
7742 ->Decl = ID;
7743
7744 for (ObjCInterfaceDecl::redecl_iterator R = ID->redecls_begin(),
7745 REnd = ID->redecls_end();
7746 R != REnd; ++R)
7747 R->Data = ID->Data;
7748
7749 continue;
7750 }
7751
7752 if (ObjCProtocolDecl *PD = dyn_cast<ObjCProtocolDecl>(*D)) {
7753 for (ObjCProtocolDecl::redecl_iterator R = PD->redecls_begin(),
7754 REnd = PD->redecls_end();
7755 R != REnd; ++R)
7756 R->Data = PD->Data;
7757
7758 continue;
7759 }
7760
7761 RedeclarableTemplateDecl *RTD
7762 = cast<RedeclarableTemplateDecl>(*D)->getCanonicalDecl();
7763 for (RedeclarableTemplateDecl::redecl_iterator R = RTD->redecls_begin(),
7764 REnd = RTD->redecls_end();
7765 R != REnd; ++R)
7766 R->Common = RTD->Common;
7767 }
7768 PendingDefinitions.clear();
7769
7770 // Load the bodies of any functions or methods we've encountered. We do
7771 // this now (delayed) so that we can be sure that the declaration chains
7772 // have been fully wired up.
7773 for (PendingBodiesMap::iterator PB = PendingBodies.begin(),
7774 PBEnd = PendingBodies.end();
7775 PB != PBEnd; ++PB) {
7776 if (FunctionDecl *FD = dyn_cast<FunctionDecl>(PB->first)) {
7777 // FIXME: Check for =delete/=default?
7778 // FIXME: Complain about ODR violations here?
7779 if (!getContext().getLangOpts().Modules || !FD->hasBody())
7780 FD->setLazyBody(PB->second);
7781 continue;
7782 }
7783
7784 ObjCMethodDecl *MD = cast<ObjCMethodDecl>(PB->first);
7785 if (!getContext().getLangOpts().Modules || !MD->hasBody())
7786 MD->setLazyBody(PB->second);
7787 }
7788 PendingBodies.clear();
7789}
7790
7791void ASTReader::FinishedDeserializing() {
7792 assert(NumCurrentElementsDeserializing &&
7793 "FinishedDeserializing not paired with StartedDeserializing");
7794 if (NumCurrentElementsDeserializing == 1) {
7795 // We decrease NumCurrentElementsDeserializing only after pending actions
7796 // are finished, to avoid recursively re-calling finishPendingActions().
7797 finishPendingActions();
7798 }
7799 --NumCurrentElementsDeserializing;
7800
7801 if (NumCurrentElementsDeserializing == 0 &&
7802 Consumer && !PassingDeclsToConsumer) {
7803 // Guard variable to avoid recursively redoing the process of passing
7804 // decls to consumer.
7805 SaveAndRestore<bool> GuardPassingDeclsToConsumer(PassingDeclsToConsumer,
7806 true);
7807
7808 while (!InterestingDecls.empty()) {
7809 // We are not in recursive loading, so it's safe to pass the "interesting"
7810 // decls to the consumer.
7811 Decl *D = InterestingDecls.front();
7812 InterestingDecls.pop_front();
7813 PassInterestingDeclToConsumer(D);
7814 }
7815 }
7816}
7817
Argyrios Kyrtzidise5edbf92013-04-26 21:33:35 +00007818void ASTReader::pushExternalDeclIntoScope(NamedDecl *D, DeclarationName Name) {
Rafael Espindola7b56f6c2013-10-19 16:55:03 +00007819 D = D->getMostRecentDecl();
Argyrios Kyrtzidise5edbf92013-04-26 21:33:35 +00007820
7821 if (SemaObj->IdResolver.tryAddTopLevelDecl(D, Name) && SemaObj->TUScope) {
7822 SemaObj->TUScope->AddDecl(D);
7823 } else if (SemaObj->TUScope) {
7824 // Adding the decl to IdResolver may have failed because it was already in
7825 // (even though it was not added in scope). If it is already in, make sure
7826 // it gets in the scope as well.
7827 if (std::find(SemaObj->IdResolver.begin(Name),
7828 SemaObj->IdResolver.end(), D) != SemaObj->IdResolver.end())
7829 SemaObj->TUScope->AddDecl(D);
7830 }
7831}
7832
Guy Benyei11169dd2012-12-18 14:30:41 +00007833ASTReader::ASTReader(Preprocessor &PP, ASTContext &Context,
7834 StringRef isysroot, bool DisableValidation,
Ben Langmuir2cb4a782014-02-05 22:21:15 +00007835 bool AllowASTWithCompilerErrors,
7836 bool AllowConfigurationMismatch,
Ben Langmuir3d4417c2014-02-07 17:31:11 +00007837 bool ValidateSystemInputs,
Ben Langmuir2cb4a782014-02-05 22:21:15 +00007838 bool UseGlobalIndex)
Guy Benyei11169dd2012-12-18 14:30:41 +00007839 : Listener(new PCHValidator(PP, *this)), DeserializationListener(0),
7840 SourceMgr(PP.getSourceManager()), FileMgr(PP.getFileManager()),
7841 Diags(PP.getDiagnostics()), SemaObj(0), PP(PP), Context(Context),
7842 Consumer(0), ModuleMgr(PP.getFileManager()),
7843 isysroot(isysroot), DisableValidation(DisableValidation),
Douglas Gregor00a50f72013-01-25 00:38:33 +00007844 AllowASTWithCompilerErrors(AllowASTWithCompilerErrors),
Ben Langmuir2cb4a782014-02-05 22:21:15 +00007845 AllowConfigurationMismatch(AllowConfigurationMismatch),
Ben Langmuir3d4417c2014-02-07 17:31:11 +00007846 ValidateSystemInputs(ValidateSystemInputs),
Douglas Gregorc1bbec82013-01-25 00:45:27 +00007847 UseGlobalIndex(UseGlobalIndex), TriedLoadingGlobalIndex(false),
Guy Benyei11169dd2012-12-18 14:30:41 +00007848 CurrentGeneration(0), CurrSwitchCaseStmts(&SwitchCaseStmts),
7849 NumSLocEntriesRead(0), TotalNumSLocEntries(0),
Douglas Gregor00a50f72013-01-25 00:38:33 +00007850 NumStatementsRead(0), TotalNumStatements(0), NumMacrosRead(0),
7851 TotalNumMacros(0), NumIdentifierLookups(0), NumIdentifierLookupHits(0),
7852 NumSelectorsRead(0), NumMethodPoolEntriesRead(0),
Douglas Gregorad2f7a52013-01-28 17:54:36 +00007853 NumMethodPoolLookups(0), NumMethodPoolHits(0),
7854 NumMethodPoolTableLookups(0), NumMethodPoolTableHits(0),
7855 TotalNumMethodPoolEntries(0),
Guy Benyei11169dd2012-12-18 14:30:41 +00007856 NumLexicalDeclContextsRead(0), TotalLexicalDeclContexts(0),
7857 NumVisibleDeclContextsRead(0), TotalVisibleDeclContexts(0),
7858 TotalModulesSizeInBits(0), NumCurrentElementsDeserializing(0),
7859 PassingDeclsToConsumer(false),
Richard Smith629ff362013-07-31 00:26:46 +00007860 NumCXXBaseSpecifiersLoaded(0), ReadingKind(Read_None)
Guy Benyei11169dd2012-12-18 14:30:41 +00007861{
7862 SourceMgr.setExternalSLocEntrySource(this);
7863}
7864
7865ASTReader::~ASTReader() {
7866 for (DeclContextVisibleUpdatesPending::iterator
7867 I = PendingVisibleUpdates.begin(),
7868 E = PendingVisibleUpdates.end();
7869 I != E; ++I) {
7870 for (DeclContextVisibleUpdates::iterator J = I->second.begin(),
7871 F = I->second.end();
7872 J != F; ++J)
7873 delete J->first;
7874 }
7875}