blob: 10a9282c98070269eb1fa8a47aaa0aa2f3c79a6f [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"
Ben Langmuirb92de022014-04-29 16:25:26 +000032#include "clang/Frontend/Utils.h"
Guy Benyei11169dd2012-12-18 14:30:41 +000033#include "clang/Lex/HeaderSearch.h"
34#include "clang/Lex/HeaderSearchOptions.h"
35#include "clang/Lex/MacroInfo.h"
36#include "clang/Lex/PreprocessingRecord.h"
37#include "clang/Lex/Preprocessor.h"
38#include "clang/Lex/PreprocessorOptions.h"
39#include "clang/Sema/Scope.h"
40#include "clang/Sema/Sema.h"
41#include "clang/Serialization/ASTDeserializationListener.h"
Douglas Gregore060e572013-01-25 01:03:03 +000042#include "clang/Serialization/GlobalModuleIndex.h"
Guy Benyei11169dd2012-12-18 14:30:41 +000043#include "clang/Serialization/ModuleManager.h"
44#include "clang/Serialization/SerializationDiagnostic.h"
Argyrios Kyrtzidis5c2a3452013-03-06 18:12:47 +000045#include "llvm/ADT/Hashing.h"
Guy Benyei11169dd2012-12-18 14:30:41 +000046#include "llvm/ADT/StringExtras.h"
47#include "llvm/Bitcode/BitstreamReader.h"
48#include "llvm/Support/ErrorHandling.h"
49#include "llvm/Support/FileSystem.h"
50#include "llvm/Support/MemoryBuffer.h"
51#include "llvm/Support/Path.h"
52#include "llvm/Support/SaveAndRestore.h"
Dmitri Gribenkof430da42014-02-12 10:33:14 +000053#include "llvm/Support/raw_ostream.h"
Guy Benyei11169dd2012-12-18 14:30:41 +000054#include "llvm/Support/system_error.h"
55#include <algorithm>
Chris Lattner91f373e2013-01-20 00:57:52 +000056#include <cstdio>
Guy Benyei11169dd2012-12-18 14:30:41 +000057#include <iterator>
58
59using namespace clang;
60using namespace clang::serialization;
61using namespace clang::serialization::reader;
Chris Lattner7fb3bef2013-01-20 00:56:42 +000062using llvm::BitstreamCursor;
Guy Benyei11169dd2012-12-18 14:30:41 +000063
Ben Langmuircb69b572014-03-07 06:40:32 +000064
65//===----------------------------------------------------------------------===//
66// ChainedASTReaderListener implementation
67//===----------------------------------------------------------------------===//
68
69bool
70ChainedASTReaderListener::ReadFullVersionInformation(StringRef FullVersion) {
71 return First->ReadFullVersionInformation(FullVersion) ||
72 Second->ReadFullVersionInformation(FullVersion);
73}
Ben Langmuir4f5212a2014-04-14 22:12:44 +000074void ChainedASTReaderListener::ReadModuleName(StringRef ModuleName) {
75 First->ReadModuleName(ModuleName);
76 Second->ReadModuleName(ModuleName);
77}
78void ChainedASTReaderListener::ReadModuleMapFile(StringRef ModuleMapPath) {
79 First->ReadModuleMapFile(ModuleMapPath);
80 Second->ReadModuleMapFile(ModuleMapPath);
81}
Ben Langmuircb69b572014-03-07 06:40:32 +000082bool ChainedASTReaderListener::ReadLanguageOptions(const LangOptions &LangOpts,
83 bool Complain) {
84 return First->ReadLanguageOptions(LangOpts, Complain) ||
85 Second->ReadLanguageOptions(LangOpts, Complain);
86}
87bool
88ChainedASTReaderListener::ReadTargetOptions(const TargetOptions &TargetOpts,
89 bool Complain) {
90 return First->ReadTargetOptions(TargetOpts, Complain) ||
91 Second->ReadTargetOptions(TargetOpts, Complain);
92}
93bool ChainedASTReaderListener::ReadDiagnosticOptions(
Ben Langmuirb92de022014-04-29 16:25:26 +000094 IntrusiveRefCntPtr<DiagnosticOptions> DiagOpts, bool Complain) {
Ben Langmuircb69b572014-03-07 06:40:32 +000095 return First->ReadDiagnosticOptions(DiagOpts, Complain) ||
96 Second->ReadDiagnosticOptions(DiagOpts, Complain);
97}
98bool
99ChainedASTReaderListener::ReadFileSystemOptions(const FileSystemOptions &FSOpts,
100 bool Complain) {
101 return First->ReadFileSystemOptions(FSOpts, Complain) ||
102 Second->ReadFileSystemOptions(FSOpts, Complain);
103}
104
105bool ChainedASTReaderListener::ReadHeaderSearchOptions(
106 const HeaderSearchOptions &HSOpts, bool Complain) {
107 return First->ReadHeaderSearchOptions(HSOpts, Complain) ||
108 Second->ReadHeaderSearchOptions(HSOpts, Complain);
109}
110bool ChainedASTReaderListener::ReadPreprocessorOptions(
111 const PreprocessorOptions &PPOpts, bool Complain,
112 std::string &SuggestedPredefines) {
113 return First->ReadPreprocessorOptions(PPOpts, Complain,
114 SuggestedPredefines) ||
115 Second->ReadPreprocessorOptions(PPOpts, Complain, SuggestedPredefines);
116}
117void ChainedASTReaderListener::ReadCounter(const serialization::ModuleFile &M,
118 unsigned Value) {
119 First->ReadCounter(M, Value);
120 Second->ReadCounter(M, Value);
121}
122bool ChainedASTReaderListener::needsInputFileVisitation() {
123 return First->needsInputFileVisitation() ||
124 Second->needsInputFileVisitation();
125}
126bool ChainedASTReaderListener::needsSystemInputFileVisitation() {
127 return First->needsSystemInputFileVisitation() ||
128 Second->needsSystemInputFileVisitation();
129}
Argyrios Kyrtzidis6d0753d2014-03-14 03:07:38 +0000130void ChainedASTReaderListener::visitModuleFile(StringRef Filename) {
131 First->visitModuleFile(Filename);
132 Second->visitModuleFile(Filename);
133}
Ben Langmuircb69b572014-03-07 06:40:32 +0000134bool ChainedASTReaderListener::visitInputFile(StringRef Filename,
Argyrios Kyrtzidis68ccbe02014-03-14 02:26:31 +0000135 bool isSystem,
136 bool isOverridden) {
137 return First->visitInputFile(Filename, isSystem, isOverridden) ||
138 Second->visitInputFile(Filename, isSystem, isOverridden);
Ben Langmuircb69b572014-03-07 06:40:32 +0000139}
140
Guy Benyei11169dd2012-12-18 14:30:41 +0000141//===----------------------------------------------------------------------===//
142// PCH validator implementation
143//===----------------------------------------------------------------------===//
144
145ASTReaderListener::~ASTReaderListener() {}
146
147/// \brief Compare the given set of language options against an existing set of
148/// language options.
149///
150/// \param Diags If non-NULL, diagnostics will be emitted via this engine.
151///
152/// \returns true if the languagae options mis-match, false otherwise.
153static bool checkLanguageOptions(const LangOptions &LangOpts,
154 const LangOptions &ExistingLangOpts,
155 DiagnosticsEngine *Diags) {
156#define LANGOPT(Name, Bits, Default, Description) \
157 if (ExistingLangOpts.Name != LangOpts.Name) { \
158 if (Diags) \
159 Diags->Report(diag::err_pch_langopt_mismatch) \
160 << Description << LangOpts.Name << ExistingLangOpts.Name; \
161 return true; \
162 }
163
164#define VALUE_LANGOPT(Name, Bits, Default, Description) \
165 if (ExistingLangOpts.Name != LangOpts.Name) { \
166 if (Diags) \
167 Diags->Report(diag::err_pch_langopt_value_mismatch) \
168 << Description; \
169 return true; \
170 }
171
172#define ENUM_LANGOPT(Name, Type, Bits, Default, Description) \
173 if (ExistingLangOpts.get##Name() != LangOpts.get##Name()) { \
174 if (Diags) \
175 Diags->Report(diag::err_pch_langopt_value_mismatch) \
176 << Description; \
177 return true; \
178 }
179
180#define BENIGN_LANGOPT(Name, Bits, Default, Description)
181#define BENIGN_ENUM_LANGOPT(Name, Type, Bits, Default, Description)
182#include "clang/Basic/LangOptions.def"
183
184 if (ExistingLangOpts.ObjCRuntime != LangOpts.ObjCRuntime) {
185 if (Diags)
186 Diags->Report(diag::err_pch_langopt_value_mismatch)
187 << "target Objective-C runtime";
188 return true;
189 }
190
Dmitri Gribenkoacf2e782013-02-22 14:21:27 +0000191 if (ExistingLangOpts.CommentOpts.BlockCommandNames !=
192 LangOpts.CommentOpts.BlockCommandNames) {
193 if (Diags)
194 Diags->Report(diag::err_pch_langopt_value_mismatch)
195 << "block command names";
196 return true;
197 }
198
Guy Benyei11169dd2012-12-18 14:30:41 +0000199 return false;
200}
201
202/// \brief Compare the given set of target options against an existing set of
203/// target options.
204///
205/// \param Diags If non-NULL, diagnostics will be emitted via this engine.
206///
207/// \returns true if the target options mis-match, false otherwise.
208static bool checkTargetOptions(const TargetOptions &TargetOpts,
209 const TargetOptions &ExistingTargetOpts,
210 DiagnosticsEngine *Diags) {
211#define CHECK_TARGET_OPT(Field, Name) \
212 if (TargetOpts.Field != ExistingTargetOpts.Field) { \
213 if (Diags) \
214 Diags->Report(diag::err_pch_targetopt_mismatch) \
215 << Name << TargetOpts.Field << ExistingTargetOpts.Field; \
216 return true; \
217 }
218
219 CHECK_TARGET_OPT(Triple, "target");
220 CHECK_TARGET_OPT(CPU, "target CPU");
221 CHECK_TARGET_OPT(ABI, "target ABI");
Guy Benyei11169dd2012-12-18 14:30:41 +0000222#undef CHECK_TARGET_OPT
223
224 // Compare feature sets.
225 SmallVector<StringRef, 4> ExistingFeatures(
226 ExistingTargetOpts.FeaturesAsWritten.begin(),
227 ExistingTargetOpts.FeaturesAsWritten.end());
228 SmallVector<StringRef, 4> ReadFeatures(TargetOpts.FeaturesAsWritten.begin(),
229 TargetOpts.FeaturesAsWritten.end());
230 std::sort(ExistingFeatures.begin(), ExistingFeatures.end());
231 std::sort(ReadFeatures.begin(), ReadFeatures.end());
232
233 unsigned ExistingIdx = 0, ExistingN = ExistingFeatures.size();
234 unsigned ReadIdx = 0, ReadN = ReadFeatures.size();
235 while (ExistingIdx < ExistingN && ReadIdx < ReadN) {
236 if (ExistingFeatures[ExistingIdx] == ReadFeatures[ReadIdx]) {
237 ++ExistingIdx;
238 ++ReadIdx;
239 continue;
240 }
241
242 if (ReadFeatures[ReadIdx] < ExistingFeatures[ExistingIdx]) {
243 if (Diags)
244 Diags->Report(diag::err_pch_targetopt_feature_mismatch)
245 << false << ReadFeatures[ReadIdx];
246 return true;
247 }
248
249 if (Diags)
250 Diags->Report(diag::err_pch_targetopt_feature_mismatch)
251 << true << ExistingFeatures[ExistingIdx];
252 return true;
253 }
254
255 if (ExistingIdx < ExistingN) {
256 if (Diags)
257 Diags->Report(diag::err_pch_targetopt_feature_mismatch)
258 << true << ExistingFeatures[ExistingIdx];
259 return true;
260 }
261
262 if (ReadIdx < ReadN) {
263 if (Diags)
264 Diags->Report(diag::err_pch_targetopt_feature_mismatch)
265 << false << ReadFeatures[ReadIdx];
266 return true;
267 }
268
269 return false;
270}
271
272bool
273PCHValidator::ReadLanguageOptions(const LangOptions &LangOpts,
274 bool Complain) {
275 const LangOptions &ExistingLangOpts = PP.getLangOpts();
276 return checkLanguageOptions(LangOpts, ExistingLangOpts,
277 Complain? &Reader.Diags : 0);
278}
279
280bool PCHValidator::ReadTargetOptions(const TargetOptions &TargetOpts,
281 bool Complain) {
282 const TargetOptions &ExistingTargetOpts = PP.getTargetInfo().getTargetOpts();
283 return checkTargetOptions(TargetOpts, ExistingTargetOpts,
284 Complain? &Reader.Diags : 0);
285}
286
287namespace {
288 typedef llvm::StringMap<std::pair<StringRef, bool /*IsUndef*/> >
289 MacroDefinitionsMap;
Craig Topper3598eb72013-07-05 04:43:31 +0000290 typedef llvm::DenseMap<DeclarationName, SmallVector<NamedDecl *, 8> >
291 DeclsMap;
Guy Benyei11169dd2012-12-18 14:30:41 +0000292}
293
Ben Langmuirb92de022014-04-29 16:25:26 +0000294static bool checkDiagnosticGroupMappings(DiagnosticsEngine &StoredDiags,
295 DiagnosticsEngine &Diags,
296 bool Complain) {
297 typedef DiagnosticsEngine::Level Level;
298
299 // Check current mappings for new -Werror mappings, and the stored mappings
300 // for cases that were explicitly mapped to *not* be errors that are now
301 // errors because of options like -Werror.
302 DiagnosticsEngine *MappingSources[] = { &Diags, &StoredDiags };
303
304 for (DiagnosticsEngine *MappingSource : MappingSources) {
305 for (auto DiagIDMappingPair : MappingSource->getDiagnosticMappings()) {
306 diag::kind DiagID = DiagIDMappingPair.first;
307 Level CurLevel = Diags.getDiagnosticLevel(DiagID, SourceLocation());
308 if (CurLevel < DiagnosticsEngine::Error)
309 continue; // not significant
310 Level StoredLevel =
311 StoredDiags.getDiagnosticLevel(DiagID, SourceLocation());
312 if (StoredLevel < DiagnosticsEngine::Error) {
313 if (Complain)
314 Diags.Report(diag::err_pch_diagopt_mismatch) << "-Werror=" +
315 Diags.getDiagnosticIDs()->getWarningOptionForDiag(DiagID).str();
316 return true;
317 }
318 }
319 }
320
321 return false;
322}
323
324static DiagnosticsEngine::ExtensionHandling
325isExtHandlingFromDiagsError(DiagnosticsEngine &Diags) {
326 DiagnosticsEngine::ExtensionHandling Ext =
327 Diags.getExtensionHandlingBehavior();
328 if (Ext == DiagnosticsEngine::Ext_Warn && Diags.getWarningsAsErrors())
329 Ext = DiagnosticsEngine::Ext_Error;
330 return Ext;
331}
332
333static bool checkDiagnosticMappings(DiagnosticsEngine &StoredDiags,
334 DiagnosticsEngine &Diags,
335 bool IsSystem, bool Complain) {
336 // Top-level options
337 if (IsSystem) {
338 if (Diags.getSuppressSystemWarnings())
339 return false;
340 // If -Wsystem-headers was not enabled before, be conservative
341 if (StoredDiags.getSuppressSystemWarnings()) {
342 if (Complain)
343 Diags.Report(diag::err_pch_diagopt_mismatch) << "-Wsystem-headers";
344 return true;
345 }
346 }
347
348 if (Diags.getWarningsAsErrors() && !StoredDiags.getWarningsAsErrors()) {
349 if (Complain)
350 Diags.Report(diag::err_pch_diagopt_mismatch) << "-Werror";
351 return true;
352 }
353
354 if (Diags.getWarningsAsErrors() && Diags.getEnableAllWarnings() &&
355 !StoredDiags.getEnableAllWarnings()) {
356 if (Complain)
357 Diags.Report(diag::err_pch_diagopt_mismatch) << "-Weverything -Werror";
358 return true;
359 }
360
361 if (isExtHandlingFromDiagsError(Diags) &&
362 !isExtHandlingFromDiagsError(StoredDiags)) {
363 if (Complain)
364 Diags.Report(diag::err_pch_diagopt_mismatch) << "-pedantic-errors";
365 return true;
366 }
367
368 return checkDiagnosticGroupMappings(StoredDiags, Diags, Complain);
369}
370
371bool PCHValidator::ReadDiagnosticOptions(
372 IntrusiveRefCntPtr<DiagnosticOptions> DiagOpts, bool Complain) {
373 DiagnosticsEngine &ExistingDiags = PP.getDiagnostics();
374 IntrusiveRefCntPtr<DiagnosticIDs> DiagIDs(ExistingDiags.getDiagnosticIDs());
375 IntrusiveRefCntPtr<DiagnosticsEngine> Diags(
376 new DiagnosticsEngine(DiagIDs, DiagOpts.getPtr()));
377 // This should never fail, because we would have processed these options
378 // before writing them to an ASTFile.
379 ProcessWarningOptions(*Diags, *DiagOpts, /*Report*/false);
380
381 ModuleManager &ModuleMgr = Reader.getModuleManager();
382 assert(ModuleMgr.size() >= 1 && "what ASTFile is this then");
383
384 // If the original import came from a file explicitly generated by the user,
385 // don't check the diagnostic mappings.
386 // FIXME: currently this is approximated by checking whether this is not a
387 // module import.
388 // Note: ModuleMgr.rbegin() may not be the current module, but it must be in
389 // the transitive closure of its imports, since unrelated modules cannot be
390 // imported until after this module finishes validation.
391 ModuleFile *TopImport = *ModuleMgr.rbegin();
392 while (!TopImport->ImportedBy.empty())
393 TopImport = TopImport->ImportedBy[0];
394 if (TopImport->Kind != MK_Module)
395 return false;
396
397 StringRef ModuleName = TopImport->ModuleName;
398 assert(!ModuleName.empty() && "diagnostic options read before module name");
399
400 Module *M = PP.getHeaderSearchInfo().lookupModule(ModuleName);
401 assert(M && "missing module");
402
403 // FIXME: if the diagnostics are incompatible, save a DiagnosticOptions that
404 // contains the union of their flags.
405 return checkDiagnosticMappings(*Diags, ExistingDiags, M->IsSystem, Complain);
406}
407
Guy Benyei11169dd2012-12-18 14:30:41 +0000408/// \brief Collect the macro definitions provided by the given preprocessor
409/// options.
410static void collectMacroDefinitions(const PreprocessorOptions &PPOpts,
411 MacroDefinitionsMap &Macros,
412 SmallVectorImpl<StringRef> *MacroNames = 0){
413 for (unsigned I = 0, N = PPOpts.Macros.size(); I != N; ++I) {
414 StringRef Macro = PPOpts.Macros[I].first;
415 bool IsUndef = PPOpts.Macros[I].second;
416
417 std::pair<StringRef, StringRef> MacroPair = Macro.split('=');
418 StringRef MacroName = MacroPair.first;
419 StringRef MacroBody = MacroPair.second;
420
421 // For an #undef'd macro, we only care about the name.
422 if (IsUndef) {
423 if (MacroNames && !Macros.count(MacroName))
424 MacroNames->push_back(MacroName);
425
426 Macros[MacroName] = std::make_pair("", true);
427 continue;
428 }
429
430 // For a #define'd macro, figure out the actual definition.
431 if (MacroName.size() == Macro.size())
432 MacroBody = "1";
433 else {
434 // Note: GCC drops anything following an end-of-line character.
435 StringRef::size_type End = MacroBody.find_first_of("\n\r");
436 MacroBody = MacroBody.substr(0, End);
437 }
438
439 if (MacroNames && !Macros.count(MacroName))
440 MacroNames->push_back(MacroName);
441 Macros[MacroName] = std::make_pair(MacroBody, false);
442 }
443}
444
445/// \brief Check the preprocessor options deserialized from the control block
446/// against the preprocessor options in an existing preprocessor.
447///
448/// \param Diags If non-null, produce diagnostics for any mismatches incurred.
449static bool checkPreprocessorOptions(const PreprocessorOptions &PPOpts,
450 const PreprocessorOptions &ExistingPPOpts,
451 DiagnosticsEngine *Diags,
452 FileManager &FileMgr,
Argyrios Kyrtzidisd3afa0c2013-04-26 21:33:40 +0000453 std::string &SuggestedPredefines,
454 const LangOptions &LangOpts) {
Guy Benyei11169dd2012-12-18 14:30:41 +0000455 // Check macro definitions.
456 MacroDefinitionsMap ASTFileMacros;
457 collectMacroDefinitions(PPOpts, ASTFileMacros);
458 MacroDefinitionsMap ExistingMacros;
459 SmallVector<StringRef, 4> ExistingMacroNames;
460 collectMacroDefinitions(ExistingPPOpts, ExistingMacros, &ExistingMacroNames);
461
462 for (unsigned I = 0, N = ExistingMacroNames.size(); I != N; ++I) {
463 // Dig out the macro definition in the existing preprocessor options.
464 StringRef MacroName = ExistingMacroNames[I];
465 std::pair<StringRef, bool> Existing = ExistingMacros[MacroName];
466
467 // Check whether we know anything about this macro name or not.
468 llvm::StringMap<std::pair<StringRef, bool /*IsUndef*/> >::iterator Known
469 = ASTFileMacros.find(MacroName);
470 if (Known == ASTFileMacros.end()) {
471 // FIXME: Check whether this identifier was referenced anywhere in the
472 // AST file. If so, we should reject the AST file. Unfortunately, this
473 // information isn't in the control block. What shall we do about it?
474
475 if (Existing.second) {
476 SuggestedPredefines += "#undef ";
477 SuggestedPredefines += MacroName.str();
478 SuggestedPredefines += '\n';
479 } else {
480 SuggestedPredefines += "#define ";
481 SuggestedPredefines += MacroName.str();
482 SuggestedPredefines += ' ';
483 SuggestedPredefines += Existing.first.str();
484 SuggestedPredefines += '\n';
485 }
486 continue;
487 }
488
489 // If the macro was defined in one but undef'd in the other, we have a
490 // conflict.
491 if (Existing.second != Known->second.second) {
492 if (Diags) {
493 Diags->Report(diag::err_pch_macro_def_undef)
494 << MacroName << Known->second.second;
495 }
496 return true;
497 }
498
499 // If the macro was #undef'd in both, or if the macro bodies are identical,
500 // it's fine.
501 if (Existing.second || Existing.first == Known->second.first)
502 continue;
503
504 // The macro bodies differ; complain.
505 if (Diags) {
506 Diags->Report(diag::err_pch_macro_def_conflict)
507 << MacroName << Known->second.first << Existing.first;
508 }
509 return true;
510 }
511
512 // Check whether we're using predefines.
513 if (PPOpts.UsePredefines != ExistingPPOpts.UsePredefines) {
514 if (Diags) {
515 Diags->Report(diag::err_pch_undef) << ExistingPPOpts.UsePredefines;
516 }
517 return true;
518 }
519
Argyrios Kyrtzidisd3afa0c2013-04-26 21:33:40 +0000520 // Detailed record is important since it is used for the module cache hash.
521 if (LangOpts.Modules &&
522 PPOpts.DetailedRecord != ExistingPPOpts.DetailedRecord) {
523 if (Diags) {
524 Diags->Report(diag::err_pch_pp_detailed_record) << PPOpts.DetailedRecord;
525 }
526 return true;
527 }
528
Guy Benyei11169dd2012-12-18 14:30:41 +0000529 // Compute the #include and #include_macros lines we need.
530 for (unsigned I = 0, N = ExistingPPOpts.Includes.size(); I != N; ++I) {
531 StringRef File = ExistingPPOpts.Includes[I];
532 if (File == ExistingPPOpts.ImplicitPCHInclude)
533 continue;
534
535 if (std::find(PPOpts.Includes.begin(), PPOpts.Includes.end(), File)
536 != PPOpts.Includes.end())
537 continue;
538
539 SuggestedPredefines += "#include \"";
540 SuggestedPredefines +=
541 HeaderSearch::NormalizeDashIncludePath(File, FileMgr);
542 SuggestedPredefines += "\"\n";
543 }
544
545 for (unsigned I = 0, N = ExistingPPOpts.MacroIncludes.size(); I != N; ++I) {
546 StringRef File = ExistingPPOpts.MacroIncludes[I];
547 if (std::find(PPOpts.MacroIncludes.begin(), PPOpts.MacroIncludes.end(),
548 File)
549 != PPOpts.MacroIncludes.end())
550 continue;
551
552 SuggestedPredefines += "#__include_macros \"";
553 SuggestedPredefines +=
554 HeaderSearch::NormalizeDashIncludePath(File, FileMgr);
555 SuggestedPredefines += "\"\n##\n";
556 }
557
558 return false;
559}
560
561bool PCHValidator::ReadPreprocessorOptions(const PreprocessorOptions &PPOpts,
562 bool Complain,
563 std::string &SuggestedPredefines) {
564 const PreprocessorOptions &ExistingPPOpts = PP.getPreprocessorOpts();
565
566 return checkPreprocessorOptions(PPOpts, ExistingPPOpts,
567 Complain? &Reader.Diags : 0,
568 PP.getFileManager(),
Argyrios Kyrtzidisd3afa0c2013-04-26 21:33:40 +0000569 SuggestedPredefines,
570 PP.getLangOpts());
Guy Benyei11169dd2012-12-18 14:30:41 +0000571}
572
Guy Benyei11169dd2012-12-18 14:30:41 +0000573void PCHValidator::ReadCounter(const ModuleFile &M, unsigned Value) {
574 PP.setCounterValue(Value);
575}
576
577//===----------------------------------------------------------------------===//
578// AST reader implementation
579//===----------------------------------------------------------------------===//
580
Nico Weber824285e2014-05-08 04:26:47 +0000581void ASTReader::setDeserializationListener(ASTDeserializationListener *Listener,
582 bool TakeOwnership) {
Guy Benyei11169dd2012-12-18 14:30:41 +0000583 DeserializationListener = Listener;
Nico Weber824285e2014-05-08 04:26:47 +0000584 OwnsDeserializationListener = TakeOwnership;
Guy Benyei11169dd2012-12-18 14:30:41 +0000585}
586
587
588
589unsigned ASTSelectorLookupTrait::ComputeHash(Selector Sel) {
590 return serialization::ComputeHash(Sel);
591}
592
593
594std::pair<unsigned, unsigned>
595ASTSelectorLookupTrait::ReadKeyDataLength(const unsigned char*& d) {
Justin Bogner57ba0b22014-03-28 22:03:24 +0000596 using namespace llvm::support;
597 unsigned KeyLen = endian::readNext<uint16_t, little, unaligned>(d);
598 unsigned DataLen = endian::readNext<uint16_t, little, unaligned>(d);
Guy Benyei11169dd2012-12-18 14:30:41 +0000599 return std::make_pair(KeyLen, DataLen);
600}
601
602ASTSelectorLookupTrait::internal_key_type
603ASTSelectorLookupTrait::ReadKey(const unsigned char* d, unsigned) {
Justin Bogner57ba0b22014-03-28 22:03:24 +0000604 using namespace llvm::support;
Guy Benyei11169dd2012-12-18 14:30:41 +0000605 SelectorTable &SelTable = Reader.getContext().Selectors;
Justin Bogner57ba0b22014-03-28 22:03:24 +0000606 unsigned N = endian::readNext<uint16_t, little, unaligned>(d);
607 IdentifierInfo *FirstII = Reader.getLocalIdentifier(
608 F, endian::readNext<uint32_t, little, unaligned>(d));
Guy Benyei11169dd2012-12-18 14:30:41 +0000609 if (N == 0)
610 return SelTable.getNullarySelector(FirstII);
611 else if (N == 1)
612 return SelTable.getUnarySelector(FirstII);
613
614 SmallVector<IdentifierInfo *, 16> Args;
615 Args.push_back(FirstII);
616 for (unsigned I = 1; I != N; ++I)
Justin Bogner57ba0b22014-03-28 22:03:24 +0000617 Args.push_back(Reader.getLocalIdentifier(
618 F, endian::readNext<uint32_t, little, unaligned>(d)));
Guy Benyei11169dd2012-12-18 14:30:41 +0000619
620 return SelTable.getSelector(N, Args.data());
621}
622
623ASTSelectorLookupTrait::data_type
624ASTSelectorLookupTrait::ReadData(Selector, const unsigned char* d,
625 unsigned DataLen) {
Justin Bogner57ba0b22014-03-28 22:03:24 +0000626 using namespace llvm::support;
Guy Benyei11169dd2012-12-18 14:30:41 +0000627
628 data_type Result;
629
Justin Bogner57ba0b22014-03-28 22:03:24 +0000630 Result.ID = Reader.getGlobalSelectorID(
631 F, endian::readNext<uint32_t, little, unaligned>(d));
632 unsigned NumInstanceMethodsAndBits =
633 endian::readNext<uint16_t, little, unaligned>(d);
634 unsigned NumFactoryMethodsAndBits =
635 endian::readNext<uint16_t, little, unaligned>(d);
Argyrios Kyrtzidisd3da6e02013-04-17 00:08:58 +0000636 Result.InstanceBits = NumInstanceMethodsAndBits & 0x3;
637 Result.FactoryBits = NumFactoryMethodsAndBits & 0x3;
638 unsigned NumInstanceMethods = NumInstanceMethodsAndBits >> 2;
639 unsigned NumFactoryMethods = NumFactoryMethodsAndBits >> 2;
Guy Benyei11169dd2012-12-18 14:30:41 +0000640
641 // Load instance methods
642 for (unsigned I = 0; I != NumInstanceMethods; ++I) {
Justin Bogner57ba0b22014-03-28 22:03:24 +0000643 if (ObjCMethodDecl *Method = Reader.GetLocalDeclAs<ObjCMethodDecl>(
644 F, endian::readNext<uint32_t, little, unaligned>(d)))
Guy Benyei11169dd2012-12-18 14:30:41 +0000645 Result.Instance.push_back(Method);
646 }
647
648 // Load factory methods
649 for (unsigned I = 0; I != NumFactoryMethods; ++I) {
Justin Bogner57ba0b22014-03-28 22:03:24 +0000650 if (ObjCMethodDecl *Method = Reader.GetLocalDeclAs<ObjCMethodDecl>(
651 F, endian::readNext<uint32_t, little, unaligned>(d)))
Guy Benyei11169dd2012-12-18 14:30:41 +0000652 Result.Factory.push_back(Method);
653 }
654
655 return Result;
656}
657
Douglas Gregorbfd73d72013-01-23 18:53:14 +0000658unsigned ASTIdentifierLookupTraitBase::ComputeHash(const internal_key_type& a) {
659 return llvm::HashString(a);
Guy Benyei11169dd2012-12-18 14:30:41 +0000660}
661
662std::pair<unsigned, unsigned>
Douglas Gregorbfd73d72013-01-23 18:53:14 +0000663ASTIdentifierLookupTraitBase::ReadKeyDataLength(const unsigned char*& d) {
Justin Bogner57ba0b22014-03-28 22:03:24 +0000664 using namespace llvm::support;
665 unsigned DataLen = endian::readNext<uint16_t, little, unaligned>(d);
666 unsigned KeyLen = endian::readNext<uint16_t, little, unaligned>(d);
Guy Benyei11169dd2012-12-18 14:30:41 +0000667 return std::make_pair(KeyLen, DataLen);
668}
669
Douglas Gregorbfd73d72013-01-23 18:53:14 +0000670ASTIdentifierLookupTraitBase::internal_key_type
671ASTIdentifierLookupTraitBase::ReadKey(const unsigned char* d, unsigned n) {
Guy Benyei11169dd2012-12-18 14:30:41 +0000672 assert(n >= 2 && d[n-1] == '\0');
Douglas Gregorbfd73d72013-01-23 18:53:14 +0000673 return StringRef((const char*) d, n-1);
Guy Benyei11169dd2012-12-18 14:30:41 +0000674}
675
Douglas Gregordcf25082013-02-11 18:16:18 +0000676/// \brief Whether the given identifier is "interesting".
677static bool isInterestingIdentifier(IdentifierInfo &II) {
678 return II.isPoisoned() ||
679 II.isExtensionToken() ||
680 II.getObjCOrBuiltinID() ||
681 II.hasRevertedTokenIDToIdentifier() ||
682 II.hadMacroDefinition() ||
683 II.getFETokenInfo<void>();
684}
685
Guy Benyei11169dd2012-12-18 14:30:41 +0000686IdentifierInfo *ASTIdentifierLookupTrait::ReadData(const internal_key_type& k,
687 const unsigned char* d,
688 unsigned DataLen) {
Justin Bogner57ba0b22014-03-28 22:03:24 +0000689 using namespace llvm::support;
690 unsigned RawID = endian::readNext<uint32_t, little, unaligned>(d);
Guy Benyei11169dd2012-12-18 14:30:41 +0000691 bool IsInteresting = RawID & 0x01;
692
693 // Wipe out the "is interesting" bit.
694 RawID = RawID >> 1;
695
696 IdentID ID = Reader.getGlobalIdentifierID(F, RawID);
697 if (!IsInteresting) {
698 // For uninteresting identifiers, just build the IdentifierInfo
699 // and associate it with the persistent ID.
700 IdentifierInfo *II = KnownII;
701 if (!II) {
Douglas Gregorbfd73d72013-01-23 18:53:14 +0000702 II = &Reader.getIdentifierTable().getOwn(k);
Guy Benyei11169dd2012-12-18 14:30:41 +0000703 KnownII = II;
704 }
705 Reader.SetIdentifierInfo(ID, II);
Douglas Gregordcf25082013-02-11 18:16:18 +0000706 if (!II->isFromAST()) {
707 bool WasInteresting = isInterestingIdentifier(*II);
708 II->setIsFromAST();
709 if (WasInteresting)
710 II->setChangedSinceDeserialization();
711 }
712 Reader.markIdentifierUpToDate(II);
Guy Benyei11169dd2012-12-18 14:30:41 +0000713 return II;
714 }
715
Justin Bogner57ba0b22014-03-28 22:03:24 +0000716 unsigned ObjCOrBuiltinID = endian::readNext<uint16_t, little, unaligned>(d);
717 unsigned Bits = endian::readNext<uint16_t, little, unaligned>(d);
Guy Benyei11169dd2012-12-18 14:30:41 +0000718 bool CPlusPlusOperatorKeyword = Bits & 0x01;
719 Bits >>= 1;
720 bool HasRevertedTokenIDToIdentifier = Bits & 0x01;
721 Bits >>= 1;
722 bool Poisoned = Bits & 0x01;
723 Bits >>= 1;
724 bool ExtensionToken = Bits & 0x01;
725 Bits >>= 1;
Argyrios Kyrtzidiseb663da2013-03-22 21:12:57 +0000726 bool hasSubmoduleMacros = Bits & 0x01;
727 Bits >>= 1;
Guy Benyei11169dd2012-12-18 14:30:41 +0000728 bool hadMacroDefinition = Bits & 0x01;
729 Bits >>= 1;
730
731 assert(Bits == 0 && "Extra bits in the identifier?");
732 DataLen -= 8;
733
734 // Build the IdentifierInfo itself and link the identifier ID with
735 // the new IdentifierInfo.
736 IdentifierInfo *II = KnownII;
737 if (!II) {
Douglas Gregorbfd73d72013-01-23 18:53:14 +0000738 II = &Reader.getIdentifierTable().getOwn(StringRef(k));
Guy Benyei11169dd2012-12-18 14:30:41 +0000739 KnownII = II;
740 }
741 Reader.markIdentifierUpToDate(II);
Douglas Gregordcf25082013-02-11 18:16:18 +0000742 if (!II->isFromAST()) {
743 bool WasInteresting = isInterestingIdentifier(*II);
744 II->setIsFromAST();
745 if (WasInteresting)
746 II->setChangedSinceDeserialization();
747 }
Guy Benyei11169dd2012-12-18 14:30:41 +0000748
749 // Set or check the various bits in the IdentifierInfo structure.
750 // Token IDs are read-only.
Argyrios Kyrtzidisddee8c92013-02-27 01:13:51 +0000751 if (HasRevertedTokenIDToIdentifier && II->getTokenID() != tok::identifier)
Guy Benyei11169dd2012-12-18 14:30:41 +0000752 II->RevertTokenIDToIdentifier();
753 II->setObjCOrBuiltinID(ObjCOrBuiltinID);
754 assert(II->isExtensionToken() == ExtensionToken &&
755 "Incorrect extension token flag");
756 (void)ExtensionToken;
757 if (Poisoned)
758 II->setIsPoisoned(true);
759 assert(II->isCPlusPlusOperatorKeyword() == CPlusPlusOperatorKeyword &&
760 "Incorrect C++ operator keyword flag");
761 (void)CPlusPlusOperatorKeyword;
762
763 // If this identifier is a macro, deserialize the macro
764 // definition.
765 if (hadMacroDefinition) {
Justin Bogner57ba0b22014-03-28 22:03:24 +0000766 uint32_t MacroDirectivesOffset =
767 endian::readNext<uint32_t, little, unaligned>(d);
Argyrios Kyrtzidiseb663da2013-03-22 21:12:57 +0000768 DataLen -= 4;
769 SmallVector<uint32_t, 8> LocalMacroIDs;
770 if (hasSubmoduleMacros) {
Justin Bogner57ba0b22014-03-28 22:03:24 +0000771 while (uint32_t LocalMacroID =
772 endian::readNext<uint32_t, little, unaligned>(d)) {
Argyrios Kyrtzidiseb663da2013-03-22 21:12:57 +0000773 DataLen -= 4;
774 LocalMacroIDs.push_back(LocalMacroID);
775 }
Argyrios Kyrtzidis719736c2013-01-19 03:14:56 +0000776 DataLen -= 4;
777 }
Argyrios Kyrtzidiseb663da2013-03-22 21:12:57 +0000778
779 if (F.Kind == MK_Module) {
Richard Smith49f906a2014-03-01 00:08:04 +0000780 // Macro definitions are stored from newest to oldest, so reverse them
781 // before registering them.
782 llvm::SmallVector<unsigned, 8> MacroSizes;
Argyrios Kyrtzidiseb663da2013-03-22 21:12:57 +0000783 for (SmallVectorImpl<uint32_t>::iterator
Richard Smith49f906a2014-03-01 00:08:04 +0000784 I = LocalMacroIDs.begin(), E = LocalMacroIDs.end(); I != E; /**/) {
785 unsigned Size = 1;
786
787 static const uint32_t HasOverridesFlag = 0x80000000U;
788 if (I + 1 != E && (I[1] & HasOverridesFlag))
789 Size += 1 + (I[1] & ~HasOverridesFlag);
790
791 MacroSizes.push_back(Size);
792 I += Size;
Argyrios Kyrtzidiseb663da2013-03-22 21:12:57 +0000793 }
Richard Smith49f906a2014-03-01 00:08:04 +0000794
795 SmallVectorImpl<uint32_t>::iterator I = LocalMacroIDs.end();
796 for (SmallVectorImpl<unsigned>::reverse_iterator SI = MacroSizes.rbegin(),
797 SE = MacroSizes.rend();
798 SI != SE; ++SI) {
799 I -= *SI;
800
801 uint32_t LocalMacroID = *I;
802 llvm::ArrayRef<uint32_t> Overrides;
803 if (*SI != 1)
804 Overrides = llvm::makeArrayRef(&I[2], *SI - 2);
805 Reader.addPendingMacroFromModule(II, &F, LocalMacroID, Overrides);
806 }
807 assert(I == LocalMacroIDs.begin());
Argyrios Kyrtzidiseb663da2013-03-22 21:12:57 +0000808 } else {
809 Reader.addPendingMacroFromPCH(II, &F, MacroDirectivesOffset);
810 }
Guy Benyei11169dd2012-12-18 14:30:41 +0000811 }
812
813 Reader.SetIdentifierInfo(ID, II);
814
815 // Read all of the declarations visible at global scope with this
816 // name.
817 if (DataLen > 0) {
818 SmallVector<uint32_t, 4> DeclIDs;
819 for (; DataLen > 0; DataLen -= 4)
Justin Bogner57ba0b22014-03-28 22:03:24 +0000820 DeclIDs.push_back(Reader.getGlobalDeclID(
821 F, endian::readNext<uint32_t, little, unaligned>(d)));
Guy Benyei11169dd2012-12-18 14:30:41 +0000822 Reader.SetGloballyVisibleDecls(II, DeclIDs);
823 }
824
825 return II;
826}
827
828unsigned
829ASTDeclContextNameLookupTrait::ComputeHash(const DeclNameKey &Key) const {
830 llvm::FoldingSetNodeID ID;
831 ID.AddInteger(Key.Kind);
832
833 switch (Key.Kind) {
834 case DeclarationName::Identifier:
835 case DeclarationName::CXXLiteralOperatorName:
836 ID.AddString(((IdentifierInfo*)Key.Data)->getName());
837 break;
838 case DeclarationName::ObjCZeroArgSelector:
839 case DeclarationName::ObjCOneArgSelector:
840 case DeclarationName::ObjCMultiArgSelector:
841 ID.AddInteger(serialization::ComputeHash(Selector(Key.Data)));
842 break;
843 case DeclarationName::CXXOperatorName:
844 ID.AddInteger((OverloadedOperatorKind)Key.Data);
845 break;
846 case DeclarationName::CXXConstructorName:
847 case DeclarationName::CXXDestructorName:
848 case DeclarationName::CXXConversionFunctionName:
849 case DeclarationName::CXXUsingDirective:
850 break;
851 }
852
853 return ID.ComputeHash();
854}
855
856ASTDeclContextNameLookupTrait::internal_key_type
857ASTDeclContextNameLookupTrait::GetInternalKey(
858 const external_key_type& Name) const {
859 DeclNameKey Key;
860 Key.Kind = Name.getNameKind();
861 switch (Name.getNameKind()) {
862 case DeclarationName::Identifier:
863 Key.Data = (uint64_t)Name.getAsIdentifierInfo();
864 break;
865 case DeclarationName::ObjCZeroArgSelector:
866 case DeclarationName::ObjCOneArgSelector:
867 case DeclarationName::ObjCMultiArgSelector:
868 Key.Data = (uint64_t)Name.getObjCSelector().getAsOpaquePtr();
869 break;
870 case DeclarationName::CXXOperatorName:
871 Key.Data = Name.getCXXOverloadedOperator();
872 break;
873 case DeclarationName::CXXLiteralOperatorName:
874 Key.Data = (uint64_t)Name.getCXXLiteralIdentifier();
875 break;
876 case DeclarationName::CXXConstructorName:
877 case DeclarationName::CXXDestructorName:
878 case DeclarationName::CXXConversionFunctionName:
879 case DeclarationName::CXXUsingDirective:
880 Key.Data = 0;
881 break;
882 }
883
884 return Key;
885}
886
887std::pair<unsigned, unsigned>
888ASTDeclContextNameLookupTrait::ReadKeyDataLength(const unsigned char*& d) {
Justin Bogner57ba0b22014-03-28 22:03:24 +0000889 using namespace llvm::support;
890 unsigned KeyLen = endian::readNext<uint16_t, little, unaligned>(d);
891 unsigned DataLen = endian::readNext<uint16_t, little, unaligned>(d);
Guy Benyei11169dd2012-12-18 14:30:41 +0000892 return std::make_pair(KeyLen, DataLen);
893}
894
895ASTDeclContextNameLookupTrait::internal_key_type
896ASTDeclContextNameLookupTrait::ReadKey(const unsigned char* d, unsigned) {
Justin Bogner57ba0b22014-03-28 22:03:24 +0000897 using namespace llvm::support;
Guy Benyei11169dd2012-12-18 14:30:41 +0000898
899 DeclNameKey Key;
900 Key.Kind = (DeclarationName::NameKind)*d++;
901 switch (Key.Kind) {
902 case DeclarationName::Identifier:
Justin Bogner57ba0b22014-03-28 22:03:24 +0000903 Key.Data = (uint64_t)Reader.getLocalIdentifier(
904 F, endian::readNext<uint32_t, little, unaligned>(d));
Guy Benyei11169dd2012-12-18 14:30:41 +0000905 break;
906 case DeclarationName::ObjCZeroArgSelector:
907 case DeclarationName::ObjCOneArgSelector:
908 case DeclarationName::ObjCMultiArgSelector:
909 Key.Data =
Justin Bogner57ba0b22014-03-28 22:03:24 +0000910 (uint64_t)Reader.getLocalSelector(
911 F, endian::readNext<uint32_t, little, unaligned>(
912 d)).getAsOpaquePtr();
Guy Benyei11169dd2012-12-18 14:30:41 +0000913 break;
914 case DeclarationName::CXXOperatorName:
915 Key.Data = *d++; // OverloadedOperatorKind
916 break;
917 case DeclarationName::CXXLiteralOperatorName:
Justin Bogner57ba0b22014-03-28 22:03:24 +0000918 Key.Data = (uint64_t)Reader.getLocalIdentifier(
919 F, endian::readNext<uint32_t, little, unaligned>(d));
Guy Benyei11169dd2012-12-18 14:30:41 +0000920 break;
921 case DeclarationName::CXXConstructorName:
922 case DeclarationName::CXXDestructorName:
923 case DeclarationName::CXXConversionFunctionName:
924 case DeclarationName::CXXUsingDirective:
925 Key.Data = 0;
926 break;
927 }
928
929 return Key;
930}
931
932ASTDeclContextNameLookupTrait::data_type
933ASTDeclContextNameLookupTrait::ReadData(internal_key_type,
934 const unsigned char* d,
935 unsigned DataLen) {
Justin Bogner57ba0b22014-03-28 22:03:24 +0000936 using namespace llvm::support;
937 unsigned NumDecls = endian::readNext<uint16_t, little, unaligned>(d);
Argyrios Kyrtzidisc57e5032013-01-11 22:29:49 +0000938 LE32DeclID *Start = reinterpret_cast<LE32DeclID *>(
939 const_cast<unsigned char *>(d));
Guy Benyei11169dd2012-12-18 14:30:41 +0000940 return std::make_pair(Start, Start + NumDecls);
941}
942
943bool ASTReader::ReadDeclContextStorage(ModuleFile &M,
Chris Lattner7fb3bef2013-01-20 00:56:42 +0000944 BitstreamCursor &Cursor,
Guy Benyei11169dd2012-12-18 14:30:41 +0000945 const std::pair<uint64_t, uint64_t> &Offsets,
946 DeclContextInfo &Info) {
947 SavedStreamPosition SavedPosition(Cursor);
948 // First the lexical decls.
949 if (Offsets.first != 0) {
950 Cursor.JumpToBit(Offsets.first);
951
952 RecordData Record;
Chris Lattner0e6c9402013-01-20 02:38:54 +0000953 StringRef Blob;
Guy Benyei11169dd2012-12-18 14:30:41 +0000954 unsigned Code = Cursor.ReadCode();
Chris Lattner0e6c9402013-01-20 02:38:54 +0000955 unsigned RecCode = Cursor.readRecord(Code, Record, &Blob);
Guy Benyei11169dd2012-12-18 14:30:41 +0000956 if (RecCode != DECL_CONTEXT_LEXICAL) {
957 Error("Expected lexical block");
958 return true;
959 }
960
Chris Lattner0e6c9402013-01-20 02:38:54 +0000961 Info.LexicalDecls = reinterpret_cast<const KindDeclIDPair*>(Blob.data());
962 Info.NumLexicalDecls = Blob.size() / sizeof(KindDeclIDPair);
Guy Benyei11169dd2012-12-18 14:30:41 +0000963 }
964
965 // Now the lookup table.
966 if (Offsets.second != 0) {
967 Cursor.JumpToBit(Offsets.second);
968
969 RecordData Record;
Chris Lattner0e6c9402013-01-20 02:38:54 +0000970 StringRef Blob;
Guy Benyei11169dd2012-12-18 14:30:41 +0000971 unsigned Code = Cursor.ReadCode();
Chris Lattner0e6c9402013-01-20 02:38:54 +0000972 unsigned RecCode = Cursor.readRecord(Code, Record, &Blob);
Guy Benyei11169dd2012-12-18 14:30:41 +0000973 if (RecCode != DECL_CONTEXT_VISIBLE) {
974 Error("Expected visible lookup table block");
975 return true;
976 }
Justin Bognerda4e6502014-04-14 16:34:29 +0000977 Info.NameLookupTableData = ASTDeclContextNameLookupTable::Create(
978 (const unsigned char *)Blob.data() + Record[0],
979 (const unsigned char *)Blob.data() + sizeof(uint32_t),
980 (const unsigned char *)Blob.data(),
981 ASTDeclContextNameLookupTrait(*this, M));
Guy Benyei11169dd2012-12-18 14:30:41 +0000982 }
983
984 return false;
985}
986
987void ASTReader::Error(StringRef Msg) {
988 Error(diag::err_fe_pch_malformed, Msg);
Douglas Gregor940e8052013-05-10 22:15:13 +0000989 if (Context.getLangOpts().Modules && !Diags.isDiagnosticInFlight()) {
990 Diag(diag::note_module_cache_path)
991 << PP.getHeaderSearchInfo().getModuleCachePath();
992 }
Guy Benyei11169dd2012-12-18 14:30:41 +0000993}
994
995void ASTReader::Error(unsigned DiagID,
996 StringRef Arg1, StringRef Arg2) {
997 if (Diags.isDiagnosticInFlight())
998 Diags.SetDelayedDiagnostic(DiagID, Arg1, Arg2);
999 else
1000 Diag(DiagID) << Arg1 << Arg2;
1001}
1002
1003//===----------------------------------------------------------------------===//
1004// Source Manager Deserialization
1005//===----------------------------------------------------------------------===//
1006
1007/// \brief Read the line table in the source manager block.
1008/// \returns true if there was an error.
1009bool ASTReader::ParseLineTable(ModuleFile &F,
1010 SmallVectorImpl<uint64_t> &Record) {
1011 unsigned Idx = 0;
1012 LineTableInfo &LineTable = SourceMgr.getLineTable();
1013
1014 // Parse the file names
1015 std::map<int, int> FileIDs;
1016 for (int I = 0, N = Record[Idx++]; I != N; ++I) {
1017 // Extract the file name
1018 unsigned FilenameLen = Record[Idx++];
1019 std::string Filename(&Record[Idx], &Record[Idx] + FilenameLen);
1020 Idx += FilenameLen;
1021 MaybeAddSystemRootToFilename(F, Filename);
1022 FileIDs[I] = LineTable.getLineTableFilenameID(Filename);
1023 }
1024
1025 // Parse the line entries
1026 std::vector<LineEntry> Entries;
1027 while (Idx < Record.size()) {
1028 int FID = Record[Idx++];
1029 assert(FID >= 0 && "Serialized line entries for non-local file.");
1030 // Remap FileID from 1-based old view.
1031 FID += F.SLocEntryBaseID - 1;
1032
1033 // Extract the line entries
1034 unsigned NumEntries = Record[Idx++];
1035 assert(NumEntries && "Numentries is 00000");
1036 Entries.clear();
1037 Entries.reserve(NumEntries);
1038 for (unsigned I = 0; I != NumEntries; ++I) {
1039 unsigned FileOffset = Record[Idx++];
1040 unsigned LineNo = Record[Idx++];
1041 int FilenameID = FileIDs[Record[Idx++]];
1042 SrcMgr::CharacteristicKind FileKind
1043 = (SrcMgr::CharacteristicKind)Record[Idx++];
1044 unsigned IncludeOffset = Record[Idx++];
1045 Entries.push_back(LineEntry::get(FileOffset, LineNo, FilenameID,
1046 FileKind, IncludeOffset));
1047 }
1048 LineTable.AddEntry(FileID::get(FID), Entries);
1049 }
1050
1051 return false;
1052}
1053
1054/// \brief Read a source manager block
1055bool ASTReader::ReadSourceManagerBlock(ModuleFile &F) {
1056 using namespace SrcMgr;
1057
Chris Lattner7fb3bef2013-01-20 00:56:42 +00001058 BitstreamCursor &SLocEntryCursor = F.SLocEntryCursor;
Guy Benyei11169dd2012-12-18 14:30:41 +00001059
1060 // Set the source-location entry cursor to the current position in
1061 // the stream. This cursor will be used to read the contents of the
1062 // source manager block initially, and then lazily read
1063 // source-location entries as needed.
1064 SLocEntryCursor = F.Stream;
1065
1066 // The stream itself is going to skip over the source manager block.
1067 if (F.Stream.SkipBlock()) {
1068 Error("malformed block record in AST file");
1069 return true;
1070 }
1071
1072 // Enter the source manager block.
1073 if (SLocEntryCursor.EnterSubBlock(SOURCE_MANAGER_BLOCK_ID)) {
1074 Error("malformed source manager block record in AST file");
1075 return true;
1076 }
1077
1078 RecordData Record;
1079 while (true) {
Chris Lattnere7b154b2013-01-19 21:39:22 +00001080 llvm::BitstreamEntry E = SLocEntryCursor.advanceSkippingSubblocks();
1081
1082 switch (E.Kind) {
1083 case llvm::BitstreamEntry::SubBlock: // Handled for us already.
1084 case llvm::BitstreamEntry::Error:
1085 Error("malformed block record in AST file");
1086 return true;
1087 case llvm::BitstreamEntry::EndBlock:
Guy Benyei11169dd2012-12-18 14:30:41 +00001088 return false;
Chris Lattnere7b154b2013-01-19 21:39:22 +00001089 case llvm::BitstreamEntry::Record:
1090 // The interesting case.
1091 break;
Guy Benyei11169dd2012-12-18 14:30:41 +00001092 }
Chris Lattnere7b154b2013-01-19 21:39:22 +00001093
Guy Benyei11169dd2012-12-18 14:30:41 +00001094 // Read a record.
Guy Benyei11169dd2012-12-18 14:30:41 +00001095 Record.clear();
Chris Lattner15c3e7d2013-01-21 18:28:26 +00001096 StringRef Blob;
1097 switch (SLocEntryCursor.readRecord(E.ID, Record, &Blob)) {
Guy Benyei11169dd2012-12-18 14:30:41 +00001098 default: // Default behavior: ignore.
1099 break;
1100
1101 case SM_SLOC_FILE_ENTRY:
1102 case SM_SLOC_BUFFER_ENTRY:
1103 case SM_SLOC_EXPANSION_ENTRY:
1104 // Once we hit one of the source location entries, we're done.
1105 return false;
1106 }
1107 }
1108}
1109
1110/// \brief If a header file is not found at the path that we expect it to be
1111/// and the PCH file was moved from its original location, try to resolve the
1112/// file by assuming that header+PCH were moved together and the header is in
1113/// the same place relative to the PCH.
1114static std::string
1115resolveFileRelativeToOriginalDir(const std::string &Filename,
1116 const std::string &OriginalDir,
1117 const std::string &CurrDir) {
1118 assert(OriginalDir != CurrDir &&
1119 "No point trying to resolve the file if the PCH dir didn't change");
1120 using namespace llvm::sys;
1121 SmallString<128> filePath(Filename);
1122 fs::make_absolute(filePath);
1123 assert(path::is_absolute(OriginalDir));
1124 SmallString<128> currPCHPath(CurrDir);
1125
1126 path::const_iterator fileDirI = path::begin(path::parent_path(filePath)),
1127 fileDirE = path::end(path::parent_path(filePath));
1128 path::const_iterator origDirI = path::begin(OriginalDir),
1129 origDirE = path::end(OriginalDir);
1130 // Skip the common path components from filePath and OriginalDir.
1131 while (fileDirI != fileDirE && origDirI != origDirE &&
1132 *fileDirI == *origDirI) {
1133 ++fileDirI;
1134 ++origDirI;
1135 }
1136 for (; origDirI != origDirE; ++origDirI)
1137 path::append(currPCHPath, "..");
1138 path::append(currPCHPath, fileDirI, fileDirE);
1139 path::append(currPCHPath, path::filename(Filename));
1140 return currPCHPath.str();
1141}
1142
1143bool ASTReader::ReadSLocEntry(int ID) {
1144 if (ID == 0)
1145 return false;
1146
1147 if (unsigned(-ID) - 2 >= getTotalNumSLocs() || ID > 0) {
1148 Error("source location entry ID out-of-range for AST file");
1149 return true;
1150 }
1151
1152 ModuleFile *F = GlobalSLocEntryMap.find(-ID)->second;
1153 F->SLocEntryCursor.JumpToBit(F->SLocEntryOffsets[ID - F->SLocEntryBaseID]);
Chris Lattner7fb3bef2013-01-20 00:56:42 +00001154 BitstreamCursor &SLocEntryCursor = F->SLocEntryCursor;
Guy Benyei11169dd2012-12-18 14:30:41 +00001155 unsigned BaseOffset = F->SLocEntryBaseOffset;
1156
1157 ++NumSLocEntriesRead;
Chris Lattnere7b154b2013-01-19 21:39:22 +00001158 llvm::BitstreamEntry Entry = SLocEntryCursor.advance();
1159 if (Entry.Kind != llvm::BitstreamEntry::Record) {
Guy Benyei11169dd2012-12-18 14:30:41 +00001160 Error("incorrectly-formatted source location entry in AST file");
1161 return true;
1162 }
Chris Lattnere7b154b2013-01-19 21:39:22 +00001163
Guy Benyei11169dd2012-12-18 14:30:41 +00001164 RecordData Record;
Chris Lattner0e6c9402013-01-20 02:38:54 +00001165 StringRef Blob;
1166 switch (SLocEntryCursor.readRecord(Entry.ID, Record, &Blob)) {
Guy Benyei11169dd2012-12-18 14:30:41 +00001167 default:
1168 Error("incorrectly-formatted source location entry in AST file");
1169 return true;
1170
1171 case SM_SLOC_FILE_ENTRY: {
1172 // We will detect whether a file changed and return 'Failure' for it, but
1173 // we will also try to fail gracefully by setting up the SLocEntry.
1174 unsigned InputID = Record[4];
1175 InputFile IF = getInputFile(*F, InputID);
Argyrios Kyrtzidis61c3d872013-03-01 03:26:04 +00001176 const FileEntry *File = IF.getFile();
1177 bool OverriddenBuffer = IF.isOverridden();
Guy Benyei11169dd2012-12-18 14:30:41 +00001178
Argyrios Kyrtzidis61c3d872013-03-01 03:26:04 +00001179 // Note that we only check if a File was returned. If it was out-of-date
1180 // we have complained but we will continue creating a FileID to recover
1181 // gracefully.
1182 if (!File)
Guy Benyei11169dd2012-12-18 14:30:41 +00001183 return true;
1184
1185 SourceLocation IncludeLoc = ReadSourceLocation(*F, Record[1]);
1186 if (IncludeLoc.isInvalid() && F->Kind != MK_MainFile) {
1187 // This is the module's main file.
1188 IncludeLoc = getImportLocation(F);
1189 }
1190 SrcMgr::CharacteristicKind
1191 FileCharacter = (SrcMgr::CharacteristicKind)Record[2];
1192 FileID FID = SourceMgr.createFileID(File, IncludeLoc, FileCharacter,
1193 ID, BaseOffset + Record[0]);
1194 SrcMgr::FileInfo &FileInfo =
1195 const_cast<SrcMgr::FileInfo&>(SourceMgr.getSLocEntry(FID).getFile());
1196 FileInfo.NumCreatedFIDs = Record[5];
1197 if (Record[3])
1198 FileInfo.setHasLineDirectives();
1199
1200 const DeclID *FirstDecl = F->FileSortedDecls + Record[6];
1201 unsigned NumFileDecls = Record[7];
1202 if (NumFileDecls) {
1203 assert(F->FileSortedDecls && "FILE_SORTED_DECLS not encountered yet ?");
1204 FileDeclIDs[FID] = FileDeclsInfo(F, llvm::makeArrayRef(FirstDecl,
1205 NumFileDecls));
1206 }
1207
1208 const SrcMgr::ContentCache *ContentCache
1209 = SourceMgr.getOrCreateContentCache(File,
1210 /*isSystemFile=*/FileCharacter != SrcMgr::C_User);
1211 if (OverriddenBuffer && !ContentCache->BufferOverridden &&
1212 ContentCache->ContentsEntry == ContentCache->OrigEntry) {
1213 unsigned Code = SLocEntryCursor.ReadCode();
1214 Record.clear();
Chris Lattner0e6c9402013-01-20 02:38:54 +00001215 unsigned RecCode = SLocEntryCursor.readRecord(Code, Record, &Blob);
Guy Benyei11169dd2012-12-18 14:30:41 +00001216
1217 if (RecCode != SM_SLOC_BUFFER_BLOB) {
1218 Error("AST record has invalid code");
1219 return true;
1220 }
1221
1222 llvm::MemoryBuffer *Buffer
Chris Lattner0e6c9402013-01-20 02:38:54 +00001223 = llvm::MemoryBuffer::getMemBuffer(Blob.drop_back(1), File->getName());
Guy Benyei11169dd2012-12-18 14:30:41 +00001224 SourceMgr.overrideFileContents(File, Buffer);
1225 }
1226
1227 break;
1228 }
1229
1230 case SM_SLOC_BUFFER_ENTRY: {
Chris Lattner0e6c9402013-01-20 02:38:54 +00001231 const char *Name = Blob.data();
Guy Benyei11169dd2012-12-18 14:30:41 +00001232 unsigned Offset = Record[0];
1233 SrcMgr::CharacteristicKind
1234 FileCharacter = (SrcMgr::CharacteristicKind)Record[2];
1235 SourceLocation IncludeLoc = ReadSourceLocation(*F, Record[1]);
1236 if (IncludeLoc.isInvalid() && F->Kind == MK_Module) {
1237 IncludeLoc = getImportLocation(F);
1238 }
1239 unsigned Code = SLocEntryCursor.ReadCode();
1240 Record.clear();
1241 unsigned RecCode
Chris Lattner0e6c9402013-01-20 02:38:54 +00001242 = SLocEntryCursor.readRecord(Code, Record, &Blob);
Guy Benyei11169dd2012-12-18 14:30:41 +00001243
1244 if (RecCode != SM_SLOC_BUFFER_BLOB) {
1245 Error("AST record has invalid code");
1246 return true;
1247 }
1248
1249 llvm::MemoryBuffer *Buffer
Chris Lattner0e6c9402013-01-20 02:38:54 +00001250 = llvm::MemoryBuffer::getMemBuffer(Blob.drop_back(1), Name);
Guy Benyei11169dd2012-12-18 14:30:41 +00001251 SourceMgr.createFileIDForMemBuffer(Buffer, FileCharacter, ID,
1252 BaseOffset + Offset, IncludeLoc);
1253 break;
1254 }
1255
1256 case SM_SLOC_EXPANSION_ENTRY: {
1257 SourceLocation SpellingLoc = ReadSourceLocation(*F, Record[1]);
1258 SourceMgr.createExpansionLoc(SpellingLoc,
1259 ReadSourceLocation(*F, Record[2]),
1260 ReadSourceLocation(*F, Record[3]),
1261 Record[4],
1262 ID,
1263 BaseOffset + Record[0]);
1264 break;
1265 }
1266 }
1267
1268 return false;
1269}
1270
1271std::pair<SourceLocation, StringRef> ASTReader::getModuleImportLoc(int ID) {
1272 if (ID == 0)
1273 return std::make_pair(SourceLocation(), "");
1274
1275 if (unsigned(-ID) - 2 >= getTotalNumSLocs() || ID > 0) {
1276 Error("source location entry ID out-of-range for AST file");
1277 return std::make_pair(SourceLocation(), "");
1278 }
1279
1280 // Find which module file this entry lands in.
1281 ModuleFile *M = GlobalSLocEntryMap.find(-ID)->second;
1282 if (M->Kind != MK_Module)
1283 return std::make_pair(SourceLocation(), "");
1284
1285 // FIXME: Can we map this down to a particular submodule? That would be
1286 // ideal.
Ben Langmuirbeee15e2014-04-14 18:00:01 +00001287 return std::make_pair(M->ImportLoc, StringRef(M->ModuleName));
Guy Benyei11169dd2012-12-18 14:30:41 +00001288}
1289
1290/// \brief Find the location where the module F is imported.
1291SourceLocation ASTReader::getImportLocation(ModuleFile *F) {
1292 if (F->ImportLoc.isValid())
1293 return F->ImportLoc;
1294
1295 // Otherwise we have a PCH. It's considered to be "imported" at the first
1296 // location of its includer.
1297 if (F->ImportedBy.empty() || !F->ImportedBy[0]) {
Ben Langmuirbeee15e2014-04-14 18:00:01 +00001298 // Main file is the importer.
1299 assert(!SourceMgr.getMainFileID().isInvalid() && "missing main file");
1300 return SourceMgr.getLocForStartOfFile(SourceMgr.getMainFileID());
Guy Benyei11169dd2012-12-18 14:30:41 +00001301 }
Guy Benyei11169dd2012-12-18 14:30:41 +00001302 return F->ImportedBy[0]->FirstLoc;
1303}
1304
1305/// ReadBlockAbbrevs - Enter a subblock of the specified BlockID with the
1306/// specified cursor. Read the abbreviations that are at the top of the block
1307/// and then leave the cursor pointing into the block.
Chris Lattner7fb3bef2013-01-20 00:56:42 +00001308bool ASTReader::ReadBlockAbbrevs(BitstreamCursor &Cursor, unsigned BlockID) {
Guy Benyei11169dd2012-12-18 14:30:41 +00001309 if (Cursor.EnterSubBlock(BlockID)) {
1310 Error("malformed block record in AST file");
1311 return Failure;
1312 }
1313
1314 while (true) {
1315 uint64_t Offset = Cursor.GetCurrentBitNo();
1316 unsigned Code = Cursor.ReadCode();
1317
1318 // We expect all abbrevs to be at the start of the block.
1319 if (Code != llvm::bitc::DEFINE_ABBREV) {
1320 Cursor.JumpToBit(Offset);
1321 return false;
1322 }
1323 Cursor.ReadAbbrevRecord();
1324 }
1325}
1326
Richard Smithe40f2ba2013-08-07 21:41:30 +00001327Token ASTReader::ReadToken(ModuleFile &F, const RecordDataImpl &Record,
John McCallf413f5e2013-05-03 00:10:13 +00001328 unsigned &Idx) {
1329 Token Tok;
1330 Tok.startToken();
1331 Tok.setLocation(ReadSourceLocation(F, Record, Idx));
1332 Tok.setLength(Record[Idx++]);
1333 if (IdentifierInfo *II = getLocalIdentifier(F, Record[Idx++]))
1334 Tok.setIdentifierInfo(II);
1335 Tok.setKind((tok::TokenKind)Record[Idx++]);
1336 Tok.setFlag((Token::TokenFlags)Record[Idx++]);
1337 return Tok;
1338}
1339
Argyrios Kyrtzidiseb663da2013-03-22 21:12:57 +00001340MacroInfo *ASTReader::ReadMacroRecord(ModuleFile &F, uint64_t Offset) {
Chris Lattner7fb3bef2013-01-20 00:56:42 +00001341 BitstreamCursor &Stream = F.MacroCursor;
Guy Benyei11169dd2012-12-18 14:30:41 +00001342
1343 // Keep track of where we are in the stream, then jump back there
1344 // after reading this macro.
1345 SavedStreamPosition SavedPosition(Stream);
1346
1347 Stream.JumpToBit(Offset);
1348 RecordData Record;
1349 SmallVector<IdentifierInfo*, 16> MacroArgs;
1350 MacroInfo *Macro = 0;
1351
Guy Benyei11169dd2012-12-18 14:30:41 +00001352 while (true) {
Chris Lattnerefa77172013-01-20 00:00:22 +00001353 // Advance to the next record, but if we get to the end of the block, don't
1354 // pop it (removing all the abbreviations from the cursor) since we want to
1355 // be able to reseek within the block and read entries.
Chris Lattner7fb3bef2013-01-20 00:56:42 +00001356 unsigned Flags = BitstreamCursor::AF_DontPopBlockAtEnd;
Chris Lattnerefa77172013-01-20 00:00:22 +00001357 llvm::BitstreamEntry Entry = Stream.advanceSkippingSubblocks(Flags);
1358
1359 switch (Entry.Kind) {
1360 case llvm::BitstreamEntry::SubBlock: // Handled for us already.
1361 case llvm::BitstreamEntry::Error:
1362 Error("malformed block record in AST file");
Argyrios Kyrtzidiseb663da2013-03-22 21:12:57 +00001363 return Macro;
Chris Lattnerefa77172013-01-20 00:00:22 +00001364 case llvm::BitstreamEntry::EndBlock:
Argyrios Kyrtzidiseb663da2013-03-22 21:12:57 +00001365 return Macro;
Chris Lattnerefa77172013-01-20 00:00:22 +00001366 case llvm::BitstreamEntry::Record:
1367 // The interesting case.
1368 break;
Guy Benyei11169dd2012-12-18 14:30:41 +00001369 }
1370
1371 // Read a record.
Guy Benyei11169dd2012-12-18 14:30:41 +00001372 Record.clear();
1373 PreprocessorRecordTypes RecType =
Chris Lattner0e6c9402013-01-20 02:38:54 +00001374 (PreprocessorRecordTypes)Stream.readRecord(Entry.ID, Record);
Guy Benyei11169dd2012-12-18 14:30:41 +00001375 switch (RecType) {
Argyrios Kyrtzidiseb663da2013-03-22 21:12:57 +00001376 case PP_MACRO_DIRECTIVE_HISTORY:
1377 return Macro;
1378
Guy Benyei11169dd2012-12-18 14:30:41 +00001379 case PP_MACRO_OBJECT_LIKE:
1380 case PP_MACRO_FUNCTION_LIKE: {
1381 // If we already have a macro, that means that we've hit the end
1382 // of the definition of the macro we were looking for. We're
1383 // done.
1384 if (Macro)
Argyrios Kyrtzidiseb663da2013-03-22 21:12:57 +00001385 return Macro;
Guy Benyei11169dd2012-12-18 14:30:41 +00001386
Argyrios Kyrtzidiseb663da2013-03-22 21:12:57 +00001387 unsigned NextIndex = 1; // Skip identifier ID.
1388 SubmoduleID SubModID = getGlobalSubmoduleID(F, Record[NextIndex++]);
Guy Benyei11169dd2012-12-18 14:30:41 +00001389 SourceLocation Loc = ReadSourceLocation(F, Record, NextIndex);
Argyrios Kyrtzidiseb663da2013-03-22 21:12:57 +00001390 MacroInfo *MI = PP.AllocateDeserializedMacroInfo(Loc, SubModID);
Argyrios Kyrtzidis7572be22013-01-07 19:16:23 +00001391 MI->setDefinitionEndLoc(ReadSourceLocation(F, Record, NextIndex));
Guy Benyei11169dd2012-12-18 14:30:41 +00001392 MI->setIsUsed(Record[NextIndex++]);
Argyrios Kyrtzidis9ef53ce2014-04-09 18:21:23 +00001393 MI->setUsedForHeaderGuard(Record[NextIndex++]);
Guy Benyei11169dd2012-12-18 14:30:41 +00001394
Guy Benyei11169dd2012-12-18 14:30:41 +00001395 if (RecType == PP_MACRO_FUNCTION_LIKE) {
1396 // Decode function-like macro info.
1397 bool isC99VarArgs = Record[NextIndex++];
1398 bool isGNUVarArgs = Record[NextIndex++];
1399 bool hasCommaPasting = Record[NextIndex++];
1400 MacroArgs.clear();
1401 unsigned NumArgs = Record[NextIndex++];
1402 for (unsigned i = 0; i != NumArgs; ++i)
1403 MacroArgs.push_back(getLocalIdentifier(F, Record[NextIndex++]));
1404
1405 // Install function-like macro info.
1406 MI->setIsFunctionLike();
1407 if (isC99VarArgs) MI->setIsC99Varargs();
1408 if (isGNUVarArgs) MI->setIsGNUVarargs();
1409 if (hasCommaPasting) MI->setHasCommaPasting();
1410 MI->setArgumentList(MacroArgs.data(), MacroArgs.size(),
1411 PP.getPreprocessorAllocator());
1412 }
1413
Guy Benyei11169dd2012-12-18 14:30:41 +00001414 // Remember that we saw this macro last so that we add the tokens that
1415 // form its body to it.
1416 Macro = MI;
1417
1418 if (NextIndex + 1 == Record.size() && PP.getPreprocessingRecord() &&
1419 Record[NextIndex]) {
1420 // We have a macro definition. Register the association
1421 PreprocessedEntityID
1422 GlobalID = getGlobalPreprocessedEntityID(F, Record[NextIndex]);
1423 PreprocessingRecord &PPRec = *PP.getPreprocessingRecord();
Argyrios Kyrtzidis832de9f2013-02-22 18:35:59 +00001424 PreprocessingRecord::PPEntityID
1425 PPID = PPRec.getPPEntityID(GlobalID-1, /*isLoaded=*/true);
1426 MacroDefinition *PPDef =
1427 cast_or_null<MacroDefinition>(PPRec.getPreprocessedEntity(PPID));
1428 if (PPDef)
1429 PPRec.RegisterMacroDefinition(Macro, PPDef);
Guy Benyei11169dd2012-12-18 14:30:41 +00001430 }
1431
1432 ++NumMacrosRead;
1433 break;
1434 }
1435
1436 case PP_TOKEN: {
1437 // If we see a TOKEN before a PP_MACRO_*, then the file is
1438 // erroneous, just pretend we didn't see this.
1439 if (Macro == 0) break;
1440
John McCallf413f5e2013-05-03 00:10:13 +00001441 unsigned Idx = 0;
1442 Token Tok = ReadToken(F, Record, Idx);
Guy Benyei11169dd2012-12-18 14:30:41 +00001443 Macro->AddTokenToBody(Tok);
1444 break;
1445 }
1446 }
1447 }
1448}
1449
1450PreprocessedEntityID
1451ASTReader::getGlobalPreprocessedEntityID(ModuleFile &M, unsigned LocalID) const {
1452 ContinuousRangeMap<uint32_t, int, 2>::const_iterator
1453 I = M.PreprocessedEntityRemap.find(LocalID - NUM_PREDEF_PP_ENTITY_IDS);
1454 assert(I != M.PreprocessedEntityRemap.end()
1455 && "Invalid index into preprocessed entity index remap");
1456
1457 return LocalID + I->second;
1458}
1459
Argyrios Kyrtzidis5c2a3452013-03-06 18:12:47 +00001460unsigned HeaderFileInfoTrait::ComputeHash(internal_key_ref ikey) {
1461 return llvm::hash_combine(ikey.Size, ikey.ModTime);
Guy Benyei11169dd2012-12-18 14:30:41 +00001462}
1463
1464HeaderFileInfoTrait::internal_key_type
Argyrios Kyrtzidis5c2a3452013-03-06 18:12:47 +00001465HeaderFileInfoTrait::GetInternalKey(const FileEntry *FE) {
1466 internal_key_type ikey = { FE->getSize(), FE->getModificationTime(),
1467 FE->getName() };
1468 return ikey;
1469}
Guy Benyei11169dd2012-12-18 14:30:41 +00001470
Argyrios Kyrtzidis5c2a3452013-03-06 18:12:47 +00001471bool HeaderFileInfoTrait::EqualKey(internal_key_ref a, internal_key_ref b) {
1472 if (a.Size != b.Size || a.ModTime != b.ModTime)
Guy Benyei11169dd2012-12-18 14:30:41 +00001473 return false;
1474
Argyrios Kyrtzidis5c2a3452013-03-06 18:12:47 +00001475 if (strcmp(a.Filename, b.Filename) == 0)
1476 return true;
1477
Guy Benyei11169dd2012-12-18 14:30:41 +00001478 // Determine whether the actual files are equivalent.
Argyrios Kyrtzidis2a513e82013-03-04 20:33:40 +00001479 FileManager &FileMgr = Reader.getFileManager();
Argyrios Kyrtzidis5c2a3452013-03-06 18:12:47 +00001480 const FileEntry *FEA = FileMgr.getFile(a.Filename);
1481 const FileEntry *FEB = FileMgr.getFile(b.Filename);
Argyrios Kyrtzidis2a513e82013-03-04 20:33:40 +00001482 return (FEA && FEA == FEB);
Guy Benyei11169dd2012-12-18 14:30:41 +00001483}
1484
1485std::pair<unsigned, unsigned>
1486HeaderFileInfoTrait::ReadKeyDataLength(const unsigned char*& d) {
Justin Bogner57ba0b22014-03-28 22:03:24 +00001487 using namespace llvm::support;
1488 unsigned KeyLen = (unsigned) endian::readNext<uint16_t, little, unaligned>(d);
Guy Benyei11169dd2012-12-18 14:30:41 +00001489 unsigned DataLen = (unsigned) *d++;
Argyrios Kyrtzidis5c2a3452013-03-06 18:12:47 +00001490 return std::make_pair(KeyLen, DataLen);
Guy Benyei11169dd2012-12-18 14:30:41 +00001491}
Argyrios Kyrtzidis5c2a3452013-03-06 18:12:47 +00001492
1493HeaderFileInfoTrait::internal_key_type
1494HeaderFileInfoTrait::ReadKey(const unsigned char *d, unsigned) {
Justin Bogner57ba0b22014-03-28 22:03:24 +00001495 using namespace llvm::support;
Argyrios Kyrtzidis5c2a3452013-03-06 18:12:47 +00001496 internal_key_type ikey;
Justin Bogner57ba0b22014-03-28 22:03:24 +00001497 ikey.Size = off_t(endian::readNext<uint64_t, little, unaligned>(d));
1498 ikey.ModTime = time_t(endian::readNext<uint64_t, little, unaligned>(d));
Argyrios Kyrtzidis5c2a3452013-03-06 18:12:47 +00001499 ikey.Filename = (const char *)d;
1500 return ikey;
1501}
1502
Guy Benyei11169dd2012-12-18 14:30:41 +00001503HeaderFileInfoTrait::data_type
Argyrios Kyrtzidisb146baa2013-03-13 21:13:51 +00001504HeaderFileInfoTrait::ReadData(internal_key_ref key, const unsigned char *d,
Guy Benyei11169dd2012-12-18 14:30:41 +00001505 unsigned DataLen) {
1506 const unsigned char *End = d + DataLen;
Justin Bogner57ba0b22014-03-28 22:03:24 +00001507 using namespace llvm::support;
Guy Benyei11169dd2012-12-18 14:30:41 +00001508 HeaderFileInfo HFI;
1509 unsigned Flags = *d++;
Lawrence Crowlb53e5482013-06-20 21:14:14 +00001510 HFI.HeaderRole = static_cast<ModuleMap::ModuleHeaderRole>
1511 ((Flags >> 6) & 0x03);
Guy Benyei11169dd2012-12-18 14:30:41 +00001512 HFI.isImport = (Flags >> 5) & 0x01;
1513 HFI.isPragmaOnce = (Flags >> 4) & 0x01;
1514 HFI.DirInfo = (Flags >> 2) & 0x03;
1515 HFI.Resolved = (Flags >> 1) & 0x01;
1516 HFI.IndexHeaderMapHeader = Flags & 0x01;
Justin Bogner57ba0b22014-03-28 22:03:24 +00001517 HFI.NumIncludes = endian::readNext<uint16_t, little, unaligned>(d);
1518 HFI.ControllingMacroID = Reader.getGlobalIdentifierID(
1519 M, endian::readNext<uint32_t, little, unaligned>(d));
1520 if (unsigned FrameworkOffset =
1521 endian::readNext<uint32_t, little, unaligned>(d)) {
Guy Benyei11169dd2012-12-18 14:30:41 +00001522 // The framework offset is 1 greater than the actual offset,
1523 // since 0 is used as an indicator for "no framework name".
1524 StringRef FrameworkName(FrameworkStrings + FrameworkOffset - 1);
1525 HFI.Framework = HS->getUniqueFrameworkName(FrameworkName);
1526 }
1527
Argyrios Kyrtzidisb146baa2013-03-13 21:13:51 +00001528 if (d != End) {
Justin Bogner57ba0b22014-03-28 22:03:24 +00001529 uint32_t LocalSMID = endian::readNext<uint32_t, little, unaligned>(d);
Argyrios Kyrtzidisb146baa2013-03-13 21:13:51 +00001530 if (LocalSMID) {
1531 // This header is part of a module. Associate it with the module to enable
1532 // implicit module import.
1533 SubmoduleID GlobalSMID = Reader.getGlobalSubmoduleID(M, LocalSMID);
1534 Module *Mod = Reader.getSubmodule(GlobalSMID);
1535 HFI.isModuleHeader = true;
1536 FileManager &FileMgr = Reader.getFileManager();
1537 ModuleMap &ModMap =
1538 Reader.getPreprocessor().getHeaderSearchInfo().getModuleMap();
Lawrence Crowlb53e5482013-06-20 21:14:14 +00001539 ModMap.addHeader(Mod, FileMgr.getFile(key.Filename), HFI.getHeaderRole());
Argyrios Kyrtzidisb146baa2013-03-13 21:13:51 +00001540 }
1541 }
1542
Guy Benyei11169dd2012-12-18 14:30:41 +00001543 assert(End == d && "Wrong data length in HeaderFileInfo deserialization");
1544 (void)End;
1545
1546 // This HeaderFileInfo was externally loaded.
1547 HFI.External = true;
1548 return HFI;
1549}
1550
Richard Smith49f906a2014-03-01 00:08:04 +00001551void
1552ASTReader::addPendingMacroFromModule(IdentifierInfo *II, ModuleFile *M,
1553 GlobalMacroID GMacID,
1554 llvm::ArrayRef<SubmoduleID> Overrides) {
Guy Benyei11169dd2012-12-18 14:30:41 +00001555 assert(NumCurrentElementsDeserializing > 0 &&"Missing deserialization guard");
Richard Smith49f906a2014-03-01 00:08:04 +00001556 SubmoduleID *OverrideData = 0;
1557 if (!Overrides.empty()) {
1558 OverrideData = new (Context) SubmoduleID[Overrides.size() + 1];
1559 OverrideData[0] = Overrides.size();
1560 for (unsigned I = 0; I != Overrides.size(); ++I)
1561 OverrideData[I + 1] = getGlobalSubmoduleID(*M, Overrides[I]);
1562 }
1563 PendingMacroIDs[II].push_back(PendingMacroInfo(M, GMacID, OverrideData));
Argyrios Kyrtzidiseb663da2013-03-22 21:12:57 +00001564}
1565
1566void ASTReader::addPendingMacroFromPCH(IdentifierInfo *II,
1567 ModuleFile *M,
1568 uint64_t MacroDirectivesOffset) {
1569 assert(NumCurrentElementsDeserializing > 0 &&"Missing deserialization guard");
1570 PendingMacroIDs[II].push_back(PendingMacroInfo(M, MacroDirectivesOffset));
Guy Benyei11169dd2012-12-18 14:30:41 +00001571}
1572
1573void ASTReader::ReadDefinedMacros() {
1574 // Note that we are loading defined macros.
1575 Deserializing Macros(this);
1576
1577 for (ModuleReverseIterator I = ModuleMgr.rbegin(),
1578 E = ModuleMgr.rend(); I != E; ++I) {
Chris Lattner7fb3bef2013-01-20 00:56:42 +00001579 BitstreamCursor &MacroCursor = (*I)->MacroCursor;
Guy Benyei11169dd2012-12-18 14:30:41 +00001580
1581 // If there was no preprocessor block, skip this file.
1582 if (!MacroCursor.getBitStreamReader())
1583 continue;
1584
Chris Lattner7fb3bef2013-01-20 00:56:42 +00001585 BitstreamCursor Cursor = MacroCursor;
Guy Benyei11169dd2012-12-18 14:30:41 +00001586 Cursor.JumpToBit((*I)->MacroStartOffset);
1587
1588 RecordData Record;
1589 while (true) {
Chris Lattnere7b154b2013-01-19 21:39:22 +00001590 llvm::BitstreamEntry E = Cursor.advanceSkippingSubblocks();
1591
1592 switch (E.Kind) {
1593 case llvm::BitstreamEntry::SubBlock: // Handled for us already.
1594 case llvm::BitstreamEntry::Error:
1595 Error("malformed block record in AST file");
1596 return;
1597 case llvm::BitstreamEntry::EndBlock:
1598 goto NextCursor;
1599
1600 case llvm::BitstreamEntry::Record:
Chris Lattnere7b154b2013-01-19 21:39:22 +00001601 Record.clear();
Chris Lattner0e6c9402013-01-20 02:38:54 +00001602 switch (Cursor.readRecord(E.ID, Record)) {
Chris Lattnere7b154b2013-01-19 21:39:22 +00001603 default: // Default behavior: ignore.
1604 break;
1605
1606 case PP_MACRO_OBJECT_LIKE:
1607 case PP_MACRO_FUNCTION_LIKE:
1608 getLocalIdentifier(**I, Record[0]);
1609 break;
1610
1611 case PP_TOKEN:
1612 // Ignore tokens.
1613 break;
Guy Benyei11169dd2012-12-18 14:30:41 +00001614 }
Guy Benyei11169dd2012-12-18 14:30:41 +00001615 break;
1616 }
1617 }
Chris Lattnere7b154b2013-01-19 21:39:22 +00001618 NextCursor: ;
Guy Benyei11169dd2012-12-18 14:30:41 +00001619 }
1620}
1621
1622namespace {
1623 /// \brief Visitor class used to look up identifirs in an AST file.
1624 class IdentifierLookupVisitor {
1625 StringRef Name;
1626 unsigned PriorGeneration;
Douglas Gregor00a50f72013-01-25 00:38:33 +00001627 unsigned &NumIdentifierLookups;
1628 unsigned &NumIdentifierLookupHits;
Guy Benyei11169dd2012-12-18 14:30:41 +00001629 IdentifierInfo *Found;
Douglas Gregor00a50f72013-01-25 00:38:33 +00001630
Guy Benyei11169dd2012-12-18 14:30:41 +00001631 public:
Douglas Gregor00a50f72013-01-25 00:38:33 +00001632 IdentifierLookupVisitor(StringRef Name, unsigned PriorGeneration,
1633 unsigned &NumIdentifierLookups,
1634 unsigned &NumIdentifierLookupHits)
Douglas Gregor7211ac12013-01-25 23:32:03 +00001635 : Name(Name), PriorGeneration(PriorGeneration),
Douglas Gregor00a50f72013-01-25 00:38:33 +00001636 NumIdentifierLookups(NumIdentifierLookups),
1637 NumIdentifierLookupHits(NumIdentifierLookupHits),
1638 Found()
1639 {
1640 }
Guy Benyei11169dd2012-12-18 14:30:41 +00001641
1642 static bool visit(ModuleFile &M, void *UserData) {
1643 IdentifierLookupVisitor *This
1644 = static_cast<IdentifierLookupVisitor *>(UserData);
1645
1646 // If we've already searched this module file, skip it now.
1647 if (M.Generation <= This->PriorGeneration)
1648 return true;
Douglas Gregore060e572013-01-25 01:03:03 +00001649
Guy Benyei11169dd2012-12-18 14:30:41 +00001650 ASTIdentifierLookupTable *IdTable
1651 = (ASTIdentifierLookupTable *)M.IdentifierLookupTable;
1652 if (!IdTable)
1653 return false;
1654
1655 ASTIdentifierLookupTrait Trait(IdTable->getInfoObj().getReader(),
1656 M, This->Found);
Douglas Gregor00a50f72013-01-25 00:38:33 +00001657 ++This->NumIdentifierLookups;
1658 ASTIdentifierLookupTable::iterator Pos = IdTable->find(This->Name,&Trait);
Guy Benyei11169dd2012-12-18 14:30:41 +00001659 if (Pos == IdTable->end())
1660 return false;
1661
1662 // Dereferencing the iterator has the effect of building the
1663 // IdentifierInfo node and populating it with the various
1664 // declarations it needs.
Douglas Gregor00a50f72013-01-25 00:38:33 +00001665 ++This->NumIdentifierLookupHits;
Guy Benyei11169dd2012-12-18 14:30:41 +00001666 This->Found = *Pos;
1667 return true;
1668 }
1669
1670 // \brief Retrieve the identifier info found within the module
1671 // files.
1672 IdentifierInfo *getIdentifierInfo() const { return Found; }
1673 };
1674}
1675
1676void ASTReader::updateOutOfDateIdentifier(IdentifierInfo &II) {
1677 // Note that we are loading an identifier.
1678 Deserializing AnIdentifier(this);
1679
1680 unsigned PriorGeneration = 0;
1681 if (getContext().getLangOpts().Modules)
1682 PriorGeneration = IdentifierGeneration[&II];
Douglas Gregore060e572013-01-25 01:03:03 +00001683
1684 // If there is a global index, look there first to determine which modules
1685 // provably do not have any results for this identifier.
Douglas Gregor7211ac12013-01-25 23:32:03 +00001686 GlobalModuleIndex::HitSet Hits;
1687 GlobalModuleIndex::HitSet *HitsPtr = 0;
Douglas Gregore060e572013-01-25 01:03:03 +00001688 if (!loadGlobalIndex()) {
Douglas Gregor7211ac12013-01-25 23:32:03 +00001689 if (GlobalIndex->lookupIdentifier(II.getName(), Hits)) {
1690 HitsPtr = &Hits;
Douglas Gregore060e572013-01-25 01:03:03 +00001691 }
1692 }
1693
Douglas Gregor7211ac12013-01-25 23:32:03 +00001694 IdentifierLookupVisitor Visitor(II.getName(), PriorGeneration,
Douglas Gregor00a50f72013-01-25 00:38:33 +00001695 NumIdentifierLookups,
1696 NumIdentifierLookupHits);
Douglas Gregor7211ac12013-01-25 23:32:03 +00001697 ModuleMgr.visit(IdentifierLookupVisitor::visit, &Visitor, HitsPtr);
Guy Benyei11169dd2012-12-18 14:30:41 +00001698 markIdentifierUpToDate(&II);
1699}
1700
1701void ASTReader::markIdentifierUpToDate(IdentifierInfo *II) {
1702 if (!II)
1703 return;
1704
1705 II->setOutOfDate(false);
1706
1707 // Update the generation for this identifier.
1708 if (getContext().getLangOpts().Modules)
1709 IdentifierGeneration[II] = CurrentGeneration;
1710}
1711
Richard Smith49f906a2014-03-01 00:08:04 +00001712struct ASTReader::ModuleMacroInfo {
1713 SubmoduleID SubModID;
1714 MacroInfo *MI;
1715 SubmoduleID *Overrides;
1716 // FIXME: Remove this.
1717 ModuleFile *F;
1718
1719 bool isDefine() const { return MI; }
1720
1721 SubmoduleID getSubmoduleID() const { return SubModID; }
1722
1723 llvm::ArrayRef<SubmoduleID> getOverriddenSubmodules() const {
1724 if (!Overrides)
1725 return llvm::ArrayRef<SubmoduleID>();
1726 return llvm::makeArrayRef(Overrides + 1, *Overrides);
1727 }
1728
1729 DefMacroDirective *import(Preprocessor &PP, SourceLocation ImportLoc) const {
1730 if (!MI)
1731 return 0;
1732 return PP.AllocateDefMacroDirective(MI, ImportLoc, /*isImported=*/true);
1733 }
1734};
1735
1736ASTReader::ModuleMacroInfo *
1737ASTReader::getModuleMacro(const PendingMacroInfo &PMInfo) {
1738 ModuleMacroInfo Info;
1739
1740 uint32_t ID = PMInfo.ModuleMacroData.MacID;
1741 if (ID & 1) {
1742 // Macro undefinition.
1743 Info.SubModID = getGlobalSubmoduleID(*PMInfo.M, ID >> 1);
1744 Info.MI = 0;
1745 } else {
1746 // Macro definition.
1747 GlobalMacroID GMacID = getGlobalMacroID(*PMInfo.M, ID >> 1);
1748 assert(GMacID);
1749
1750 // If this macro has already been loaded, don't do so again.
1751 // FIXME: This is highly dubious. Multiple macro definitions can have the
1752 // same MacroInfo (and hence the same GMacID) due to #pragma push_macro etc.
1753 if (MacrosLoaded[GMacID - NUM_PREDEF_MACRO_IDS])
1754 return 0;
1755
1756 Info.MI = getMacro(GMacID);
1757 Info.SubModID = Info.MI->getOwningModuleID();
1758 }
1759 Info.Overrides = PMInfo.ModuleMacroData.Overrides;
1760 Info.F = PMInfo.M;
1761
1762 return new (Context) ModuleMacroInfo(Info);
1763}
1764
Argyrios Kyrtzidiseb663da2013-03-22 21:12:57 +00001765void ASTReader::resolvePendingMacro(IdentifierInfo *II,
1766 const PendingMacroInfo &PMInfo) {
1767 assert(II);
1768
1769 if (PMInfo.M->Kind != MK_Module) {
1770 installPCHMacroDirectives(II, *PMInfo.M,
1771 PMInfo.PCHMacroData.MacroDirectivesOffset);
1772 return;
1773 }
Richard Smith49f906a2014-03-01 00:08:04 +00001774
Argyrios Kyrtzidiseb663da2013-03-22 21:12:57 +00001775 // Module Macro.
1776
Richard Smith49f906a2014-03-01 00:08:04 +00001777 ModuleMacroInfo *MMI = getModuleMacro(PMInfo);
1778 if (!MMI)
Argyrios Kyrtzidiseb663da2013-03-22 21:12:57 +00001779 return;
1780
Richard Smith49f906a2014-03-01 00:08:04 +00001781 Module *Owner = getSubmodule(MMI->getSubmoduleID());
1782 if (Owner && Owner->NameVisibility == Module::Hidden) {
1783 // Macros in the owning module are hidden. Just remember this macro to
1784 // install if we make this module visible.
1785 HiddenNamesMap[Owner].HiddenMacros.insert(std::make_pair(II, MMI));
1786 } else {
1787 installImportedMacro(II, MMI, Owner);
Argyrios Kyrtzidiseb663da2013-03-22 21:12:57 +00001788 }
Argyrios Kyrtzidiseb663da2013-03-22 21:12:57 +00001789}
1790
1791void ASTReader::installPCHMacroDirectives(IdentifierInfo *II,
1792 ModuleFile &M, uint64_t Offset) {
1793 assert(M.Kind != MK_Module);
1794
1795 BitstreamCursor &Cursor = M.MacroCursor;
1796 SavedStreamPosition SavedPosition(Cursor);
1797 Cursor.JumpToBit(Offset);
1798
1799 llvm::BitstreamEntry Entry =
1800 Cursor.advance(BitstreamCursor::AF_DontPopBlockAtEnd);
1801 if (Entry.Kind != llvm::BitstreamEntry::Record) {
1802 Error("malformed block record in AST file");
1803 return;
1804 }
1805
1806 RecordData Record;
1807 PreprocessorRecordTypes RecType =
1808 (PreprocessorRecordTypes)Cursor.readRecord(Entry.ID, Record);
1809 if (RecType != PP_MACRO_DIRECTIVE_HISTORY) {
1810 Error("malformed block record in AST file");
1811 return;
1812 }
1813
1814 // Deserialize the macro directives history in reverse source-order.
1815 MacroDirective *Latest = 0, *Earliest = 0;
1816 unsigned Idx = 0, N = Record.size();
1817 while (Idx < N) {
Argyrios Kyrtzidisb6210df2013-03-26 17:17:01 +00001818 MacroDirective *MD = 0;
Argyrios Kyrtzidiseb663da2013-03-22 21:12:57 +00001819 SourceLocation Loc = ReadSourceLocation(M, Record, Idx);
Argyrios Kyrtzidisb6210df2013-03-26 17:17:01 +00001820 MacroDirective::Kind K = (MacroDirective::Kind)Record[Idx++];
1821 switch (K) {
1822 case MacroDirective::MD_Define: {
1823 GlobalMacroID GMacID = getGlobalMacroID(M, Record[Idx++]);
1824 MacroInfo *MI = getMacro(GMacID);
1825 bool isImported = Record[Idx++];
1826 bool isAmbiguous = Record[Idx++];
1827 DefMacroDirective *DefMD =
1828 PP.AllocateDefMacroDirective(MI, Loc, isImported);
1829 DefMD->setAmbiguous(isAmbiguous);
1830 MD = DefMD;
1831 break;
1832 }
1833 case MacroDirective::MD_Undefine:
1834 MD = PP.AllocateUndefMacroDirective(Loc);
1835 break;
1836 case MacroDirective::MD_Visibility: {
1837 bool isPublic = Record[Idx++];
1838 MD = PP.AllocateVisibilityMacroDirective(Loc, isPublic);
1839 break;
1840 }
1841 }
Argyrios Kyrtzidiseb663da2013-03-22 21:12:57 +00001842
1843 if (!Latest)
1844 Latest = MD;
1845 if (Earliest)
1846 Earliest->setPrevious(MD);
1847 Earliest = MD;
1848 }
1849
1850 PP.setLoadedMacroDirective(II, Latest);
1851}
1852
Argyrios Kyrtzidis3a9c42c2013-03-27 01:25:34 +00001853/// \brief For the given macro definitions, check if they are both in system
Douglas Gregor0b202052013-04-12 21:00:54 +00001854/// modules.
1855static bool areDefinedInSystemModules(MacroInfo *PrevMI, MacroInfo *NewMI,
Douglas Gregor5e461192013-06-07 22:56:11 +00001856 Module *NewOwner, ASTReader &Reader) {
Argyrios Kyrtzidis3a9c42c2013-03-27 01:25:34 +00001857 assert(PrevMI && NewMI);
Argyrios Kyrtzidis3a9c42c2013-03-27 01:25:34 +00001858 Module *PrevOwner = 0;
1859 if (SubmoduleID PrevModID = PrevMI->getOwningModuleID())
1860 PrevOwner = Reader.getSubmodule(PrevModID);
Douglas Gregor5e461192013-06-07 22:56:11 +00001861 SourceManager &SrcMgr = Reader.getSourceManager();
1862 bool PrevInSystem
1863 = PrevOwner? PrevOwner->IsSystem
1864 : SrcMgr.isInSystemHeader(PrevMI->getDefinitionLoc());
1865 bool NewInSystem
1866 = NewOwner? NewOwner->IsSystem
1867 : SrcMgr.isInSystemHeader(NewMI->getDefinitionLoc());
1868 if (PrevOwner && PrevOwner == NewOwner)
Argyrios Kyrtzidis3a9c42c2013-03-27 01:25:34 +00001869 return false;
Douglas Gregor5e461192013-06-07 22:56:11 +00001870 return PrevInSystem && NewInSystem;
Argyrios Kyrtzidis3a9c42c2013-03-27 01:25:34 +00001871}
1872
Richard Smith49f906a2014-03-01 00:08:04 +00001873void ASTReader::removeOverriddenMacros(IdentifierInfo *II,
1874 AmbiguousMacros &Ambig,
1875 llvm::ArrayRef<SubmoduleID> Overrides) {
1876 for (unsigned OI = 0, ON = Overrides.size(); OI != ON; ++OI) {
1877 SubmoduleID OwnerID = Overrides[OI];
Argyrios Kyrtzidiseb663da2013-03-22 21:12:57 +00001878
Richard Smith49f906a2014-03-01 00:08:04 +00001879 // If this macro is not yet visible, remove it from the hidden names list.
1880 Module *Owner = getSubmodule(OwnerID);
1881 HiddenNames &Hidden = HiddenNamesMap[Owner];
1882 HiddenMacrosMap::iterator HI = Hidden.HiddenMacros.find(II);
1883 if (HI != Hidden.HiddenMacros.end()) {
Richard Smith9d100862014-03-06 03:16:27 +00001884 auto SubOverrides = HI->second->getOverriddenSubmodules();
Richard Smith49f906a2014-03-01 00:08:04 +00001885 Hidden.HiddenMacros.erase(HI);
Richard Smith9d100862014-03-06 03:16:27 +00001886 removeOverriddenMacros(II, Ambig, SubOverrides);
Richard Smith49f906a2014-03-01 00:08:04 +00001887 }
1888
1889 // If this macro is already in our list of conflicts, remove it from there.
Richard Smithbb29e512014-03-06 00:33:23 +00001890 Ambig.erase(
1891 std::remove_if(Ambig.begin(), Ambig.end(), [&](DefMacroDirective *MD) {
1892 return MD->getInfo()->getOwningModuleID() == OwnerID;
1893 }),
1894 Ambig.end());
Richard Smith49f906a2014-03-01 00:08:04 +00001895 }
1896}
1897
1898ASTReader::AmbiguousMacros *
1899ASTReader::removeOverriddenMacros(IdentifierInfo *II,
1900 llvm::ArrayRef<SubmoduleID> Overrides) {
Argyrios Kyrtzidiseb663da2013-03-22 21:12:57 +00001901 MacroDirective *Prev = PP.getMacroDirective(II);
Richard Smith49f906a2014-03-01 00:08:04 +00001902 if (!Prev && Overrides.empty())
1903 return 0;
1904
1905 DefMacroDirective *PrevDef = Prev ? Prev->getDefinition().getDirective() : 0;
1906 if (PrevDef && PrevDef->isAmbiguous()) {
1907 // We had a prior ambiguity. Check whether we resolve it (or make it worse).
1908 AmbiguousMacros &Ambig = AmbiguousMacroDefs[II];
1909 Ambig.push_back(PrevDef);
1910
1911 removeOverriddenMacros(II, Ambig, Overrides);
1912
1913 if (!Ambig.empty())
1914 return &Ambig;
1915
1916 AmbiguousMacroDefs.erase(II);
1917 } else {
1918 // There's no ambiguity yet. Maybe we're introducing one.
Benjamin Kramer834652a2014-05-03 18:44:26 +00001919 AmbiguousMacros Ambig;
Richard Smith49f906a2014-03-01 00:08:04 +00001920 if (PrevDef)
1921 Ambig.push_back(PrevDef);
1922
1923 removeOverriddenMacros(II, Ambig, Overrides);
1924
1925 if (!Ambig.empty()) {
1926 AmbiguousMacros &Result = AmbiguousMacroDefs[II];
Benjamin Kramer834652a2014-05-03 18:44:26 +00001927 std::swap(Result, Ambig);
Richard Smith49f906a2014-03-01 00:08:04 +00001928 return &Result;
Argyrios Kyrtzidisb6210df2013-03-26 17:17:01 +00001929 }
Argyrios Kyrtzidiseb663da2013-03-22 21:12:57 +00001930 }
Richard Smith49f906a2014-03-01 00:08:04 +00001931
1932 // We ended up with no ambiguity.
1933 return 0;
1934}
1935
1936void ASTReader::installImportedMacro(IdentifierInfo *II, ModuleMacroInfo *MMI,
1937 Module *Owner) {
1938 assert(II && Owner);
1939
1940 SourceLocation ImportLoc = Owner->MacroVisibilityLoc;
1941 if (ImportLoc.isInvalid()) {
1942 // FIXME: If we made macros from this module visible but didn't provide a
1943 // source location for the import, we don't have a location for the macro.
1944 // Use the location at which the containing module file was first imported
1945 // for now.
1946 ImportLoc = MMI->F->DirectImportLoc;
Richard Smith56be7542014-03-21 00:33:59 +00001947 assert(ImportLoc.isValid() && "no import location for a visible macro?");
Richard Smith49f906a2014-03-01 00:08:04 +00001948 }
1949
Benjamin Kramer834652a2014-05-03 18:44:26 +00001950 AmbiguousMacros *Prev =
Richard Smith49f906a2014-03-01 00:08:04 +00001951 removeOverriddenMacros(II, MMI->getOverriddenSubmodules());
1952
Richard Smith49f906a2014-03-01 00:08:04 +00001953 // Create a synthetic macro definition corresponding to the import (or null
1954 // if this was an undefinition of the macro).
1955 DefMacroDirective *MD = MMI->import(PP, ImportLoc);
1956
1957 // If there's no ambiguity, just install the macro.
1958 if (!Prev) {
1959 if (MD)
1960 PP.appendMacroDirective(II, MD);
1961 else
1962 PP.appendMacroDirective(II, PP.AllocateUndefMacroDirective(ImportLoc));
1963 return;
1964 }
1965 assert(!Prev->empty());
1966
1967 if (!MD) {
1968 // We imported a #undef that didn't remove all prior definitions. The most
1969 // recent prior definition remains, and we install it in the place of the
1970 // imported directive.
1971 MacroInfo *NewMI = Prev->back()->getInfo();
1972 Prev->pop_back();
1973 MD = PP.AllocateDefMacroDirective(NewMI, ImportLoc, /*Imported*/true);
1974 }
1975
1976 // We're introducing a macro definition that creates or adds to an ambiguity.
1977 // We can resolve that ambiguity if this macro is token-for-token identical to
1978 // all of the existing definitions.
1979 MacroInfo *NewMI = MD->getInfo();
1980 assert(NewMI && "macro definition with no MacroInfo?");
1981 while (!Prev->empty()) {
1982 MacroInfo *PrevMI = Prev->back()->getInfo();
1983 assert(PrevMI && "macro definition with no MacroInfo?");
1984
1985 // Before marking the macros as ambiguous, check if this is a case where
1986 // both macros are in system headers. If so, we trust that the system
1987 // did not get it wrong. This also handles cases where Clang's own
1988 // headers have a different spelling of certain system macros:
1989 // #define LONG_MAX __LONG_MAX__ (clang's limits.h)
1990 // #define LONG_MAX 0x7fffffffffffffffL (system's limits.h)
1991 //
1992 // FIXME: Remove the defined-in-system-headers check. clang's limits.h
1993 // overrides the system limits.h's macros, so there's no conflict here.
1994 if (NewMI != PrevMI &&
1995 !PrevMI->isIdenticalTo(*NewMI, PP, /*Syntactically=*/true) &&
1996 !areDefinedInSystemModules(PrevMI, NewMI, Owner, *this))
1997 break;
1998
1999 // The previous definition is the same as this one (or both are defined in
2000 // system modules so we can assume they're equivalent); we don't need to
2001 // track it any more.
2002 Prev->pop_back();
2003 }
2004
2005 if (!Prev->empty())
2006 MD->setAmbiguous(true);
2007
Argyrios Kyrtzidisb6210df2013-03-26 17:17:01 +00002008 PP.appendMacroDirective(II, MD);
Argyrios Kyrtzidiseb663da2013-03-22 21:12:57 +00002009}
2010
Argyrios Kyrtzidisce9b49e2014-03-14 02:26:27 +00002011ASTReader::InputFileInfo
2012ASTReader::readInputFileInfo(ModuleFile &F, unsigned ID) {
Ben Langmuir198c1682014-03-07 07:27:49 +00002013 // Go find this input file.
2014 BitstreamCursor &Cursor = F.InputFilesCursor;
2015 SavedStreamPosition SavedPosition(Cursor);
2016 Cursor.JumpToBit(F.InputFileOffsets[ID-1]);
2017
2018 unsigned Code = Cursor.ReadCode();
2019 RecordData Record;
2020 StringRef Blob;
2021
2022 unsigned Result = Cursor.readRecord(Code, Record, &Blob);
2023 assert(static_cast<InputFileRecordTypes>(Result) == INPUT_FILE &&
2024 "invalid record type for input file");
2025 (void)Result;
2026
Argyrios Kyrtzidisce9b49e2014-03-14 02:26:27 +00002027 std::string Filename;
2028 off_t StoredSize;
2029 time_t StoredTime;
2030 bool Overridden;
2031
Ben Langmuir198c1682014-03-07 07:27:49 +00002032 assert(Record[0] == ID && "Bogus stored ID or offset");
2033 StoredSize = static_cast<off_t>(Record[1]);
2034 StoredTime = static_cast<time_t>(Record[2]);
2035 Overridden = static_cast<bool>(Record[3]);
2036 Filename = Blob;
2037 MaybeAddSystemRootToFilename(F, Filename);
Argyrios Kyrtzidisce9b49e2014-03-14 02:26:27 +00002038
Hans Wennborg73945142014-03-14 17:45:06 +00002039 InputFileInfo R = { std::move(Filename), StoredSize, StoredTime, Overridden };
2040 return R;
Ben Langmuir198c1682014-03-07 07:27:49 +00002041}
2042
2043std::string ASTReader::getInputFileName(ModuleFile &F, unsigned int ID) {
Argyrios Kyrtzidisce9b49e2014-03-14 02:26:27 +00002044 return readInputFileInfo(F, ID).Filename;
Ben Langmuir198c1682014-03-07 07:27:49 +00002045}
2046
Argyrios Kyrtzidis61c3d872013-03-01 03:26:04 +00002047InputFile ASTReader::getInputFile(ModuleFile &F, unsigned ID, bool Complain) {
Guy Benyei11169dd2012-12-18 14:30:41 +00002048 // If this ID is bogus, just return an empty input file.
2049 if (ID == 0 || ID > F.InputFilesLoaded.size())
2050 return InputFile();
2051
2052 // If we've already loaded this input file, return it.
Argyrios Kyrtzidis61c3d872013-03-01 03:26:04 +00002053 if (F.InputFilesLoaded[ID-1].getFile())
Guy Benyei11169dd2012-12-18 14:30:41 +00002054 return F.InputFilesLoaded[ID-1];
2055
Argyrios Kyrtzidis9308f0a2014-01-08 19:13:34 +00002056 if (F.InputFilesLoaded[ID-1].isNotFound())
2057 return InputFile();
2058
Guy Benyei11169dd2012-12-18 14:30:41 +00002059 // Go find this input file.
Chris Lattner7fb3bef2013-01-20 00:56:42 +00002060 BitstreamCursor &Cursor = F.InputFilesCursor;
Guy Benyei11169dd2012-12-18 14:30:41 +00002061 SavedStreamPosition SavedPosition(Cursor);
2062 Cursor.JumpToBit(F.InputFileOffsets[ID-1]);
2063
Argyrios Kyrtzidisce9b49e2014-03-14 02:26:27 +00002064 InputFileInfo FI = readInputFileInfo(F, ID);
2065 off_t StoredSize = FI.StoredSize;
2066 time_t StoredTime = FI.StoredTime;
2067 bool Overridden = FI.Overridden;
2068 StringRef Filename = FI.Filename;
Argyrios Kyrtzidis61c3d872013-03-01 03:26:04 +00002069
Ben Langmuir198c1682014-03-07 07:27:49 +00002070 const FileEntry *File
2071 = Overridden? FileMgr.getVirtualFile(Filename, StoredSize, StoredTime)
2072 : FileMgr.getFile(Filename, /*OpenFile=*/false);
2073
2074 // If we didn't find the file, resolve it relative to the
2075 // original directory from which this AST file was created.
2076 if (File == 0 && !F.OriginalDir.empty() && !CurrentDir.empty() &&
2077 F.OriginalDir != CurrentDir) {
2078 std::string Resolved = resolveFileRelativeToOriginalDir(Filename,
2079 F.OriginalDir,
2080 CurrentDir);
2081 if (!Resolved.empty())
2082 File = FileMgr.getFile(Resolved);
2083 }
2084
2085 // For an overridden file, create a virtual file with the stored
2086 // size/timestamp.
2087 if (Overridden && File == 0) {
2088 File = FileMgr.getVirtualFile(Filename, StoredSize, StoredTime);
2089 }
2090
2091 if (File == 0) {
2092 if (Complain) {
2093 std::string ErrorStr = "could not find file '";
2094 ErrorStr += Filename;
2095 ErrorStr += "' referenced by AST file";
2096 Error(ErrorStr.c_str());
Guy Benyei11169dd2012-12-18 14:30:41 +00002097 }
Ben Langmuir198c1682014-03-07 07:27:49 +00002098 // Record that we didn't find the file.
2099 F.InputFilesLoaded[ID-1] = InputFile::getNotFound();
2100 return InputFile();
2101 }
Guy Benyei11169dd2012-12-18 14:30:41 +00002102
Ben Langmuir198c1682014-03-07 07:27:49 +00002103 // Check if there was a request to override the contents of the file
2104 // that was part of the precompiled header. Overridding such a file
2105 // can lead to problems when lexing using the source locations from the
2106 // PCH.
2107 SourceManager &SM = getSourceManager();
2108 if (!Overridden && SM.isFileOverridden(File)) {
2109 if (Complain)
2110 Error(diag::err_fe_pch_file_overridden, Filename);
2111 // After emitting the diagnostic, recover by disabling the override so
2112 // that the original file will be used.
2113 SM.disableFileContentsOverride(File);
2114 // The FileEntry is a virtual file entry with the size of the contents
2115 // that would override the original contents. Set it to the original's
2116 // size/time.
2117 FileMgr.modifyFileEntry(const_cast<FileEntry*>(File),
2118 StoredSize, StoredTime);
2119 }
Guy Benyei11169dd2012-12-18 14:30:41 +00002120
Ben Langmuir198c1682014-03-07 07:27:49 +00002121 bool IsOutOfDate = false;
2122
2123 // For an overridden file, there is nothing to validate.
2124 if (!Overridden && (StoredSize != File->getSize()
Guy Benyei11169dd2012-12-18 14:30:41 +00002125#if !defined(LLVM_ON_WIN32)
Ben Langmuir198c1682014-03-07 07:27:49 +00002126 // In our regression testing, the Windows file system seems to
2127 // have inconsistent modification times that sometimes
2128 // erroneously trigger this error-handling path.
2129 || StoredTime != File->getModificationTime()
Guy Benyei11169dd2012-12-18 14:30:41 +00002130#endif
Ben Langmuir198c1682014-03-07 07:27:49 +00002131 )) {
2132 if (Complain) {
2133 // Build a list of the PCH imports that got us here (in reverse).
2134 SmallVector<ModuleFile *, 4> ImportStack(1, &F);
2135 while (ImportStack.back()->ImportedBy.size() > 0)
2136 ImportStack.push_back(ImportStack.back()->ImportedBy[0]);
Ben Langmuire82630d2014-01-17 00:19:09 +00002137
Ben Langmuir198c1682014-03-07 07:27:49 +00002138 // The top-level PCH is stale.
2139 StringRef TopLevelPCHName(ImportStack.back()->FileName);
2140 Error(diag::err_fe_pch_file_modified, Filename, TopLevelPCHName);
Ben Langmuire82630d2014-01-17 00:19:09 +00002141
Ben Langmuir198c1682014-03-07 07:27:49 +00002142 // Print the import stack.
2143 if (ImportStack.size() > 1 && !Diags.isDiagnosticInFlight()) {
2144 Diag(diag::note_pch_required_by)
2145 << Filename << ImportStack[0]->FileName;
2146 for (unsigned I = 1; I < ImportStack.size(); ++I)
Ben Langmuire82630d2014-01-17 00:19:09 +00002147 Diag(diag::note_pch_required_by)
Ben Langmuir198c1682014-03-07 07:27:49 +00002148 << ImportStack[I-1]->FileName << ImportStack[I]->FileName;
Douglas Gregor7029ce12013-03-19 00:28:20 +00002149 }
2150
Ben Langmuir198c1682014-03-07 07:27:49 +00002151 if (!Diags.isDiagnosticInFlight())
2152 Diag(diag::note_pch_rebuild_required) << TopLevelPCHName;
Guy Benyei11169dd2012-12-18 14:30:41 +00002153 }
2154
Ben Langmuir198c1682014-03-07 07:27:49 +00002155 IsOutOfDate = true;
Guy Benyei11169dd2012-12-18 14:30:41 +00002156 }
2157
Ben Langmuir198c1682014-03-07 07:27:49 +00002158 InputFile IF = InputFile(File, Overridden, IsOutOfDate);
2159
2160 // Note that we've loaded this input file.
2161 F.InputFilesLoaded[ID-1] = IF;
2162 return IF;
Guy Benyei11169dd2012-12-18 14:30:41 +00002163}
2164
2165const FileEntry *ASTReader::getFileEntry(StringRef filenameStrRef) {
2166 ModuleFile &M = ModuleMgr.getPrimaryModule();
2167 std::string Filename = filenameStrRef;
2168 MaybeAddSystemRootToFilename(M, Filename);
2169 const FileEntry *File = FileMgr.getFile(Filename);
2170 if (File == 0 && !M.OriginalDir.empty() && !CurrentDir.empty() &&
2171 M.OriginalDir != CurrentDir) {
2172 std::string resolved = resolveFileRelativeToOriginalDir(Filename,
2173 M.OriginalDir,
2174 CurrentDir);
2175 if (!resolved.empty())
2176 File = FileMgr.getFile(resolved);
2177 }
2178
2179 return File;
2180}
2181
2182/// \brief If we are loading a relocatable PCH file, and the filename is
2183/// not an absolute path, add the system root to the beginning of the file
2184/// name.
2185void ASTReader::MaybeAddSystemRootToFilename(ModuleFile &M,
2186 std::string &Filename) {
2187 // If this is not a relocatable PCH file, there's nothing to do.
2188 if (!M.RelocatablePCH)
2189 return;
2190
2191 if (Filename.empty() || llvm::sys::path::is_absolute(Filename))
2192 return;
2193
2194 if (isysroot.empty()) {
2195 // If no system root was given, default to '/'
2196 Filename.insert(Filename.begin(), '/');
2197 return;
2198 }
2199
2200 unsigned Length = isysroot.size();
2201 if (isysroot[Length - 1] != '/')
2202 Filename.insert(Filename.begin(), '/');
2203
2204 Filename.insert(Filename.begin(), isysroot.begin(), isysroot.end());
2205}
2206
2207ASTReader::ASTReadResult
2208ASTReader::ReadControlBlock(ModuleFile &F,
Dmitri Gribenkof8579502013-01-12 19:30:44 +00002209 SmallVectorImpl<ImportedModule> &Loaded,
Ben Langmuirbeee15e2014-04-14 18:00:01 +00002210 const ModuleFile *ImportedBy,
Guy Benyei11169dd2012-12-18 14:30:41 +00002211 unsigned ClientLoadCapabilities) {
Chris Lattner7fb3bef2013-01-20 00:56:42 +00002212 BitstreamCursor &Stream = F.Stream;
Guy Benyei11169dd2012-12-18 14:30:41 +00002213
2214 if (Stream.EnterSubBlock(CONTROL_BLOCK_ID)) {
2215 Error("malformed block record in AST file");
2216 return Failure;
2217 }
2218
2219 // Read all of the records and blocks in the control block.
2220 RecordData Record;
Chris Lattnere7b154b2013-01-19 21:39:22 +00002221 while (1) {
2222 llvm::BitstreamEntry Entry = Stream.advance();
2223
2224 switch (Entry.Kind) {
2225 case llvm::BitstreamEntry::Error:
2226 Error("malformed block record in AST file");
2227 return Failure;
Dmitri Gribenkof430da42014-02-12 10:33:14 +00002228 case llvm::BitstreamEntry::EndBlock: {
2229 // Validate input files.
2230 const HeaderSearchOptions &HSOpts =
2231 PP.getHeaderSearchInfo().getHeaderSearchOpts();
Ben Langmuircb69b572014-03-07 06:40:32 +00002232
2233 // All user input files reside at the index range [0, Record[1]), and
2234 // system input files reside at [Record[1], Record[0]).
2235 // Record is the one from INPUT_FILE_OFFSETS.
2236 unsigned NumInputs = Record[0];
2237 unsigned NumUserInputs = Record[1];
2238
Dmitri Gribenkof430da42014-02-12 10:33:14 +00002239 if (!DisableValidation &&
Ben Langmuir1e258222014-04-08 15:36:28 +00002240 (ValidateSystemInputs || !HSOpts.ModulesValidateOncePerBuildSession ||
Dmitri Gribenkof430da42014-02-12 10:33:14 +00002241 F.InputFilesValidationTimestamp <= HSOpts.BuildSessionTimestamp)) {
Guy Benyei11169dd2012-12-18 14:30:41 +00002242 bool Complain = (ClientLoadCapabilities & ARR_OutOfDate) == 0;
Ben Langmuircb69b572014-03-07 06:40:32 +00002243
Dmitri Gribenkof430da42014-02-12 10:33:14 +00002244 // If we are reading a module, we will create a verification timestamp,
2245 // so we verify all input files. Otherwise, verify only user input
2246 // files.
Ben Langmuircb69b572014-03-07 06:40:32 +00002247
2248 unsigned N = NumUserInputs;
2249 if (ValidateSystemInputs ||
Ben Langmuircb69b572014-03-07 06:40:32 +00002250 (HSOpts.ModulesValidateOncePerBuildSession && F.Kind == MK_Module))
2251 N = NumInputs;
2252
Ben Langmuir3d4417c2014-02-07 17:31:11 +00002253 for (unsigned I = 0; I < N; ++I) {
Argyrios Kyrtzidis61c3d872013-03-01 03:26:04 +00002254 InputFile IF = getInputFile(F, I+1, Complain);
2255 if (!IF.getFile() || IF.isOutOfDate())
Guy Benyei11169dd2012-12-18 14:30:41 +00002256 return OutOfDate;
Argyrios Kyrtzidis61c3d872013-03-01 03:26:04 +00002257 }
Guy Benyei11169dd2012-12-18 14:30:41 +00002258 }
Ben Langmuircb69b572014-03-07 06:40:32 +00002259
Argyrios Kyrtzidis6d0753d2014-03-14 03:07:38 +00002260 if (Listener)
2261 Listener->visitModuleFile(F.FileName);
2262
Ben Langmuircb69b572014-03-07 06:40:32 +00002263 if (Listener && Listener->needsInputFileVisitation()) {
2264 unsigned N = Listener->needsSystemInputFileVisitation() ? NumInputs
2265 : NumUserInputs;
Argyrios Kyrtzidis68ccbe02014-03-14 02:26:31 +00002266 for (unsigned I = 0; I < N; ++I) {
2267 bool IsSystem = I >= NumUserInputs;
2268 InputFileInfo FI = readInputFileInfo(F, I+1);
2269 Listener->visitInputFile(FI.Filename, IsSystem, FI.Overridden);
2270 }
Ben Langmuircb69b572014-03-07 06:40:32 +00002271 }
2272
Guy Benyei11169dd2012-12-18 14:30:41 +00002273 return Success;
Dmitri Gribenkof430da42014-02-12 10:33:14 +00002274 }
2275
Chris Lattnere7b154b2013-01-19 21:39:22 +00002276 case llvm::BitstreamEntry::SubBlock:
2277 switch (Entry.ID) {
Guy Benyei11169dd2012-12-18 14:30:41 +00002278 case INPUT_FILES_BLOCK_ID:
2279 F.InputFilesCursor = Stream;
2280 if (Stream.SkipBlock() || // Skip with the main cursor
2281 // Read the abbreviations
2282 ReadBlockAbbrevs(F.InputFilesCursor, INPUT_FILES_BLOCK_ID)) {
2283 Error("malformed block record in AST file");
2284 return Failure;
2285 }
2286 continue;
Chris Lattnere7b154b2013-01-19 21:39:22 +00002287
Guy Benyei11169dd2012-12-18 14:30:41 +00002288 default:
Chris Lattnere7b154b2013-01-19 21:39:22 +00002289 if (Stream.SkipBlock()) {
2290 Error("malformed block record in AST file");
2291 return Failure;
2292 }
2293 continue;
Guy Benyei11169dd2012-12-18 14:30:41 +00002294 }
Chris Lattnere7b154b2013-01-19 21:39:22 +00002295
2296 case llvm::BitstreamEntry::Record:
2297 // The interesting case.
2298 break;
Guy Benyei11169dd2012-12-18 14:30:41 +00002299 }
2300
2301 // Read and process a record.
2302 Record.clear();
Chris Lattner0e6c9402013-01-20 02:38:54 +00002303 StringRef Blob;
2304 switch ((ControlRecordTypes)Stream.readRecord(Entry.ID, Record, &Blob)) {
Guy Benyei11169dd2012-12-18 14:30:41 +00002305 case METADATA: {
2306 if (Record[0] != VERSION_MAJOR && !DisableValidation) {
2307 if ((ClientLoadCapabilities & ARR_VersionMismatch) == 0)
Dmitri Gribenko2228cd32014-02-11 15:40:09 +00002308 Diag(Record[0] < VERSION_MAJOR? diag::err_pch_version_too_old
2309 : diag::err_pch_version_too_new);
Guy Benyei11169dd2012-12-18 14:30:41 +00002310 return VersionMismatch;
2311 }
2312
2313 bool hasErrors = Record[5];
2314 if (hasErrors && !DisableValidation && !AllowASTWithCompilerErrors) {
2315 Diag(diag::err_pch_with_compiler_errors);
2316 return HadErrors;
2317 }
2318
2319 F.RelocatablePCH = Record[4];
2320
2321 const std::string &CurBranch = getClangFullRepositoryVersion();
Chris Lattner0e6c9402013-01-20 02:38:54 +00002322 StringRef ASTBranch = Blob;
Guy Benyei11169dd2012-12-18 14:30:41 +00002323 if (StringRef(CurBranch) != ASTBranch && !DisableValidation) {
2324 if ((ClientLoadCapabilities & ARR_VersionMismatch) == 0)
Dmitri Gribenko2228cd32014-02-11 15:40:09 +00002325 Diag(diag::err_pch_different_branch) << ASTBranch << CurBranch;
Guy Benyei11169dd2012-12-18 14:30:41 +00002326 return VersionMismatch;
2327 }
2328 break;
2329 }
2330
2331 case IMPORTS: {
2332 // Load each of the imported PCH files.
2333 unsigned Idx = 0, N = Record.size();
2334 while (Idx < N) {
2335 // Read information about the AST file.
2336 ModuleKind ImportedKind = (ModuleKind)Record[Idx++];
2337 // The import location will be the local one for now; we will adjust
2338 // all import locations of module imports after the global source
2339 // location info are setup.
2340 SourceLocation ImportLoc =
2341 SourceLocation::getFromRawEncoding(Record[Idx++]);
Douglas Gregor7029ce12013-03-19 00:28:20 +00002342 off_t StoredSize = (off_t)Record[Idx++];
2343 time_t StoredModTime = (time_t)Record[Idx++];
Guy Benyei11169dd2012-12-18 14:30:41 +00002344 unsigned Length = Record[Idx++];
2345 SmallString<128> ImportedFile(Record.begin() + Idx,
2346 Record.begin() + Idx + Length);
2347 Idx += Length;
2348
2349 // Load the AST file.
2350 switch(ReadASTCore(ImportedFile, ImportedKind, ImportLoc, &F, Loaded,
Douglas Gregor7029ce12013-03-19 00:28:20 +00002351 StoredSize, StoredModTime,
Guy Benyei11169dd2012-12-18 14:30:41 +00002352 ClientLoadCapabilities)) {
2353 case Failure: return Failure;
2354 // If we have to ignore the dependency, we'll have to ignore this too.
Douglas Gregor2f1806e2013-03-19 00:38:50 +00002355 case Missing:
Guy Benyei11169dd2012-12-18 14:30:41 +00002356 case OutOfDate: return OutOfDate;
2357 case VersionMismatch: return VersionMismatch;
2358 case ConfigurationMismatch: return ConfigurationMismatch;
2359 case HadErrors: return HadErrors;
2360 case Success: break;
2361 }
2362 }
2363 break;
2364 }
2365
2366 case LANGUAGE_OPTIONS: {
2367 bool Complain = (ClientLoadCapabilities & ARR_ConfigurationMismatch) == 0;
2368 if (Listener && &F == *ModuleMgr.begin() &&
2369 ParseLanguageOptions(Record, Complain, *Listener) &&
Ben Langmuir2cb4a782014-02-05 22:21:15 +00002370 !DisableValidation && !AllowConfigurationMismatch)
Guy Benyei11169dd2012-12-18 14:30:41 +00002371 return ConfigurationMismatch;
2372 break;
2373 }
2374
2375 case TARGET_OPTIONS: {
2376 bool Complain = (ClientLoadCapabilities & ARR_ConfigurationMismatch)==0;
2377 if (Listener && &F == *ModuleMgr.begin() &&
2378 ParseTargetOptions(Record, Complain, *Listener) &&
Ben Langmuir2cb4a782014-02-05 22:21:15 +00002379 !DisableValidation && !AllowConfigurationMismatch)
Guy Benyei11169dd2012-12-18 14:30:41 +00002380 return ConfigurationMismatch;
2381 break;
2382 }
2383
2384 case DIAGNOSTIC_OPTIONS: {
Ben Langmuirb92de022014-04-29 16:25:26 +00002385 bool Complain = (ClientLoadCapabilities & ARR_OutOfDate)==0;
Guy Benyei11169dd2012-12-18 14:30:41 +00002386 if (Listener && &F == *ModuleMgr.begin() &&
2387 ParseDiagnosticOptions(Record, Complain, *Listener) &&
Ben Langmuirb92de022014-04-29 16:25:26 +00002388 !DisableValidation)
2389 return OutOfDate;
Guy Benyei11169dd2012-12-18 14:30:41 +00002390 break;
2391 }
2392
2393 case FILE_SYSTEM_OPTIONS: {
2394 bool Complain = (ClientLoadCapabilities & ARR_ConfigurationMismatch)==0;
2395 if (Listener && &F == *ModuleMgr.begin() &&
2396 ParseFileSystemOptions(Record, Complain, *Listener) &&
Ben Langmuir2cb4a782014-02-05 22:21:15 +00002397 !DisableValidation && !AllowConfigurationMismatch)
Guy Benyei11169dd2012-12-18 14:30:41 +00002398 return ConfigurationMismatch;
2399 break;
2400 }
2401
2402 case HEADER_SEARCH_OPTIONS: {
2403 bool Complain = (ClientLoadCapabilities & ARR_ConfigurationMismatch)==0;
2404 if (Listener && &F == *ModuleMgr.begin() &&
2405 ParseHeaderSearchOptions(Record, Complain, *Listener) &&
Ben Langmuir2cb4a782014-02-05 22:21:15 +00002406 !DisableValidation && !AllowConfigurationMismatch)
Guy Benyei11169dd2012-12-18 14:30:41 +00002407 return ConfigurationMismatch;
2408 break;
2409 }
2410
2411 case PREPROCESSOR_OPTIONS: {
2412 bool Complain = (ClientLoadCapabilities & ARR_ConfigurationMismatch)==0;
2413 if (Listener && &F == *ModuleMgr.begin() &&
2414 ParsePreprocessorOptions(Record, Complain, *Listener,
2415 SuggestedPredefines) &&
Ben Langmuir2cb4a782014-02-05 22:21:15 +00002416 !DisableValidation && !AllowConfigurationMismatch)
Guy Benyei11169dd2012-12-18 14:30:41 +00002417 return ConfigurationMismatch;
2418 break;
2419 }
2420
2421 case ORIGINAL_FILE:
2422 F.OriginalSourceFileID = FileID::get(Record[0]);
Chris Lattner0e6c9402013-01-20 02:38:54 +00002423 F.ActualOriginalSourceFileName = Blob;
Guy Benyei11169dd2012-12-18 14:30:41 +00002424 F.OriginalSourceFileName = F.ActualOriginalSourceFileName;
2425 MaybeAddSystemRootToFilename(F, F.OriginalSourceFileName);
2426 break;
2427
2428 case ORIGINAL_FILE_ID:
2429 F.OriginalSourceFileID = FileID::get(Record[0]);
2430 break;
2431
2432 case ORIGINAL_PCH_DIR:
Chris Lattner0e6c9402013-01-20 02:38:54 +00002433 F.OriginalDir = Blob;
Guy Benyei11169dd2012-12-18 14:30:41 +00002434 break;
2435
Ben Langmuirbeee15e2014-04-14 18:00:01 +00002436 case MODULE_NAME:
2437 F.ModuleName = Blob;
Ben Langmuir4f5212a2014-04-14 22:12:44 +00002438 if (Listener)
2439 Listener->ReadModuleName(F.ModuleName);
Ben Langmuirbeee15e2014-04-14 18:00:01 +00002440 break;
2441
2442 case MODULE_MAP_FILE:
2443 F.ModuleMapPath = Blob;
2444
2445 // Try to resolve ModuleName in the current header search context and
2446 // verify that it is found in the same module map file as we saved. If the
2447 // top-level AST file is a main file, skip this check because there is no
2448 // usable header search context.
2449 assert(!F.ModuleName.empty() &&
2450 "MODULE_NAME should come before MOUDLE_MAP_FILE");
2451 if (F.Kind == MK_Module &&
2452 (*ModuleMgr.begin())->Kind != MK_MainFile) {
2453 Module *M = PP.getHeaderSearchInfo().lookupModule(F.ModuleName);
2454 if (!M) {
2455 assert(ImportedBy && "top-level import should be verified");
2456 if ((ClientLoadCapabilities & ARR_Missing) == 0)
2457 Diag(diag::err_imported_module_not_found)
2458 << F.ModuleName << ImportedBy->FileName;
2459 return Missing;
2460 }
2461
2462 const FileEntry *StoredModMap = FileMgr.getFile(F.ModuleMapPath);
2463 if (StoredModMap == nullptr || StoredModMap != M->ModuleMap) {
2464 assert(M->ModuleMap && "found module is missing module map file");
2465 assert(M->Name == F.ModuleName && "found module with different name");
2466 assert(ImportedBy && "top-level import should be verified");
2467 if ((ClientLoadCapabilities & ARR_OutOfDate) == 0)
2468 Diag(diag::err_imported_module_modmap_changed)
2469 << F.ModuleName << ImportedBy->FileName
2470 << M->ModuleMap->getName() << F.ModuleMapPath;
2471 return OutOfDate;
2472 }
2473 }
Ben Langmuir4f5212a2014-04-14 22:12:44 +00002474
2475 if (Listener)
2476 Listener->ReadModuleMapFile(F.ModuleMapPath);
Ben Langmuirbeee15e2014-04-14 18:00:01 +00002477 break;
2478
Guy Benyei11169dd2012-12-18 14:30:41 +00002479 case INPUT_FILE_OFFSETS:
Chris Lattner0e6c9402013-01-20 02:38:54 +00002480 F.InputFileOffsets = (const uint32_t *)Blob.data();
Guy Benyei11169dd2012-12-18 14:30:41 +00002481 F.InputFilesLoaded.resize(Record[0]);
2482 break;
2483 }
2484 }
Guy Benyei11169dd2012-12-18 14:30:41 +00002485}
2486
Ben Langmuir2c9af442014-04-10 17:57:43 +00002487ASTReader::ASTReadResult
2488ASTReader::ReadASTBlock(ModuleFile &F, unsigned ClientLoadCapabilities) {
Chris Lattner7fb3bef2013-01-20 00:56:42 +00002489 BitstreamCursor &Stream = F.Stream;
Guy Benyei11169dd2012-12-18 14:30:41 +00002490
2491 if (Stream.EnterSubBlock(AST_BLOCK_ID)) {
2492 Error("malformed block record in AST file");
Ben Langmuir2c9af442014-04-10 17:57:43 +00002493 return Failure;
Guy Benyei11169dd2012-12-18 14:30:41 +00002494 }
2495
2496 // Read all of the records and blocks for the AST file.
2497 RecordData Record;
Chris Lattnere7b154b2013-01-19 21:39:22 +00002498 while (1) {
2499 llvm::BitstreamEntry Entry = Stream.advance();
2500
2501 switch (Entry.Kind) {
2502 case llvm::BitstreamEntry::Error:
2503 Error("error at end of module block in AST file");
Ben Langmuir2c9af442014-04-10 17:57:43 +00002504 return Failure;
Chris Lattnere7b154b2013-01-19 21:39:22 +00002505 case llvm::BitstreamEntry::EndBlock: {
Richard Smithc0fbba72013-04-03 22:49:41 +00002506 // Outside of C++, we do not store a lookup map for the translation unit.
2507 // Instead, mark it as needing a lookup map to be built if this module
2508 // contains any declarations lexically within it (which it always does!).
2509 // This usually has no cost, since we very rarely need the lookup map for
2510 // the translation unit outside C++.
Guy Benyei11169dd2012-12-18 14:30:41 +00002511 DeclContext *DC = Context.getTranslationUnitDecl();
Richard Smithc0fbba72013-04-03 22:49:41 +00002512 if (DC->hasExternalLexicalStorage() &&
2513 !getContext().getLangOpts().CPlusPlus)
Guy Benyei11169dd2012-12-18 14:30:41 +00002514 DC->setMustBuildLookupTable();
Chris Lattnere7b154b2013-01-19 21:39:22 +00002515
Ben Langmuir2c9af442014-04-10 17:57:43 +00002516 return Success;
Guy Benyei11169dd2012-12-18 14:30:41 +00002517 }
Chris Lattnere7b154b2013-01-19 21:39:22 +00002518 case llvm::BitstreamEntry::SubBlock:
2519 switch (Entry.ID) {
Guy Benyei11169dd2012-12-18 14:30:41 +00002520 case DECLTYPES_BLOCK_ID:
2521 // We lazily load the decls block, but we want to set up the
2522 // DeclsCursor cursor to point into it. Clone our current bitcode
2523 // cursor to it, enter the block and read the abbrevs in that block.
2524 // With the main cursor, we just skip over it.
2525 F.DeclsCursor = Stream;
2526 if (Stream.SkipBlock() || // Skip with the main cursor.
2527 // Read the abbrevs.
2528 ReadBlockAbbrevs(F.DeclsCursor, DECLTYPES_BLOCK_ID)) {
2529 Error("malformed block record in AST file");
Ben Langmuir2c9af442014-04-10 17:57:43 +00002530 return Failure;
Guy Benyei11169dd2012-12-18 14:30:41 +00002531 }
2532 break;
Richard Smithb9eab6d2014-03-20 19:44:17 +00002533
Guy Benyei11169dd2012-12-18 14:30:41 +00002534 case PREPROCESSOR_BLOCK_ID:
2535 F.MacroCursor = Stream;
2536 if (!PP.getExternalSource())
2537 PP.setExternalSource(this);
Chris Lattnere7b154b2013-01-19 21:39:22 +00002538
Guy Benyei11169dd2012-12-18 14:30:41 +00002539 if (Stream.SkipBlock() ||
2540 ReadBlockAbbrevs(F.MacroCursor, PREPROCESSOR_BLOCK_ID)) {
2541 Error("malformed block record in AST file");
Ben Langmuir2c9af442014-04-10 17:57:43 +00002542 return Failure;
Guy Benyei11169dd2012-12-18 14:30:41 +00002543 }
2544 F.MacroStartOffset = F.MacroCursor.GetCurrentBitNo();
2545 break;
Chris Lattnere7b154b2013-01-19 21:39:22 +00002546
Guy Benyei11169dd2012-12-18 14:30:41 +00002547 case PREPROCESSOR_DETAIL_BLOCK_ID:
2548 F.PreprocessorDetailCursor = Stream;
2549 if (Stream.SkipBlock() ||
Chris Lattnere7b154b2013-01-19 21:39:22 +00002550 ReadBlockAbbrevs(F.PreprocessorDetailCursor,
Guy Benyei11169dd2012-12-18 14:30:41 +00002551 PREPROCESSOR_DETAIL_BLOCK_ID)) {
Chris Lattnere7b154b2013-01-19 21:39:22 +00002552 Error("malformed preprocessor detail record in AST file");
Ben Langmuir2c9af442014-04-10 17:57:43 +00002553 return Failure;
Chris Lattnere7b154b2013-01-19 21:39:22 +00002554 }
Guy Benyei11169dd2012-12-18 14:30:41 +00002555 F.PreprocessorDetailStartOffset
Chris Lattnere7b154b2013-01-19 21:39:22 +00002556 = F.PreprocessorDetailCursor.GetCurrentBitNo();
2557
Guy Benyei11169dd2012-12-18 14:30:41 +00002558 if (!PP.getPreprocessingRecord())
2559 PP.createPreprocessingRecord();
2560 if (!PP.getPreprocessingRecord()->getExternalSource())
2561 PP.getPreprocessingRecord()->SetExternalSource(*this);
2562 break;
2563
2564 case SOURCE_MANAGER_BLOCK_ID:
2565 if (ReadSourceManagerBlock(F))
Ben Langmuir2c9af442014-04-10 17:57:43 +00002566 return Failure;
Guy Benyei11169dd2012-12-18 14:30:41 +00002567 break;
Chris Lattnere7b154b2013-01-19 21:39:22 +00002568
Guy Benyei11169dd2012-12-18 14:30:41 +00002569 case SUBMODULE_BLOCK_ID:
Ben Langmuir2c9af442014-04-10 17:57:43 +00002570 if (ASTReadResult Result = ReadSubmoduleBlock(F, ClientLoadCapabilities))
2571 return Result;
Guy Benyei11169dd2012-12-18 14:30:41 +00002572 break;
Chris Lattnere7b154b2013-01-19 21:39:22 +00002573
Guy Benyei11169dd2012-12-18 14:30:41 +00002574 case COMMENTS_BLOCK_ID: {
Chris Lattner7fb3bef2013-01-20 00:56:42 +00002575 BitstreamCursor C = Stream;
Guy Benyei11169dd2012-12-18 14:30:41 +00002576 if (Stream.SkipBlock() ||
2577 ReadBlockAbbrevs(C, COMMENTS_BLOCK_ID)) {
2578 Error("malformed comments block in AST file");
Ben Langmuir2c9af442014-04-10 17:57:43 +00002579 return Failure;
Guy Benyei11169dd2012-12-18 14:30:41 +00002580 }
2581 CommentsCursors.push_back(std::make_pair(C, &F));
2582 break;
2583 }
Chris Lattnere7b154b2013-01-19 21:39:22 +00002584
Guy Benyei11169dd2012-12-18 14:30:41 +00002585 default:
Chris Lattnere7b154b2013-01-19 21:39:22 +00002586 if (Stream.SkipBlock()) {
2587 Error("malformed block record in AST file");
Ben Langmuir2c9af442014-04-10 17:57:43 +00002588 return Failure;
Chris Lattnere7b154b2013-01-19 21:39:22 +00002589 }
2590 break;
Guy Benyei11169dd2012-12-18 14:30:41 +00002591 }
2592 continue;
Chris Lattnere7b154b2013-01-19 21:39:22 +00002593
2594 case llvm::BitstreamEntry::Record:
2595 // The interesting case.
2596 break;
Guy Benyei11169dd2012-12-18 14:30:41 +00002597 }
2598
2599 // Read and process a record.
2600 Record.clear();
Chris Lattner0e6c9402013-01-20 02:38:54 +00002601 StringRef Blob;
2602 switch ((ASTRecordTypes)Stream.readRecord(Entry.ID, Record, &Blob)) {
Guy Benyei11169dd2012-12-18 14:30:41 +00002603 default: // Default behavior: ignore.
2604 break;
2605
2606 case TYPE_OFFSET: {
2607 if (F.LocalNumTypes != 0) {
2608 Error("duplicate TYPE_OFFSET record in AST file");
Ben Langmuir2c9af442014-04-10 17:57:43 +00002609 return Failure;
Guy Benyei11169dd2012-12-18 14:30:41 +00002610 }
Chris Lattner0e6c9402013-01-20 02:38:54 +00002611 F.TypeOffsets = (const uint32_t *)Blob.data();
Guy Benyei11169dd2012-12-18 14:30:41 +00002612 F.LocalNumTypes = Record[0];
2613 unsigned LocalBaseTypeIndex = Record[1];
2614 F.BaseTypeIndex = getTotalNumTypes();
2615
2616 if (F.LocalNumTypes > 0) {
2617 // Introduce the global -> local mapping for types within this module.
2618 GlobalTypeMap.insert(std::make_pair(getTotalNumTypes(), &F));
2619
2620 // Introduce the local -> global mapping for types within this module.
2621 F.TypeRemap.insertOrReplace(
2622 std::make_pair(LocalBaseTypeIndex,
2623 F.BaseTypeIndex - LocalBaseTypeIndex));
2624
2625 TypesLoaded.resize(TypesLoaded.size() + F.LocalNumTypes);
2626 }
2627 break;
2628 }
2629
2630 case DECL_OFFSET: {
2631 if (F.LocalNumDecls != 0) {
2632 Error("duplicate DECL_OFFSET record in AST file");
Ben Langmuir2c9af442014-04-10 17:57:43 +00002633 return Failure;
Guy Benyei11169dd2012-12-18 14:30:41 +00002634 }
Chris Lattner0e6c9402013-01-20 02:38:54 +00002635 F.DeclOffsets = (const DeclOffset *)Blob.data();
Guy Benyei11169dd2012-12-18 14:30:41 +00002636 F.LocalNumDecls = Record[0];
2637 unsigned LocalBaseDeclID = Record[1];
2638 F.BaseDeclID = getTotalNumDecls();
2639
2640 if (F.LocalNumDecls > 0) {
2641 // Introduce the global -> local mapping for declarations within this
2642 // module.
2643 GlobalDeclMap.insert(
2644 std::make_pair(getTotalNumDecls() + NUM_PREDEF_DECL_IDS, &F));
2645
2646 // Introduce the local -> global mapping for declarations within this
2647 // module.
2648 F.DeclRemap.insertOrReplace(
2649 std::make_pair(LocalBaseDeclID, F.BaseDeclID - LocalBaseDeclID));
2650
2651 // Introduce the global -> local mapping for declarations within this
2652 // module.
2653 F.GlobalToLocalDeclIDs[&F] = LocalBaseDeclID;
2654
2655 DeclsLoaded.resize(DeclsLoaded.size() + F.LocalNumDecls);
2656 }
2657 break;
2658 }
2659
2660 case TU_UPDATE_LEXICAL: {
2661 DeclContext *TU = Context.getTranslationUnitDecl();
2662 DeclContextInfo &Info = F.DeclContextInfos[TU];
Chris Lattner0e6c9402013-01-20 02:38:54 +00002663 Info.LexicalDecls = reinterpret_cast<const KindDeclIDPair *>(Blob.data());
Guy Benyei11169dd2012-12-18 14:30:41 +00002664 Info.NumLexicalDecls
Chris Lattner0e6c9402013-01-20 02:38:54 +00002665 = static_cast<unsigned int>(Blob.size() / sizeof(KindDeclIDPair));
Guy Benyei11169dd2012-12-18 14:30:41 +00002666 TU->setHasExternalLexicalStorage(true);
2667 break;
2668 }
2669
2670 case UPDATE_VISIBLE: {
2671 unsigned Idx = 0;
2672 serialization::DeclID ID = ReadDeclID(F, Record, Idx);
2673 ASTDeclContextNameLookupTable *Table =
Justin Bognerda4e6502014-04-14 16:34:29 +00002674 ASTDeclContextNameLookupTable::Create(
2675 (const unsigned char *)Blob.data() + Record[Idx++],
2676 (const unsigned char *)Blob.data() + sizeof(uint32_t),
2677 (const unsigned char *)Blob.data(),
2678 ASTDeclContextNameLookupTrait(*this, F));
Richard Smithcd45dbc2014-04-19 03:48:30 +00002679 if (Decl *D = GetExistingDecl(ID)) {
Richard Smithd9174792014-03-11 03:10:46 +00002680 auto *DC = cast<DeclContext>(D);
2681 DC->getPrimaryContext()->setHasExternalVisibleStorage(true);
Richard Smith52e3fba2014-03-11 07:17:35 +00002682 auto *&LookupTable = F.DeclContextInfos[DC].NameLookupTableData;
Richard Smithcd45dbc2014-04-19 03:48:30 +00002683 // FIXME: There should never be an existing lookup table.
Richard Smith52e3fba2014-03-11 07:17:35 +00002684 delete LookupTable;
2685 LookupTable = Table;
Guy Benyei11169dd2012-12-18 14:30:41 +00002686 } else
2687 PendingVisibleUpdates[ID].push_back(std::make_pair(Table, &F));
2688 break;
2689 }
2690
2691 case IDENTIFIER_TABLE:
Chris Lattner0e6c9402013-01-20 02:38:54 +00002692 F.IdentifierTableData = Blob.data();
Guy Benyei11169dd2012-12-18 14:30:41 +00002693 if (Record[0]) {
Justin Bognerda4e6502014-04-14 16:34:29 +00002694 F.IdentifierLookupTable = ASTIdentifierLookupTable::Create(
2695 (const unsigned char *)F.IdentifierTableData + Record[0],
2696 (const unsigned char *)F.IdentifierTableData + sizeof(uint32_t),
2697 (const unsigned char *)F.IdentifierTableData,
2698 ASTIdentifierLookupTrait(*this, F));
Guy Benyei11169dd2012-12-18 14:30:41 +00002699
2700 PP.getIdentifierTable().setExternalIdentifierLookup(this);
2701 }
2702 break;
2703
2704 case IDENTIFIER_OFFSET: {
2705 if (F.LocalNumIdentifiers != 0) {
2706 Error("duplicate IDENTIFIER_OFFSET record in AST file");
Ben Langmuir2c9af442014-04-10 17:57:43 +00002707 return Failure;
Guy Benyei11169dd2012-12-18 14:30:41 +00002708 }
Chris Lattner0e6c9402013-01-20 02:38:54 +00002709 F.IdentifierOffsets = (const uint32_t *)Blob.data();
Guy Benyei11169dd2012-12-18 14:30:41 +00002710 F.LocalNumIdentifiers = Record[0];
2711 unsigned LocalBaseIdentifierID = Record[1];
2712 F.BaseIdentifierID = getTotalNumIdentifiers();
2713
2714 if (F.LocalNumIdentifiers > 0) {
2715 // Introduce the global -> local mapping for identifiers within this
2716 // module.
2717 GlobalIdentifierMap.insert(std::make_pair(getTotalNumIdentifiers() + 1,
2718 &F));
2719
2720 // Introduce the local -> global mapping for identifiers within this
2721 // module.
2722 F.IdentifierRemap.insertOrReplace(
2723 std::make_pair(LocalBaseIdentifierID,
2724 F.BaseIdentifierID - LocalBaseIdentifierID));
2725
2726 IdentifiersLoaded.resize(IdentifiersLoaded.size()
2727 + F.LocalNumIdentifiers);
2728 }
2729 break;
2730 }
2731
Ben Langmuir332aafe2014-01-31 01:06:56 +00002732 case EAGERLY_DESERIALIZED_DECLS:
Guy Benyei11169dd2012-12-18 14:30:41 +00002733 for (unsigned I = 0, N = Record.size(); I != N; ++I)
Ben Langmuir332aafe2014-01-31 01:06:56 +00002734 EagerlyDeserializedDecls.push_back(getGlobalDeclID(F, Record[I]));
Guy Benyei11169dd2012-12-18 14:30:41 +00002735 break;
2736
2737 case SPECIAL_TYPES:
Douglas Gregor44180f82013-02-01 23:45:03 +00002738 if (SpecialTypes.empty()) {
2739 for (unsigned I = 0, N = Record.size(); I != N; ++I)
2740 SpecialTypes.push_back(getGlobalTypeID(F, Record[I]));
2741 break;
2742 }
2743
2744 if (SpecialTypes.size() != Record.size()) {
2745 Error("invalid special-types record");
Ben Langmuir2c9af442014-04-10 17:57:43 +00002746 return Failure;
Douglas Gregor44180f82013-02-01 23:45:03 +00002747 }
2748
2749 for (unsigned I = 0, N = Record.size(); I != N; ++I) {
2750 serialization::TypeID ID = getGlobalTypeID(F, Record[I]);
2751 if (!SpecialTypes[I])
2752 SpecialTypes[I] = ID;
2753 // FIXME: If ID && SpecialTypes[I] != ID, do we need a separate
2754 // merge step?
2755 }
Guy Benyei11169dd2012-12-18 14:30:41 +00002756 break;
2757
2758 case STATISTICS:
2759 TotalNumStatements += Record[0];
2760 TotalNumMacros += Record[1];
2761 TotalLexicalDeclContexts += Record[2];
2762 TotalVisibleDeclContexts += Record[3];
2763 break;
2764
2765 case UNUSED_FILESCOPED_DECLS:
2766 for (unsigned I = 0, N = Record.size(); I != N; ++I)
2767 UnusedFileScopedDecls.push_back(getGlobalDeclID(F, Record[I]));
2768 break;
2769
2770 case DELEGATING_CTORS:
2771 for (unsigned I = 0, N = Record.size(); I != N; ++I)
2772 DelegatingCtorDecls.push_back(getGlobalDeclID(F, Record[I]));
2773 break;
2774
2775 case WEAK_UNDECLARED_IDENTIFIERS:
2776 if (Record.size() % 4 != 0) {
2777 Error("invalid weak identifiers record");
Ben Langmuir2c9af442014-04-10 17:57:43 +00002778 return Failure;
Guy Benyei11169dd2012-12-18 14:30:41 +00002779 }
2780
2781 // FIXME: Ignore weak undeclared identifiers from non-original PCH
2782 // files. This isn't the way to do it :)
2783 WeakUndeclaredIdentifiers.clear();
2784
2785 // Translate the weak, undeclared identifiers into global IDs.
2786 for (unsigned I = 0, N = Record.size(); I < N; /* in loop */) {
2787 WeakUndeclaredIdentifiers.push_back(
2788 getGlobalIdentifierID(F, Record[I++]));
2789 WeakUndeclaredIdentifiers.push_back(
2790 getGlobalIdentifierID(F, Record[I++]));
2791 WeakUndeclaredIdentifiers.push_back(
2792 ReadSourceLocation(F, Record, I).getRawEncoding());
2793 WeakUndeclaredIdentifiers.push_back(Record[I++]);
2794 }
2795 break;
2796
Richard Smith78165b52013-01-10 23:43:47 +00002797 case LOCALLY_SCOPED_EXTERN_C_DECLS:
Guy Benyei11169dd2012-12-18 14:30:41 +00002798 for (unsigned I = 0, N = Record.size(); I != N; ++I)
Richard Smith78165b52013-01-10 23:43:47 +00002799 LocallyScopedExternCDecls.push_back(getGlobalDeclID(F, Record[I]));
Guy Benyei11169dd2012-12-18 14:30:41 +00002800 break;
2801
2802 case SELECTOR_OFFSETS: {
Chris Lattner0e6c9402013-01-20 02:38:54 +00002803 F.SelectorOffsets = (const uint32_t *)Blob.data();
Guy Benyei11169dd2012-12-18 14:30:41 +00002804 F.LocalNumSelectors = Record[0];
2805 unsigned LocalBaseSelectorID = Record[1];
2806 F.BaseSelectorID = getTotalNumSelectors();
2807
2808 if (F.LocalNumSelectors > 0) {
2809 // Introduce the global -> local mapping for selectors within this
2810 // module.
2811 GlobalSelectorMap.insert(std::make_pair(getTotalNumSelectors()+1, &F));
2812
2813 // Introduce the local -> global mapping for selectors within this
2814 // module.
2815 F.SelectorRemap.insertOrReplace(
2816 std::make_pair(LocalBaseSelectorID,
2817 F.BaseSelectorID - LocalBaseSelectorID));
2818
2819 SelectorsLoaded.resize(SelectorsLoaded.size() + F.LocalNumSelectors);
2820 }
2821 break;
2822 }
2823
2824 case METHOD_POOL:
Chris Lattner0e6c9402013-01-20 02:38:54 +00002825 F.SelectorLookupTableData = (const unsigned char *)Blob.data();
Guy Benyei11169dd2012-12-18 14:30:41 +00002826 if (Record[0])
2827 F.SelectorLookupTable
2828 = ASTSelectorLookupTable::Create(
2829 F.SelectorLookupTableData + Record[0],
2830 F.SelectorLookupTableData,
2831 ASTSelectorLookupTrait(*this, F));
2832 TotalNumMethodPoolEntries += Record[1];
2833 break;
2834
2835 case REFERENCED_SELECTOR_POOL:
2836 if (!Record.empty()) {
2837 for (unsigned Idx = 0, N = Record.size() - 1; Idx < N; /* in loop */) {
2838 ReferencedSelectorsData.push_back(getGlobalSelectorID(F,
2839 Record[Idx++]));
2840 ReferencedSelectorsData.push_back(ReadSourceLocation(F, Record, Idx).
2841 getRawEncoding());
2842 }
2843 }
2844 break;
2845
2846 case PP_COUNTER_VALUE:
2847 if (!Record.empty() && Listener)
2848 Listener->ReadCounter(F, Record[0]);
2849 break;
2850
2851 case FILE_SORTED_DECLS:
Chris Lattner0e6c9402013-01-20 02:38:54 +00002852 F.FileSortedDecls = (const DeclID *)Blob.data();
Guy Benyei11169dd2012-12-18 14:30:41 +00002853 F.NumFileSortedDecls = Record[0];
2854 break;
2855
2856 case SOURCE_LOCATION_OFFSETS: {
Chris Lattner0e6c9402013-01-20 02:38:54 +00002857 F.SLocEntryOffsets = (const uint32_t *)Blob.data();
Guy Benyei11169dd2012-12-18 14:30:41 +00002858 F.LocalNumSLocEntries = Record[0];
2859 unsigned SLocSpaceSize = Record[1];
Benjamin Kramer867ea1d2014-03-02 13:01:17 +00002860 std::tie(F.SLocEntryBaseID, F.SLocEntryBaseOffset) =
Guy Benyei11169dd2012-12-18 14:30:41 +00002861 SourceMgr.AllocateLoadedSLocEntries(F.LocalNumSLocEntries,
2862 SLocSpaceSize);
2863 // Make our entry in the range map. BaseID is negative and growing, so
2864 // we invert it. Because we invert it, though, we need the other end of
2865 // the range.
2866 unsigned RangeStart =
2867 unsigned(-F.SLocEntryBaseID) - F.LocalNumSLocEntries + 1;
2868 GlobalSLocEntryMap.insert(std::make_pair(RangeStart, &F));
2869 F.FirstLoc = SourceLocation::getFromRawEncoding(F.SLocEntryBaseOffset);
2870
2871 // SLocEntryBaseOffset is lower than MaxLoadedOffset and decreasing.
2872 assert((F.SLocEntryBaseOffset & (1U << 31U)) == 0);
2873 GlobalSLocOffsetMap.insert(
2874 std::make_pair(SourceManager::MaxLoadedOffset - F.SLocEntryBaseOffset
2875 - SLocSpaceSize,&F));
2876
2877 // Initialize the remapping table.
2878 // Invalid stays invalid.
Richard Smithb9eab6d2014-03-20 19:44:17 +00002879 F.SLocRemap.insertOrReplace(std::make_pair(0U, 0));
Guy Benyei11169dd2012-12-18 14:30:41 +00002880 // This module. Base was 2 when being compiled.
Richard Smithb9eab6d2014-03-20 19:44:17 +00002881 F.SLocRemap.insertOrReplace(std::make_pair(2U,
Guy Benyei11169dd2012-12-18 14:30:41 +00002882 static_cast<int>(F.SLocEntryBaseOffset - 2)));
2883
2884 TotalNumSLocEntries += F.LocalNumSLocEntries;
2885 break;
2886 }
2887
2888 case MODULE_OFFSET_MAP: {
2889 // Additional remapping information.
Chris Lattner0e6c9402013-01-20 02:38:54 +00002890 const unsigned char *Data = (const unsigned char*)Blob.data();
2891 const unsigned char *DataEnd = Data + Blob.size();
Richard Smithb9eab6d2014-03-20 19:44:17 +00002892
2893 // If we see this entry before SOURCE_LOCATION_OFFSETS, add placeholders.
2894 if (F.SLocRemap.find(0) == F.SLocRemap.end()) {
2895 F.SLocRemap.insert(std::make_pair(0U, 0));
2896 F.SLocRemap.insert(std::make_pair(2U, 1));
2897 }
2898
Guy Benyei11169dd2012-12-18 14:30:41 +00002899 // Continuous range maps we may be updating in our module.
2900 ContinuousRangeMap<uint32_t, int, 2>::Builder SLocRemap(F.SLocRemap);
2901 ContinuousRangeMap<uint32_t, int, 2>::Builder
2902 IdentifierRemap(F.IdentifierRemap);
2903 ContinuousRangeMap<uint32_t, int, 2>::Builder
2904 MacroRemap(F.MacroRemap);
2905 ContinuousRangeMap<uint32_t, int, 2>::Builder
2906 PreprocessedEntityRemap(F.PreprocessedEntityRemap);
2907 ContinuousRangeMap<uint32_t, int, 2>::Builder
2908 SubmoduleRemap(F.SubmoduleRemap);
2909 ContinuousRangeMap<uint32_t, int, 2>::Builder
2910 SelectorRemap(F.SelectorRemap);
2911 ContinuousRangeMap<uint32_t, int, 2>::Builder DeclRemap(F.DeclRemap);
2912 ContinuousRangeMap<uint32_t, int, 2>::Builder TypeRemap(F.TypeRemap);
2913
2914 while(Data < DataEnd) {
Justin Bogner57ba0b22014-03-28 22:03:24 +00002915 using namespace llvm::support;
2916 uint16_t Len = endian::readNext<uint16_t, little, unaligned>(Data);
Guy Benyei11169dd2012-12-18 14:30:41 +00002917 StringRef Name = StringRef((const char*)Data, Len);
2918 Data += Len;
2919 ModuleFile *OM = ModuleMgr.lookup(Name);
2920 if (!OM) {
2921 Error("SourceLocation remap refers to unknown module");
Ben Langmuir2c9af442014-04-10 17:57:43 +00002922 return Failure;
Guy Benyei11169dd2012-12-18 14:30:41 +00002923 }
2924
Justin Bogner57ba0b22014-03-28 22:03:24 +00002925 uint32_t SLocOffset =
2926 endian::readNext<uint32_t, little, unaligned>(Data);
2927 uint32_t IdentifierIDOffset =
2928 endian::readNext<uint32_t, little, unaligned>(Data);
2929 uint32_t MacroIDOffset =
2930 endian::readNext<uint32_t, little, unaligned>(Data);
2931 uint32_t PreprocessedEntityIDOffset =
2932 endian::readNext<uint32_t, little, unaligned>(Data);
2933 uint32_t SubmoduleIDOffset =
2934 endian::readNext<uint32_t, little, unaligned>(Data);
2935 uint32_t SelectorIDOffset =
2936 endian::readNext<uint32_t, little, unaligned>(Data);
2937 uint32_t DeclIDOffset =
2938 endian::readNext<uint32_t, little, unaligned>(Data);
2939 uint32_t TypeIndexOffset =
2940 endian::readNext<uint32_t, little, unaligned>(Data);
2941
Guy Benyei11169dd2012-12-18 14:30:41 +00002942 // Source location offset is mapped to OM->SLocEntryBaseOffset.
2943 SLocRemap.insert(std::make_pair(SLocOffset,
2944 static_cast<int>(OM->SLocEntryBaseOffset - SLocOffset)));
2945 IdentifierRemap.insert(
2946 std::make_pair(IdentifierIDOffset,
2947 OM->BaseIdentifierID - IdentifierIDOffset));
2948 MacroRemap.insert(std::make_pair(MacroIDOffset,
2949 OM->BaseMacroID - MacroIDOffset));
2950 PreprocessedEntityRemap.insert(
2951 std::make_pair(PreprocessedEntityIDOffset,
2952 OM->BasePreprocessedEntityID - PreprocessedEntityIDOffset));
2953 SubmoduleRemap.insert(std::make_pair(SubmoduleIDOffset,
2954 OM->BaseSubmoduleID - SubmoduleIDOffset));
2955 SelectorRemap.insert(std::make_pair(SelectorIDOffset,
2956 OM->BaseSelectorID - SelectorIDOffset));
2957 DeclRemap.insert(std::make_pair(DeclIDOffset,
2958 OM->BaseDeclID - DeclIDOffset));
2959
2960 TypeRemap.insert(std::make_pair(TypeIndexOffset,
2961 OM->BaseTypeIndex - TypeIndexOffset));
2962
2963 // Global -> local mappings.
2964 F.GlobalToLocalDeclIDs[OM] = DeclIDOffset;
2965 }
2966 break;
2967 }
2968
2969 case SOURCE_MANAGER_LINE_TABLE:
2970 if (ParseLineTable(F, Record))
Ben Langmuir2c9af442014-04-10 17:57:43 +00002971 return Failure;
Guy Benyei11169dd2012-12-18 14:30:41 +00002972 break;
2973
2974 case SOURCE_LOCATION_PRELOADS: {
2975 // Need to transform from the local view (1-based IDs) to the global view,
2976 // which is based off F.SLocEntryBaseID.
2977 if (!F.PreloadSLocEntries.empty()) {
2978 Error("Multiple SOURCE_LOCATION_PRELOADS records in AST file");
Ben Langmuir2c9af442014-04-10 17:57:43 +00002979 return Failure;
Guy Benyei11169dd2012-12-18 14:30:41 +00002980 }
2981
2982 F.PreloadSLocEntries.swap(Record);
2983 break;
2984 }
2985
2986 case EXT_VECTOR_DECLS:
2987 for (unsigned I = 0, N = Record.size(); I != N; ++I)
2988 ExtVectorDecls.push_back(getGlobalDeclID(F, Record[I]));
2989 break;
2990
2991 case VTABLE_USES:
2992 if (Record.size() % 3 != 0) {
2993 Error("Invalid VTABLE_USES record");
Ben Langmuir2c9af442014-04-10 17:57:43 +00002994 return Failure;
Guy Benyei11169dd2012-12-18 14:30:41 +00002995 }
2996
2997 // Later tables overwrite earlier ones.
2998 // FIXME: Modules will have some trouble with this. This is clearly not
2999 // the right way to do this.
3000 VTableUses.clear();
3001
3002 for (unsigned Idx = 0, N = Record.size(); Idx != N; /* In loop */) {
3003 VTableUses.push_back(getGlobalDeclID(F, Record[Idx++]));
3004 VTableUses.push_back(
3005 ReadSourceLocation(F, Record, Idx).getRawEncoding());
3006 VTableUses.push_back(Record[Idx++]);
3007 }
3008 break;
3009
3010 case DYNAMIC_CLASSES:
3011 for (unsigned I = 0, N = Record.size(); I != N; ++I)
3012 DynamicClasses.push_back(getGlobalDeclID(F, Record[I]));
3013 break;
3014
3015 case PENDING_IMPLICIT_INSTANTIATIONS:
3016 if (PendingInstantiations.size() % 2 != 0) {
3017 Error("Invalid existing PendingInstantiations");
Ben Langmuir2c9af442014-04-10 17:57:43 +00003018 return Failure;
Guy Benyei11169dd2012-12-18 14:30:41 +00003019 }
3020
3021 if (Record.size() % 2 != 0) {
3022 Error("Invalid PENDING_IMPLICIT_INSTANTIATIONS block");
Ben Langmuir2c9af442014-04-10 17:57:43 +00003023 return Failure;
Guy Benyei11169dd2012-12-18 14:30:41 +00003024 }
3025
3026 for (unsigned I = 0, N = Record.size(); I != N; /* in loop */) {
3027 PendingInstantiations.push_back(getGlobalDeclID(F, Record[I++]));
3028 PendingInstantiations.push_back(
3029 ReadSourceLocation(F, Record, I).getRawEncoding());
3030 }
3031 break;
3032
3033 case SEMA_DECL_REFS:
Richard Smith3d8e97e2013-10-18 06:54:39 +00003034 if (Record.size() != 2) {
3035 Error("Invalid SEMA_DECL_REFS block");
Ben Langmuir2c9af442014-04-10 17:57:43 +00003036 return Failure;
Richard Smith3d8e97e2013-10-18 06:54:39 +00003037 }
Guy Benyei11169dd2012-12-18 14:30:41 +00003038 for (unsigned I = 0, N = Record.size(); I != N; ++I)
3039 SemaDeclRefs.push_back(getGlobalDeclID(F, Record[I]));
3040 break;
3041
3042 case PPD_ENTITIES_OFFSETS: {
Chris Lattner0e6c9402013-01-20 02:38:54 +00003043 F.PreprocessedEntityOffsets = (const PPEntityOffset *)Blob.data();
3044 assert(Blob.size() % sizeof(PPEntityOffset) == 0);
3045 F.NumPreprocessedEntities = Blob.size() / sizeof(PPEntityOffset);
Guy Benyei11169dd2012-12-18 14:30:41 +00003046
3047 unsigned LocalBasePreprocessedEntityID = Record[0];
3048
3049 unsigned StartingID;
3050 if (!PP.getPreprocessingRecord())
3051 PP.createPreprocessingRecord();
3052 if (!PP.getPreprocessingRecord()->getExternalSource())
3053 PP.getPreprocessingRecord()->SetExternalSource(*this);
3054 StartingID
3055 = PP.getPreprocessingRecord()
3056 ->allocateLoadedEntities(F.NumPreprocessedEntities);
3057 F.BasePreprocessedEntityID = StartingID;
3058
3059 if (F.NumPreprocessedEntities > 0) {
3060 // Introduce the global -> local mapping for preprocessed entities in
3061 // this module.
3062 GlobalPreprocessedEntityMap.insert(std::make_pair(StartingID, &F));
3063
3064 // Introduce the local -> global mapping for preprocessed entities in
3065 // this module.
3066 F.PreprocessedEntityRemap.insertOrReplace(
3067 std::make_pair(LocalBasePreprocessedEntityID,
3068 F.BasePreprocessedEntityID - LocalBasePreprocessedEntityID));
3069 }
3070
3071 break;
3072 }
3073
3074 case DECL_UPDATE_OFFSETS: {
3075 if (Record.size() % 2 != 0) {
3076 Error("invalid DECL_UPDATE_OFFSETS block in AST file");
Ben Langmuir2c9af442014-04-10 17:57:43 +00003077 return Failure;
Guy Benyei11169dd2012-12-18 14:30:41 +00003078 }
Richard Smithcd45dbc2014-04-19 03:48:30 +00003079 for (unsigned I = 0, N = Record.size(); I != N; I += 2) {
3080 GlobalDeclID ID = getGlobalDeclID(F, Record[I]);
3081 DeclUpdateOffsets[ID].push_back(std::make_pair(&F, Record[I + 1]));
3082
3083 // If we've already loaded the decl, perform the updates when we finish
3084 // loading this block.
3085 if (Decl *D = GetExistingDecl(ID))
3086 PendingUpdateRecords.push_back(std::make_pair(ID, D));
3087 }
Guy Benyei11169dd2012-12-18 14:30:41 +00003088 break;
3089 }
3090
3091 case DECL_REPLACEMENTS: {
3092 if (Record.size() % 3 != 0) {
3093 Error("invalid DECL_REPLACEMENTS block in AST file");
Ben Langmuir2c9af442014-04-10 17:57:43 +00003094 return Failure;
Guy Benyei11169dd2012-12-18 14:30:41 +00003095 }
3096 for (unsigned I = 0, N = Record.size(); I != N; I += 3)
3097 ReplacedDecls[getGlobalDeclID(F, Record[I])]
3098 = ReplacedDeclInfo(&F, Record[I+1], Record[I+2]);
3099 break;
3100 }
3101
3102 case OBJC_CATEGORIES_MAP: {
3103 if (F.LocalNumObjCCategoriesInMap != 0) {
3104 Error("duplicate OBJC_CATEGORIES_MAP record in AST file");
Ben Langmuir2c9af442014-04-10 17:57:43 +00003105 return Failure;
Guy Benyei11169dd2012-12-18 14:30:41 +00003106 }
3107
3108 F.LocalNumObjCCategoriesInMap = Record[0];
Chris Lattner0e6c9402013-01-20 02:38:54 +00003109 F.ObjCCategoriesMap = (const ObjCCategoriesInfo *)Blob.data();
Guy Benyei11169dd2012-12-18 14:30:41 +00003110 break;
3111 }
3112
3113 case OBJC_CATEGORIES:
3114 F.ObjCCategories.swap(Record);
3115 break;
3116
3117 case CXX_BASE_SPECIFIER_OFFSETS: {
3118 if (F.LocalNumCXXBaseSpecifiers != 0) {
3119 Error("duplicate CXX_BASE_SPECIFIER_OFFSETS record in AST file");
Ben Langmuir2c9af442014-04-10 17:57:43 +00003120 return Failure;
Guy Benyei11169dd2012-12-18 14:30:41 +00003121 }
3122
3123 F.LocalNumCXXBaseSpecifiers = Record[0];
Chris Lattner0e6c9402013-01-20 02:38:54 +00003124 F.CXXBaseSpecifiersOffsets = (const uint32_t *)Blob.data();
Guy Benyei11169dd2012-12-18 14:30:41 +00003125 NumCXXBaseSpecifiersLoaded += F.LocalNumCXXBaseSpecifiers;
3126 break;
3127 }
3128
3129 case DIAG_PRAGMA_MAPPINGS:
3130 if (F.PragmaDiagMappings.empty())
3131 F.PragmaDiagMappings.swap(Record);
3132 else
3133 F.PragmaDiagMappings.insert(F.PragmaDiagMappings.end(),
3134 Record.begin(), Record.end());
3135 break;
3136
3137 case CUDA_SPECIAL_DECL_REFS:
3138 // Later tables overwrite earlier ones.
3139 // FIXME: Modules will have trouble with this.
3140 CUDASpecialDeclRefs.clear();
3141 for (unsigned I = 0, N = Record.size(); I != N; ++I)
3142 CUDASpecialDeclRefs.push_back(getGlobalDeclID(F, Record[I]));
3143 break;
3144
3145 case HEADER_SEARCH_TABLE: {
Chris Lattner0e6c9402013-01-20 02:38:54 +00003146 F.HeaderFileInfoTableData = Blob.data();
Guy Benyei11169dd2012-12-18 14:30:41 +00003147 F.LocalNumHeaderFileInfos = Record[1];
Guy Benyei11169dd2012-12-18 14:30:41 +00003148 if (Record[0]) {
3149 F.HeaderFileInfoTable
3150 = HeaderFileInfoLookupTable::Create(
3151 (const unsigned char *)F.HeaderFileInfoTableData + Record[0],
3152 (const unsigned char *)F.HeaderFileInfoTableData,
3153 HeaderFileInfoTrait(*this, F,
3154 &PP.getHeaderSearchInfo(),
Chris Lattner0e6c9402013-01-20 02:38:54 +00003155 Blob.data() + Record[2]));
Guy Benyei11169dd2012-12-18 14:30:41 +00003156
3157 PP.getHeaderSearchInfo().SetExternalSource(this);
3158 if (!PP.getHeaderSearchInfo().getExternalLookup())
3159 PP.getHeaderSearchInfo().SetExternalLookup(this);
3160 }
3161 break;
3162 }
3163
3164 case FP_PRAGMA_OPTIONS:
3165 // Later tables overwrite earlier ones.
3166 FPPragmaOptions.swap(Record);
3167 break;
3168
3169 case OPENCL_EXTENSIONS:
3170 // Later tables overwrite earlier ones.
3171 OpenCLExtensions.swap(Record);
3172 break;
3173
3174 case TENTATIVE_DEFINITIONS:
3175 for (unsigned I = 0, N = Record.size(); I != N; ++I)
3176 TentativeDefinitions.push_back(getGlobalDeclID(F, Record[I]));
3177 break;
3178
3179 case KNOWN_NAMESPACES:
3180 for (unsigned I = 0, N = Record.size(); I != N; ++I)
3181 KnownNamespaces.push_back(getGlobalDeclID(F, Record[I]));
3182 break;
Nick Lewycky8334af82013-01-26 00:35:08 +00003183
Nick Lewycky9c7eb1d2013-02-01 08:13:20 +00003184 case UNDEFINED_BUT_USED:
3185 if (UndefinedButUsed.size() % 2 != 0) {
3186 Error("Invalid existing UndefinedButUsed");
Ben Langmuir2c9af442014-04-10 17:57:43 +00003187 return Failure;
Nick Lewycky8334af82013-01-26 00:35:08 +00003188 }
3189
3190 if (Record.size() % 2 != 0) {
Nick Lewycky9c7eb1d2013-02-01 08:13:20 +00003191 Error("invalid undefined-but-used record");
Ben Langmuir2c9af442014-04-10 17:57:43 +00003192 return Failure;
Nick Lewycky8334af82013-01-26 00:35:08 +00003193 }
3194 for (unsigned I = 0, N = Record.size(); I != N; /* in loop */) {
Nick Lewycky9c7eb1d2013-02-01 08:13:20 +00003195 UndefinedButUsed.push_back(getGlobalDeclID(F, Record[I++]));
3196 UndefinedButUsed.push_back(
Nick Lewycky8334af82013-01-26 00:35:08 +00003197 ReadSourceLocation(F, Record, I).getRawEncoding());
3198 }
3199 break;
3200
Guy Benyei11169dd2012-12-18 14:30:41 +00003201 case IMPORTED_MODULES: {
3202 if (F.Kind != MK_Module) {
3203 // If we aren't loading a module (which has its own exports), make
3204 // all of the imported modules visible.
3205 // FIXME: Deal with macros-only imports.
Richard Smith56be7542014-03-21 00:33:59 +00003206 for (unsigned I = 0, N = Record.size(); I != N; /**/) {
3207 unsigned GlobalID = getGlobalSubmoduleID(F, Record[I++]);
3208 SourceLocation Loc = ReadSourceLocation(F, Record, I);
3209 if (GlobalID)
Aaron Ballman4f45b712014-03-21 15:22:56 +00003210 ImportedModules.push_back(ImportedSubmodule(GlobalID, Loc));
Guy Benyei11169dd2012-12-18 14:30:41 +00003211 }
3212 }
3213 break;
3214 }
3215
3216 case LOCAL_REDECLARATIONS: {
3217 F.RedeclarationChains.swap(Record);
3218 break;
3219 }
3220
3221 case LOCAL_REDECLARATIONS_MAP: {
3222 if (F.LocalNumRedeclarationsInMap != 0) {
3223 Error("duplicate LOCAL_REDECLARATIONS_MAP record in AST file");
Ben Langmuir2c9af442014-04-10 17:57:43 +00003224 return Failure;
Guy Benyei11169dd2012-12-18 14:30:41 +00003225 }
3226
3227 F.LocalNumRedeclarationsInMap = Record[0];
Chris Lattner0e6c9402013-01-20 02:38:54 +00003228 F.RedeclarationsMap = (const LocalRedeclarationsInfo *)Blob.data();
Guy Benyei11169dd2012-12-18 14:30:41 +00003229 break;
3230 }
3231
3232 case MERGED_DECLARATIONS: {
3233 for (unsigned Idx = 0; Idx < Record.size(); /* increment in loop */) {
3234 GlobalDeclID CanonID = getGlobalDeclID(F, Record[Idx++]);
3235 SmallVectorImpl<GlobalDeclID> &Decls = StoredMergedDecls[CanonID];
3236 for (unsigned N = Record[Idx++]; N > 0; --N)
3237 Decls.push_back(getGlobalDeclID(F, Record[Idx++]));
3238 }
3239 break;
3240 }
3241
3242 case MACRO_OFFSET: {
3243 if (F.LocalNumMacros != 0) {
3244 Error("duplicate MACRO_OFFSET record in AST file");
Ben Langmuir2c9af442014-04-10 17:57:43 +00003245 return Failure;
Guy Benyei11169dd2012-12-18 14:30:41 +00003246 }
Chris Lattner0e6c9402013-01-20 02:38:54 +00003247 F.MacroOffsets = (const uint32_t *)Blob.data();
Guy Benyei11169dd2012-12-18 14:30:41 +00003248 F.LocalNumMacros = Record[0];
3249 unsigned LocalBaseMacroID = Record[1];
3250 F.BaseMacroID = getTotalNumMacros();
3251
3252 if (F.LocalNumMacros > 0) {
3253 // Introduce the global -> local mapping for macros within this module.
3254 GlobalMacroMap.insert(std::make_pair(getTotalNumMacros() + 1, &F));
3255
3256 // Introduce the local -> global mapping for macros within this module.
3257 F.MacroRemap.insertOrReplace(
3258 std::make_pair(LocalBaseMacroID,
3259 F.BaseMacroID - LocalBaseMacroID));
3260
3261 MacrosLoaded.resize(MacrosLoaded.size() + F.LocalNumMacros);
3262 }
3263 break;
3264 }
3265
Argyrios Kyrtzidiseb663da2013-03-22 21:12:57 +00003266 case MACRO_TABLE: {
3267 // FIXME: Not used yet.
Guy Benyei11169dd2012-12-18 14:30:41 +00003268 break;
3269 }
Richard Smithe40f2ba2013-08-07 21:41:30 +00003270
3271 case LATE_PARSED_TEMPLATE: {
3272 LateParsedTemplates.append(Record.begin(), Record.end());
3273 break;
3274 }
Guy Benyei11169dd2012-12-18 14:30:41 +00003275 }
3276 }
Guy Benyei11169dd2012-12-18 14:30:41 +00003277}
3278
Douglas Gregorc1489562013-02-12 23:36:21 +00003279/// \brief Move the given method to the back of the global list of methods.
3280static void moveMethodToBackOfGlobalList(Sema &S, ObjCMethodDecl *Method) {
3281 // Find the entry for this selector in the method pool.
3282 Sema::GlobalMethodPool::iterator Known
3283 = S.MethodPool.find(Method->getSelector());
3284 if (Known == S.MethodPool.end())
3285 return;
3286
3287 // Retrieve the appropriate method list.
3288 ObjCMethodList &Start = Method->isInstanceMethod()? Known->second.first
3289 : Known->second.second;
3290 bool Found = false;
Argyrios Kyrtzidisd3da6e02013-04-17 00:08:58 +00003291 for (ObjCMethodList *List = &Start; List; List = List->getNext()) {
Douglas Gregorc1489562013-02-12 23:36:21 +00003292 if (!Found) {
3293 if (List->Method == Method) {
3294 Found = true;
3295 } else {
3296 // Keep searching.
3297 continue;
3298 }
3299 }
3300
Argyrios Kyrtzidisd3da6e02013-04-17 00:08:58 +00003301 if (List->getNext())
3302 List->Method = List->getNext()->Method;
Douglas Gregorc1489562013-02-12 23:36:21 +00003303 else
3304 List->Method = Method;
3305 }
3306}
3307
Argyrios Kyrtzidis3a9c42c2013-03-27 01:25:34 +00003308void ASTReader::makeNamesVisible(const HiddenNames &Names, Module *Owner) {
Richard Smith49f906a2014-03-01 00:08:04 +00003309 for (unsigned I = 0, N = Names.HiddenDecls.size(); I != N; ++I) {
3310 Decl *D = Names.HiddenDecls[I];
3311 bool wasHidden = D->Hidden;
3312 D->Hidden = false;
Guy Benyei11169dd2012-12-18 14:30:41 +00003313
Richard Smith49f906a2014-03-01 00:08:04 +00003314 if (wasHidden && SemaObj) {
3315 if (ObjCMethodDecl *Method = dyn_cast<ObjCMethodDecl>(D)) {
3316 moveMethodToBackOfGlobalList(*SemaObj, Method);
Douglas Gregorc1489562013-02-12 23:36:21 +00003317 }
Guy Benyei11169dd2012-12-18 14:30:41 +00003318 }
3319 }
Richard Smith49f906a2014-03-01 00:08:04 +00003320
3321 for (HiddenMacrosMap::const_iterator I = Names.HiddenMacros.begin(),
3322 E = Names.HiddenMacros.end();
3323 I != E; ++I)
3324 installImportedMacro(I->first, I->second, Owner);
Guy Benyei11169dd2012-12-18 14:30:41 +00003325}
3326
Richard Smith49f906a2014-03-01 00:08:04 +00003327void ASTReader::makeModuleVisible(Module *Mod,
Argyrios Kyrtzidis125df052013-02-01 16:36:12 +00003328 Module::NameVisibilityKind NameVisibility,
Douglas Gregorfb912652013-03-20 21:10:35 +00003329 SourceLocation ImportLoc,
3330 bool Complain) {
Guy Benyei11169dd2012-12-18 14:30:41 +00003331 llvm::SmallPtrSet<Module *, 4> Visited;
Dmitri Gribenkof8579502013-01-12 19:30:44 +00003332 SmallVector<Module *, 4> Stack;
Robert Wilhelm25284cc2013-08-23 16:11:15 +00003333 Stack.push_back(Mod);
Guy Benyei11169dd2012-12-18 14:30:41 +00003334 while (!Stack.empty()) {
Robert Wilhelm25284cc2013-08-23 16:11:15 +00003335 Mod = Stack.pop_back_val();
Guy Benyei11169dd2012-12-18 14:30:41 +00003336
3337 if (NameVisibility <= Mod->NameVisibility) {
Robert Wilhelm25284cc2013-08-23 16:11:15 +00003338 // This module already has this level of visibility (or greater), so
Guy Benyei11169dd2012-12-18 14:30:41 +00003339 // there is nothing more to do.
3340 continue;
3341 }
Richard Smith49f906a2014-03-01 00:08:04 +00003342
Guy Benyei11169dd2012-12-18 14:30:41 +00003343 if (!Mod->isAvailable()) {
3344 // Modules that aren't available cannot be made visible.
3345 continue;
3346 }
3347
3348 // Update the module's name visibility.
Richard Smith49f906a2014-03-01 00:08:04 +00003349 if (NameVisibility >= Module::MacrosVisible &&
3350 Mod->NameVisibility < Module::MacrosVisible)
3351 Mod->MacroVisibilityLoc = ImportLoc;
Guy Benyei11169dd2012-12-18 14:30:41 +00003352 Mod->NameVisibility = NameVisibility;
Richard Smith49f906a2014-03-01 00:08:04 +00003353
Guy Benyei11169dd2012-12-18 14:30:41 +00003354 // If we've already deserialized any names from this module,
3355 // mark them as visible.
3356 HiddenNamesMapType::iterator Hidden = HiddenNamesMap.find(Mod);
3357 if (Hidden != HiddenNamesMap.end()) {
Argyrios Kyrtzidis3a9c42c2013-03-27 01:25:34 +00003358 makeNamesVisible(Hidden->second, Hidden->first);
Guy Benyei11169dd2012-12-18 14:30:41 +00003359 HiddenNamesMap.erase(Hidden);
3360 }
Dmitri Gribenkoe9bcf5b2013-11-04 21:51:33 +00003361
Guy Benyei11169dd2012-12-18 14:30:41 +00003362 // Push any exported modules onto the stack to be marked as visible.
Argyrios Kyrtzidis8739f7b2013-02-19 19:34:40 +00003363 SmallVector<Module *, 16> Exports;
3364 Mod->getExportedModules(Exports);
3365 for (SmallVectorImpl<Module *>::iterator
3366 I = Exports.begin(), E = Exports.end(); I != E; ++I) {
3367 Module *Exported = *I;
3368 if (Visited.insert(Exported))
3369 Stack.push_back(Exported);
Guy Benyei11169dd2012-12-18 14:30:41 +00003370 }
Douglas Gregorfb912652013-03-20 21:10:35 +00003371
3372 // Detect any conflicts.
3373 if (Complain) {
3374 assert(ImportLoc.isValid() && "Missing import location");
3375 for (unsigned I = 0, N = Mod->Conflicts.size(); I != N; ++I) {
3376 if (Mod->Conflicts[I].Other->NameVisibility >= NameVisibility) {
3377 Diag(ImportLoc, diag::warn_module_conflict)
3378 << Mod->getFullModuleName()
3379 << Mod->Conflicts[I].Other->getFullModuleName()
3380 << Mod->Conflicts[I].Message;
3381 // FIXME: Need note where the other module was imported.
3382 }
3383 }
3384 }
Guy Benyei11169dd2012-12-18 14:30:41 +00003385 }
3386}
3387
Douglas Gregore060e572013-01-25 01:03:03 +00003388bool ASTReader::loadGlobalIndex() {
3389 if (GlobalIndex)
3390 return false;
3391
3392 if (TriedLoadingGlobalIndex || !UseGlobalIndex ||
3393 !Context.getLangOpts().Modules)
3394 return true;
3395
3396 // Try to load the global index.
3397 TriedLoadingGlobalIndex = true;
3398 StringRef ModuleCachePath
3399 = getPreprocessor().getHeaderSearchInfo().getModuleCachePath();
3400 std::pair<GlobalModuleIndex *, GlobalModuleIndex::ErrorCode> Result
Douglas Gregor7029ce12013-03-19 00:28:20 +00003401 = GlobalModuleIndex::readIndex(ModuleCachePath);
Douglas Gregore060e572013-01-25 01:03:03 +00003402 if (!Result.first)
3403 return true;
3404
3405 GlobalIndex.reset(Result.first);
Douglas Gregor7211ac12013-01-25 23:32:03 +00003406 ModuleMgr.setGlobalIndex(GlobalIndex.get());
Douglas Gregore060e572013-01-25 01:03:03 +00003407 return false;
3408}
3409
3410bool ASTReader::isGlobalIndexUnavailable() const {
3411 return Context.getLangOpts().Modules && UseGlobalIndex &&
3412 !hasGlobalIndex() && TriedLoadingGlobalIndex;
3413}
3414
Dmitri Gribenkof430da42014-02-12 10:33:14 +00003415static void updateModuleTimestamp(ModuleFile &MF) {
3416 // Overwrite the timestamp file contents so that file's mtime changes.
3417 std::string TimestampFilename = MF.getTimestampFilename();
3418 std::string ErrorInfo;
Rafael Espindola04a13be2014-02-24 15:06:52 +00003419 llvm::raw_fd_ostream OS(TimestampFilename.c_str(), ErrorInfo,
Rafael Espindola4fbd3732014-02-24 18:20:21 +00003420 llvm::sys::fs::F_Text);
Dmitri Gribenkof430da42014-02-12 10:33:14 +00003421 if (!ErrorInfo.empty())
3422 return;
3423 OS << "Timestamp file\n";
3424}
3425
Guy Benyei11169dd2012-12-18 14:30:41 +00003426ASTReader::ASTReadResult ASTReader::ReadAST(const std::string &FileName,
3427 ModuleKind Type,
3428 SourceLocation ImportLoc,
3429 unsigned ClientLoadCapabilities) {
Argyrios Kyrtzidisdc9fdaf2013-05-24 05:44:08 +00003430 llvm::SaveAndRestore<SourceLocation>
3431 SetCurImportLocRAII(CurrentImportLoc, ImportLoc);
3432
Richard Smithd1c46742014-04-30 02:24:17 +00003433 // Defer any pending actions until we get to the end of reading the AST file.
3434 Deserializing AnASTFile(this);
3435
Guy Benyei11169dd2012-12-18 14:30:41 +00003436 // Bump the generation number.
3437 unsigned PreviousGeneration = CurrentGeneration++;
3438
3439 unsigned NumModules = ModuleMgr.size();
Dmitri Gribenkof8579502013-01-12 19:30:44 +00003440 SmallVector<ImportedModule, 4> Loaded;
Guy Benyei11169dd2012-12-18 14:30:41 +00003441 switch(ASTReadResult ReadResult = ReadASTCore(FileName, Type, ImportLoc,
3442 /*ImportedBy=*/0, Loaded,
Douglas Gregor7029ce12013-03-19 00:28:20 +00003443 0, 0,
Guy Benyei11169dd2012-12-18 14:30:41 +00003444 ClientLoadCapabilities)) {
3445 case Failure:
Douglas Gregor7029ce12013-03-19 00:28:20 +00003446 case Missing:
Guy Benyei11169dd2012-12-18 14:30:41 +00003447 case OutOfDate:
3448 case VersionMismatch:
3449 case ConfigurationMismatch:
3450 case HadErrors:
Douglas Gregor7029ce12013-03-19 00:28:20 +00003451 ModuleMgr.removeModules(ModuleMgr.begin() + NumModules, ModuleMgr.end(),
3452 Context.getLangOpts().Modules
3453 ? &PP.getHeaderSearchInfo().getModuleMap()
3454 : 0);
Douglas Gregore060e572013-01-25 01:03:03 +00003455
3456 // If we find that any modules are unusable, the global index is going
3457 // to be out-of-date. Just remove it.
3458 GlobalIndex.reset();
Douglas Gregor7211ac12013-01-25 23:32:03 +00003459 ModuleMgr.setGlobalIndex(0);
Guy Benyei11169dd2012-12-18 14:30:41 +00003460 return ReadResult;
3461
3462 case Success:
3463 break;
3464 }
3465
3466 // Here comes stuff that we only do once the entire chain is loaded.
3467
3468 // Load the AST blocks of all of the modules that we loaded.
Dmitri Gribenkof8579502013-01-12 19:30:44 +00003469 for (SmallVectorImpl<ImportedModule>::iterator M = Loaded.begin(),
3470 MEnd = Loaded.end();
Guy Benyei11169dd2012-12-18 14:30:41 +00003471 M != MEnd; ++M) {
3472 ModuleFile &F = *M->Mod;
3473
3474 // Read the AST block.
Ben Langmuir2c9af442014-04-10 17:57:43 +00003475 if (ASTReadResult Result = ReadASTBlock(F, ClientLoadCapabilities))
3476 return Result;
Guy Benyei11169dd2012-12-18 14:30:41 +00003477
3478 // Once read, set the ModuleFile bit base offset and update the size in
3479 // bits of all files we've seen.
3480 F.GlobalBitOffset = TotalModulesSizeInBits;
3481 TotalModulesSizeInBits += F.SizeInBits;
3482 GlobalBitOffsetsMap.insert(std::make_pair(F.GlobalBitOffset, &F));
3483
3484 // Preload SLocEntries.
3485 for (unsigned I = 0, N = F.PreloadSLocEntries.size(); I != N; ++I) {
3486 int Index = int(F.PreloadSLocEntries[I] - 1) + F.SLocEntryBaseID;
3487 // Load it through the SourceManager and don't call ReadSLocEntry()
3488 // directly because the entry may have already been loaded in which case
3489 // calling ReadSLocEntry() directly would trigger an assertion in
3490 // SourceManager.
3491 SourceMgr.getLoadedSLocEntryByID(Index);
3492 }
3493 }
3494
Douglas Gregor603cd862013-03-22 18:50:14 +00003495 // Setup the import locations and notify the module manager that we've
3496 // committed to these module files.
Dmitri Gribenkof8579502013-01-12 19:30:44 +00003497 for (SmallVectorImpl<ImportedModule>::iterator M = Loaded.begin(),
3498 MEnd = Loaded.end();
Guy Benyei11169dd2012-12-18 14:30:41 +00003499 M != MEnd; ++M) {
3500 ModuleFile &F = *M->Mod;
Douglas Gregor603cd862013-03-22 18:50:14 +00003501
3502 ModuleMgr.moduleFileAccepted(&F);
3503
3504 // Set the import location.
Argyrios Kyrtzidis71c1af82013-02-01 16:36:14 +00003505 F.DirectImportLoc = ImportLoc;
Guy Benyei11169dd2012-12-18 14:30:41 +00003506 if (!M->ImportedBy)
3507 F.ImportLoc = M->ImportLoc;
3508 else
3509 F.ImportLoc = ReadSourceLocation(*M->ImportedBy,
3510 M->ImportLoc.getRawEncoding());
3511 }
3512
3513 // Mark all of the identifiers in the identifier table as being out of date,
3514 // so that various accessors know to check the loaded modules when the
3515 // identifier is used.
3516 for (IdentifierTable::iterator Id = PP.getIdentifierTable().begin(),
3517 IdEnd = PP.getIdentifierTable().end();
3518 Id != IdEnd; ++Id)
3519 Id->second->setOutOfDate(true);
3520
3521 // Resolve any unresolved module exports.
Douglas Gregorfb912652013-03-20 21:10:35 +00003522 for (unsigned I = 0, N = UnresolvedModuleRefs.size(); I != N; ++I) {
3523 UnresolvedModuleRef &Unresolved = UnresolvedModuleRefs[I];
Guy Benyei11169dd2012-12-18 14:30:41 +00003524 SubmoduleID GlobalID = getGlobalSubmoduleID(*Unresolved.File,Unresolved.ID);
3525 Module *ResolvedMod = getSubmodule(GlobalID);
Douglas Gregorfb912652013-03-20 21:10:35 +00003526
3527 switch (Unresolved.Kind) {
3528 case UnresolvedModuleRef::Conflict:
3529 if (ResolvedMod) {
3530 Module::Conflict Conflict;
3531 Conflict.Other = ResolvedMod;
3532 Conflict.Message = Unresolved.String.str();
3533 Unresolved.Mod->Conflicts.push_back(Conflict);
3534 }
3535 continue;
3536
3537 case UnresolvedModuleRef::Import:
Guy Benyei11169dd2012-12-18 14:30:41 +00003538 if (ResolvedMod)
3539 Unresolved.Mod->Imports.push_back(ResolvedMod);
3540 continue;
Guy Benyei11169dd2012-12-18 14:30:41 +00003541
Douglas Gregorfb912652013-03-20 21:10:35 +00003542 case UnresolvedModuleRef::Export:
3543 if (ResolvedMod || Unresolved.IsWildcard)
3544 Unresolved.Mod->Exports.push_back(
3545 Module::ExportDecl(ResolvedMod, Unresolved.IsWildcard));
3546 continue;
3547 }
Guy Benyei11169dd2012-12-18 14:30:41 +00003548 }
Douglas Gregorfb912652013-03-20 21:10:35 +00003549 UnresolvedModuleRefs.clear();
Daniel Jasperba7f2f72013-09-24 09:14:14 +00003550
3551 // FIXME: How do we load the 'use'd modules? They may not be submodules.
3552 // Might be unnecessary as use declarations are only used to build the
3553 // module itself.
Guy Benyei11169dd2012-12-18 14:30:41 +00003554
3555 InitializeContext();
3556
Richard Smith3d8e97e2013-10-18 06:54:39 +00003557 if (SemaObj)
3558 UpdateSema();
3559
Guy Benyei11169dd2012-12-18 14:30:41 +00003560 if (DeserializationListener)
3561 DeserializationListener->ReaderInitialized(this);
3562
3563 ModuleFile &PrimaryModule = ModuleMgr.getPrimaryModule();
3564 if (!PrimaryModule.OriginalSourceFileID.isInvalid()) {
3565 PrimaryModule.OriginalSourceFileID
3566 = FileID::get(PrimaryModule.SLocEntryBaseID
3567 + PrimaryModule.OriginalSourceFileID.getOpaqueValue() - 1);
3568
3569 // If this AST file is a precompiled preamble, then set the
3570 // preamble file ID of the source manager to the file source file
3571 // from which the preamble was built.
3572 if (Type == MK_Preamble) {
3573 SourceMgr.setPreambleFileID(PrimaryModule.OriginalSourceFileID);
3574 } else if (Type == MK_MainFile) {
3575 SourceMgr.setMainFileID(PrimaryModule.OriginalSourceFileID);
3576 }
3577 }
3578
3579 // For any Objective-C class definitions we have already loaded, make sure
3580 // that we load any additional categories.
3581 for (unsigned I = 0, N = ObjCClassesLoaded.size(); I != N; ++I) {
3582 loadObjCCategories(ObjCClassesLoaded[I]->getGlobalID(),
3583 ObjCClassesLoaded[I],
3584 PreviousGeneration);
3585 }
Douglas Gregore060e572013-01-25 01:03:03 +00003586
Dmitri Gribenkof430da42014-02-12 10:33:14 +00003587 if (PP.getHeaderSearchInfo()
3588 .getHeaderSearchOpts()
3589 .ModulesValidateOncePerBuildSession) {
3590 // Now we are certain that the module and all modules it depends on are
3591 // up to date. Create or update timestamp files for modules that are
3592 // located in the module cache (not for PCH files that could be anywhere
3593 // in the filesystem).
3594 for (unsigned I = 0, N = Loaded.size(); I != N; ++I) {
3595 ImportedModule &M = Loaded[I];
3596 if (M.Mod->Kind == MK_Module) {
3597 updateModuleTimestamp(*M.Mod);
3598 }
3599 }
3600 }
3601
Guy Benyei11169dd2012-12-18 14:30:41 +00003602 return Success;
3603}
3604
3605ASTReader::ASTReadResult
3606ASTReader::ReadASTCore(StringRef FileName,
3607 ModuleKind Type,
3608 SourceLocation ImportLoc,
3609 ModuleFile *ImportedBy,
Dmitri Gribenkof8579502013-01-12 19:30:44 +00003610 SmallVectorImpl<ImportedModule> &Loaded,
Douglas Gregor7029ce12013-03-19 00:28:20 +00003611 off_t ExpectedSize, time_t ExpectedModTime,
Guy Benyei11169dd2012-12-18 14:30:41 +00003612 unsigned ClientLoadCapabilities) {
3613 ModuleFile *M;
Guy Benyei11169dd2012-12-18 14:30:41 +00003614 std::string ErrorStr;
Douglas Gregor7029ce12013-03-19 00:28:20 +00003615 ModuleManager::AddModuleResult AddResult
3616 = ModuleMgr.addModule(FileName, Type, ImportLoc, ImportedBy,
3617 CurrentGeneration, ExpectedSize, ExpectedModTime,
3618 M, ErrorStr);
Guy Benyei11169dd2012-12-18 14:30:41 +00003619
Douglas Gregor7029ce12013-03-19 00:28:20 +00003620 switch (AddResult) {
3621 case ModuleManager::AlreadyLoaded:
3622 return Success;
3623
3624 case ModuleManager::NewlyLoaded:
3625 // Load module file below.
3626 break;
3627
3628 case ModuleManager::Missing:
3629 // The module file was missing; if the client handle handle, that, return
3630 // it.
3631 if (ClientLoadCapabilities & ARR_Missing)
3632 return Missing;
3633
3634 // Otherwise, return an error.
3635 {
3636 std::string Msg = "Unable to load module \"" + FileName.str() + "\": "
3637 + ErrorStr;
3638 Error(Msg);
3639 }
3640 return Failure;
3641
3642 case ModuleManager::OutOfDate:
3643 // We couldn't load the module file because it is out-of-date. If the
3644 // client can handle out-of-date, return it.
3645 if (ClientLoadCapabilities & ARR_OutOfDate)
3646 return OutOfDate;
3647
3648 // Otherwise, return an error.
3649 {
3650 std::string Msg = "Unable to load module \"" + FileName.str() + "\": "
3651 + ErrorStr;
3652 Error(Msg);
3653 }
Guy Benyei11169dd2012-12-18 14:30:41 +00003654 return Failure;
3655 }
3656
Douglas Gregor7029ce12013-03-19 00:28:20 +00003657 assert(M && "Missing module file");
Guy Benyei11169dd2012-12-18 14:30:41 +00003658
3659 // FIXME: This seems rather a hack. Should CurrentDir be part of the
3660 // module?
3661 if (FileName != "-") {
3662 CurrentDir = llvm::sys::path::parent_path(FileName);
3663 if (CurrentDir.empty()) CurrentDir = ".";
3664 }
3665
3666 ModuleFile &F = *M;
Chris Lattner7fb3bef2013-01-20 00:56:42 +00003667 BitstreamCursor &Stream = F.Stream;
Guy Benyei11169dd2012-12-18 14:30:41 +00003668 Stream.init(F.StreamFile);
3669 F.SizeInBits = F.Buffer->getBufferSize() * 8;
3670
3671 // Sniff for the signature.
3672 if (Stream.Read(8) != 'C' ||
3673 Stream.Read(8) != 'P' ||
3674 Stream.Read(8) != 'C' ||
3675 Stream.Read(8) != 'H') {
3676 Diag(diag::err_not_a_pch_file) << FileName;
3677 return Failure;
3678 }
3679
3680 // This is used for compatibility with older PCH formats.
3681 bool HaveReadControlBlock = false;
3682
Chris Lattnerefa77172013-01-20 00:00:22 +00003683 while (1) {
3684 llvm::BitstreamEntry Entry = Stream.advance();
3685
3686 switch (Entry.Kind) {
3687 case llvm::BitstreamEntry::Error:
3688 case llvm::BitstreamEntry::EndBlock:
3689 case llvm::BitstreamEntry::Record:
Guy Benyei11169dd2012-12-18 14:30:41 +00003690 Error("invalid record at top-level of AST file");
3691 return Failure;
Chris Lattnerefa77172013-01-20 00:00:22 +00003692
3693 case llvm::BitstreamEntry::SubBlock:
3694 break;
Guy Benyei11169dd2012-12-18 14:30:41 +00003695 }
3696
Guy Benyei11169dd2012-12-18 14:30:41 +00003697 // We only know the control subblock ID.
Chris Lattnerefa77172013-01-20 00:00:22 +00003698 switch (Entry.ID) {
Guy Benyei11169dd2012-12-18 14:30:41 +00003699 case llvm::bitc::BLOCKINFO_BLOCK_ID:
3700 if (Stream.ReadBlockInfoBlock()) {
3701 Error("malformed BlockInfoBlock in AST file");
3702 return Failure;
3703 }
3704 break;
3705 case CONTROL_BLOCK_ID:
3706 HaveReadControlBlock = true;
Ben Langmuirbeee15e2014-04-14 18:00:01 +00003707 switch (ReadControlBlock(F, Loaded, ImportedBy, ClientLoadCapabilities)) {
Guy Benyei11169dd2012-12-18 14:30:41 +00003708 case Success:
3709 break;
3710
3711 case Failure: return Failure;
Douglas Gregor7029ce12013-03-19 00:28:20 +00003712 case Missing: return Missing;
Guy Benyei11169dd2012-12-18 14:30:41 +00003713 case OutOfDate: return OutOfDate;
3714 case VersionMismatch: return VersionMismatch;
3715 case ConfigurationMismatch: return ConfigurationMismatch;
3716 case HadErrors: return HadErrors;
3717 }
3718 break;
3719 case AST_BLOCK_ID:
3720 if (!HaveReadControlBlock) {
3721 if ((ClientLoadCapabilities & ARR_VersionMismatch) == 0)
Dmitri Gribenko2228cd32014-02-11 15:40:09 +00003722 Diag(diag::err_pch_version_too_old);
Guy Benyei11169dd2012-12-18 14:30:41 +00003723 return VersionMismatch;
3724 }
3725
3726 // Record that we've loaded this module.
3727 Loaded.push_back(ImportedModule(M, ImportedBy, ImportLoc));
3728 return Success;
3729
3730 default:
3731 if (Stream.SkipBlock()) {
3732 Error("malformed block record in AST file");
3733 return Failure;
3734 }
3735 break;
3736 }
3737 }
3738
3739 return Success;
3740}
3741
3742void ASTReader::InitializeContext() {
3743 // If there's a listener, notify them that we "read" the translation unit.
3744 if (DeserializationListener)
3745 DeserializationListener->DeclRead(PREDEF_DECL_TRANSLATION_UNIT_ID,
3746 Context.getTranslationUnitDecl());
3747
Guy Benyei11169dd2012-12-18 14:30:41 +00003748 // FIXME: Find a better way to deal with collisions between these
3749 // built-in types. Right now, we just ignore the problem.
3750
3751 // Load the special types.
3752 if (SpecialTypes.size() >= NumSpecialTypeIDs) {
3753 if (unsigned String = SpecialTypes[SPECIAL_TYPE_CF_CONSTANT_STRING]) {
3754 if (!Context.CFConstantStringTypeDecl)
3755 Context.setCFConstantStringType(GetType(String));
3756 }
3757
3758 if (unsigned File = SpecialTypes[SPECIAL_TYPE_FILE]) {
3759 QualType FileType = GetType(File);
3760 if (FileType.isNull()) {
3761 Error("FILE type is NULL");
3762 return;
3763 }
3764
3765 if (!Context.FILEDecl) {
3766 if (const TypedefType *Typedef = FileType->getAs<TypedefType>())
3767 Context.setFILEDecl(Typedef->getDecl());
3768 else {
3769 const TagType *Tag = FileType->getAs<TagType>();
3770 if (!Tag) {
3771 Error("Invalid FILE type in AST file");
3772 return;
3773 }
3774 Context.setFILEDecl(Tag->getDecl());
3775 }
3776 }
3777 }
3778
3779 if (unsigned Jmp_buf = SpecialTypes[SPECIAL_TYPE_JMP_BUF]) {
3780 QualType Jmp_bufType = GetType(Jmp_buf);
3781 if (Jmp_bufType.isNull()) {
3782 Error("jmp_buf type is NULL");
3783 return;
3784 }
3785
3786 if (!Context.jmp_bufDecl) {
3787 if (const TypedefType *Typedef = Jmp_bufType->getAs<TypedefType>())
3788 Context.setjmp_bufDecl(Typedef->getDecl());
3789 else {
3790 const TagType *Tag = Jmp_bufType->getAs<TagType>();
3791 if (!Tag) {
3792 Error("Invalid jmp_buf type in AST file");
3793 return;
3794 }
3795 Context.setjmp_bufDecl(Tag->getDecl());
3796 }
3797 }
3798 }
3799
3800 if (unsigned Sigjmp_buf = SpecialTypes[SPECIAL_TYPE_SIGJMP_BUF]) {
3801 QualType Sigjmp_bufType = GetType(Sigjmp_buf);
3802 if (Sigjmp_bufType.isNull()) {
3803 Error("sigjmp_buf type is NULL");
3804 return;
3805 }
3806
3807 if (!Context.sigjmp_bufDecl) {
3808 if (const TypedefType *Typedef = Sigjmp_bufType->getAs<TypedefType>())
3809 Context.setsigjmp_bufDecl(Typedef->getDecl());
3810 else {
3811 const TagType *Tag = Sigjmp_bufType->getAs<TagType>();
3812 assert(Tag && "Invalid sigjmp_buf type in AST file");
3813 Context.setsigjmp_bufDecl(Tag->getDecl());
3814 }
3815 }
3816 }
3817
3818 if (unsigned ObjCIdRedef
3819 = SpecialTypes[SPECIAL_TYPE_OBJC_ID_REDEFINITION]) {
3820 if (Context.ObjCIdRedefinitionType.isNull())
3821 Context.ObjCIdRedefinitionType = GetType(ObjCIdRedef);
3822 }
3823
3824 if (unsigned ObjCClassRedef
3825 = SpecialTypes[SPECIAL_TYPE_OBJC_CLASS_REDEFINITION]) {
3826 if (Context.ObjCClassRedefinitionType.isNull())
3827 Context.ObjCClassRedefinitionType = GetType(ObjCClassRedef);
3828 }
3829
3830 if (unsigned ObjCSelRedef
3831 = SpecialTypes[SPECIAL_TYPE_OBJC_SEL_REDEFINITION]) {
3832 if (Context.ObjCSelRedefinitionType.isNull())
3833 Context.ObjCSelRedefinitionType = GetType(ObjCSelRedef);
3834 }
3835
3836 if (unsigned Ucontext_t = SpecialTypes[SPECIAL_TYPE_UCONTEXT_T]) {
3837 QualType Ucontext_tType = GetType(Ucontext_t);
3838 if (Ucontext_tType.isNull()) {
3839 Error("ucontext_t type is NULL");
3840 return;
3841 }
3842
3843 if (!Context.ucontext_tDecl) {
3844 if (const TypedefType *Typedef = Ucontext_tType->getAs<TypedefType>())
3845 Context.setucontext_tDecl(Typedef->getDecl());
3846 else {
3847 const TagType *Tag = Ucontext_tType->getAs<TagType>();
3848 assert(Tag && "Invalid ucontext_t type in AST file");
3849 Context.setucontext_tDecl(Tag->getDecl());
3850 }
3851 }
3852 }
3853 }
3854
3855 ReadPragmaDiagnosticMappings(Context.getDiagnostics());
3856
3857 // If there were any CUDA special declarations, deserialize them.
3858 if (!CUDASpecialDeclRefs.empty()) {
3859 assert(CUDASpecialDeclRefs.size() == 1 && "More decl refs than expected!");
3860 Context.setcudaConfigureCallDecl(
3861 cast<FunctionDecl>(GetDecl(CUDASpecialDeclRefs[0])));
3862 }
Richard Smith56be7542014-03-21 00:33:59 +00003863
Guy Benyei11169dd2012-12-18 14:30:41 +00003864 // Re-export any modules that were imported by a non-module AST file.
Richard Smith56be7542014-03-21 00:33:59 +00003865 // FIXME: This does not make macro-only imports visible again. It also doesn't
3866 // make #includes mapped to module imports visible.
3867 for (auto &Import : ImportedModules) {
3868 if (Module *Imported = getSubmodule(Import.ID))
Argyrios Kyrtzidis125df052013-02-01 16:36:12 +00003869 makeModuleVisible(Imported, Module::AllVisible,
Richard Smith56be7542014-03-21 00:33:59 +00003870 /*ImportLoc=*/Import.ImportLoc,
Douglas Gregorfb912652013-03-20 21:10:35 +00003871 /*Complain=*/false);
Guy Benyei11169dd2012-12-18 14:30:41 +00003872 }
3873 ImportedModules.clear();
3874}
3875
3876void ASTReader::finalizeForWriting() {
3877 for (HiddenNamesMapType::iterator Hidden = HiddenNamesMap.begin(),
3878 HiddenEnd = HiddenNamesMap.end();
3879 Hidden != HiddenEnd; ++Hidden) {
Argyrios Kyrtzidis3a9c42c2013-03-27 01:25:34 +00003880 makeNamesVisible(Hidden->second, Hidden->first);
Guy Benyei11169dd2012-12-18 14:30:41 +00003881 }
3882 HiddenNamesMap.clear();
3883}
3884
Argyrios Kyrtzidisc4cd2c42013-05-06 19:23:40 +00003885/// \brief Given a cursor at the start of an AST file, scan ahead and drop the
3886/// cursor into the start of the given block ID, returning false on success and
3887/// true on failure.
3888static bool SkipCursorToBlock(BitstreamCursor &Cursor, unsigned BlockID) {
Chris Lattner7fb3bef2013-01-20 00:56:42 +00003889 while (1) {
3890 llvm::BitstreamEntry Entry = Cursor.advance();
3891 switch (Entry.Kind) {
3892 case llvm::BitstreamEntry::Error:
3893 case llvm::BitstreamEntry::EndBlock:
3894 return true;
3895
3896 case llvm::BitstreamEntry::Record:
3897 // Ignore top-level records.
3898 Cursor.skipRecord(Entry.ID);
3899 break;
3900
3901 case llvm::BitstreamEntry::SubBlock:
Argyrios Kyrtzidisc4cd2c42013-05-06 19:23:40 +00003902 if (Entry.ID == BlockID) {
3903 if (Cursor.EnterSubBlock(BlockID))
Chris Lattner7fb3bef2013-01-20 00:56:42 +00003904 return true;
3905 // Found it!
3906 return false;
3907 }
3908
3909 if (Cursor.SkipBlock())
3910 return true;
3911 }
3912 }
3913}
3914
Guy Benyei11169dd2012-12-18 14:30:41 +00003915/// \brief Retrieve the name of the original source file name
3916/// directly from the AST file, without actually loading the AST
3917/// file.
3918std::string ASTReader::getOriginalSourceFile(const std::string &ASTFileName,
3919 FileManager &FileMgr,
3920 DiagnosticsEngine &Diags) {
3921 // Open the AST file.
3922 std::string ErrStr;
Ahmed Charlesb8984322014-03-07 20:03:18 +00003923 std::unique_ptr<llvm::MemoryBuffer> Buffer;
Guy Benyei11169dd2012-12-18 14:30:41 +00003924 Buffer.reset(FileMgr.getBufferForFile(ASTFileName, &ErrStr));
3925 if (!Buffer) {
3926 Diags.Report(diag::err_fe_unable_to_read_pch_file) << ASTFileName << ErrStr;
3927 return std::string();
3928 }
3929
3930 // Initialize the stream
3931 llvm::BitstreamReader StreamFile;
Chris Lattner7fb3bef2013-01-20 00:56:42 +00003932 BitstreamCursor Stream;
Guy Benyei11169dd2012-12-18 14:30:41 +00003933 StreamFile.init((const unsigned char *)Buffer->getBufferStart(),
3934 (const unsigned char *)Buffer->getBufferEnd());
3935 Stream.init(StreamFile);
3936
3937 // Sniff for the signature.
3938 if (Stream.Read(8) != 'C' ||
3939 Stream.Read(8) != 'P' ||
3940 Stream.Read(8) != 'C' ||
3941 Stream.Read(8) != 'H') {
3942 Diags.Report(diag::err_fe_not_a_pch_file) << ASTFileName;
3943 return std::string();
3944 }
Chris Lattner7fb3bef2013-01-20 00:56:42 +00003945
Chris Lattnere7b154b2013-01-19 21:39:22 +00003946 // Scan for the CONTROL_BLOCK_ID block.
Argyrios Kyrtzidisc4cd2c42013-05-06 19:23:40 +00003947 if (SkipCursorToBlock(Stream, CONTROL_BLOCK_ID)) {
Chris Lattner7fb3bef2013-01-20 00:56:42 +00003948 Diags.Report(diag::err_fe_pch_malformed_block) << ASTFileName;
3949 return std::string();
Chris Lattnere7b154b2013-01-19 21:39:22 +00003950 }
Guy Benyei11169dd2012-12-18 14:30:41 +00003951
Chris Lattner7fb3bef2013-01-20 00:56:42 +00003952 // Scan for ORIGINAL_FILE inside the control block.
3953 RecordData Record;
Chris Lattnere7b154b2013-01-19 21:39:22 +00003954 while (1) {
Chris Lattner7fb3bef2013-01-20 00:56:42 +00003955 llvm::BitstreamEntry Entry = Stream.advanceSkippingSubblocks();
Chris Lattnere7b154b2013-01-19 21:39:22 +00003956 if (Entry.Kind == llvm::BitstreamEntry::EndBlock)
3957 return std::string();
3958
3959 if (Entry.Kind != llvm::BitstreamEntry::Record) {
3960 Diags.Report(diag::err_fe_pch_malformed_block) << ASTFileName;
3961 return std::string();
Guy Benyei11169dd2012-12-18 14:30:41 +00003962 }
Chris Lattnere7b154b2013-01-19 21:39:22 +00003963
Guy Benyei11169dd2012-12-18 14:30:41 +00003964 Record.clear();
Chris Lattner0e6c9402013-01-20 02:38:54 +00003965 StringRef Blob;
3966 if (Stream.readRecord(Entry.ID, Record, &Blob) == ORIGINAL_FILE)
3967 return Blob.str();
Guy Benyei11169dd2012-12-18 14:30:41 +00003968 }
Guy Benyei11169dd2012-12-18 14:30:41 +00003969}
3970
3971namespace {
3972 class SimplePCHValidator : public ASTReaderListener {
3973 const LangOptions &ExistingLangOpts;
3974 const TargetOptions &ExistingTargetOpts;
3975 const PreprocessorOptions &ExistingPPOpts;
3976 FileManager &FileMgr;
3977
3978 public:
3979 SimplePCHValidator(const LangOptions &ExistingLangOpts,
3980 const TargetOptions &ExistingTargetOpts,
3981 const PreprocessorOptions &ExistingPPOpts,
3982 FileManager &FileMgr)
3983 : ExistingLangOpts(ExistingLangOpts),
3984 ExistingTargetOpts(ExistingTargetOpts),
3985 ExistingPPOpts(ExistingPPOpts),
3986 FileMgr(FileMgr)
3987 {
3988 }
3989
Craig Topper3e89dfe2014-03-13 02:13:41 +00003990 bool ReadLanguageOptions(const LangOptions &LangOpts,
3991 bool Complain) override {
Guy Benyei11169dd2012-12-18 14:30:41 +00003992 return checkLanguageOptions(ExistingLangOpts, LangOpts, 0);
3993 }
Craig Topper3e89dfe2014-03-13 02:13:41 +00003994 bool ReadTargetOptions(const TargetOptions &TargetOpts,
3995 bool Complain) override {
Guy Benyei11169dd2012-12-18 14:30:41 +00003996 return checkTargetOptions(ExistingTargetOpts, TargetOpts, 0);
3997 }
Craig Topper3e89dfe2014-03-13 02:13:41 +00003998 bool ReadPreprocessorOptions(const PreprocessorOptions &PPOpts,
3999 bool Complain,
4000 std::string &SuggestedPredefines) override {
Guy Benyei11169dd2012-12-18 14:30:41 +00004001 return checkPreprocessorOptions(ExistingPPOpts, PPOpts, 0, FileMgr,
Argyrios Kyrtzidisd3afa0c2013-04-26 21:33:40 +00004002 SuggestedPredefines, ExistingLangOpts);
Guy Benyei11169dd2012-12-18 14:30:41 +00004003 }
4004 };
4005}
4006
4007bool ASTReader::readASTFileControlBlock(StringRef Filename,
4008 FileManager &FileMgr,
4009 ASTReaderListener &Listener) {
4010 // Open the AST file.
4011 std::string ErrStr;
Ahmed Charlesb8984322014-03-07 20:03:18 +00004012 std::unique_ptr<llvm::MemoryBuffer> Buffer;
Guy Benyei11169dd2012-12-18 14:30:41 +00004013 Buffer.reset(FileMgr.getBufferForFile(Filename, &ErrStr));
4014 if (!Buffer) {
4015 return true;
4016 }
4017
4018 // Initialize the stream
4019 llvm::BitstreamReader StreamFile;
Chris Lattner7fb3bef2013-01-20 00:56:42 +00004020 BitstreamCursor Stream;
Guy Benyei11169dd2012-12-18 14:30:41 +00004021 StreamFile.init((const unsigned char *)Buffer->getBufferStart(),
4022 (const unsigned char *)Buffer->getBufferEnd());
4023 Stream.init(StreamFile);
4024
4025 // Sniff for the signature.
4026 if (Stream.Read(8) != 'C' ||
4027 Stream.Read(8) != 'P' ||
4028 Stream.Read(8) != 'C' ||
4029 Stream.Read(8) != 'H') {
4030 return true;
4031 }
4032
Chris Lattner7fb3bef2013-01-20 00:56:42 +00004033 // Scan for the CONTROL_BLOCK_ID block.
Argyrios Kyrtzidisc4cd2c42013-05-06 19:23:40 +00004034 if (SkipCursorToBlock(Stream, CONTROL_BLOCK_ID))
Chris Lattner7fb3bef2013-01-20 00:56:42 +00004035 return true;
Argyrios Kyrtzidisc4cd2c42013-05-06 19:23:40 +00004036
4037 bool NeedsInputFiles = Listener.needsInputFileVisitation();
Ben Langmuircb69b572014-03-07 06:40:32 +00004038 bool NeedsSystemInputFiles = Listener.needsSystemInputFileVisitation();
Argyrios Kyrtzidisc4cd2c42013-05-06 19:23:40 +00004039 BitstreamCursor InputFilesCursor;
4040 if (NeedsInputFiles) {
4041 InputFilesCursor = Stream;
4042 if (SkipCursorToBlock(InputFilesCursor, INPUT_FILES_BLOCK_ID))
4043 return true;
4044
4045 // Read the abbreviations
4046 while (true) {
4047 uint64_t Offset = InputFilesCursor.GetCurrentBitNo();
4048 unsigned Code = InputFilesCursor.ReadCode();
4049
4050 // We expect all abbrevs to be at the start of the block.
4051 if (Code != llvm::bitc::DEFINE_ABBREV) {
4052 InputFilesCursor.JumpToBit(Offset);
4053 break;
4054 }
4055 InputFilesCursor.ReadAbbrevRecord();
4056 }
4057 }
Chris Lattner7fb3bef2013-01-20 00:56:42 +00004058
4059 // Scan for ORIGINAL_FILE inside the control block.
Guy Benyei11169dd2012-12-18 14:30:41 +00004060 RecordData Record;
Chris Lattner7fb3bef2013-01-20 00:56:42 +00004061 while (1) {
4062 llvm::BitstreamEntry Entry = Stream.advanceSkippingSubblocks();
4063 if (Entry.Kind == llvm::BitstreamEntry::EndBlock)
4064 return false;
4065
4066 if (Entry.Kind != llvm::BitstreamEntry::Record)
4067 return true;
4068
Guy Benyei11169dd2012-12-18 14:30:41 +00004069 Record.clear();
Chris Lattner0e6c9402013-01-20 02:38:54 +00004070 StringRef Blob;
4071 unsigned RecCode = Stream.readRecord(Entry.ID, Record, &Blob);
Chris Lattner7fb3bef2013-01-20 00:56:42 +00004072 switch ((ControlRecordTypes)RecCode) {
4073 case METADATA: {
4074 if (Record[0] != VERSION_MAJOR)
4075 return true;
Guy Benyei11169dd2012-12-18 14:30:41 +00004076
Douglas Gregorbf7fc9c2013-03-27 16:47:18 +00004077 if (Listener.ReadFullVersionInformation(Blob))
Chris Lattner7fb3bef2013-01-20 00:56:42 +00004078 return true;
Douglas Gregorbf7fc9c2013-03-27 16:47:18 +00004079
Chris Lattner7fb3bef2013-01-20 00:56:42 +00004080 break;
4081 }
Ben Langmuir4f5212a2014-04-14 22:12:44 +00004082 case MODULE_NAME:
4083 Listener.ReadModuleName(Blob);
4084 break;
4085 case MODULE_MAP_FILE:
4086 Listener.ReadModuleMapFile(Blob);
4087 break;
Chris Lattner7fb3bef2013-01-20 00:56:42 +00004088 case LANGUAGE_OPTIONS:
4089 if (ParseLanguageOptions(Record, false, Listener))
4090 return true;
4091 break;
Guy Benyei11169dd2012-12-18 14:30:41 +00004092
Chris Lattner7fb3bef2013-01-20 00:56:42 +00004093 case TARGET_OPTIONS:
4094 if (ParseTargetOptions(Record, false, Listener))
4095 return true;
4096 break;
Guy Benyei11169dd2012-12-18 14:30:41 +00004097
Chris Lattner7fb3bef2013-01-20 00:56:42 +00004098 case DIAGNOSTIC_OPTIONS:
4099 if (ParseDiagnosticOptions(Record, false, Listener))
4100 return true;
4101 break;
Guy Benyei11169dd2012-12-18 14:30:41 +00004102
Chris Lattner7fb3bef2013-01-20 00:56:42 +00004103 case FILE_SYSTEM_OPTIONS:
4104 if (ParseFileSystemOptions(Record, false, Listener))
4105 return true;
4106 break;
Guy Benyei11169dd2012-12-18 14:30:41 +00004107
Chris Lattner7fb3bef2013-01-20 00:56:42 +00004108 case HEADER_SEARCH_OPTIONS:
4109 if (ParseHeaderSearchOptions(Record, false, Listener))
4110 return true;
4111 break;
Guy Benyei11169dd2012-12-18 14:30:41 +00004112
Chris Lattner7fb3bef2013-01-20 00:56:42 +00004113 case PREPROCESSOR_OPTIONS: {
4114 std::string IgnoredSuggestedPredefines;
4115 if (ParsePreprocessorOptions(Record, false, Listener,
4116 IgnoredSuggestedPredefines))
4117 return true;
4118 break;
4119 }
Guy Benyei11169dd2012-12-18 14:30:41 +00004120
Argyrios Kyrtzidisc4cd2c42013-05-06 19:23:40 +00004121 case INPUT_FILE_OFFSETS: {
4122 if (!NeedsInputFiles)
4123 break;
4124
4125 unsigned NumInputFiles = Record[0];
4126 unsigned NumUserFiles = Record[1];
4127 const uint32_t *InputFileOffs = (const uint32_t *)Blob.data();
4128 for (unsigned I = 0; I != NumInputFiles; ++I) {
4129 // Go find this input file.
4130 bool isSystemFile = I >= NumUserFiles;
Ben Langmuircb69b572014-03-07 06:40:32 +00004131
4132 if (isSystemFile && !NeedsSystemInputFiles)
4133 break; // the rest are system input files
4134
Argyrios Kyrtzidisc4cd2c42013-05-06 19:23:40 +00004135 BitstreamCursor &Cursor = InputFilesCursor;
4136 SavedStreamPosition SavedPosition(Cursor);
4137 Cursor.JumpToBit(InputFileOffs[I]);
4138
4139 unsigned Code = Cursor.ReadCode();
4140 RecordData Record;
4141 StringRef Blob;
4142 bool shouldContinue = false;
4143 switch ((InputFileRecordTypes)Cursor.readRecord(Code, Record, &Blob)) {
4144 case INPUT_FILE:
Argyrios Kyrtzidis68ccbe02014-03-14 02:26:31 +00004145 bool Overridden = static_cast<bool>(Record[3]);
4146 shouldContinue = Listener.visitInputFile(Blob, isSystemFile, Overridden);
Argyrios Kyrtzidisc4cd2c42013-05-06 19:23:40 +00004147 break;
4148 }
4149 if (!shouldContinue)
4150 break;
4151 }
4152 break;
4153 }
4154
Chris Lattner7fb3bef2013-01-20 00:56:42 +00004155 default:
4156 // No other validation to perform.
4157 break;
Guy Benyei11169dd2012-12-18 14:30:41 +00004158 }
4159 }
Guy Benyei11169dd2012-12-18 14:30:41 +00004160}
4161
4162
4163bool ASTReader::isAcceptableASTFile(StringRef Filename,
4164 FileManager &FileMgr,
4165 const LangOptions &LangOpts,
4166 const TargetOptions &TargetOpts,
4167 const PreprocessorOptions &PPOpts) {
4168 SimplePCHValidator validator(LangOpts, TargetOpts, PPOpts, FileMgr);
4169 return !readASTFileControlBlock(Filename, FileMgr, validator);
4170}
4171
Ben Langmuir2c9af442014-04-10 17:57:43 +00004172ASTReader::ASTReadResult
4173ASTReader::ReadSubmoduleBlock(ModuleFile &F, unsigned ClientLoadCapabilities) {
Guy Benyei11169dd2012-12-18 14:30:41 +00004174 // Enter the submodule block.
4175 if (F.Stream.EnterSubBlock(SUBMODULE_BLOCK_ID)) {
4176 Error("malformed submodule block record in AST file");
Ben Langmuir2c9af442014-04-10 17:57:43 +00004177 return Failure;
Guy Benyei11169dd2012-12-18 14:30:41 +00004178 }
4179
4180 ModuleMap &ModMap = PP.getHeaderSearchInfo().getModuleMap();
4181 bool First = true;
4182 Module *CurrentModule = 0;
4183 RecordData Record;
4184 while (true) {
Chris Lattner7fb3bef2013-01-20 00:56:42 +00004185 llvm::BitstreamEntry Entry = F.Stream.advanceSkippingSubblocks();
4186
4187 switch (Entry.Kind) {
4188 case llvm::BitstreamEntry::SubBlock: // Handled for us already.
4189 case llvm::BitstreamEntry::Error:
4190 Error("malformed block record in AST file");
Ben Langmuir2c9af442014-04-10 17:57:43 +00004191 return Failure;
Chris Lattner7fb3bef2013-01-20 00:56:42 +00004192 case llvm::BitstreamEntry::EndBlock:
Ben Langmuir2c9af442014-04-10 17:57:43 +00004193 return Success;
Chris Lattner7fb3bef2013-01-20 00:56:42 +00004194 case llvm::BitstreamEntry::Record:
4195 // The interesting case.
4196 break;
Guy Benyei11169dd2012-12-18 14:30:41 +00004197 }
Chris Lattner7fb3bef2013-01-20 00:56:42 +00004198
Guy Benyei11169dd2012-12-18 14:30:41 +00004199 // Read a record.
Chris Lattner0e6c9402013-01-20 02:38:54 +00004200 StringRef Blob;
Guy Benyei11169dd2012-12-18 14:30:41 +00004201 Record.clear();
Chris Lattner0e6c9402013-01-20 02:38:54 +00004202 switch (F.Stream.readRecord(Entry.ID, Record, &Blob)) {
Guy Benyei11169dd2012-12-18 14:30:41 +00004203 default: // Default behavior: ignore.
4204 break;
4205
4206 case SUBMODULE_DEFINITION: {
4207 if (First) {
4208 Error("missing submodule metadata record at beginning of block");
Ben Langmuir2c9af442014-04-10 17:57:43 +00004209 return Failure;
Guy Benyei11169dd2012-12-18 14:30:41 +00004210 }
4211
Douglas Gregor8d932422013-03-20 03:59:18 +00004212 if (Record.size() < 8) {
Guy Benyei11169dd2012-12-18 14:30:41 +00004213 Error("malformed module definition");
Ben Langmuir2c9af442014-04-10 17:57:43 +00004214 return Failure;
Guy Benyei11169dd2012-12-18 14:30:41 +00004215 }
4216
Chris Lattner0e6c9402013-01-20 02:38:54 +00004217 StringRef Name = Blob;
Richard Smith9bca2982014-03-08 00:03:56 +00004218 unsigned Idx = 0;
4219 SubmoduleID GlobalID = getGlobalSubmoduleID(F, Record[Idx++]);
4220 SubmoduleID Parent = getGlobalSubmoduleID(F, Record[Idx++]);
4221 bool IsFramework = Record[Idx++];
4222 bool IsExplicit = Record[Idx++];
4223 bool IsSystem = Record[Idx++];
4224 bool IsExternC = Record[Idx++];
4225 bool InferSubmodules = Record[Idx++];
4226 bool InferExplicitSubmodules = Record[Idx++];
4227 bool InferExportWildcard = Record[Idx++];
4228 bool ConfigMacrosExhaustive = Record[Idx++];
Douglas Gregor8d932422013-03-20 03:59:18 +00004229
Ben Langmuirbeee15e2014-04-14 18:00:01 +00004230 Module *ParentModule = nullptr;
4231 const FileEntry *ModuleMap = nullptr;
4232 if (Parent) {
Guy Benyei11169dd2012-12-18 14:30:41 +00004233 ParentModule = getSubmodule(Parent);
Ben Langmuirbeee15e2014-04-14 18:00:01 +00004234 ModuleMap = ParentModule->ModuleMap;
4235 }
4236
4237 if (!F.ModuleMapPath.empty())
4238 ModuleMap = FileMgr.getFile(F.ModuleMapPath);
4239
Guy Benyei11169dd2012-12-18 14:30:41 +00004240 // Retrieve this (sub)module from the module map, creating it if
4241 // necessary.
Ben Langmuirbeee15e2014-04-14 18:00:01 +00004242 CurrentModule = ModMap.findOrCreateModule(Name, ParentModule, ModuleMap,
Guy Benyei11169dd2012-12-18 14:30:41 +00004243 IsFramework,
4244 IsExplicit).first;
4245 SubmoduleID GlobalIndex = GlobalID - NUM_PREDEF_SUBMODULE_IDS;
4246 if (GlobalIndex >= SubmodulesLoaded.size() ||
4247 SubmodulesLoaded[GlobalIndex]) {
4248 Error("too many submodules");
Ben Langmuir2c9af442014-04-10 17:57:43 +00004249 return Failure;
Guy Benyei11169dd2012-12-18 14:30:41 +00004250 }
Douglas Gregor8a114ab2013-02-06 22:40:31 +00004251
Douglas Gregor7029ce12013-03-19 00:28:20 +00004252 if (!ParentModule) {
4253 if (const FileEntry *CurFile = CurrentModule->getASTFile()) {
4254 if (CurFile != F.File) {
4255 if (!Diags.isDiagnosticInFlight()) {
4256 Diag(diag::err_module_file_conflict)
4257 << CurrentModule->getTopLevelModuleName()
4258 << CurFile->getName()
4259 << F.File->getName();
4260 }
Ben Langmuir2c9af442014-04-10 17:57:43 +00004261 return Failure;
Douglas Gregor8a114ab2013-02-06 22:40:31 +00004262 }
Douglas Gregor8a114ab2013-02-06 22:40:31 +00004263 }
Douglas Gregor7029ce12013-03-19 00:28:20 +00004264
4265 CurrentModule->setASTFile(F.File);
Douglas Gregor8a114ab2013-02-06 22:40:31 +00004266 }
Ben Langmuirbeee15e2014-04-14 18:00:01 +00004267
Guy Benyei11169dd2012-12-18 14:30:41 +00004268 CurrentModule->IsFromModuleFile = true;
4269 CurrentModule->IsSystem = IsSystem || CurrentModule->IsSystem;
Richard Smith9bca2982014-03-08 00:03:56 +00004270 CurrentModule->IsExternC = IsExternC;
Guy Benyei11169dd2012-12-18 14:30:41 +00004271 CurrentModule->InferSubmodules = InferSubmodules;
4272 CurrentModule->InferExplicitSubmodules = InferExplicitSubmodules;
4273 CurrentModule->InferExportWildcard = InferExportWildcard;
Douglas Gregor8d932422013-03-20 03:59:18 +00004274 CurrentModule->ConfigMacrosExhaustive = ConfigMacrosExhaustive;
Guy Benyei11169dd2012-12-18 14:30:41 +00004275 if (DeserializationListener)
4276 DeserializationListener->ModuleRead(GlobalID, CurrentModule);
4277
4278 SubmodulesLoaded[GlobalIndex] = CurrentModule;
Douglas Gregor6ddfca92013-01-14 17:21:00 +00004279
Douglas Gregorfb912652013-03-20 21:10:35 +00004280 // Clear out data that will be replaced by what is the module file.
Douglas Gregor6ddfca92013-01-14 17:21:00 +00004281 CurrentModule->LinkLibraries.clear();
Douglas Gregor8d932422013-03-20 03:59:18 +00004282 CurrentModule->ConfigMacros.clear();
Douglas Gregorfb912652013-03-20 21:10:35 +00004283 CurrentModule->UnresolvedConflicts.clear();
4284 CurrentModule->Conflicts.clear();
Guy Benyei11169dd2012-12-18 14:30:41 +00004285 break;
4286 }
4287
4288 case SUBMODULE_UMBRELLA_HEADER: {
4289 if (First) {
4290 Error("missing submodule metadata record at beginning of block");
Ben Langmuir2c9af442014-04-10 17:57:43 +00004291 return Failure;
Guy Benyei11169dd2012-12-18 14:30:41 +00004292 }
4293
4294 if (!CurrentModule)
4295 break;
4296
Chris Lattner0e6c9402013-01-20 02:38:54 +00004297 if (const FileEntry *Umbrella = PP.getFileManager().getFile(Blob)) {
Guy Benyei11169dd2012-12-18 14:30:41 +00004298 if (!CurrentModule->getUmbrellaHeader())
4299 ModMap.setUmbrellaHeader(CurrentModule, Umbrella);
4300 else if (CurrentModule->getUmbrellaHeader() != Umbrella) {
Ben Langmuir2c9af442014-04-10 17:57:43 +00004301 if ((ClientLoadCapabilities & ARR_OutOfDate) == 0)
4302 Error("mismatched umbrella headers in submodule");
4303 return OutOfDate;
Guy Benyei11169dd2012-12-18 14:30:41 +00004304 }
4305 }
4306 break;
4307 }
4308
4309 case SUBMODULE_HEADER: {
4310 if (First) {
4311 Error("missing submodule metadata record at beginning of block");
Ben Langmuir2c9af442014-04-10 17:57:43 +00004312 return Failure;
Guy Benyei11169dd2012-12-18 14:30:41 +00004313 }
4314
4315 if (!CurrentModule)
4316 break;
4317
Argyrios Kyrtzidisb146baa2013-03-13 21:13:51 +00004318 // We lazily associate headers with their modules via the HeaderInfoTable.
4319 // FIXME: Re-evaluate this section; maybe only store InputFile IDs instead
4320 // of complete filenames or remove it entirely.
Guy Benyei11169dd2012-12-18 14:30:41 +00004321 break;
4322 }
4323
4324 case SUBMODULE_EXCLUDED_HEADER: {
4325 if (First) {
4326 Error("missing submodule metadata record at beginning of block");
Ben Langmuir2c9af442014-04-10 17:57:43 +00004327 return Failure;
Guy Benyei11169dd2012-12-18 14:30:41 +00004328 }
4329
4330 if (!CurrentModule)
4331 break;
4332
Argyrios Kyrtzidisb146baa2013-03-13 21:13:51 +00004333 // We lazily associate headers with their modules via the HeaderInfoTable.
4334 // FIXME: Re-evaluate this section; maybe only store InputFile IDs instead
4335 // of complete filenames or remove it entirely.
Guy Benyei11169dd2012-12-18 14:30:41 +00004336 break;
4337 }
4338
Lawrence Crowlb53e5482013-06-20 21:14:14 +00004339 case SUBMODULE_PRIVATE_HEADER: {
4340 if (First) {
4341 Error("missing submodule metadata record at beginning of block");
Ben Langmuir2c9af442014-04-10 17:57:43 +00004342 return Failure;
Lawrence Crowlb53e5482013-06-20 21:14:14 +00004343 }
4344
4345 if (!CurrentModule)
4346 break;
4347
4348 // We lazily associate headers with their modules via the HeaderInfoTable.
4349 // FIXME: Re-evaluate this section; maybe only store InputFile IDs instead
4350 // of complete filenames or remove it entirely.
4351 break;
4352 }
4353
Guy Benyei11169dd2012-12-18 14:30:41 +00004354 case SUBMODULE_TOPHEADER: {
4355 if (First) {
4356 Error("missing submodule metadata record at beginning of block");
Ben Langmuir2c9af442014-04-10 17:57:43 +00004357 return Failure;
Guy Benyei11169dd2012-12-18 14:30:41 +00004358 }
4359
4360 if (!CurrentModule)
4361 break;
4362
Argyrios Kyrtzidis3c5305c2013-03-13 21:13:43 +00004363 CurrentModule->addTopHeaderFilename(Blob);
Guy Benyei11169dd2012-12-18 14:30:41 +00004364 break;
4365 }
4366
4367 case SUBMODULE_UMBRELLA_DIR: {
4368 if (First) {
4369 Error("missing submodule metadata record at beginning of block");
Ben Langmuir2c9af442014-04-10 17:57:43 +00004370 return Failure;
Guy Benyei11169dd2012-12-18 14:30:41 +00004371 }
4372
4373 if (!CurrentModule)
4374 break;
4375
Guy Benyei11169dd2012-12-18 14:30:41 +00004376 if (const DirectoryEntry *Umbrella
Chris Lattner0e6c9402013-01-20 02:38:54 +00004377 = PP.getFileManager().getDirectory(Blob)) {
Guy Benyei11169dd2012-12-18 14:30:41 +00004378 if (!CurrentModule->getUmbrellaDir())
4379 ModMap.setUmbrellaDir(CurrentModule, Umbrella);
4380 else if (CurrentModule->getUmbrellaDir() != Umbrella) {
Ben Langmuir2c9af442014-04-10 17:57:43 +00004381 if ((ClientLoadCapabilities & ARR_OutOfDate) == 0)
4382 Error("mismatched umbrella directories in submodule");
4383 return OutOfDate;
Guy Benyei11169dd2012-12-18 14:30:41 +00004384 }
4385 }
4386 break;
4387 }
4388
4389 case SUBMODULE_METADATA: {
4390 if (!First) {
4391 Error("submodule metadata record not at beginning of block");
Ben Langmuir2c9af442014-04-10 17:57:43 +00004392 return Failure;
Guy Benyei11169dd2012-12-18 14:30:41 +00004393 }
4394 First = false;
4395
4396 F.BaseSubmoduleID = getTotalNumSubmodules();
4397 F.LocalNumSubmodules = Record[0];
4398 unsigned LocalBaseSubmoduleID = Record[1];
4399 if (F.LocalNumSubmodules > 0) {
4400 // Introduce the global -> local mapping for submodules within this
4401 // module.
4402 GlobalSubmoduleMap.insert(std::make_pair(getTotalNumSubmodules()+1,&F));
4403
4404 // Introduce the local -> global mapping for submodules within this
4405 // module.
4406 F.SubmoduleRemap.insertOrReplace(
4407 std::make_pair(LocalBaseSubmoduleID,
4408 F.BaseSubmoduleID - LocalBaseSubmoduleID));
4409
4410 SubmodulesLoaded.resize(SubmodulesLoaded.size() + F.LocalNumSubmodules);
4411 }
4412 break;
4413 }
4414
4415 case SUBMODULE_IMPORTS: {
4416 if (First) {
4417 Error("missing submodule metadata record at beginning of block");
Ben Langmuir2c9af442014-04-10 17:57:43 +00004418 return Failure;
Guy Benyei11169dd2012-12-18 14:30:41 +00004419 }
4420
4421 if (!CurrentModule)
4422 break;
4423
4424 for (unsigned Idx = 0; Idx != Record.size(); ++Idx) {
Douglas Gregorfb912652013-03-20 21:10:35 +00004425 UnresolvedModuleRef Unresolved;
Guy Benyei11169dd2012-12-18 14:30:41 +00004426 Unresolved.File = &F;
4427 Unresolved.Mod = CurrentModule;
4428 Unresolved.ID = Record[Idx];
Douglas Gregorfb912652013-03-20 21:10:35 +00004429 Unresolved.Kind = UnresolvedModuleRef::Import;
Guy Benyei11169dd2012-12-18 14:30:41 +00004430 Unresolved.IsWildcard = false;
Douglas Gregorfb912652013-03-20 21:10:35 +00004431 UnresolvedModuleRefs.push_back(Unresolved);
Guy Benyei11169dd2012-12-18 14:30:41 +00004432 }
4433 break;
4434 }
4435
4436 case SUBMODULE_EXPORTS: {
4437 if (First) {
4438 Error("missing submodule metadata record at beginning of block");
Ben Langmuir2c9af442014-04-10 17:57:43 +00004439 return Failure;
Guy Benyei11169dd2012-12-18 14:30:41 +00004440 }
4441
4442 if (!CurrentModule)
4443 break;
4444
4445 for (unsigned Idx = 0; Idx + 1 < Record.size(); Idx += 2) {
Douglas Gregorfb912652013-03-20 21:10:35 +00004446 UnresolvedModuleRef Unresolved;
Guy Benyei11169dd2012-12-18 14:30:41 +00004447 Unresolved.File = &F;
4448 Unresolved.Mod = CurrentModule;
4449 Unresolved.ID = Record[Idx];
Douglas Gregorfb912652013-03-20 21:10:35 +00004450 Unresolved.Kind = UnresolvedModuleRef::Export;
Guy Benyei11169dd2012-12-18 14:30:41 +00004451 Unresolved.IsWildcard = Record[Idx + 1];
Douglas Gregorfb912652013-03-20 21:10:35 +00004452 UnresolvedModuleRefs.push_back(Unresolved);
Guy Benyei11169dd2012-12-18 14:30:41 +00004453 }
4454
4455 // Once we've loaded the set of exports, there's no reason to keep
4456 // the parsed, unresolved exports around.
4457 CurrentModule->UnresolvedExports.clear();
4458 break;
4459 }
4460 case SUBMODULE_REQUIRES: {
4461 if (First) {
4462 Error("missing submodule metadata record at beginning of block");
Ben Langmuir2c9af442014-04-10 17:57:43 +00004463 return Failure;
Guy Benyei11169dd2012-12-18 14:30:41 +00004464 }
4465
4466 if (!CurrentModule)
4467 break;
4468
Richard Smitha3feee22013-10-28 22:18:19 +00004469 CurrentModule->addRequirement(Blob, Record[0], Context.getLangOpts(),
Guy Benyei11169dd2012-12-18 14:30:41 +00004470 Context.getTargetInfo());
4471 break;
4472 }
Douglas Gregor6ddfca92013-01-14 17:21:00 +00004473
4474 case SUBMODULE_LINK_LIBRARY:
4475 if (First) {
4476 Error("missing submodule metadata record at beginning of block");
Ben Langmuir2c9af442014-04-10 17:57:43 +00004477 return Failure;
Douglas Gregor6ddfca92013-01-14 17:21:00 +00004478 }
4479
4480 if (!CurrentModule)
4481 break;
4482
4483 CurrentModule->LinkLibraries.push_back(
Chris Lattner0e6c9402013-01-20 02:38:54 +00004484 Module::LinkLibrary(Blob, Record[0]));
Douglas Gregor6ddfca92013-01-14 17:21:00 +00004485 break;
Douglas Gregor35b13ec2013-03-20 00:22:05 +00004486
4487 case SUBMODULE_CONFIG_MACRO:
4488 if (First) {
4489 Error("missing submodule metadata record at beginning of block");
Ben Langmuir2c9af442014-04-10 17:57:43 +00004490 return Failure;
Douglas Gregor35b13ec2013-03-20 00:22:05 +00004491 }
4492
4493 if (!CurrentModule)
4494 break;
4495
4496 CurrentModule->ConfigMacros.push_back(Blob.str());
4497 break;
Douglas Gregorfb912652013-03-20 21:10:35 +00004498
4499 case SUBMODULE_CONFLICT: {
4500 if (First) {
4501 Error("missing submodule metadata record at beginning of block");
Ben Langmuir2c9af442014-04-10 17:57:43 +00004502 return Failure;
Douglas Gregorfb912652013-03-20 21:10:35 +00004503 }
4504
4505 if (!CurrentModule)
4506 break;
4507
4508 UnresolvedModuleRef Unresolved;
4509 Unresolved.File = &F;
4510 Unresolved.Mod = CurrentModule;
4511 Unresolved.ID = Record[0];
4512 Unresolved.Kind = UnresolvedModuleRef::Conflict;
4513 Unresolved.IsWildcard = false;
4514 Unresolved.String = Blob;
4515 UnresolvedModuleRefs.push_back(Unresolved);
4516 break;
4517 }
Guy Benyei11169dd2012-12-18 14:30:41 +00004518 }
4519 }
4520}
4521
4522/// \brief Parse the record that corresponds to a LangOptions data
4523/// structure.
4524///
4525/// This routine parses the language options from the AST file and then gives
4526/// them to the AST listener if one is set.
4527///
4528/// \returns true if the listener deems the file unacceptable, false otherwise.
4529bool ASTReader::ParseLanguageOptions(const RecordData &Record,
4530 bool Complain,
4531 ASTReaderListener &Listener) {
4532 LangOptions LangOpts;
4533 unsigned Idx = 0;
4534#define LANGOPT(Name, Bits, Default, Description) \
4535 LangOpts.Name = Record[Idx++];
4536#define ENUM_LANGOPT(Name, Type, Bits, Default, Description) \
4537 LangOpts.set##Name(static_cast<LangOptions::Type>(Record[Idx++]));
4538#include "clang/Basic/LangOptions.def"
Will Dietzf54319c2013-01-18 11:30:38 +00004539#define SANITIZER(NAME, ID) LangOpts.Sanitize.ID = Record[Idx++];
4540#include "clang/Basic/Sanitizers.def"
Guy Benyei11169dd2012-12-18 14:30:41 +00004541
4542 ObjCRuntime::Kind runtimeKind = (ObjCRuntime::Kind) Record[Idx++];
4543 VersionTuple runtimeVersion = ReadVersionTuple(Record, Idx);
4544 LangOpts.ObjCRuntime = ObjCRuntime(runtimeKind, runtimeVersion);
4545
4546 unsigned Length = Record[Idx++];
4547 LangOpts.CurrentModule.assign(Record.begin() + Idx,
4548 Record.begin() + Idx + Length);
Dmitri Gribenkoacf2e782013-02-22 14:21:27 +00004549
4550 Idx += Length;
4551
4552 // Comment options.
4553 for (unsigned N = Record[Idx++]; N; --N) {
4554 LangOpts.CommentOpts.BlockCommandNames.push_back(
4555 ReadString(Record, Idx));
4556 }
Dmitri Gribenkoa7d16ce2013-04-10 15:35:17 +00004557 LangOpts.CommentOpts.ParseAllComments = Record[Idx++];
Dmitri Gribenkoacf2e782013-02-22 14:21:27 +00004558
Guy Benyei11169dd2012-12-18 14:30:41 +00004559 return Listener.ReadLanguageOptions(LangOpts, Complain);
4560}
4561
4562bool ASTReader::ParseTargetOptions(const RecordData &Record,
4563 bool Complain,
4564 ASTReaderListener &Listener) {
4565 unsigned Idx = 0;
4566 TargetOptions TargetOpts;
4567 TargetOpts.Triple = ReadString(Record, Idx);
4568 TargetOpts.CPU = ReadString(Record, Idx);
4569 TargetOpts.ABI = ReadString(Record, Idx);
Guy Benyei11169dd2012-12-18 14:30:41 +00004570 for (unsigned N = Record[Idx++]; N; --N) {
4571 TargetOpts.FeaturesAsWritten.push_back(ReadString(Record, Idx));
4572 }
4573 for (unsigned N = Record[Idx++]; N; --N) {
4574 TargetOpts.Features.push_back(ReadString(Record, Idx));
4575 }
4576
4577 return Listener.ReadTargetOptions(TargetOpts, Complain);
4578}
4579
4580bool ASTReader::ParseDiagnosticOptions(const RecordData &Record, bool Complain,
4581 ASTReaderListener &Listener) {
Ben Langmuirb92de022014-04-29 16:25:26 +00004582 IntrusiveRefCntPtr<DiagnosticOptions> DiagOpts(new DiagnosticOptions);
Guy Benyei11169dd2012-12-18 14:30:41 +00004583 unsigned Idx = 0;
Ben Langmuirb92de022014-04-29 16:25:26 +00004584#define DIAGOPT(Name, Bits, Default) DiagOpts->Name = Record[Idx++];
Guy Benyei11169dd2012-12-18 14:30:41 +00004585#define ENUM_DIAGOPT(Name, Type, Bits, Default) \
Ben Langmuirb92de022014-04-29 16:25:26 +00004586 DiagOpts->set##Name(static_cast<Type>(Record[Idx++]));
Guy Benyei11169dd2012-12-18 14:30:41 +00004587#include "clang/Basic/DiagnosticOptions.def"
4588
4589 for (unsigned N = Record[Idx++]; N; --N) {
Ben Langmuirb92de022014-04-29 16:25:26 +00004590 DiagOpts->Warnings.push_back(ReadString(Record, Idx));
Guy Benyei11169dd2012-12-18 14:30:41 +00004591 }
4592
4593 return Listener.ReadDiagnosticOptions(DiagOpts, Complain);
4594}
4595
4596bool ASTReader::ParseFileSystemOptions(const RecordData &Record, bool Complain,
4597 ASTReaderListener &Listener) {
4598 FileSystemOptions FSOpts;
4599 unsigned Idx = 0;
4600 FSOpts.WorkingDir = ReadString(Record, Idx);
4601 return Listener.ReadFileSystemOptions(FSOpts, Complain);
4602}
4603
4604bool ASTReader::ParseHeaderSearchOptions(const RecordData &Record,
4605 bool Complain,
4606 ASTReaderListener &Listener) {
4607 HeaderSearchOptions HSOpts;
4608 unsigned Idx = 0;
4609 HSOpts.Sysroot = ReadString(Record, Idx);
4610
4611 // Include entries.
4612 for (unsigned N = Record[Idx++]; N; --N) {
4613 std::string Path = ReadString(Record, Idx);
4614 frontend::IncludeDirGroup Group
4615 = static_cast<frontend::IncludeDirGroup>(Record[Idx++]);
Guy Benyei11169dd2012-12-18 14:30:41 +00004616 bool IsFramework = Record[Idx++];
4617 bool IgnoreSysRoot = Record[Idx++];
Guy Benyei11169dd2012-12-18 14:30:41 +00004618 HSOpts.UserEntries.push_back(
Daniel Dunbar53681732013-01-30 00:34:26 +00004619 HeaderSearchOptions::Entry(Path, Group, IsFramework, IgnoreSysRoot));
Guy Benyei11169dd2012-12-18 14:30:41 +00004620 }
4621
4622 // System header prefixes.
4623 for (unsigned N = Record[Idx++]; N; --N) {
4624 std::string Prefix = ReadString(Record, Idx);
4625 bool IsSystemHeader = Record[Idx++];
4626 HSOpts.SystemHeaderPrefixes.push_back(
4627 HeaderSearchOptions::SystemHeaderPrefix(Prefix, IsSystemHeader));
4628 }
4629
4630 HSOpts.ResourceDir = ReadString(Record, Idx);
4631 HSOpts.ModuleCachePath = ReadString(Record, Idx);
Argyrios Kyrtzidis1594c152014-03-03 08:12:05 +00004632 HSOpts.ModuleUserBuildPath = ReadString(Record, Idx);
Guy Benyei11169dd2012-12-18 14:30:41 +00004633 HSOpts.DisableModuleHash = Record[Idx++];
4634 HSOpts.UseBuiltinIncludes = Record[Idx++];
4635 HSOpts.UseStandardSystemIncludes = Record[Idx++];
4636 HSOpts.UseStandardCXXIncludes = Record[Idx++];
4637 HSOpts.UseLibcxx = Record[Idx++];
4638
4639 return Listener.ReadHeaderSearchOptions(HSOpts, Complain);
4640}
4641
4642bool ASTReader::ParsePreprocessorOptions(const RecordData &Record,
4643 bool Complain,
4644 ASTReaderListener &Listener,
4645 std::string &SuggestedPredefines) {
4646 PreprocessorOptions PPOpts;
4647 unsigned Idx = 0;
4648
4649 // Macro definitions/undefs
4650 for (unsigned N = Record[Idx++]; N; --N) {
4651 std::string Macro = ReadString(Record, Idx);
4652 bool IsUndef = Record[Idx++];
4653 PPOpts.Macros.push_back(std::make_pair(Macro, IsUndef));
4654 }
4655
4656 // Includes
4657 for (unsigned N = Record[Idx++]; N; --N) {
4658 PPOpts.Includes.push_back(ReadString(Record, Idx));
4659 }
4660
4661 // Macro Includes
4662 for (unsigned N = Record[Idx++]; N; --N) {
4663 PPOpts.MacroIncludes.push_back(ReadString(Record, Idx));
4664 }
4665
4666 PPOpts.UsePredefines = Record[Idx++];
Argyrios Kyrtzidisd3afa0c2013-04-26 21:33:40 +00004667 PPOpts.DetailedRecord = Record[Idx++];
Guy Benyei11169dd2012-12-18 14:30:41 +00004668 PPOpts.ImplicitPCHInclude = ReadString(Record, Idx);
4669 PPOpts.ImplicitPTHInclude = ReadString(Record, Idx);
4670 PPOpts.ObjCXXARCStandardLibrary =
4671 static_cast<ObjCXXARCStandardLibraryKind>(Record[Idx++]);
4672 SuggestedPredefines.clear();
4673 return Listener.ReadPreprocessorOptions(PPOpts, Complain,
4674 SuggestedPredefines);
4675}
4676
4677std::pair<ModuleFile *, unsigned>
4678ASTReader::getModulePreprocessedEntity(unsigned GlobalIndex) {
4679 GlobalPreprocessedEntityMapType::iterator
4680 I = GlobalPreprocessedEntityMap.find(GlobalIndex);
4681 assert(I != GlobalPreprocessedEntityMap.end() &&
4682 "Corrupted global preprocessed entity map");
4683 ModuleFile *M = I->second;
4684 unsigned LocalIndex = GlobalIndex - M->BasePreprocessedEntityID;
4685 return std::make_pair(M, LocalIndex);
4686}
4687
4688std::pair<PreprocessingRecord::iterator, PreprocessingRecord::iterator>
4689ASTReader::getModulePreprocessedEntities(ModuleFile &Mod) const {
4690 if (PreprocessingRecord *PPRec = PP.getPreprocessingRecord())
4691 return PPRec->getIteratorsForLoadedRange(Mod.BasePreprocessedEntityID,
4692 Mod.NumPreprocessedEntities);
4693
4694 return std::make_pair(PreprocessingRecord::iterator(),
4695 PreprocessingRecord::iterator());
4696}
4697
4698std::pair<ASTReader::ModuleDeclIterator, ASTReader::ModuleDeclIterator>
4699ASTReader::getModuleFileLevelDecls(ModuleFile &Mod) {
4700 return std::make_pair(ModuleDeclIterator(this, &Mod, Mod.FileSortedDecls),
4701 ModuleDeclIterator(this, &Mod,
4702 Mod.FileSortedDecls + Mod.NumFileSortedDecls));
4703}
4704
4705PreprocessedEntity *ASTReader::ReadPreprocessedEntity(unsigned Index) {
4706 PreprocessedEntityID PPID = Index+1;
4707 std::pair<ModuleFile *, unsigned> PPInfo = getModulePreprocessedEntity(Index);
4708 ModuleFile &M = *PPInfo.first;
4709 unsigned LocalIndex = PPInfo.second;
4710 const PPEntityOffset &PPOffs = M.PreprocessedEntityOffsets[LocalIndex];
4711
Guy Benyei11169dd2012-12-18 14:30:41 +00004712 if (!PP.getPreprocessingRecord()) {
4713 Error("no preprocessing record");
4714 return 0;
4715 }
4716
Chris Lattner7fb3bef2013-01-20 00:56:42 +00004717 SavedStreamPosition SavedPosition(M.PreprocessorDetailCursor);
4718 M.PreprocessorDetailCursor.JumpToBit(PPOffs.BitOffset);
4719
4720 llvm::BitstreamEntry Entry =
4721 M.PreprocessorDetailCursor.advance(BitstreamCursor::AF_DontPopBlockAtEnd);
4722 if (Entry.Kind != llvm::BitstreamEntry::Record)
4723 return 0;
4724
Guy Benyei11169dd2012-12-18 14:30:41 +00004725 // Read the record.
4726 SourceRange Range(ReadSourceLocation(M, PPOffs.Begin),
4727 ReadSourceLocation(M, PPOffs.End));
4728 PreprocessingRecord &PPRec = *PP.getPreprocessingRecord();
Chris Lattner0e6c9402013-01-20 02:38:54 +00004729 StringRef Blob;
Guy Benyei11169dd2012-12-18 14:30:41 +00004730 RecordData Record;
4731 PreprocessorDetailRecordTypes RecType =
Chris Lattner0e6c9402013-01-20 02:38:54 +00004732 (PreprocessorDetailRecordTypes)M.PreprocessorDetailCursor.readRecord(
4733 Entry.ID, Record, &Blob);
Guy Benyei11169dd2012-12-18 14:30:41 +00004734 switch (RecType) {
4735 case PPD_MACRO_EXPANSION: {
4736 bool isBuiltin = Record[0];
4737 IdentifierInfo *Name = 0;
4738 MacroDefinition *Def = 0;
4739 if (isBuiltin)
4740 Name = getLocalIdentifier(M, Record[1]);
4741 else {
4742 PreprocessedEntityID
4743 GlobalID = getGlobalPreprocessedEntityID(M, Record[1]);
4744 Def =cast<MacroDefinition>(PPRec.getLoadedPreprocessedEntity(GlobalID-1));
4745 }
4746
4747 MacroExpansion *ME;
4748 if (isBuiltin)
4749 ME = new (PPRec) MacroExpansion(Name, Range);
4750 else
4751 ME = new (PPRec) MacroExpansion(Def, Range);
4752
4753 return ME;
4754 }
4755
4756 case PPD_MACRO_DEFINITION: {
4757 // Decode the identifier info and then check again; if the macro is
4758 // still defined and associated with the identifier,
4759 IdentifierInfo *II = getLocalIdentifier(M, Record[0]);
4760 MacroDefinition *MD
4761 = new (PPRec) MacroDefinition(II, Range);
4762
4763 if (DeserializationListener)
4764 DeserializationListener->MacroDefinitionRead(PPID, MD);
4765
4766 return MD;
4767 }
4768
4769 case PPD_INCLUSION_DIRECTIVE: {
Chris Lattner0e6c9402013-01-20 02:38:54 +00004770 const char *FullFileNameStart = Blob.data() + Record[0];
4771 StringRef FullFileName(FullFileNameStart, Blob.size() - Record[0]);
Guy Benyei11169dd2012-12-18 14:30:41 +00004772 const FileEntry *File = 0;
4773 if (!FullFileName.empty())
4774 File = PP.getFileManager().getFile(FullFileName);
4775
4776 // FIXME: Stable encoding
4777 InclusionDirective::InclusionKind Kind
4778 = static_cast<InclusionDirective::InclusionKind>(Record[2]);
4779 InclusionDirective *ID
4780 = new (PPRec) InclusionDirective(PPRec, Kind,
Chris Lattner0e6c9402013-01-20 02:38:54 +00004781 StringRef(Blob.data(), Record[0]),
Guy Benyei11169dd2012-12-18 14:30:41 +00004782 Record[1], Record[3],
4783 File,
4784 Range);
4785 return ID;
4786 }
4787 }
4788
4789 llvm_unreachable("Invalid PreprocessorDetailRecordTypes");
4790}
4791
4792/// \brief \arg SLocMapI points at a chunk of a module that contains no
4793/// preprocessed entities or the entities it contains are not the ones we are
4794/// looking for. Find the next module that contains entities and return the ID
4795/// of the first entry.
4796PreprocessedEntityID ASTReader::findNextPreprocessedEntity(
4797 GlobalSLocOffsetMapType::const_iterator SLocMapI) const {
4798 ++SLocMapI;
4799 for (GlobalSLocOffsetMapType::const_iterator
4800 EndI = GlobalSLocOffsetMap.end(); SLocMapI != EndI; ++SLocMapI) {
4801 ModuleFile &M = *SLocMapI->second;
4802 if (M.NumPreprocessedEntities)
4803 return M.BasePreprocessedEntityID;
4804 }
4805
4806 return getTotalNumPreprocessedEntities();
4807}
4808
4809namespace {
4810
4811template <unsigned PPEntityOffset::*PPLoc>
4812struct PPEntityComp {
4813 const ASTReader &Reader;
4814 ModuleFile &M;
4815
4816 PPEntityComp(const ASTReader &Reader, ModuleFile &M) : Reader(Reader), M(M) { }
4817
4818 bool operator()(const PPEntityOffset &L, const PPEntityOffset &R) const {
4819 SourceLocation LHS = getLoc(L);
4820 SourceLocation RHS = getLoc(R);
4821 return Reader.getSourceManager().isBeforeInTranslationUnit(LHS, RHS);
4822 }
4823
4824 bool operator()(const PPEntityOffset &L, SourceLocation RHS) const {
4825 SourceLocation LHS = getLoc(L);
4826 return Reader.getSourceManager().isBeforeInTranslationUnit(LHS, RHS);
4827 }
4828
4829 bool operator()(SourceLocation LHS, const PPEntityOffset &R) const {
4830 SourceLocation RHS = getLoc(R);
4831 return Reader.getSourceManager().isBeforeInTranslationUnit(LHS, RHS);
4832 }
4833
4834 SourceLocation getLoc(const PPEntityOffset &PPE) const {
4835 return Reader.ReadSourceLocation(M, PPE.*PPLoc);
4836 }
4837};
4838
4839}
4840
4841/// \brief Returns the first preprocessed entity ID that ends after \arg BLoc.
4842PreprocessedEntityID
4843ASTReader::findBeginPreprocessedEntity(SourceLocation BLoc) const {
4844 if (SourceMgr.isLocalSourceLocation(BLoc))
4845 return getTotalNumPreprocessedEntities();
4846
4847 GlobalSLocOffsetMapType::const_iterator
4848 SLocMapI = GlobalSLocOffsetMap.find(SourceManager::MaxLoadedOffset -
Argyrios Kyrtzidis503c83a2013-03-08 02:32:34 +00004849 BLoc.getOffset() - 1);
Guy Benyei11169dd2012-12-18 14:30:41 +00004850 assert(SLocMapI != GlobalSLocOffsetMap.end() &&
4851 "Corrupted global sloc offset map");
4852
4853 if (SLocMapI->second->NumPreprocessedEntities == 0)
4854 return findNextPreprocessedEntity(SLocMapI);
4855
4856 ModuleFile &M = *SLocMapI->second;
4857 typedef const PPEntityOffset *pp_iterator;
4858 pp_iterator pp_begin = M.PreprocessedEntityOffsets;
4859 pp_iterator pp_end = pp_begin + M.NumPreprocessedEntities;
4860
4861 size_t Count = M.NumPreprocessedEntities;
4862 size_t Half;
4863 pp_iterator First = pp_begin;
4864 pp_iterator PPI;
4865
4866 // Do a binary search manually instead of using std::lower_bound because
4867 // The end locations of entities may be unordered (when a macro expansion
4868 // is inside another macro argument), but for this case it is not important
4869 // whether we get the first macro expansion or its containing macro.
4870 while (Count > 0) {
4871 Half = Count/2;
4872 PPI = First;
4873 std::advance(PPI, Half);
4874 if (SourceMgr.isBeforeInTranslationUnit(ReadSourceLocation(M, PPI->End),
4875 BLoc)){
4876 First = PPI;
4877 ++First;
4878 Count = Count - Half - 1;
4879 } else
4880 Count = Half;
4881 }
4882
4883 if (PPI == pp_end)
4884 return findNextPreprocessedEntity(SLocMapI);
4885
4886 return M.BasePreprocessedEntityID + (PPI - pp_begin);
4887}
4888
4889/// \brief Returns the first preprocessed entity ID that begins after \arg ELoc.
4890PreprocessedEntityID
4891ASTReader::findEndPreprocessedEntity(SourceLocation ELoc) const {
4892 if (SourceMgr.isLocalSourceLocation(ELoc))
4893 return getTotalNumPreprocessedEntities();
4894
4895 GlobalSLocOffsetMapType::const_iterator
4896 SLocMapI = GlobalSLocOffsetMap.find(SourceManager::MaxLoadedOffset -
Argyrios Kyrtzidis503c83a2013-03-08 02:32:34 +00004897 ELoc.getOffset() - 1);
Guy Benyei11169dd2012-12-18 14:30:41 +00004898 assert(SLocMapI != GlobalSLocOffsetMap.end() &&
4899 "Corrupted global sloc offset map");
4900
4901 if (SLocMapI->second->NumPreprocessedEntities == 0)
4902 return findNextPreprocessedEntity(SLocMapI);
4903
4904 ModuleFile &M = *SLocMapI->second;
4905 typedef const PPEntityOffset *pp_iterator;
4906 pp_iterator pp_begin = M.PreprocessedEntityOffsets;
4907 pp_iterator pp_end = pp_begin + M.NumPreprocessedEntities;
4908 pp_iterator PPI =
4909 std::upper_bound(pp_begin, pp_end, ELoc,
4910 PPEntityComp<&PPEntityOffset::Begin>(*this, M));
4911
4912 if (PPI == pp_end)
4913 return findNextPreprocessedEntity(SLocMapI);
4914
4915 return M.BasePreprocessedEntityID + (PPI - pp_begin);
4916}
4917
4918/// \brief Returns a pair of [Begin, End) indices of preallocated
4919/// preprocessed entities that \arg Range encompasses.
4920std::pair<unsigned, unsigned>
4921 ASTReader::findPreprocessedEntitiesInRange(SourceRange Range) {
4922 if (Range.isInvalid())
4923 return std::make_pair(0,0);
4924 assert(!SourceMgr.isBeforeInTranslationUnit(Range.getEnd(),Range.getBegin()));
4925
4926 PreprocessedEntityID BeginID = findBeginPreprocessedEntity(Range.getBegin());
4927 PreprocessedEntityID EndID = findEndPreprocessedEntity(Range.getEnd());
4928 return std::make_pair(BeginID, EndID);
4929}
4930
4931/// \brief Optionally returns true or false if the preallocated preprocessed
4932/// entity with index \arg Index came from file \arg FID.
David Blaikie05785d12013-02-20 22:23:23 +00004933Optional<bool> ASTReader::isPreprocessedEntityInFileID(unsigned Index,
Guy Benyei11169dd2012-12-18 14:30:41 +00004934 FileID FID) {
4935 if (FID.isInvalid())
4936 return false;
4937
4938 std::pair<ModuleFile *, unsigned> PPInfo = getModulePreprocessedEntity(Index);
4939 ModuleFile &M = *PPInfo.first;
4940 unsigned LocalIndex = PPInfo.second;
4941 const PPEntityOffset &PPOffs = M.PreprocessedEntityOffsets[LocalIndex];
4942
4943 SourceLocation Loc = ReadSourceLocation(M, PPOffs.Begin);
4944 if (Loc.isInvalid())
4945 return false;
4946
4947 if (SourceMgr.isInFileID(SourceMgr.getFileLoc(Loc), FID))
4948 return true;
4949 else
4950 return false;
4951}
4952
4953namespace {
4954 /// \brief Visitor used to search for information about a header file.
4955 class HeaderFileInfoVisitor {
Guy Benyei11169dd2012-12-18 14:30:41 +00004956 const FileEntry *FE;
4957
David Blaikie05785d12013-02-20 22:23:23 +00004958 Optional<HeaderFileInfo> HFI;
Guy Benyei11169dd2012-12-18 14:30:41 +00004959
4960 public:
Argyrios Kyrtzidis61a38962013-03-06 18:12:44 +00004961 explicit HeaderFileInfoVisitor(const FileEntry *FE)
4962 : FE(FE) { }
Guy Benyei11169dd2012-12-18 14:30:41 +00004963
4964 static bool visit(ModuleFile &M, void *UserData) {
4965 HeaderFileInfoVisitor *This
4966 = static_cast<HeaderFileInfoVisitor *>(UserData);
4967
Guy Benyei11169dd2012-12-18 14:30:41 +00004968 HeaderFileInfoLookupTable *Table
4969 = static_cast<HeaderFileInfoLookupTable *>(M.HeaderFileInfoTable);
4970 if (!Table)
4971 return false;
4972
4973 // Look in the on-disk hash table for an entry for this file name.
Argyrios Kyrtzidis5c2a3452013-03-06 18:12:47 +00004974 HeaderFileInfoLookupTable::iterator Pos = Table->find(This->FE);
Guy Benyei11169dd2012-12-18 14:30:41 +00004975 if (Pos == Table->end())
4976 return false;
4977
4978 This->HFI = *Pos;
4979 return true;
4980 }
4981
David Blaikie05785d12013-02-20 22:23:23 +00004982 Optional<HeaderFileInfo> getHeaderFileInfo() const { return HFI; }
Guy Benyei11169dd2012-12-18 14:30:41 +00004983 };
4984}
4985
4986HeaderFileInfo ASTReader::GetHeaderFileInfo(const FileEntry *FE) {
Argyrios Kyrtzidis61a38962013-03-06 18:12:44 +00004987 HeaderFileInfoVisitor Visitor(FE);
Guy Benyei11169dd2012-12-18 14:30:41 +00004988 ModuleMgr.visit(&HeaderFileInfoVisitor::visit, &Visitor);
Argyrios Kyrtzidis1054bbf2013-05-08 23:46:55 +00004989 if (Optional<HeaderFileInfo> HFI = Visitor.getHeaderFileInfo())
Guy Benyei11169dd2012-12-18 14:30:41 +00004990 return *HFI;
Guy Benyei11169dd2012-12-18 14:30:41 +00004991
4992 return HeaderFileInfo();
4993}
4994
4995void ASTReader::ReadPragmaDiagnosticMappings(DiagnosticsEngine &Diag) {
4996 // FIXME: Make it work properly with modules.
Dmitri Gribenkof8579502013-01-12 19:30:44 +00004997 SmallVector<DiagnosticsEngine::DiagState *, 32> DiagStates;
Guy Benyei11169dd2012-12-18 14:30:41 +00004998 for (ModuleIterator I = ModuleMgr.begin(), E = ModuleMgr.end(); I != E; ++I) {
4999 ModuleFile &F = *(*I);
5000 unsigned Idx = 0;
5001 DiagStates.clear();
5002 assert(!Diag.DiagStates.empty());
5003 DiagStates.push_back(&Diag.DiagStates.front()); // the command-line one.
5004 while (Idx < F.PragmaDiagMappings.size()) {
5005 SourceLocation Loc = ReadSourceLocation(F, F.PragmaDiagMappings[Idx++]);
5006 unsigned DiagStateID = F.PragmaDiagMappings[Idx++];
5007 if (DiagStateID != 0) {
5008 Diag.DiagStatePoints.push_back(
5009 DiagnosticsEngine::DiagStatePoint(DiagStates[DiagStateID-1],
5010 FullSourceLoc(Loc, SourceMgr)));
5011 continue;
5012 }
5013
5014 assert(DiagStateID == 0);
5015 // A new DiagState was created here.
5016 Diag.DiagStates.push_back(*Diag.GetCurDiagState());
5017 DiagnosticsEngine::DiagState *NewState = &Diag.DiagStates.back();
5018 DiagStates.push_back(NewState);
5019 Diag.DiagStatePoints.push_back(
5020 DiagnosticsEngine::DiagStatePoint(NewState,
5021 FullSourceLoc(Loc, SourceMgr)));
5022 while (1) {
5023 assert(Idx < F.PragmaDiagMappings.size() &&
5024 "Invalid data, didn't find '-1' marking end of diag/map pairs");
5025 if (Idx >= F.PragmaDiagMappings.size()) {
5026 break; // Something is messed up but at least avoid infinite loop in
5027 // release build.
5028 }
5029 unsigned DiagID = F.PragmaDiagMappings[Idx++];
5030 if (DiagID == (unsigned)-1) {
5031 break; // no more diag/map pairs for this location.
5032 }
5033 diag::Mapping Map = (diag::Mapping)F.PragmaDiagMappings[Idx++];
5034 DiagnosticMappingInfo MappingInfo = Diag.makeMappingInfo(Map, Loc);
5035 Diag.GetCurDiagState()->setMappingInfo(DiagID, MappingInfo);
5036 }
5037 }
5038 }
5039}
5040
5041/// \brief Get the correct cursor and offset for loading a type.
5042ASTReader::RecordLocation ASTReader::TypeCursorForIndex(unsigned Index) {
5043 GlobalTypeMapType::iterator I = GlobalTypeMap.find(Index);
5044 assert(I != GlobalTypeMap.end() && "Corrupted global type map");
5045 ModuleFile *M = I->second;
5046 return RecordLocation(M, M->TypeOffsets[Index - M->BaseTypeIndex]);
5047}
5048
5049/// \brief Read and return the type with the given index..
5050///
5051/// The index is the type ID, shifted and minus the number of predefs. This
5052/// routine actually reads the record corresponding to the type at the given
5053/// location. It is a helper routine for GetType, which deals with reading type
5054/// IDs.
5055QualType ASTReader::readTypeRecord(unsigned Index) {
5056 RecordLocation Loc = TypeCursorForIndex(Index);
Chris Lattner7fb3bef2013-01-20 00:56:42 +00005057 BitstreamCursor &DeclsCursor = Loc.F->DeclsCursor;
Guy Benyei11169dd2012-12-18 14:30:41 +00005058
5059 // Keep track of where we are in the stream, then jump back there
5060 // after reading this type.
5061 SavedStreamPosition SavedPosition(DeclsCursor);
5062
5063 ReadingKindTracker ReadingKind(Read_Type, *this);
5064
5065 // Note that we are loading a type record.
5066 Deserializing AType(this);
5067
5068 unsigned Idx = 0;
5069 DeclsCursor.JumpToBit(Loc.Offset);
5070 RecordData Record;
5071 unsigned Code = DeclsCursor.ReadCode();
Chris Lattner0e6c9402013-01-20 02:38:54 +00005072 switch ((TypeCode)DeclsCursor.readRecord(Code, Record)) {
Guy Benyei11169dd2012-12-18 14:30:41 +00005073 case TYPE_EXT_QUAL: {
5074 if (Record.size() != 2) {
5075 Error("Incorrect encoding of extended qualifier type");
5076 return QualType();
5077 }
5078 QualType Base = readType(*Loc.F, Record, Idx);
5079 Qualifiers Quals = Qualifiers::fromOpaqueValue(Record[Idx++]);
5080 return Context.getQualifiedType(Base, Quals);
5081 }
5082
5083 case TYPE_COMPLEX: {
5084 if (Record.size() != 1) {
5085 Error("Incorrect encoding of complex type");
5086 return QualType();
5087 }
5088 QualType ElemType = readType(*Loc.F, Record, Idx);
5089 return Context.getComplexType(ElemType);
5090 }
5091
5092 case TYPE_POINTER: {
5093 if (Record.size() != 1) {
5094 Error("Incorrect encoding of pointer type");
5095 return QualType();
5096 }
5097 QualType PointeeType = readType(*Loc.F, Record, Idx);
5098 return Context.getPointerType(PointeeType);
5099 }
5100
Reid Kleckner8a365022013-06-24 17:51:48 +00005101 case TYPE_DECAYED: {
5102 if (Record.size() != 1) {
5103 Error("Incorrect encoding of decayed type");
5104 return QualType();
5105 }
5106 QualType OriginalType = readType(*Loc.F, Record, Idx);
5107 QualType DT = Context.getAdjustedParameterType(OriginalType);
5108 if (!isa<DecayedType>(DT))
5109 Error("Decayed type does not decay");
5110 return DT;
5111 }
5112
Reid Kleckner0503a872013-12-05 01:23:43 +00005113 case TYPE_ADJUSTED: {
5114 if (Record.size() != 2) {
5115 Error("Incorrect encoding of adjusted type");
5116 return QualType();
5117 }
5118 QualType OriginalTy = readType(*Loc.F, Record, Idx);
5119 QualType AdjustedTy = readType(*Loc.F, Record, Idx);
5120 return Context.getAdjustedType(OriginalTy, AdjustedTy);
5121 }
5122
Guy Benyei11169dd2012-12-18 14:30:41 +00005123 case TYPE_BLOCK_POINTER: {
5124 if (Record.size() != 1) {
5125 Error("Incorrect encoding of block pointer type");
5126 return QualType();
5127 }
5128 QualType PointeeType = readType(*Loc.F, Record, Idx);
5129 return Context.getBlockPointerType(PointeeType);
5130 }
5131
5132 case TYPE_LVALUE_REFERENCE: {
5133 if (Record.size() != 2) {
5134 Error("Incorrect encoding of lvalue reference type");
5135 return QualType();
5136 }
5137 QualType PointeeType = readType(*Loc.F, Record, Idx);
5138 return Context.getLValueReferenceType(PointeeType, Record[1]);
5139 }
5140
5141 case TYPE_RVALUE_REFERENCE: {
5142 if (Record.size() != 1) {
5143 Error("Incorrect encoding of rvalue reference type");
5144 return QualType();
5145 }
5146 QualType PointeeType = readType(*Loc.F, Record, Idx);
5147 return Context.getRValueReferenceType(PointeeType);
5148 }
5149
5150 case TYPE_MEMBER_POINTER: {
5151 if (Record.size() != 2) {
5152 Error("Incorrect encoding of member pointer type");
5153 return QualType();
5154 }
5155 QualType PointeeType = readType(*Loc.F, Record, Idx);
5156 QualType ClassType = readType(*Loc.F, Record, Idx);
5157 if (PointeeType.isNull() || ClassType.isNull())
5158 return QualType();
5159
5160 return Context.getMemberPointerType(PointeeType, ClassType.getTypePtr());
5161 }
5162
5163 case TYPE_CONSTANT_ARRAY: {
5164 QualType ElementType = readType(*Loc.F, Record, Idx);
5165 ArrayType::ArraySizeModifier ASM = (ArrayType::ArraySizeModifier)Record[1];
5166 unsigned IndexTypeQuals = Record[2];
5167 unsigned Idx = 3;
5168 llvm::APInt Size = ReadAPInt(Record, Idx);
5169 return Context.getConstantArrayType(ElementType, Size,
5170 ASM, IndexTypeQuals);
5171 }
5172
5173 case TYPE_INCOMPLETE_ARRAY: {
5174 QualType ElementType = readType(*Loc.F, Record, Idx);
5175 ArrayType::ArraySizeModifier ASM = (ArrayType::ArraySizeModifier)Record[1];
5176 unsigned IndexTypeQuals = Record[2];
5177 return Context.getIncompleteArrayType(ElementType, ASM, IndexTypeQuals);
5178 }
5179
5180 case TYPE_VARIABLE_ARRAY: {
5181 QualType ElementType = readType(*Loc.F, Record, Idx);
5182 ArrayType::ArraySizeModifier ASM = (ArrayType::ArraySizeModifier)Record[1];
5183 unsigned IndexTypeQuals = Record[2];
5184 SourceLocation LBLoc = ReadSourceLocation(*Loc.F, Record[3]);
5185 SourceLocation RBLoc = ReadSourceLocation(*Loc.F, Record[4]);
5186 return Context.getVariableArrayType(ElementType, ReadExpr(*Loc.F),
5187 ASM, IndexTypeQuals,
5188 SourceRange(LBLoc, RBLoc));
5189 }
5190
5191 case TYPE_VECTOR: {
5192 if (Record.size() != 3) {
5193 Error("incorrect encoding of vector type in AST file");
5194 return QualType();
5195 }
5196
5197 QualType ElementType = readType(*Loc.F, Record, Idx);
5198 unsigned NumElements = Record[1];
5199 unsigned VecKind = Record[2];
5200 return Context.getVectorType(ElementType, NumElements,
5201 (VectorType::VectorKind)VecKind);
5202 }
5203
5204 case TYPE_EXT_VECTOR: {
5205 if (Record.size() != 3) {
5206 Error("incorrect encoding of extended vector type in AST file");
5207 return QualType();
5208 }
5209
5210 QualType ElementType = readType(*Loc.F, Record, Idx);
5211 unsigned NumElements = Record[1];
5212 return Context.getExtVectorType(ElementType, NumElements);
5213 }
5214
5215 case TYPE_FUNCTION_NO_PROTO: {
5216 if (Record.size() != 6) {
5217 Error("incorrect encoding of no-proto function type");
5218 return QualType();
5219 }
5220 QualType ResultType = readType(*Loc.F, Record, Idx);
5221 FunctionType::ExtInfo Info(Record[1], Record[2], Record[3],
5222 (CallingConv)Record[4], Record[5]);
5223 return Context.getFunctionNoProtoType(ResultType, Info);
5224 }
5225
5226 case TYPE_FUNCTION_PROTO: {
5227 QualType ResultType = readType(*Loc.F, Record, Idx);
5228
5229 FunctionProtoType::ExtProtoInfo EPI;
5230 EPI.ExtInfo = FunctionType::ExtInfo(/*noreturn*/ Record[1],
5231 /*hasregparm*/ Record[2],
5232 /*regparm*/ Record[3],
5233 static_cast<CallingConv>(Record[4]),
5234 /*produces*/ Record[5]);
5235
5236 unsigned Idx = 6;
5237 unsigned NumParams = Record[Idx++];
5238 SmallVector<QualType, 16> ParamTypes;
5239 for (unsigned I = 0; I != NumParams; ++I)
5240 ParamTypes.push_back(readType(*Loc.F, Record, Idx));
5241
5242 EPI.Variadic = Record[Idx++];
5243 EPI.HasTrailingReturn = Record[Idx++];
5244 EPI.TypeQuals = Record[Idx++];
5245 EPI.RefQualifier = static_cast<RefQualifierKind>(Record[Idx++]);
Richard Smith564417a2014-03-20 21:47:22 +00005246 SmallVector<QualType, 8> ExceptionStorage;
5247 readExceptionSpec(*Loc.F, ExceptionStorage, EPI, Record, Idx);
Jordan Rose5c382722013-03-08 21:51:21 +00005248 return Context.getFunctionType(ResultType, ParamTypes, EPI);
Guy Benyei11169dd2012-12-18 14:30:41 +00005249 }
5250
5251 case TYPE_UNRESOLVED_USING: {
5252 unsigned Idx = 0;
5253 return Context.getTypeDeclType(
5254 ReadDeclAs<UnresolvedUsingTypenameDecl>(*Loc.F, Record, Idx));
5255 }
5256
5257 case TYPE_TYPEDEF: {
5258 if (Record.size() != 2) {
5259 Error("incorrect encoding of typedef type");
5260 return QualType();
5261 }
5262 unsigned Idx = 0;
5263 TypedefNameDecl *Decl = ReadDeclAs<TypedefNameDecl>(*Loc.F, Record, Idx);
5264 QualType Canonical = readType(*Loc.F, Record, Idx);
5265 if (!Canonical.isNull())
5266 Canonical = Context.getCanonicalType(Canonical);
5267 return Context.getTypedefType(Decl, Canonical);
5268 }
5269
5270 case TYPE_TYPEOF_EXPR:
5271 return Context.getTypeOfExprType(ReadExpr(*Loc.F));
5272
5273 case TYPE_TYPEOF: {
5274 if (Record.size() != 1) {
5275 Error("incorrect encoding of typeof(type) in AST file");
5276 return QualType();
5277 }
5278 QualType UnderlyingType = readType(*Loc.F, Record, Idx);
5279 return Context.getTypeOfType(UnderlyingType);
5280 }
5281
5282 case TYPE_DECLTYPE: {
5283 QualType UnderlyingType = readType(*Loc.F, Record, Idx);
5284 return Context.getDecltypeType(ReadExpr(*Loc.F), UnderlyingType);
5285 }
5286
5287 case TYPE_UNARY_TRANSFORM: {
5288 QualType BaseType = readType(*Loc.F, Record, Idx);
5289 QualType UnderlyingType = readType(*Loc.F, Record, Idx);
5290 UnaryTransformType::UTTKind UKind = (UnaryTransformType::UTTKind)Record[2];
5291 return Context.getUnaryTransformType(BaseType, UnderlyingType, UKind);
5292 }
5293
Richard Smith74aeef52013-04-26 16:15:35 +00005294 case TYPE_AUTO: {
5295 QualType Deduced = readType(*Loc.F, Record, Idx);
5296 bool IsDecltypeAuto = Record[Idx++];
Richard Smith27d807c2013-04-30 13:56:41 +00005297 bool IsDependent = Deduced.isNull() ? Record[Idx++] : false;
Manuel Klimek2fdbea22013-08-22 12:12:24 +00005298 return Context.getAutoType(Deduced, IsDecltypeAuto, IsDependent);
Richard Smith74aeef52013-04-26 16:15:35 +00005299 }
Guy Benyei11169dd2012-12-18 14:30:41 +00005300
5301 case TYPE_RECORD: {
5302 if (Record.size() != 2) {
5303 Error("incorrect encoding of record type");
5304 return QualType();
5305 }
5306 unsigned Idx = 0;
5307 bool IsDependent = Record[Idx++];
5308 RecordDecl *RD = ReadDeclAs<RecordDecl>(*Loc.F, Record, Idx);
5309 RD = cast_or_null<RecordDecl>(RD->getCanonicalDecl());
5310 QualType T = Context.getRecordType(RD);
5311 const_cast<Type*>(T.getTypePtr())->setDependent(IsDependent);
5312 return T;
5313 }
5314
5315 case TYPE_ENUM: {
5316 if (Record.size() != 2) {
5317 Error("incorrect encoding of enum type");
5318 return QualType();
5319 }
5320 unsigned Idx = 0;
5321 bool IsDependent = Record[Idx++];
5322 QualType T
5323 = Context.getEnumType(ReadDeclAs<EnumDecl>(*Loc.F, Record, Idx));
5324 const_cast<Type*>(T.getTypePtr())->setDependent(IsDependent);
5325 return T;
5326 }
5327
5328 case TYPE_ATTRIBUTED: {
5329 if (Record.size() != 3) {
5330 Error("incorrect encoding of attributed type");
5331 return QualType();
5332 }
5333 QualType modifiedType = readType(*Loc.F, Record, Idx);
5334 QualType equivalentType = readType(*Loc.F, Record, Idx);
5335 AttributedType::Kind kind = static_cast<AttributedType::Kind>(Record[2]);
5336 return Context.getAttributedType(kind, modifiedType, equivalentType);
5337 }
5338
5339 case TYPE_PAREN: {
5340 if (Record.size() != 1) {
5341 Error("incorrect encoding of paren type");
5342 return QualType();
5343 }
5344 QualType InnerType = readType(*Loc.F, Record, Idx);
5345 return Context.getParenType(InnerType);
5346 }
5347
5348 case TYPE_PACK_EXPANSION: {
5349 if (Record.size() != 2) {
5350 Error("incorrect encoding of pack expansion type");
5351 return QualType();
5352 }
5353 QualType Pattern = readType(*Loc.F, Record, Idx);
5354 if (Pattern.isNull())
5355 return QualType();
David Blaikie05785d12013-02-20 22:23:23 +00005356 Optional<unsigned> NumExpansions;
Guy Benyei11169dd2012-12-18 14:30:41 +00005357 if (Record[1])
5358 NumExpansions = Record[1] - 1;
5359 return Context.getPackExpansionType(Pattern, NumExpansions);
5360 }
5361
5362 case TYPE_ELABORATED: {
5363 unsigned Idx = 0;
5364 ElaboratedTypeKeyword Keyword = (ElaboratedTypeKeyword)Record[Idx++];
5365 NestedNameSpecifier *NNS = ReadNestedNameSpecifier(*Loc.F, Record, Idx);
5366 QualType NamedType = readType(*Loc.F, Record, Idx);
5367 return Context.getElaboratedType(Keyword, NNS, NamedType);
5368 }
5369
5370 case TYPE_OBJC_INTERFACE: {
5371 unsigned Idx = 0;
5372 ObjCInterfaceDecl *ItfD
5373 = ReadDeclAs<ObjCInterfaceDecl>(*Loc.F, Record, Idx);
5374 return Context.getObjCInterfaceType(ItfD->getCanonicalDecl());
5375 }
5376
5377 case TYPE_OBJC_OBJECT: {
5378 unsigned Idx = 0;
5379 QualType Base = readType(*Loc.F, Record, Idx);
5380 unsigned NumProtos = Record[Idx++];
5381 SmallVector<ObjCProtocolDecl*, 4> Protos;
5382 for (unsigned I = 0; I != NumProtos; ++I)
5383 Protos.push_back(ReadDeclAs<ObjCProtocolDecl>(*Loc.F, Record, Idx));
5384 return Context.getObjCObjectType(Base, Protos.data(), NumProtos);
5385 }
5386
5387 case TYPE_OBJC_OBJECT_POINTER: {
5388 unsigned Idx = 0;
5389 QualType Pointee = readType(*Loc.F, Record, Idx);
5390 return Context.getObjCObjectPointerType(Pointee);
5391 }
5392
5393 case TYPE_SUBST_TEMPLATE_TYPE_PARM: {
5394 unsigned Idx = 0;
5395 QualType Parm = readType(*Loc.F, Record, Idx);
5396 QualType Replacement = readType(*Loc.F, Record, Idx);
Stephan Tolksdorfe96f8b32014-03-15 10:23:27 +00005397 return Context.getSubstTemplateTypeParmType(
5398 cast<TemplateTypeParmType>(Parm),
5399 Context.getCanonicalType(Replacement));
Guy Benyei11169dd2012-12-18 14:30:41 +00005400 }
5401
5402 case TYPE_SUBST_TEMPLATE_TYPE_PARM_PACK: {
5403 unsigned Idx = 0;
5404 QualType Parm = readType(*Loc.F, Record, Idx);
5405 TemplateArgument ArgPack = ReadTemplateArgument(*Loc.F, Record, Idx);
5406 return Context.getSubstTemplateTypeParmPackType(
5407 cast<TemplateTypeParmType>(Parm),
5408 ArgPack);
5409 }
5410
5411 case TYPE_INJECTED_CLASS_NAME: {
5412 CXXRecordDecl *D = ReadDeclAs<CXXRecordDecl>(*Loc.F, Record, Idx);
5413 QualType TST = readType(*Loc.F, Record, Idx); // probably derivable
5414 // FIXME: ASTContext::getInjectedClassNameType is not currently suitable
5415 // for AST reading, too much interdependencies.
Richard Smithf17fdbd2014-04-24 02:25:27 +00005416 const Type *T;
5417 if (const Type *Existing = D->getTypeForDecl())
5418 T = Existing;
5419 else if (auto *Prev = D->getPreviousDecl())
5420 T = Prev->getTypeForDecl();
5421 else
5422 T = new (Context, TypeAlignment) InjectedClassNameType(D, TST);
5423 return QualType(T, 0);
Guy Benyei11169dd2012-12-18 14:30:41 +00005424 }
5425
5426 case TYPE_TEMPLATE_TYPE_PARM: {
5427 unsigned Idx = 0;
5428 unsigned Depth = Record[Idx++];
5429 unsigned Index = Record[Idx++];
5430 bool Pack = Record[Idx++];
5431 TemplateTypeParmDecl *D
5432 = ReadDeclAs<TemplateTypeParmDecl>(*Loc.F, Record, Idx);
5433 return Context.getTemplateTypeParmType(Depth, Index, Pack, D);
5434 }
5435
5436 case TYPE_DEPENDENT_NAME: {
5437 unsigned Idx = 0;
5438 ElaboratedTypeKeyword Keyword = (ElaboratedTypeKeyword)Record[Idx++];
5439 NestedNameSpecifier *NNS = ReadNestedNameSpecifier(*Loc.F, Record, Idx);
5440 const IdentifierInfo *Name = this->GetIdentifierInfo(*Loc.F, Record, Idx);
5441 QualType Canon = readType(*Loc.F, Record, Idx);
5442 if (!Canon.isNull())
5443 Canon = Context.getCanonicalType(Canon);
5444 return Context.getDependentNameType(Keyword, NNS, Name, Canon);
5445 }
5446
5447 case TYPE_DEPENDENT_TEMPLATE_SPECIALIZATION: {
5448 unsigned Idx = 0;
5449 ElaboratedTypeKeyword Keyword = (ElaboratedTypeKeyword)Record[Idx++];
5450 NestedNameSpecifier *NNS = ReadNestedNameSpecifier(*Loc.F, Record, Idx);
5451 const IdentifierInfo *Name = this->GetIdentifierInfo(*Loc.F, Record, Idx);
5452 unsigned NumArgs = Record[Idx++];
5453 SmallVector<TemplateArgument, 8> Args;
5454 Args.reserve(NumArgs);
5455 while (NumArgs--)
5456 Args.push_back(ReadTemplateArgument(*Loc.F, Record, Idx));
5457 return Context.getDependentTemplateSpecializationType(Keyword, NNS, Name,
5458 Args.size(), Args.data());
5459 }
5460
5461 case TYPE_DEPENDENT_SIZED_ARRAY: {
5462 unsigned Idx = 0;
5463
5464 // ArrayType
5465 QualType ElementType = readType(*Loc.F, Record, Idx);
5466 ArrayType::ArraySizeModifier ASM
5467 = (ArrayType::ArraySizeModifier)Record[Idx++];
5468 unsigned IndexTypeQuals = Record[Idx++];
5469
5470 // DependentSizedArrayType
5471 Expr *NumElts = ReadExpr(*Loc.F);
5472 SourceRange Brackets = ReadSourceRange(*Loc.F, Record, Idx);
5473
5474 return Context.getDependentSizedArrayType(ElementType, NumElts, ASM,
5475 IndexTypeQuals, Brackets);
5476 }
5477
5478 case TYPE_TEMPLATE_SPECIALIZATION: {
5479 unsigned Idx = 0;
5480 bool IsDependent = Record[Idx++];
5481 TemplateName Name = ReadTemplateName(*Loc.F, Record, Idx);
5482 SmallVector<TemplateArgument, 8> Args;
5483 ReadTemplateArgumentList(Args, *Loc.F, Record, Idx);
5484 QualType Underlying = readType(*Loc.F, Record, Idx);
5485 QualType T;
5486 if (Underlying.isNull())
5487 T = Context.getCanonicalTemplateSpecializationType(Name, Args.data(),
5488 Args.size());
5489 else
5490 T = Context.getTemplateSpecializationType(Name, Args.data(),
5491 Args.size(), Underlying);
5492 const_cast<Type*>(T.getTypePtr())->setDependent(IsDependent);
5493 return T;
5494 }
5495
5496 case TYPE_ATOMIC: {
5497 if (Record.size() != 1) {
5498 Error("Incorrect encoding of atomic type");
5499 return QualType();
5500 }
5501 QualType ValueType = readType(*Loc.F, Record, Idx);
5502 return Context.getAtomicType(ValueType);
5503 }
5504 }
5505 llvm_unreachable("Invalid TypeCode!");
5506}
5507
Richard Smith564417a2014-03-20 21:47:22 +00005508void ASTReader::readExceptionSpec(ModuleFile &ModuleFile,
5509 SmallVectorImpl<QualType> &Exceptions,
5510 FunctionProtoType::ExtProtoInfo &EPI,
5511 const RecordData &Record, unsigned &Idx) {
5512 ExceptionSpecificationType EST =
5513 static_cast<ExceptionSpecificationType>(Record[Idx++]);
5514 EPI.ExceptionSpecType = EST;
5515 if (EST == EST_Dynamic) {
5516 EPI.NumExceptions = Record[Idx++];
5517 for (unsigned I = 0; I != EPI.NumExceptions; ++I)
5518 Exceptions.push_back(readType(ModuleFile, Record, Idx));
5519 EPI.Exceptions = Exceptions.data();
5520 } else if (EST == EST_ComputedNoexcept) {
5521 EPI.NoexceptExpr = ReadExpr(ModuleFile);
5522 } else if (EST == EST_Uninstantiated) {
5523 EPI.ExceptionSpecDecl = ReadDeclAs<FunctionDecl>(ModuleFile, Record, Idx);
5524 EPI.ExceptionSpecTemplate =
5525 ReadDeclAs<FunctionDecl>(ModuleFile, Record, Idx);
5526 } else if (EST == EST_Unevaluated) {
5527 EPI.ExceptionSpecDecl = ReadDeclAs<FunctionDecl>(ModuleFile, Record, Idx);
5528 }
5529}
5530
Guy Benyei11169dd2012-12-18 14:30:41 +00005531class clang::TypeLocReader : public TypeLocVisitor<TypeLocReader> {
5532 ASTReader &Reader;
5533 ModuleFile &F;
5534 const ASTReader::RecordData &Record;
5535 unsigned &Idx;
5536
5537 SourceLocation ReadSourceLocation(const ASTReader::RecordData &R,
5538 unsigned &I) {
5539 return Reader.ReadSourceLocation(F, R, I);
5540 }
5541
5542 template<typename T>
5543 T *ReadDeclAs(const ASTReader::RecordData &Record, unsigned &Idx) {
5544 return Reader.ReadDeclAs<T>(F, Record, Idx);
5545 }
5546
5547public:
5548 TypeLocReader(ASTReader &Reader, ModuleFile &F,
5549 const ASTReader::RecordData &Record, unsigned &Idx)
5550 : Reader(Reader), F(F), Record(Record), Idx(Idx)
5551 { }
5552
5553 // We want compile-time assurance that we've enumerated all of
5554 // these, so unfortunately we have to declare them first, then
5555 // define them out-of-line.
5556#define ABSTRACT_TYPELOC(CLASS, PARENT)
5557#define TYPELOC(CLASS, PARENT) \
5558 void Visit##CLASS##TypeLoc(CLASS##TypeLoc TyLoc);
5559#include "clang/AST/TypeLocNodes.def"
5560
5561 void VisitFunctionTypeLoc(FunctionTypeLoc);
5562 void VisitArrayTypeLoc(ArrayTypeLoc);
5563};
5564
5565void TypeLocReader::VisitQualifiedTypeLoc(QualifiedTypeLoc TL) {
5566 // nothing to do
5567}
5568void TypeLocReader::VisitBuiltinTypeLoc(BuiltinTypeLoc TL) {
5569 TL.setBuiltinLoc(ReadSourceLocation(Record, Idx));
5570 if (TL.needsExtraLocalData()) {
5571 TL.setWrittenTypeSpec(static_cast<DeclSpec::TST>(Record[Idx++]));
5572 TL.setWrittenSignSpec(static_cast<DeclSpec::TSS>(Record[Idx++]));
5573 TL.setWrittenWidthSpec(static_cast<DeclSpec::TSW>(Record[Idx++]));
5574 TL.setModeAttr(Record[Idx++]);
5575 }
5576}
5577void TypeLocReader::VisitComplexTypeLoc(ComplexTypeLoc TL) {
5578 TL.setNameLoc(ReadSourceLocation(Record, Idx));
5579}
5580void TypeLocReader::VisitPointerTypeLoc(PointerTypeLoc TL) {
5581 TL.setStarLoc(ReadSourceLocation(Record, Idx));
5582}
Reid Kleckner8a365022013-06-24 17:51:48 +00005583void TypeLocReader::VisitDecayedTypeLoc(DecayedTypeLoc TL) {
5584 // nothing to do
5585}
Reid Kleckner0503a872013-12-05 01:23:43 +00005586void TypeLocReader::VisitAdjustedTypeLoc(AdjustedTypeLoc TL) {
5587 // nothing to do
5588}
Guy Benyei11169dd2012-12-18 14:30:41 +00005589void TypeLocReader::VisitBlockPointerTypeLoc(BlockPointerTypeLoc TL) {
5590 TL.setCaretLoc(ReadSourceLocation(Record, Idx));
5591}
5592void TypeLocReader::VisitLValueReferenceTypeLoc(LValueReferenceTypeLoc TL) {
5593 TL.setAmpLoc(ReadSourceLocation(Record, Idx));
5594}
5595void TypeLocReader::VisitRValueReferenceTypeLoc(RValueReferenceTypeLoc TL) {
5596 TL.setAmpAmpLoc(ReadSourceLocation(Record, Idx));
5597}
5598void TypeLocReader::VisitMemberPointerTypeLoc(MemberPointerTypeLoc TL) {
5599 TL.setStarLoc(ReadSourceLocation(Record, Idx));
5600 TL.setClassTInfo(Reader.GetTypeSourceInfo(F, Record, Idx));
5601}
5602void TypeLocReader::VisitArrayTypeLoc(ArrayTypeLoc TL) {
5603 TL.setLBracketLoc(ReadSourceLocation(Record, Idx));
5604 TL.setRBracketLoc(ReadSourceLocation(Record, Idx));
5605 if (Record[Idx++])
5606 TL.setSizeExpr(Reader.ReadExpr(F));
5607 else
5608 TL.setSizeExpr(0);
5609}
5610void TypeLocReader::VisitConstantArrayTypeLoc(ConstantArrayTypeLoc TL) {
5611 VisitArrayTypeLoc(TL);
5612}
5613void TypeLocReader::VisitIncompleteArrayTypeLoc(IncompleteArrayTypeLoc TL) {
5614 VisitArrayTypeLoc(TL);
5615}
5616void TypeLocReader::VisitVariableArrayTypeLoc(VariableArrayTypeLoc TL) {
5617 VisitArrayTypeLoc(TL);
5618}
5619void TypeLocReader::VisitDependentSizedArrayTypeLoc(
5620 DependentSizedArrayTypeLoc TL) {
5621 VisitArrayTypeLoc(TL);
5622}
5623void TypeLocReader::VisitDependentSizedExtVectorTypeLoc(
5624 DependentSizedExtVectorTypeLoc TL) {
5625 TL.setNameLoc(ReadSourceLocation(Record, Idx));
5626}
5627void TypeLocReader::VisitVectorTypeLoc(VectorTypeLoc TL) {
5628 TL.setNameLoc(ReadSourceLocation(Record, Idx));
5629}
5630void TypeLocReader::VisitExtVectorTypeLoc(ExtVectorTypeLoc TL) {
5631 TL.setNameLoc(ReadSourceLocation(Record, Idx));
5632}
5633void TypeLocReader::VisitFunctionTypeLoc(FunctionTypeLoc TL) {
5634 TL.setLocalRangeBegin(ReadSourceLocation(Record, Idx));
5635 TL.setLParenLoc(ReadSourceLocation(Record, Idx));
5636 TL.setRParenLoc(ReadSourceLocation(Record, Idx));
5637 TL.setLocalRangeEnd(ReadSourceLocation(Record, Idx));
Alp Tokerb3fd5cf2014-01-21 00:32:38 +00005638 for (unsigned i = 0, e = TL.getNumParams(); i != e; ++i) {
5639 TL.setParam(i, ReadDeclAs<ParmVarDecl>(Record, Idx));
Guy Benyei11169dd2012-12-18 14:30:41 +00005640 }
5641}
5642void TypeLocReader::VisitFunctionProtoTypeLoc(FunctionProtoTypeLoc TL) {
5643 VisitFunctionTypeLoc(TL);
5644}
5645void TypeLocReader::VisitFunctionNoProtoTypeLoc(FunctionNoProtoTypeLoc TL) {
5646 VisitFunctionTypeLoc(TL);
5647}
5648void TypeLocReader::VisitUnresolvedUsingTypeLoc(UnresolvedUsingTypeLoc TL) {
5649 TL.setNameLoc(ReadSourceLocation(Record, Idx));
5650}
5651void TypeLocReader::VisitTypedefTypeLoc(TypedefTypeLoc TL) {
5652 TL.setNameLoc(ReadSourceLocation(Record, Idx));
5653}
5654void TypeLocReader::VisitTypeOfExprTypeLoc(TypeOfExprTypeLoc TL) {
5655 TL.setTypeofLoc(ReadSourceLocation(Record, Idx));
5656 TL.setLParenLoc(ReadSourceLocation(Record, Idx));
5657 TL.setRParenLoc(ReadSourceLocation(Record, Idx));
5658}
5659void TypeLocReader::VisitTypeOfTypeLoc(TypeOfTypeLoc TL) {
5660 TL.setTypeofLoc(ReadSourceLocation(Record, Idx));
5661 TL.setLParenLoc(ReadSourceLocation(Record, Idx));
5662 TL.setRParenLoc(ReadSourceLocation(Record, Idx));
5663 TL.setUnderlyingTInfo(Reader.GetTypeSourceInfo(F, Record, Idx));
5664}
5665void TypeLocReader::VisitDecltypeTypeLoc(DecltypeTypeLoc TL) {
5666 TL.setNameLoc(ReadSourceLocation(Record, Idx));
5667}
5668void TypeLocReader::VisitUnaryTransformTypeLoc(UnaryTransformTypeLoc TL) {
5669 TL.setKWLoc(ReadSourceLocation(Record, Idx));
5670 TL.setLParenLoc(ReadSourceLocation(Record, Idx));
5671 TL.setRParenLoc(ReadSourceLocation(Record, Idx));
5672 TL.setUnderlyingTInfo(Reader.GetTypeSourceInfo(F, Record, Idx));
5673}
5674void TypeLocReader::VisitAutoTypeLoc(AutoTypeLoc TL) {
5675 TL.setNameLoc(ReadSourceLocation(Record, Idx));
5676}
5677void TypeLocReader::VisitRecordTypeLoc(RecordTypeLoc TL) {
5678 TL.setNameLoc(ReadSourceLocation(Record, Idx));
5679}
5680void TypeLocReader::VisitEnumTypeLoc(EnumTypeLoc TL) {
5681 TL.setNameLoc(ReadSourceLocation(Record, Idx));
5682}
5683void TypeLocReader::VisitAttributedTypeLoc(AttributedTypeLoc TL) {
5684 TL.setAttrNameLoc(ReadSourceLocation(Record, Idx));
5685 if (TL.hasAttrOperand()) {
5686 SourceRange range;
5687 range.setBegin(ReadSourceLocation(Record, Idx));
5688 range.setEnd(ReadSourceLocation(Record, Idx));
5689 TL.setAttrOperandParensRange(range);
5690 }
5691 if (TL.hasAttrExprOperand()) {
5692 if (Record[Idx++])
5693 TL.setAttrExprOperand(Reader.ReadExpr(F));
5694 else
5695 TL.setAttrExprOperand(0);
5696 } else if (TL.hasAttrEnumOperand())
5697 TL.setAttrEnumOperandLoc(ReadSourceLocation(Record, Idx));
5698}
5699void TypeLocReader::VisitTemplateTypeParmTypeLoc(TemplateTypeParmTypeLoc TL) {
5700 TL.setNameLoc(ReadSourceLocation(Record, Idx));
5701}
5702void TypeLocReader::VisitSubstTemplateTypeParmTypeLoc(
5703 SubstTemplateTypeParmTypeLoc TL) {
5704 TL.setNameLoc(ReadSourceLocation(Record, Idx));
5705}
5706void TypeLocReader::VisitSubstTemplateTypeParmPackTypeLoc(
5707 SubstTemplateTypeParmPackTypeLoc TL) {
5708 TL.setNameLoc(ReadSourceLocation(Record, Idx));
5709}
5710void TypeLocReader::VisitTemplateSpecializationTypeLoc(
5711 TemplateSpecializationTypeLoc TL) {
5712 TL.setTemplateKeywordLoc(ReadSourceLocation(Record, Idx));
5713 TL.setTemplateNameLoc(ReadSourceLocation(Record, Idx));
5714 TL.setLAngleLoc(ReadSourceLocation(Record, Idx));
5715 TL.setRAngleLoc(ReadSourceLocation(Record, Idx));
5716 for (unsigned i = 0, e = TL.getNumArgs(); i != e; ++i)
5717 TL.setArgLocInfo(i,
5718 Reader.GetTemplateArgumentLocInfo(F,
5719 TL.getTypePtr()->getArg(i).getKind(),
5720 Record, Idx));
5721}
5722void TypeLocReader::VisitParenTypeLoc(ParenTypeLoc TL) {
5723 TL.setLParenLoc(ReadSourceLocation(Record, Idx));
5724 TL.setRParenLoc(ReadSourceLocation(Record, Idx));
5725}
5726void TypeLocReader::VisitElaboratedTypeLoc(ElaboratedTypeLoc TL) {
5727 TL.setElaboratedKeywordLoc(ReadSourceLocation(Record, Idx));
5728 TL.setQualifierLoc(Reader.ReadNestedNameSpecifierLoc(F, Record, Idx));
5729}
5730void TypeLocReader::VisitInjectedClassNameTypeLoc(InjectedClassNameTypeLoc TL) {
5731 TL.setNameLoc(ReadSourceLocation(Record, Idx));
5732}
5733void TypeLocReader::VisitDependentNameTypeLoc(DependentNameTypeLoc TL) {
5734 TL.setElaboratedKeywordLoc(ReadSourceLocation(Record, Idx));
5735 TL.setQualifierLoc(Reader.ReadNestedNameSpecifierLoc(F, Record, Idx));
5736 TL.setNameLoc(ReadSourceLocation(Record, Idx));
5737}
5738void TypeLocReader::VisitDependentTemplateSpecializationTypeLoc(
5739 DependentTemplateSpecializationTypeLoc TL) {
5740 TL.setElaboratedKeywordLoc(ReadSourceLocation(Record, Idx));
5741 TL.setQualifierLoc(Reader.ReadNestedNameSpecifierLoc(F, Record, Idx));
5742 TL.setTemplateKeywordLoc(ReadSourceLocation(Record, Idx));
5743 TL.setTemplateNameLoc(ReadSourceLocation(Record, Idx));
5744 TL.setLAngleLoc(ReadSourceLocation(Record, Idx));
5745 TL.setRAngleLoc(ReadSourceLocation(Record, Idx));
5746 for (unsigned I = 0, E = TL.getNumArgs(); I != E; ++I)
5747 TL.setArgLocInfo(I,
5748 Reader.GetTemplateArgumentLocInfo(F,
5749 TL.getTypePtr()->getArg(I).getKind(),
5750 Record, Idx));
5751}
5752void TypeLocReader::VisitPackExpansionTypeLoc(PackExpansionTypeLoc TL) {
5753 TL.setEllipsisLoc(ReadSourceLocation(Record, Idx));
5754}
5755void TypeLocReader::VisitObjCInterfaceTypeLoc(ObjCInterfaceTypeLoc TL) {
5756 TL.setNameLoc(ReadSourceLocation(Record, Idx));
5757}
5758void TypeLocReader::VisitObjCObjectTypeLoc(ObjCObjectTypeLoc TL) {
5759 TL.setHasBaseTypeAsWritten(Record[Idx++]);
5760 TL.setLAngleLoc(ReadSourceLocation(Record, Idx));
5761 TL.setRAngleLoc(ReadSourceLocation(Record, Idx));
5762 for (unsigned i = 0, e = TL.getNumProtocols(); i != e; ++i)
5763 TL.setProtocolLoc(i, ReadSourceLocation(Record, Idx));
5764}
5765void TypeLocReader::VisitObjCObjectPointerTypeLoc(ObjCObjectPointerTypeLoc TL) {
5766 TL.setStarLoc(ReadSourceLocation(Record, Idx));
5767}
5768void TypeLocReader::VisitAtomicTypeLoc(AtomicTypeLoc TL) {
5769 TL.setKWLoc(ReadSourceLocation(Record, Idx));
5770 TL.setLParenLoc(ReadSourceLocation(Record, Idx));
5771 TL.setRParenLoc(ReadSourceLocation(Record, Idx));
5772}
5773
5774TypeSourceInfo *ASTReader::GetTypeSourceInfo(ModuleFile &F,
5775 const RecordData &Record,
5776 unsigned &Idx) {
5777 QualType InfoTy = readType(F, Record, Idx);
5778 if (InfoTy.isNull())
5779 return 0;
5780
5781 TypeSourceInfo *TInfo = getContext().CreateTypeSourceInfo(InfoTy);
5782 TypeLocReader TLR(*this, F, Record, Idx);
5783 for (TypeLoc TL = TInfo->getTypeLoc(); !TL.isNull(); TL = TL.getNextTypeLoc())
5784 TLR.Visit(TL);
5785 return TInfo;
5786}
5787
5788QualType ASTReader::GetType(TypeID ID) {
5789 unsigned FastQuals = ID & Qualifiers::FastMask;
5790 unsigned Index = ID >> Qualifiers::FastWidth;
5791
5792 if (Index < NUM_PREDEF_TYPE_IDS) {
5793 QualType T;
5794 switch ((PredefinedTypeIDs)Index) {
5795 case PREDEF_TYPE_NULL_ID: return QualType();
5796 case PREDEF_TYPE_VOID_ID: T = Context.VoidTy; break;
5797 case PREDEF_TYPE_BOOL_ID: T = Context.BoolTy; break;
5798
5799 case PREDEF_TYPE_CHAR_U_ID:
5800 case PREDEF_TYPE_CHAR_S_ID:
5801 // FIXME: Check that the signedness of CharTy is correct!
5802 T = Context.CharTy;
5803 break;
5804
5805 case PREDEF_TYPE_UCHAR_ID: T = Context.UnsignedCharTy; break;
5806 case PREDEF_TYPE_USHORT_ID: T = Context.UnsignedShortTy; break;
5807 case PREDEF_TYPE_UINT_ID: T = Context.UnsignedIntTy; break;
5808 case PREDEF_TYPE_ULONG_ID: T = Context.UnsignedLongTy; break;
5809 case PREDEF_TYPE_ULONGLONG_ID: T = Context.UnsignedLongLongTy; break;
5810 case PREDEF_TYPE_UINT128_ID: T = Context.UnsignedInt128Ty; break;
5811 case PREDEF_TYPE_SCHAR_ID: T = Context.SignedCharTy; break;
5812 case PREDEF_TYPE_WCHAR_ID: T = Context.WCharTy; break;
5813 case PREDEF_TYPE_SHORT_ID: T = Context.ShortTy; break;
5814 case PREDEF_TYPE_INT_ID: T = Context.IntTy; break;
5815 case PREDEF_TYPE_LONG_ID: T = Context.LongTy; break;
5816 case PREDEF_TYPE_LONGLONG_ID: T = Context.LongLongTy; break;
5817 case PREDEF_TYPE_INT128_ID: T = Context.Int128Ty; break;
5818 case PREDEF_TYPE_HALF_ID: T = Context.HalfTy; break;
5819 case PREDEF_TYPE_FLOAT_ID: T = Context.FloatTy; break;
5820 case PREDEF_TYPE_DOUBLE_ID: T = Context.DoubleTy; break;
5821 case PREDEF_TYPE_LONGDOUBLE_ID: T = Context.LongDoubleTy; break;
5822 case PREDEF_TYPE_OVERLOAD_ID: T = Context.OverloadTy; break;
5823 case PREDEF_TYPE_BOUND_MEMBER: T = Context.BoundMemberTy; break;
5824 case PREDEF_TYPE_PSEUDO_OBJECT: T = Context.PseudoObjectTy; break;
5825 case PREDEF_TYPE_DEPENDENT_ID: T = Context.DependentTy; break;
5826 case PREDEF_TYPE_UNKNOWN_ANY: T = Context.UnknownAnyTy; break;
5827 case PREDEF_TYPE_NULLPTR_ID: T = Context.NullPtrTy; break;
5828 case PREDEF_TYPE_CHAR16_ID: T = Context.Char16Ty; break;
5829 case PREDEF_TYPE_CHAR32_ID: T = Context.Char32Ty; break;
5830 case PREDEF_TYPE_OBJC_ID: T = Context.ObjCBuiltinIdTy; break;
5831 case PREDEF_TYPE_OBJC_CLASS: T = Context.ObjCBuiltinClassTy; break;
5832 case PREDEF_TYPE_OBJC_SEL: T = Context.ObjCBuiltinSelTy; break;
Guy Benyeid8a08ea2012-12-18 14:38:23 +00005833 case PREDEF_TYPE_IMAGE1D_ID: T = Context.OCLImage1dTy; break;
5834 case PREDEF_TYPE_IMAGE1D_ARR_ID: T = Context.OCLImage1dArrayTy; break;
5835 case PREDEF_TYPE_IMAGE1D_BUFF_ID: T = Context.OCLImage1dBufferTy; break;
5836 case PREDEF_TYPE_IMAGE2D_ID: T = Context.OCLImage2dTy; break;
5837 case PREDEF_TYPE_IMAGE2D_ARR_ID: T = Context.OCLImage2dArrayTy; break;
5838 case PREDEF_TYPE_IMAGE3D_ID: T = Context.OCLImage3dTy; break;
Guy Benyei61054192013-02-07 10:55:47 +00005839 case PREDEF_TYPE_SAMPLER_ID: T = Context.OCLSamplerTy; break;
Guy Benyei1b4fb3e2013-01-20 12:31:11 +00005840 case PREDEF_TYPE_EVENT_ID: T = Context.OCLEventTy; break;
Guy Benyei11169dd2012-12-18 14:30:41 +00005841 case PREDEF_TYPE_AUTO_DEDUCT: T = Context.getAutoDeductType(); break;
5842
5843 case PREDEF_TYPE_AUTO_RREF_DEDUCT:
5844 T = Context.getAutoRRefDeductType();
5845 break;
5846
5847 case PREDEF_TYPE_ARC_UNBRIDGED_CAST:
5848 T = Context.ARCUnbridgedCastTy;
5849 break;
5850
5851 case PREDEF_TYPE_VA_LIST_TAG:
5852 T = Context.getVaListTagType();
5853 break;
5854
5855 case PREDEF_TYPE_BUILTIN_FN:
5856 T = Context.BuiltinFnTy;
5857 break;
5858 }
5859
5860 assert(!T.isNull() && "Unknown predefined type");
5861 return T.withFastQualifiers(FastQuals);
5862 }
5863
5864 Index -= NUM_PREDEF_TYPE_IDS;
5865 assert(Index < TypesLoaded.size() && "Type index out-of-range");
5866 if (TypesLoaded[Index].isNull()) {
5867 TypesLoaded[Index] = readTypeRecord(Index);
5868 if (TypesLoaded[Index].isNull())
5869 return QualType();
5870
5871 TypesLoaded[Index]->setFromAST();
5872 if (DeserializationListener)
5873 DeserializationListener->TypeRead(TypeIdx::fromTypeID(ID),
5874 TypesLoaded[Index]);
5875 }
5876
5877 return TypesLoaded[Index].withFastQualifiers(FastQuals);
5878}
5879
5880QualType ASTReader::getLocalType(ModuleFile &F, unsigned LocalID) {
5881 return GetType(getGlobalTypeID(F, LocalID));
5882}
5883
5884serialization::TypeID
5885ASTReader::getGlobalTypeID(ModuleFile &F, unsigned LocalID) const {
5886 unsigned FastQuals = LocalID & Qualifiers::FastMask;
5887 unsigned LocalIndex = LocalID >> Qualifiers::FastWidth;
5888
5889 if (LocalIndex < NUM_PREDEF_TYPE_IDS)
5890 return LocalID;
5891
5892 ContinuousRangeMap<uint32_t, int, 2>::iterator I
5893 = F.TypeRemap.find(LocalIndex - NUM_PREDEF_TYPE_IDS);
5894 assert(I != F.TypeRemap.end() && "Invalid index into type index remap");
5895
5896 unsigned GlobalIndex = LocalIndex + I->second;
5897 return (GlobalIndex << Qualifiers::FastWidth) | FastQuals;
5898}
5899
5900TemplateArgumentLocInfo
5901ASTReader::GetTemplateArgumentLocInfo(ModuleFile &F,
5902 TemplateArgument::ArgKind Kind,
5903 const RecordData &Record,
5904 unsigned &Index) {
5905 switch (Kind) {
5906 case TemplateArgument::Expression:
5907 return ReadExpr(F);
5908 case TemplateArgument::Type:
5909 return GetTypeSourceInfo(F, Record, Index);
5910 case TemplateArgument::Template: {
5911 NestedNameSpecifierLoc QualifierLoc = ReadNestedNameSpecifierLoc(F, Record,
5912 Index);
5913 SourceLocation TemplateNameLoc = ReadSourceLocation(F, Record, Index);
5914 return TemplateArgumentLocInfo(QualifierLoc, TemplateNameLoc,
5915 SourceLocation());
5916 }
5917 case TemplateArgument::TemplateExpansion: {
5918 NestedNameSpecifierLoc QualifierLoc = ReadNestedNameSpecifierLoc(F, Record,
5919 Index);
5920 SourceLocation TemplateNameLoc = ReadSourceLocation(F, Record, Index);
5921 SourceLocation EllipsisLoc = ReadSourceLocation(F, Record, Index);
5922 return TemplateArgumentLocInfo(QualifierLoc, TemplateNameLoc,
5923 EllipsisLoc);
5924 }
5925 case TemplateArgument::Null:
5926 case TemplateArgument::Integral:
5927 case TemplateArgument::Declaration:
5928 case TemplateArgument::NullPtr:
5929 case TemplateArgument::Pack:
5930 // FIXME: Is this right?
5931 return TemplateArgumentLocInfo();
5932 }
5933 llvm_unreachable("unexpected template argument loc");
5934}
5935
5936TemplateArgumentLoc
5937ASTReader::ReadTemplateArgumentLoc(ModuleFile &F,
5938 const RecordData &Record, unsigned &Index) {
5939 TemplateArgument Arg = ReadTemplateArgument(F, Record, Index);
5940
5941 if (Arg.getKind() == TemplateArgument::Expression) {
5942 if (Record[Index++]) // bool InfoHasSameExpr.
5943 return TemplateArgumentLoc(Arg, TemplateArgumentLocInfo(Arg.getAsExpr()));
5944 }
5945 return TemplateArgumentLoc(Arg, GetTemplateArgumentLocInfo(F, Arg.getKind(),
5946 Record, Index));
5947}
5948
Enea Zaffanella6dbe1872013-08-10 07:24:53 +00005949const ASTTemplateArgumentListInfo*
5950ASTReader::ReadASTTemplateArgumentListInfo(ModuleFile &F,
5951 const RecordData &Record,
5952 unsigned &Index) {
5953 SourceLocation LAngleLoc = ReadSourceLocation(F, Record, Index);
5954 SourceLocation RAngleLoc = ReadSourceLocation(F, Record, Index);
5955 unsigned NumArgsAsWritten = Record[Index++];
5956 TemplateArgumentListInfo TemplArgsInfo(LAngleLoc, RAngleLoc);
5957 for (unsigned i = 0; i != NumArgsAsWritten; ++i)
5958 TemplArgsInfo.addArgument(ReadTemplateArgumentLoc(F, Record, Index));
5959 return ASTTemplateArgumentListInfo::Create(getContext(), TemplArgsInfo);
5960}
5961
Guy Benyei11169dd2012-12-18 14:30:41 +00005962Decl *ASTReader::GetExternalDecl(uint32_t ID) {
5963 return GetDecl(ID);
5964}
5965
Richard Smithcd45dbc2014-04-19 03:48:30 +00005966uint64_t ASTReader::readCXXBaseSpecifiers(ModuleFile &M,
5967 const RecordData &Record,
5968 unsigned &Idx) {
5969 if (Idx >= Record.size() || Record[Idx] > M.LocalNumCXXBaseSpecifiers) {
5970 Error("malformed AST file: missing C++ base specifier");
Guy Benyei11169dd2012-12-18 14:30:41 +00005971 return 0;
Richard Smithcd45dbc2014-04-19 03:48:30 +00005972 }
5973
Guy Benyei11169dd2012-12-18 14:30:41 +00005974 unsigned LocalID = Record[Idx++];
5975 return getGlobalBitOffset(M, M.CXXBaseSpecifiersOffsets[LocalID - 1]);
5976}
5977
5978CXXBaseSpecifier *ASTReader::GetExternalCXXBaseSpecifiers(uint64_t Offset) {
5979 RecordLocation Loc = getLocalBitOffset(Offset);
Chris Lattner7fb3bef2013-01-20 00:56:42 +00005980 BitstreamCursor &Cursor = Loc.F->DeclsCursor;
Guy Benyei11169dd2012-12-18 14:30:41 +00005981 SavedStreamPosition SavedPosition(Cursor);
5982 Cursor.JumpToBit(Loc.Offset);
5983 ReadingKindTracker ReadingKind(Read_Decl, *this);
5984 RecordData Record;
5985 unsigned Code = Cursor.ReadCode();
Chris Lattner0e6c9402013-01-20 02:38:54 +00005986 unsigned RecCode = Cursor.readRecord(Code, Record);
Guy Benyei11169dd2012-12-18 14:30:41 +00005987 if (RecCode != DECL_CXX_BASE_SPECIFIERS) {
Richard Smithcd45dbc2014-04-19 03:48:30 +00005988 Error("malformed AST file: missing C++ base specifiers");
Guy Benyei11169dd2012-12-18 14:30:41 +00005989 return 0;
5990 }
5991
5992 unsigned Idx = 0;
5993 unsigned NumBases = Record[Idx++];
5994 void *Mem = Context.Allocate(sizeof(CXXBaseSpecifier) * NumBases);
5995 CXXBaseSpecifier *Bases = new (Mem) CXXBaseSpecifier [NumBases];
5996 for (unsigned I = 0; I != NumBases; ++I)
5997 Bases[I] = ReadCXXBaseSpecifier(*Loc.F, Record, Idx);
5998 return Bases;
5999}
6000
6001serialization::DeclID
6002ASTReader::getGlobalDeclID(ModuleFile &F, LocalDeclID LocalID) const {
6003 if (LocalID < NUM_PREDEF_DECL_IDS)
6004 return LocalID;
6005
6006 ContinuousRangeMap<uint32_t, int, 2>::iterator I
6007 = F.DeclRemap.find(LocalID - NUM_PREDEF_DECL_IDS);
6008 assert(I != F.DeclRemap.end() && "Invalid index into decl index remap");
6009
6010 return LocalID + I->second;
6011}
6012
6013bool ASTReader::isDeclIDFromModule(serialization::GlobalDeclID ID,
6014 ModuleFile &M) const {
6015 GlobalDeclMapType::const_iterator I = GlobalDeclMap.find(ID);
6016 assert(I != GlobalDeclMap.end() && "Corrupted global declaration map");
6017 return &M == I->second;
6018}
6019
Douglas Gregor9f782892013-01-21 15:25:38 +00006020ModuleFile *ASTReader::getOwningModuleFile(const Decl *D) {
Guy Benyei11169dd2012-12-18 14:30:41 +00006021 if (!D->isFromASTFile())
6022 return 0;
6023 GlobalDeclMapType::const_iterator I = GlobalDeclMap.find(D->getGlobalID());
6024 assert(I != GlobalDeclMap.end() && "Corrupted global declaration map");
6025 return I->second;
6026}
6027
6028SourceLocation ASTReader::getSourceLocationForDeclID(GlobalDeclID ID) {
6029 if (ID < NUM_PREDEF_DECL_IDS)
6030 return SourceLocation();
Richard Smithcd45dbc2014-04-19 03:48:30 +00006031
Guy Benyei11169dd2012-12-18 14:30:41 +00006032 unsigned Index = ID - NUM_PREDEF_DECL_IDS;
6033
6034 if (Index > DeclsLoaded.size()) {
6035 Error("declaration ID out-of-range for AST file");
6036 return SourceLocation();
6037 }
Richard Smithcd45dbc2014-04-19 03:48:30 +00006038
Guy Benyei11169dd2012-12-18 14:30:41 +00006039 if (Decl *D = DeclsLoaded[Index])
6040 return D->getLocation();
6041
6042 unsigned RawLocation = 0;
6043 RecordLocation Rec = DeclCursorForID(ID, RawLocation);
6044 return ReadSourceLocation(*Rec.F, RawLocation);
6045}
6046
Richard Smithcd45dbc2014-04-19 03:48:30 +00006047Decl *ASTReader::GetExistingDecl(DeclID ID) {
6048 if (ID < NUM_PREDEF_DECL_IDS) {
Guy Benyei11169dd2012-12-18 14:30:41 +00006049 switch ((PredefinedDeclIDs)ID) {
6050 case PREDEF_DECL_NULL_ID:
6051 return 0;
Richard Smithcd45dbc2014-04-19 03:48:30 +00006052
Guy Benyei11169dd2012-12-18 14:30:41 +00006053 case PREDEF_DECL_TRANSLATION_UNIT_ID:
6054 return Context.getTranslationUnitDecl();
Richard Smithcd45dbc2014-04-19 03:48:30 +00006055
Guy Benyei11169dd2012-12-18 14:30:41 +00006056 case PREDEF_DECL_OBJC_ID_ID:
6057 return Context.getObjCIdDecl();
6058
6059 case PREDEF_DECL_OBJC_SEL_ID:
6060 return Context.getObjCSelDecl();
6061
6062 case PREDEF_DECL_OBJC_CLASS_ID:
6063 return Context.getObjCClassDecl();
Richard Smithcd45dbc2014-04-19 03:48:30 +00006064
Guy Benyei11169dd2012-12-18 14:30:41 +00006065 case PREDEF_DECL_OBJC_PROTOCOL_ID:
6066 return Context.getObjCProtocolDecl();
Richard Smithcd45dbc2014-04-19 03:48:30 +00006067
Guy Benyei11169dd2012-12-18 14:30:41 +00006068 case PREDEF_DECL_INT_128_ID:
6069 return Context.getInt128Decl();
6070
6071 case PREDEF_DECL_UNSIGNED_INT_128_ID:
6072 return Context.getUInt128Decl();
Richard Smithcd45dbc2014-04-19 03:48:30 +00006073
Guy Benyei11169dd2012-12-18 14:30:41 +00006074 case PREDEF_DECL_OBJC_INSTANCETYPE_ID:
6075 return Context.getObjCInstanceTypeDecl();
6076
6077 case PREDEF_DECL_BUILTIN_VA_LIST_ID:
6078 return Context.getBuiltinVaListDecl();
6079 }
6080 }
Richard Smithcd45dbc2014-04-19 03:48:30 +00006081
Guy Benyei11169dd2012-12-18 14:30:41 +00006082 unsigned Index = ID - NUM_PREDEF_DECL_IDS;
6083
6084 if (Index >= DeclsLoaded.size()) {
6085 assert(0 && "declaration ID out-of-range for AST file");
6086 Error("declaration ID out-of-range for AST file");
6087 return 0;
6088 }
Richard Smithcd45dbc2014-04-19 03:48:30 +00006089
6090 return DeclsLoaded[Index];
6091}
6092
6093Decl *ASTReader::GetDecl(DeclID ID) {
6094 if (ID < NUM_PREDEF_DECL_IDS)
6095 return GetExistingDecl(ID);
6096
6097 unsigned Index = ID - NUM_PREDEF_DECL_IDS;
6098
6099 if (Index >= DeclsLoaded.size()) {
6100 assert(0 && "declaration ID out-of-range for AST file");
6101 Error("declaration ID out-of-range for AST file");
6102 return 0;
6103 }
6104
Guy Benyei11169dd2012-12-18 14:30:41 +00006105 if (!DeclsLoaded[Index]) {
6106 ReadDeclRecord(ID);
6107 if (DeserializationListener)
6108 DeserializationListener->DeclRead(ID, DeclsLoaded[Index]);
6109 }
6110
6111 return DeclsLoaded[Index];
6112}
6113
6114DeclID ASTReader::mapGlobalIDToModuleFileGlobalID(ModuleFile &M,
6115 DeclID GlobalID) {
6116 if (GlobalID < NUM_PREDEF_DECL_IDS)
6117 return GlobalID;
6118
6119 GlobalDeclMapType::const_iterator I = GlobalDeclMap.find(GlobalID);
6120 assert(I != GlobalDeclMap.end() && "Corrupted global declaration map");
6121 ModuleFile *Owner = I->second;
6122
6123 llvm::DenseMap<ModuleFile *, serialization::DeclID>::iterator Pos
6124 = M.GlobalToLocalDeclIDs.find(Owner);
6125 if (Pos == M.GlobalToLocalDeclIDs.end())
6126 return 0;
6127
6128 return GlobalID - Owner->BaseDeclID + Pos->second;
6129}
6130
6131serialization::DeclID ASTReader::ReadDeclID(ModuleFile &F,
6132 const RecordData &Record,
6133 unsigned &Idx) {
6134 if (Idx >= Record.size()) {
6135 Error("Corrupted AST file");
6136 return 0;
6137 }
6138
6139 return getGlobalDeclID(F, Record[Idx++]);
6140}
6141
6142/// \brief Resolve the offset of a statement into a statement.
6143///
6144/// This operation will read a new statement from the external
6145/// source each time it is called, and is meant to be used via a
6146/// LazyOffsetPtr (which is used by Decls for the body of functions, etc).
6147Stmt *ASTReader::GetExternalDeclStmt(uint64_t Offset) {
6148 // Switch case IDs are per Decl.
6149 ClearSwitchCaseIDs();
6150
6151 // Offset here is a global offset across the entire chain.
6152 RecordLocation Loc = getLocalBitOffset(Offset);
6153 Loc.F->DeclsCursor.JumpToBit(Loc.Offset);
6154 return ReadStmtFromStream(*Loc.F);
6155}
6156
6157namespace {
6158 class FindExternalLexicalDeclsVisitor {
6159 ASTReader &Reader;
6160 const DeclContext *DC;
6161 bool (*isKindWeWant)(Decl::Kind);
6162
6163 SmallVectorImpl<Decl*> &Decls;
6164 bool PredefsVisited[NUM_PREDEF_DECL_IDS];
6165
6166 public:
6167 FindExternalLexicalDeclsVisitor(ASTReader &Reader, const DeclContext *DC,
6168 bool (*isKindWeWant)(Decl::Kind),
6169 SmallVectorImpl<Decl*> &Decls)
6170 : Reader(Reader), DC(DC), isKindWeWant(isKindWeWant), Decls(Decls)
6171 {
6172 for (unsigned I = 0; I != NUM_PREDEF_DECL_IDS; ++I)
6173 PredefsVisited[I] = false;
6174 }
6175
6176 static bool visit(ModuleFile &M, bool Preorder, void *UserData) {
6177 if (Preorder)
6178 return false;
6179
6180 FindExternalLexicalDeclsVisitor *This
6181 = static_cast<FindExternalLexicalDeclsVisitor *>(UserData);
6182
6183 ModuleFile::DeclContextInfosMap::iterator Info
6184 = M.DeclContextInfos.find(This->DC);
6185 if (Info == M.DeclContextInfos.end() || !Info->second.LexicalDecls)
6186 return false;
6187
6188 // Load all of the declaration IDs
6189 for (const KindDeclIDPair *ID = Info->second.LexicalDecls,
6190 *IDE = ID + Info->second.NumLexicalDecls;
6191 ID != IDE; ++ID) {
6192 if (This->isKindWeWant && !This->isKindWeWant((Decl::Kind)ID->first))
6193 continue;
6194
6195 // Don't add predefined declarations to the lexical context more
6196 // than once.
6197 if (ID->second < NUM_PREDEF_DECL_IDS) {
6198 if (This->PredefsVisited[ID->second])
6199 continue;
6200
6201 This->PredefsVisited[ID->second] = true;
6202 }
6203
6204 if (Decl *D = This->Reader.GetLocalDecl(M, ID->second)) {
6205 if (!This->DC->isDeclInLexicalTraversal(D))
6206 This->Decls.push_back(D);
6207 }
6208 }
6209
6210 return false;
6211 }
6212 };
6213}
6214
6215ExternalLoadResult ASTReader::FindExternalLexicalDecls(const DeclContext *DC,
6216 bool (*isKindWeWant)(Decl::Kind),
6217 SmallVectorImpl<Decl*> &Decls) {
6218 // There might be lexical decls in multiple modules, for the TU at
6219 // least. Walk all of the modules in the order they were loaded.
6220 FindExternalLexicalDeclsVisitor Visitor(*this, DC, isKindWeWant, Decls);
6221 ModuleMgr.visitDepthFirst(&FindExternalLexicalDeclsVisitor::visit, &Visitor);
6222 ++NumLexicalDeclContextsRead;
6223 return ELR_Success;
6224}
6225
6226namespace {
6227
6228class DeclIDComp {
6229 ASTReader &Reader;
6230 ModuleFile &Mod;
6231
6232public:
6233 DeclIDComp(ASTReader &Reader, ModuleFile &M) : Reader(Reader), Mod(M) {}
6234
6235 bool operator()(LocalDeclID L, LocalDeclID R) const {
6236 SourceLocation LHS = getLocation(L);
6237 SourceLocation RHS = getLocation(R);
6238 return Reader.getSourceManager().isBeforeInTranslationUnit(LHS, RHS);
6239 }
6240
6241 bool operator()(SourceLocation LHS, LocalDeclID R) const {
6242 SourceLocation RHS = getLocation(R);
6243 return Reader.getSourceManager().isBeforeInTranslationUnit(LHS, RHS);
6244 }
6245
6246 bool operator()(LocalDeclID L, SourceLocation RHS) const {
6247 SourceLocation LHS = getLocation(L);
6248 return Reader.getSourceManager().isBeforeInTranslationUnit(LHS, RHS);
6249 }
6250
6251 SourceLocation getLocation(LocalDeclID ID) const {
6252 return Reader.getSourceManager().getFileLoc(
6253 Reader.getSourceLocationForDeclID(Reader.getGlobalDeclID(Mod, ID)));
6254 }
6255};
6256
6257}
6258
6259void ASTReader::FindFileRegionDecls(FileID File,
6260 unsigned Offset, unsigned Length,
6261 SmallVectorImpl<Decl *> &Decls) {
6262 SourceManager &SM = getSourceManager();
6263
6264 llvm::DenseMap<FileID, FileDeclsInfo>::iterator I = FileDeclIDs.find(File);
6265 if (I == FileDeclIDs.end())
6266 return;
6267
6268 FileDeclsInfo &DInfo = I->second;
6269 if (DInfo.Decls.empty())
6270 return;
6271
6272 SourceLocation
6273 BeginLoc = SM.getLocForStartOfFile(File).getLocWithOffset(Offset);
6274 SourceLocation EndLoc = BeginLoc.getLocWithOffset(Length);
6275
6276 DeclIDComp DIDComp(*this, *DInfo.Mod);
6277 ArrayRef<serialization::LocalDeclID>::iterator
6278 BeginIt = std::lower_bound(DInfo.Decls.begin(), DInfo.Decls.end(),
6279 BeginLoc, DIDComp);
6280 if (BeginIt != DInfo.Decls.begin())
6281 --BeginIt;
6282
6283 // If we are pointing at a top-level decl inside an objc container, we need
6284 // to backtrack until we find it otherwise we will fail to report that the
6285 // region overlaps with an objc container.
6286 while (BeginIt != DInfo.Decls.begin() &&
6287 GetDecl(getGlobalDeclID(*DInfo.Mod, *BeginIt))
6288 ->isTopLevelDeclInObjCContainer())
6289 --BeginIt;
6290
6291 ArrayRef<serialization::LocalDeclID>::iterator
6292 EndIt = std::upper_bound(DInfo.Decls.begin(), DInfo.Decls.end(),
6293 EndLoc, DIDComp);
6294 if (EndIt != DInfo.Decls.end())
6295 ++EndIt;
6296
6297 for (ArrayRef<serialization::LocalDeclID>::iterator
6298 DIt = BeginIt; DIt != EndIt; ++DIt)
6299 Decls.push_back(GetDecl(getGlobalDeclID(*DInfo.Mod, *DIt)));
6300}
6301
6302namespace {
6303 /// \brief ModuleFile visitor used to perform name lookup into a
6304 /// declaration context.
6305 class DeclContextNameLookupVisitor {
6306 ASTReader &Reader;
Dmitri Gribenkof8579502013-01-12 19:30:44 +00006307 SmallVectorImpl<const DeclContext *> &Contexts;
Guy Benyei11169dd2012-12-18 14:30:41 +00006308 DeclarationName Name;
6309 SmallVectorImpl<NamedDecl *> &Decls;
6310
6311 public:
6312 DeclContextNameLookupVisitor(ASTReader &Reader,
6313 SmallVectorImpl<const DeclContext *> &Contexts,
6314 DeclarationName Name,
6315 SmallVectorImpl<NamedDecl *> &Decls)
6316 : Reader(Reader), Contexts(Contexts), Name(Name), Decls(Decls) { }
6317
6318 static bool visit(ModuleFile &M, void *UserData) {
6319 DeclContextNameLookupVisitor *This
6320 = static_cast<DeclContextNameLookupVisitor *>(UserData);
6321
6322 // Check whether we have any visible declaration information for
6323 // this context in this module.
6324 ModuleFile::DeclContextInfosMap::iterator Info;
6325 bool FoundInfo = false;
6326 for (unsigned I = 0, N = This->Contexts.size(); I != N; ++I) {
6327 Info = M.DeclContextInfos.find(This->Contexts[I]);
6328 if (Info != M.DeclContextInfos.end() &&
6329 Info->second.NameLookupTableData) {
6330 FoundInfo = true;
6331 break;
6332 }
6333 }
6334
6335 if (!FoundInfo)
6336 return false;
6337
6338 // Look for this name within this module.
Richard Smith52e3fba2014-03-11 07:17:35 +00006339 ASTDeclContextNameLookupTable *LookupTable =
Guy Benyei11169dd2012-12-18 14:30:41 +00006340 Info->second.NameLookupTableData;
6341 ASTDeclContextNameLookupTable::iterator Pos
6342 = LookupTable->find(This->Name);
6343 if (Pos == LookupTable->end())
6344 return false;
6345
6346 bool FoundAnything = false;
6347 ASTDeclContextNameLookupTrait::data_type Data = *Pos;
6348 for (; Data.first != Data.second; ++Data.first) {
6349 NamedDecl *ND = This->Reader.GetLocalDeclAs<NamedDecl>(M, *Data.first);
6350 if (!ND)
6351 continue;
6352
6353 if (ND->getDeclName() != This->Name) {
6354 // A name might be null because the decl's redeclarable part is
6355 // currently read before reading its name. The lookup is triggered by
6356 // building that decl (likely indirectly), and so it is later in the
6357 // sense of "already existing" and can be ignored here.
6358 continue;
6359 }
6360
6361 // Record this declaration.
6362 FoundAnything = true;
6363 This->Decls.push_back(ND);
6364 }
6365
6366 return FoundAnything;
6367 }
6368 };
6369}
6370
Douglas Gregor9f782892013-01-21 15:25:38 +00006371/// \brief Retrieve the "definitive" module file for the definition of the
6372/// given declaration context, if there is one.
6373///
6374/// The "definitive" module file is the only place where we need to look to
6375/// find information about the declarations within the given declaration
6376/// context. For example, C++ and Objective-C classes, C structs/unions, and
6377/// Objective-C protocols, categories, and extensions are all defined in a
6378/// single place in the source code, so they have definitive module files
6379/// associated with them. C++ namespaces, on the other hand, can have
6380/// definitions in multiple different module files.
6381///
6382/// Note: this needs to be kept in sync with ASTWriter::AddedVisibleDecl's
6383/// NDEBUG checking.
6384static ModuleFile *getDefinitiveModuleFileFor(const DeclContext *DC,
6385 ASTReader &Reader) {
Douglas Gregor7a6e2002013-01-22 17:08:30 +00006386 if (const DeclContext *DefDC = getDefinitiveDeclContext(DC))
6387 return Reader.getOwningModuleFile(cast<Decl>(DefDC));
Douglas Gregor9f782892013-01-21 15:25:38 +00006388
6389 return 0;
6390}
6391
Richard Smith9ce12e32013-02-07 03:30:24 +00006392bool
Guy Benyei11169dd2012-12-18 14:30:41 +00006393ASTReader::FindExternalVisibleDeclsByName(const DeclContext *DC,
6394 DeclarationName Name) {
6395 assert(DC->hasExternalVisibleStorage() &&
6396 "DeclContext has no visible decls in storage");
6397 if (!Name)
Richard Smith9ce12e32013-02-07 03:30:24 +00006398 return false;
Guy Benyei11169dd2012-12-18 14:30:41 +00006399
6400 SmallVector<NamedDecl *, 64> Decls;
6401
6402 // Compute the declaration contexts we need to look into. Multiple such
6403 // declaration contexts occur when two declaration contexts from disjoint
6404 // modules get merged, e.g., when two namespaces with the same name are
6405 // independently defined in separate modules.
6406 SmallVector<const DeclContext *, 2> Contexts;
6407 Contexts.push_back(DC);
6408
6409 if (DC->isNamespace()) {
Richard Smithcd45dbc2014-04-19 03:48:30 +00006410 auto Merged = MergedDecls.find(const_cast<Decl *>(cast<Decl>(DC)));
Guy Benyei11169dd2012-12-18 14:30:41 +00006411 if (Merged != MergedDecls.end()) {
6412 for (unsigned I = 0, N = Merged->second.size(); I != N; ++I)
6413 Contexts.push_back(cast<DeclContext>(GetDecl(Merged->second[I])));
6414 }
6415 }
Richard Smithcd45dbc2014-04-19 03:48:30 +00006416 if (isa<CXXRecordDecl>(DC)) {
6417 auto Merged = MergedLookups.find(DC);
6418 if (Merged != MergedLookups.end())
6419 Contexts.insert(Contexts.end(), Merged->second.begin(),
6420 Merged->second.end());
6421 }
6422
Guy Benyei11169dd2012-12-18 14:30:41 +00006423 DeclContextNameLookupVisitor Visitor(*this, Contexts, Name, Decls);
Douglas Gregor9f782892013-01-21 15:25:38 +00006424
6425 // If we can definitively determine which module file to look into,
6426 // only look there. Otherwise, look in all module files.
6427 ModuleFile *Definitive;
6428 if (Contexts.size() == 1 &&
6429 (Definitive = getDefinitiveModuleFileFor(DC, *this))) {
6430 DeclContextNameLookupVisitor::visit(*Definitive, &Visitor);
6431 } else {
6432 ModuleMgr.visit(&DeclContextNameLookupVisitor::visit, &Visitor);
6433 }
Guy Benyei11169dd2012-12-18 14:30:41 +00006434 ++NumVisibleDeclContextsRead;
6435 SetExternalVisibleDeclsForName(DC, Name, Decls);
Richard Smith9ce12e32013-02-07 03:30:24 +00006436 return !Decls.empty();
Guy Benyei11169dd2012-12-18 14:30:41 +00006437}
6438
6439namespace {
6440 /// \brief ModuleFile visitor used to retrieve all visible names in a
6441 /// declaration context.
6442 class DeclContextAllNamesVisitor {
6443 ASTReader &Reader;
Dmitri Gribenkof8579502013-01-12 19:30:44 +00006444 SmallVectorImpl<const DeclContext *> &Contexts;
Craig Topper3598eb72013-07-05 04:43:31 +00006445 DeclsMap &Decls;
Argyrios Kyrtzidis2810e9d2012-12-19 22:21:18 +00006446 bool VisitAll;
Guy Benyei11169dd2012-12-18 14:30:41 +00006447
6448 public:
6449 DeclContextAllNamesVisitor(ASTReader &Reader,
6450 SmallVectorImpl<const DeclContext *> &Contexts,
Craig Topper3598eb72013-07-05 04:43:31 +00006451 DeclsMap &Decls, bool VisitAll)
Argyrios Kyrtzidis2810e9d2012-12-19 22:21:18 +00006452 : Reader(Reader), Contexts(Contexts), Decls(Decls), VisitAll(VisitAll) { }
Guy Benyei11169dd2012-12-18 14:30:41 +00006453
6454 static bool visit(ModuleFile &M, void *UserData) {
6455 DeclContextAllNamesVisitor *This
6456 = static_cast<DeclContextAllNamesVisitor *>(UserData);
6457
6458 // Check whether we have any visible declaration information for
6459 // this context in this module.
6460 ModuleFile::DeclContextInfosMap::iterator Info;
6461 bool FoundInfo = false;
6462 for (unsigned I = 0, N = This->Contexts.size(); I != N; ++I) {
6463 Info = M.DeclContextInfos.find(This->Contexts[I]);
6464 if (Info != M.DeclContextInfos.end() &&
6465 Info->second.NameLookupTableData) {
6466 FoundInfo = true;
6467 break;
6468 }
6469 }
6470
6471 if (!FoundInfo)
6472 return false;
6473
Richard Smith52e3fba2014-03-11 07:17:35 +00006474 ASTDeclContextNameLookupTable *LookupTable =
Guy Benyei11169dd2012-12-18 14:30:41 +00006475 Info->second.NameLookupTableData;
6476 bool FoundAnything = false;
6477 for (ASTDeclContextNameLookupTable::data_iterator
Douglas Gregor5e306b12013-01-23 22:38:11 +00006478 I = LookupTable->data_begin(), E = LookupTable->data_end();
6479 I != E;
6480 ++I) {
Guy Benyei11169dd2012-12-18 14:30:41 +00006481 ASTDeclContextNameLookupTrait::data_type Data = *I;
6482 for (; Data.first != Data.second; ++Data.first) {
6483 NamedDecl *ND = This->Reader.GetLocalDeclAs<NamedDecl>(M,
6484 *Data.first);
6485 if (!ND)
6486 continue;
6487
6488 // Record this declaration.
6489 FoundAnything = true;
6490 This->Decls[ND->getDeclName()].push_back(ND);
6491 }
6492 }
6493
Argyrios Kyrtzidis2810e9d2012-12-19 22:21:18 +00006494 return FoundAnything && !This->VisitAll;
Guy Benyei11169dd2012-12-18 14:30:41 +00006495 }
6496 };
6497}
6498
6499void ASTReader::completeVisibleDeclsMap(const DeclContext *DC) {
6500 if (!DC->hasExternalVisibleStorage())
6501 return;
Craig Topper79be4cd2013-07-05 04:33:53 +00006502 DeclsMap Decls;
Guy Benyei11169dd2012-12-18 14:30:41 +00006503
6504 // Compute the declaration contexts we need to look into. Multiple such
6505 // declaration contexts occur when two declaration contexts from disjoint
6506 // modules get merged, e.g., when two namespaces with the same name are
6507 // independently defined in separate modules.
6508 SmallVector<const DeclContext *, 2> Contexts;
6509 Contexts.push_back(DC);
6510
6511 if (DC->isNamespace()) {
6512 MergedDeclsMap::iterator Merged
6513 = MergedDecls.find(const_cast<Decl *>(cast<Decl>(DC)));
6514 if (Merged != MergedDecls.end()) {
6515 for (unsigned I = 0, N = Merged->second.size(); I != N; ++I)
6516 Contexts.push_back(cast<DeclContext>(GetDecl(Merged->second[I])));
6517 }
6518 }
6519
Argyrios Kyrtzidis2810e9d2012-12-19 22:21:18 +00006520 DeclContextAllNamesVisitor Visitor(*this, Contexts, Decls,
6521 /*VisitAll=*/DC->isFileContext());
Guy Benyei11169dd2012-12-18 14:30:41 +00006522 ModuleMgr.visit(&DeclContextAllNamesVisitor::visit, &Visitor);
6523 ++NumVisibleDeclContextsRead;
6524
Craig Topper79be4cd2013-07-05 04:33:53 +00006525 for (DeclsMap::iterator I = Decls.begin(), E = Decls.end(); I != E; ++I) {
Guy Benyei11169dd2012-12-18 14:30:41 +00006526 SetExternalVisibleDeclsForName(DC, I->first, I->second);
6527 }
6528 const_cast<DeclContext *>(DC)->setHasExternalVisibleStorage(false);
6529}
6530
6531/// \brief Under non-PCH compilation the consumer receives the objc methods
6532/// before receiving the implementation, and codegen depends on this.
6533/// We simulate this by deserializing and passing to consumer the methods of the
6534/// implementation before passing the deserialized implementation decl.
6535static void PassObjCImplDeclToConsumer(ObjCImplDecl *ImplD,
6536 ASTConsumer *Consumer) {
6537 assert(ImplD && Consumer);
6538
Aaron Ballmanaff18c02014-03-13 19:03:34 +00006539 for (auto *I : ImplD->methods())
6540 Consumer->HandleInterestingDecl(DeclGroupRef(I));
Guy Benyei11169dd2012-12-18 14:30:41 +00006541
6542 Consumer->HandleInterestingDecl(DeclGroupRef(ImplD));
6543}
6544
6545void ASTReader::PassInterestingDeclsToConsumer() {
6546 assert(Consumer);
Richard Smith04d05b52014-03-23 00:27:18 +00006547
6548 if (PassingDeclsToConsumer)
6549 return;
6550
6551 // Guard variable to avoid recursively redoing the process of passing
6552 // decls to consumer.
6553 SaveAndRestore<bool> GuardPassingDeclsToConsumer(PassingDeclsToConsumer,
6554 true);
6555
Guy Benyei11169dd2012-12-18 14:30:41 +00006556 while (!InterestingDecls.empty()) {
6557 Decl *D = InterestingDecls.front();
6558 InterestingDecls.pop_front();
6559
6560 PassInterestingDeclToConsumer(D);
6561 }
6562}
6563
6564void ASTReader::PassInterestingDeclToConsumer(Decl *D) {
6565 if (ObjCImplDecl *ImplD = dyn_cast<ObjCImplDecl>(D))
6566 PassObjCImplDeclToConsumer(ImplD, Consumer);
6567 else
6568 Consumer->HandleInterestingDecl(DeclGroupRef(D));
6569}
6570
6571void ASTReader::StartTranslationUnit(ASTConsumer *Consumer) {
6572 this->Consumer = Consumer;
6573
6574 if (!Consumer)
6575 return;
6576
Ben Langmuir332aafe2014-01-31 01:06:56 +00006577 for (unsigned I = 0, N = EagerlyDeserializedDecls.size(); I != N; ++I) {
Guy Benyei11169dd2012-12-18 14:30:41 +00006578 // Force deserialization of this decl, which will cause it to be queued for
6579 // passing to the consumer.
Ben Langmuir332aafe2014-01-31 01:06:56 +00006580 GetDecl(EagerlyDeserializedDecls[I]);
Guy Benyei11169dd2012-12-18 14:30:41 +00006581 }
Ben Langmuir332aafe2014-01-31 01:06:56 +00006582 EagerlyDeserializedDecls.clear();
Guy Benyei11169dd2012-12-18 14:30:41 +00006583
6584 PassInterestingDeclsToConsumer();
6585}
6586
6587void ASTReader::PrintStats() {
6588 std::fprintf(stderr, "*** AST File Statistics:\n");
6589
6590 unsigned NumTypesLoaded
6591 = TypesLoaded.size() - std::count(TypesLoaded.begin(), TypesLoaded.end(),
6592 QualType());
6593 unsigned NumDeclsLoaded
6594 = DeclsLoaded.size() - std::count(DeclsLoaded.begin(), DeclsLoaded.end(),
6595 (Decl *)0);
6596 unsigned NumIdentifiersLoaded
6597 = IdentifiersLoaded.size() - std::count(IdentifiersLoaded.begin(),
6598 IdentifiersLoaded.end(),
6599 (IdentifierInfo *)0);
6600 unsigned NumMacrosLoaded
6601 = MacrosLoaded.size() - std::count(MacrosLoaded.begin(),
6602 MacrosLoaded.end(),
Argyrios Kyrtzidiseb663da2013-03-22 21:12:57 +00006603 (MacroInfo *)0);
Guy Benyei11169dd2012-12-18 14:30:41 +00006604 unsigned NumSelectorsLoaded
6605 = SelectorsLoaded.size() - std::count(SelectorsLoaded.begin(),
6606 SelectorsLoaded.end(),
6607 Selector());
6608
6609 if (unsigned TotalNumSLocEntries = getTotalNumSLocs())
6610 std::fprintf(stderr, " %u/%u source location entries read (%f%%)\n",
6611 NumSLocEntriesRead, TotalNumSLocEntries,
6612 ((float)NumSLocEntriesRead/TotalNumSLocEntries * 100));
6613 if (!TypesLoaded.empty())
6614 std::fprintf(stderr, " %u/%u types read (%f%%)\n",
6615 NumTypesLoaded, (unsigned)TypesLoaded.size(),
6616 ((float)NumTypesLoaded/TypesLoaded.size() * 100));
6617 if (!DeclsLoaded.empty())
6618 std::fprintf(stderr, " %u/%u declarations read (%f%%)\n",
6619 NumDeclsLoaded, (unsigned)DeclsLoaded.size(),
6620 ((float)NumDeclsLoaded/DeclsLoaded.size() * 100));
6621 if (!IdentifiersLoaded.empty())
6622 std::fprintf(stderr, " %u/%u identifiers read (%f%%)\n",
6623 NumIdentifiersLoaded, (unsigned)IdentifiersLoaded.size(),
6624 ((float)NumIdentifiersLoaded/IdentifiersLoaded.size() * 100));
6625 if (!MacrosLoaded.empty())
6626 std::fprintf(stderr, " %u/%u macros read (%f%%)\n",
6627 NumMacrosLoaded, (unsigned)MacrosLoaded.size(),
6628 ((float)NumMacrosLoaded/MacrosLoaded.size() * 100));
6629 if (!SelectorsLoaded.empty())
6630 std::fprintf(stderr, " %u/%u selectors read (%f%%)\n",
6631 NumSelectorsLoaded, (unsigned)SelectorsLoaded.size(),
6632 ((float)NumSelectorsLoaded/SelectorsLoaded.size() * 100));
6633 if (TotalNumStatements)
6634 std::fprintf(stderr, " %u/%u statements read (%f%%)\n",
6635 NumStatementsRead, TotalNumStatements,
6636 ((float)NumStatementsRead/TotalNumStatements * 100));
6637 if (TotalNumMacros)
6638 std::fprintf(stderr, " %u/%u macros read (%f%%)\n",
6639 NumMacrosRead, TotalNumMacros,
6640 ((float)NumMacrosRead/TotalNumMacros * 100));
6641 if (TotalLexicalDeclContexts)
6642 std::fprintf(stderr, " %u/%u lexical declcontexts read (%f%%)\n",
6643 NumLexicalDeclContextsRead, TotalLexicalDeclContexts,
6644 ((float)NumLexicalDeclContextsRead/TotalLexicalDeclContexts
6645 * 100));
6646 if (TotalVisibleDeclContexts)
6647 std::fprintf(stderr, " %u/%u visible declcontexts read (%f%%)\n",
6648 NumVisibleDeclContextsRead, TotalVisibleDeclContexts,
6649 ((float)NumVisibleDeclContextsRead/TotalVisibleDeclContexts
6650 * 100));
6651 if (TotalNumMethodPoolEntries) {
6652 std::fprintf(stderr, " %u/%u method pool entries read (%f%%)\n",
6653 NumMethodPoolEntriesRead, TotalNumMethodPoolEntries,
6654 ((float)NumMethodPoolEntriesRead/TotalNumMethodPoolEntries
6655 * 100));
Guy Benyei11169dd2012-12-18 14:30:41 +00006656 }
Douglas Gregorad2f7a52013-01-28 17:54:36 +00006657 if (NumMethodPoolLookups) {
6658 std::fprintf(stderr, " %u/%u method pool lookups succeeded (%f%%)\n",
6659 NumMethodPoolHits, NumMethodPoolLookups,
6660 ((float)NumMethodPoolHits/NumMethodPoolLookups * 100.0));
6661 }
6662 if (NumMethodPoolTableLookups) {
6663 std::fprintf(stderr, " %u/%u method pool table lookups succeeded (%f%%)\n",
6664 NumMethodPoolTableHits, NumMethodPoolTableLookups,
6665 ((float)NumMethodPoolTableHits/NumMethodPoolTableLookups
6666 * 100.0));
6667 }
6668
Douglas Gregor00a50f72013-01-25 00:38:33 +00006669 if (NumIdentifierLookupHits) {
6670 std::fprintf(stderr,
6671 " %u / %u identifier table lookups succeeded (%f%%)\n",
6672 NumIdentifierLookupHits, NumIdentifierLookups,
6673 (double)NumIdentifierLookupHits*100.0/NumIdentifierLookups);
6674 }
6675
Douglas Gregore060e572013-01-25 01:03:03 +00006676 if (GlobalIndex) {
6677 std::fprintf(stderr, "\n");
6678 GlobalIndex->printStats();
6679 }
6680
Guy Benyei11169dd2012-12-18 14:30:41 +00006681 std::fprintf(stderr, "\n");
6682 dump();
6683 std::fprintf(stderr, "\n");
6684}
6685
6686template<typename Key, typename ModuleFile, unsigned InitialCapacity>
6687static void
6688dumpModuleIDMap(StringRef Name,
6689 const ContinuousRangeMap<Key, ModuleFile *,
6690 InitialCapacity> &Map) {
6691 if (Map.begin() == Map.end())
6692 return;
6693
6694 typedef ContinuousRangeMap<Key, ModuleFile *, InitialCapacity> MapType;
6695 llvm::errs() << Name << ":\n";
6696 for (typename MapType::const_iterator I = Map.begin(), IEnd = Map.end();
6697 I != IEnd; ++I) {
6698 llvm::errs() << " " << I->first << " -> " << I->second->FileName
6699 << "\n";
6700 }
6701}
6702
6703void ASTReader::dump() {
6704 llvm::errs() << "*** PCH/ModuleFile Remappings:\n";
6705 dumpModuleIDMap("Global bit offset map", GlobalBitOffsetsMap);
6706 dumpModuleIDMap("Global source location entry map", GlobalSLocEntryMap);
6707 dumpModuleIDMap("Global type map", GlobalTypeMap);
6708 dumpModuleIDMap("Global declaration map", GlobalDeclMap);
6709 dumpModuleIDMap("Global identifier map", GlobalIdentifierMap);
6710 dumpModuleIDMap("Global macro map", GlobalMacroMap);
6711 dumpModuleIDMap("Global submodule map", GlobalSubmoduleMap);
6712 dumpModuleIDMap("Global selector map", GlobalSelectorMap);
6713 dumpModuleIDMap("Global preprocessed entity map",
6714 GlobalPreprocessedEntityMap);
6715
6716 llvm::errs() << "\n*** PCH/Modules Loaded:";
6717 for (ModuleManager::ModuleConstIterator M = ModuleMgr.begin(),
6718 MEnd = ModuleMgr.end();
6719 M != MEnd; ++M)
6720 (*M)->dump();
6721}
6722
6723/// Return the amount of memory used by memory buffers, breaking down
6724/// by heap-backed versus mmap'ed memory.
6725void ASTReader::getMemoryBufferSizes(MemoryBufferSizes &sizes) const {
6726 for (ModuleConstIterator I = ModuleMgr.begin(),
6727 E = ModuleMgr.end(); I != E; ++I) {
6728 if (llvm::MemoryBuffer *buf = (*I)->Buffer.get()) {
6729 size_t bytes = buf->getBufferSize();
6730 switch (buf->getBufferKind()) {
6731 case llvm::MemoryBuffer::MemoryBuffer_Malloc:
6732 sizes.malloc_bytes += bytes;
6733 break;
6734 case llvm::MemoryBuffer::MemoryBuffer_MMap:
6735 sizes.mmap_bytes += bytes;
6736 break;
6737 }
6738 }
6739 }
6740}
6741
6742void ASTReader::InitializeSema(Sema &S) {
6743 SemaObj = &S;
6744 S.addExternalSource(this);
6745
6746 // Makes sure any declarations that were deserialized "too early"
6747 // still get added to the identifier's declaration chains.
6748 for (unsigned I = 0, N = PreloadedDecls.size(); I != N; ++I) {
Argyrios Kyrtzidise5edbf92013-04-26 21:33:35 +00006749 pushExternalDeclIntoScope(PreloadedDecls[I],
6750 PreloadedDecls[I]->getDeclName());
Guy Benyei11169dd2012-12-18 14:30:41 +00006751 }
6752 PreloadedDecls.clear();
6753
Richard Smith3d8e97e2013-10-18 06:54:39 +00006754 // FIXME: What happens if these are changed by a module import?
Guy Benyei11169dd2012-12-18 14:30:41 +00006755 if (!FPPragmaOptions.empty()) {
6756 assert(FPPragmaOptions.size() == 1 && "Wrong number of FP_PRAGMA_OPTIONS");
6757 SemaObj->FPFeatures.fp_contract = FPPragmaOptions[0];
6758 }
6759
Richard Smith3d8e97e2013-10-18 06:54:39 +00006760 // FIXME: What happens if these are changed by a module import?
Guy Benyei11169dd2012-12-18 14:30:41 +00006761 if (!OpenCLExtensions.empty()) {
6762 unsigned I = 0;
6763#define OPENCLEXT(nm) SemaObj->OpenCLFeatures.nm = OpenCLExtensions[I++];
6764#include "clang/Basic/OpenCLExtensions.def"
6765
6766 assert(OpenCLExtensions.size() == I && "Wrong number of OPENCL_EXTENSIONS");
6767 }
Richard Smith3d8e97e2013-10-18 06:54:39 +00006768
6769 UpdateSema();
6770}
6771
6772void ASTReader::UpdateSema() {
6773 assert(SemaObj && "no Sema to update");
6774
6775 // Load the offsets of the declarations that Sema references.
6776 // They will be lazily deserialized when needed.
6777 if (!SemaDeclRefs.empty()) {
6778 assert(SemaDeclRefs.size() % 2 == 0);
6779 for (unsigned I = 0; I != SemaDeclRefs.size(); I += 2) {
6780 if (!SemaObj->StdNamespace)
6781 SemaObj->StdNamespace = SemaDeclRefs[I];
6782 if (!SemaObj->StdBadAlloc)
6783 SemaObj->StdBadAlloc = SemaDeclRefs[I+1];
6784 }
6785 SemaDeclRefs.clear();
6786 }
Guy Benyei11169dd2012-12-18 14:30:41 +00006787}
6788
6789IdentifierInfo* ASTReader::get(const char *NameStart, const char *NameEnd) {
6790 // Note that we are loading an identifier.
6791 Deserializing AnIdentifier(this);
Douglas Gregore060e572013-01-25 01:03:03 +00006792 StringRef Name(NameStart, NameEnd - NameStart);
6793
6794 // If there is a global index, look there first to determine which modules
6795 // provably do not have any results for this identifier.
Douglas Gregor7211ac12013-01-25 23:32:03 +00006796 GlobalModuleIndex::HitSet Hits;
6797 GlobalModuleIndex::HitSet *HitsPtr = 0;
Douglas Gregore060e572013-01-25 01:03:03 +00006798 if (!loadGlobalIndex()) {
Douglas Gregor7211ac12013-01-25 23:32:03 +00006799 if (GlobalIndex->lookupIdentifier(Name, Hits)) {
6800 HitsPtr = &Hits;
Douglas Gregore060e572013-01-25 01:03:03 +00006801 }
6802 }
Douglas Gregor7211ac12013-01-25 23:32:03 +00006803 IdentifierLookupVisitor Visitor(Name, /*PriorGeneration=*/0,
Douglas Gregor00a50f72013-01-25 00:38:33 +00006804 NumIdentifierLookups,
6805 NumIdentifierLookupHits);
Douglas Gregor7211ac12013-01-25 23:32:03 +00006806 ModuleMgr.visit(IdentifierLookupVisitor::visit, &Visitor, HitsPtr);
Guy Benyei11169dd2012-12-18 14:30:41 +00006807 IdentifierInfo *II = Visitor.getIdentifierInfo();
6808 markIdentifierUpToDate(II);
6809 return II;
6810}
6811
6812namespace clang {
6813 /// \brief An identifier-lookup iterator that enumerates all of the
6814 /// identifiers stored within a set of AST files.
6815 class ASTIdentifierIterator : public IdentifierIterator {
6816 /// \brief The AST reader whose identifiers are being enumerated.
6817 const ASTReader &Reader;
6818
6819 /// \brief The current index into the chain of AST files stored in
6820 /// the AST reader.
6821 unsigned Index;
6822
6823 /// \brief The current position within the identifier lookup table
6824 /// of the current AST file.
6825 ASTIdentifierLookupTable::key_iterator Current;
6826
6827 /// \brief The end position within the identifier lookup table of
6828 /// the current AST file.
6829 ASTIdentifierLookupTable::key_iterator End;
6830
6831 public:
6832 explicit ASTIdentifierIterator(const ASTReader &Reader);
6833
Craig Topper3e89dfe2014-03-13 02:13:41 +00006834 StringRef Next() override;
Guy Benyei11169dd2012-12-18 14:30:41 +00006835 };
6836}
6837
6838ASTIdentifierIterator::ASTIdentifierIterator(const ASTReader &Reader)
6839 : Reader(Reader), Index(Reader.ModuleMgr.size() - 1) {
6840 ASTIdentifierLookupTable *IdTable
6841 = (ASTIdentifierLookupTable *)Reader.ModuleMgr[Index].IdentifierLookupTable;
6842 Current = IdTable->key_begin();
6843 End = IdTable->key_end();
6844}
6845
6846StringRef ASTIdentifierIterator::Next() {
6847 while (Current == End) {
6848 // If we have exhausted all of our AST files, we're done.
6849 if (Index == 0)
6850 return StringRef();
6851
6852 --Index;
6853 ASTIdentifierLookupTable *IdTable
6854 = (ASTIdentifierLookupTable *)Reader.ModuleMgr[Index].
6855 IdentifierLookupTable;
6856 Current = IdTable->key_begin();
6857 End = IdTable->key_end();
6858 }
6859
6860 // We have any identifiers remaining in the current AST file; return
6861 // the next one.
Douglas Gregorbfd73d72013-01-23 18:53:14 +00006862 StringRef Result = *Current;
Guy Benyei11169dd2012-12-18 14:30:41 +00006863 ++Current;
Douglas Gregorbfd73d72013-01-23 18:53:14 +00006864 return Result;
Guy Benyei11169dd2012-12-18 14:30:41 +00006865}
6866
Argyrios Kyrtzidis9aca3c62013-04-17 22:10:55 +00006867IdentifierIterator *ASTReader::getIdentifiers() {
6868 if (!loadGlobalIndex())
6869 return GlobalIndex->createIdentifierIterator();
6870
Guy Benyei11169dd2012-12-18 14:30:41 +00006871 return new ASTIdentifierIterator(*this);
6872}
6873
6874namespace clang { namespace serialization {
6875 class ReadMethodPoolVisitor {
6876 ASTReader &Reader;
6877 Selector Sel;
6878 unsigned PriorGeneration;
Argyrios Kyrtzidisd3da6e02013-04-17 00:08:58 +00006879 unsigned InstanceBits;
6880 unsigned FactoryBits;
Dmitri Gribenkof8579502013-01-12 19:30:44 +00006881 SmallVector<ObjCMethodDecl *, 4> InstanceMethods;
6882 SmallVector<ObjCMethodDecl *, 4> FactoryMethods;
Guy Benyei11169dd2012-12-18 14:30:41 +00006883
6884 public:
6885 ReadMethodPoolVisitor(ASTReader &Reader, Selector Sel,
6886 unsigned PriorGeneration)
Argyrios Kyrtzidisd3da6e02013-04-17 00:08:58 +00006887 : Reader(Reader), Sel(Sel), PriorGeneration(PriorGeneration),
6888 InstanceBits(0), FactoryBits(0) { }
Guy Benyei11169dd2012-12-18 14:30:41 +00006889
6890 static bool visit(ModuleFile &M, void *UserData) {
6891 ReadMethodPoolVisitor *This
6892 = static_cast<ReadMethodPoolVisitor *>(UserData);
6893
6894 if (!M.SelectorLookupTable)
6895 return false;
6896
6897 // If we've already searched this module file, skip it now.
6898 if (M.Generation <= This->PriorGeneration)
6899 return true;
6900
Douglas Gregorad2f7a52013-01-28 17:54:36 +00006901 ++This->Reader.NumMethodPoolTableLookups;
Guy Benyei11169dd2012-12-18 14:30:41 +00006902 ASTSelectorLookupTable *PoolTable
6903 = (ASTSelectorLookupTable*)M.SelectorLookupTable;
6904 ASTSelectorLookupTable::iterator Pos = PoolTable->find(This->Sel);
6905 if (Pos == PoolTable->end())
6906 return false;
Douglas Gregorad2f7a52013-01-28 17:54:36 +00006907
6908 ++This->Reader.NumMethodPoolTableHits;
Guy Benyei11169dd2012-12-18 14:30:41 +00006909 ++This->Reader.NumSelectorsRead;
6910 // FIXME: Not quite happy with the statistics here. We probably should
6911 // disable this tracking when called via LoadSelector.
6912 // Also, should entries without methods count as misses?
6913 ++This->Reader.NumMethodPoolEntriesRead;
6914 ASTSelectorLookupTrait::data_type Data = *Pos;
6915 if (This->Reader.DeserializationListener)
6916 This->Reader.DeserializationListener->SelectorRead(Data.ID,
6917 This->Sel);
6918
6919 This->InstanceMethods.append(Data.Instance.begin(), Data.Instance.end());
6920 This->FactoryMethods.append(Data.Factory.begin(), Data.Factory.end());
Argyrios Kyrtzidisd3da6e02013-04-17 00:08:58 +00006921 This->InstanceBits = Data.InstanceBits;
6922 This->FactoryBits = Data.FactoryBits;
Guy Benyei11169dd2012-12-18 14:30:41 +00006923 return true;
6924 }
6925
6926 /// \brief Retrieve the instance methods found by this visitor.
6927 ArrayRef<ObjCMethodDecl *> getInstanceMethods() const {
6928 return InstanceMethods;
6929 }
6930
6931 /// \brief Retrieve the instance methods found by this visitor.
6932 ArrayRef<ObjCMethodDecl *> getFactoryMethods() const {
6933 return FactoryMethods;
6934 }
Argyrios Kyrtzidisd3da6e02013-04-17 00:08:58 +00006935
6936 unsigned getInstanceBits() const { return InstanceBits; }
6937 unsigned getFactoryBits() const { return FactoryBits; }
Guy Benyei11169dd2012-12-18 14:30:41 +00006938 };
6939} } // end namespace clang::serialization
6940
6941/// \brief Add the given set of methods to the method list.
6942static void addMethodsToPool(Sema &S, ArrayRef<ObjCMethodDecl *> Methods,
6943 ObjCMethodList &List) {
6944 for (unsigned I = 0, N = Methods.size(); I != N; ++I) {
6945 S.addMethodToGlobalList(&List, Methods[I]);
6946 }
6947}
6948
6949void ASTReader::ReadMethodPool(Selector Sel) {
6950 // Get the selector generation and update it to the current generation.
6951 unsigned &Generation = SelectorGeneration[Sel];
6952 unsigned PriorGeneration = Generation;
6953 Generation = CurrentGeneration;
6954
6955 // Search for methods defined with this selector.
Douglas Gregorad2f7a52013-01-28 17:54:36 +00006956 ++NumMethodPoolLookups;
Guy Benyei11169dd2012-12-18 14:30:41 +00006957 ReadMethodPoolVisitor Visitor(*this, Sel, PriorGeneration);
6958 ModuleMgr.visit(&ReadMethodPoolVisitor::visit, &Visitor);
6959
6960 if (Visitor.getInstanceMethods().empty() &&
Douglas Gregorad2f7a52013-01-28 17:54:36 +00006961 Visitor.getFactoryMethods().empty())
Guy Benyei11169dd2012-12-18 14:30:41 +00006962 return;
Douglas Gregorad2f7a52013-01-28 17:54:36 +00006963
6964 ++NumMethodPoolHits;
6965
Guy Benyei11169dd2012-12-18 14:30:41 +00006966 if (!getSema())
6967 return;
6968
6969 Sema &S = *getSema();
6970 Sema::GlobalMethodPool::iterator Pos
6971 = S.MethodPool.insert(std::make_pair(Sel, Sema::GlobalMethods())).first;
6972
6973 addMethodsToPool(S, Visitor.getInstanceMethods(), Pos->second.first);
6974 addMethodsToPool(S, Visitor.getFactoryMethods(), Pos->second.second);
Argyrios Kyrtzidisd3da6e02013-04-17 00:08:58 +00006975 Pos->second.first.setBits(Visitor.getInstanceBits());
6976 Pos->second.second.setBits(Visitor.getFactoryBits());
Guy Benyei11169dd2012-12-18 14:30:41 +00006977}
6978
6979void ASTReader::ReadKnownNamespaces(
6980 SmallVectorImpl<NamespaceDecl *> &Namespaces) {
6981 Namespaces.clear();
6982
6983 for (unsigned I = 0, N = KnownNamespaces.size(); I != N; ++I) {
6984 if (NamespaceDecl *Namespace
6985 = dyn_cast_or_null<NamespaceDecl>(GetDecl(KnownNamespaces[I])))
6986 Namespaces.push_back(Namespace);
6987 }
6988}
6989
Nick Lewycky9c7eb1d2013-02-01 08:13:20 +00006990void ASTReader::ReadUndefinedButUsed(
Nick Lewyckyf0f56162013-01-31 03:23:57 +00006991 llvm::DenseMap<NamedDecl*, SourceLocation> &Undefined) {
Nick Lewycky9c7eb1d2013-02-01 08:13:20 +00006992 for (unsigned Idx = 0, N = UndefinedButUsed.size(); Idx != N;) {
6993 NamedDecl *D = cast<NamedDecl>(GetDecl(UndefinedButUsed[Idx++]));
Nick Lewycky8334af82013-01-26 00:35:08 +00006994 SourceLocation Loc =
Nick Lewycky9c7eb1d2013-02-01 08:13:20 +00006995 SourceLocation::getFromRawEncoding(UndefinedButUsed[Idx++]);
Nick Lewycky8334af82013-01-26 00:35:08 +00006996 Undefined.insert(std::make_pair(D, Loc));
6997 }
6998}
Nick Lewycky8334af82013-01-26 00:35:08 +00006999
Guy Benyei11169dd2012-12-18 14:30:41 +00007000void ASTReader::ReadTentativeDefinitions(
7001 SmallVectorImpl<VarDecl *> &TentativeDefs) {
7002 for (unsigned I = 0, N = TentativeDefinitions.size(); I != N; ++I) {
7003 VarDecl *Var = dyn_cast_or_null<VarDecl>(GetDecl(TentativeDefinitions[I]));
7004 if (Var)
7005 TentativeDefs.push_back(Var);
7006 }
7007 TentativeDefinitions.clear();
7008}
7009
7010void ASTReader::ReadUnusedFileScopedDecls(
7011 SmallVectorImpl<const DeclaratorDecl *> &Decls) {
7012 for (unsigned I = 0, N = UnusedFileScopedDecls.size(); I != N; ++I) {
7013 DeclaratorDecl *D
7014 = dyn_cast_or_null<DeclaratorDecl>(GetDecl(UnusedFileScopedDecls[I]));
7015 if (D)
7016 Decls.push_back(D);
7017 }
7018 UnusedFileScopedDecls.clear();
7019}
7020
7021void ASTReader::ReadDelegatingConstructors(
7022 SmallVectorImpl<CXXConstructorDecl *> &Decls) {
7023 for (unsigned I = 0, N = DelegatingCtorDecls.size(); I != N; ++I) {
7024 CXXConstructorDecl *D
7025 = dyn_cast_or_null<CXXConstructorDecl>(GetDecl(DelegatingCtorDecls[I]));
7026 if (D)
7027 Decls.push_back(D);
7028 }
7029 DelegatingCtorDecls.clear();
7030}
7031
7032void ASTReader::ReadExtVectorDecls(SmallVectorImpl<TypedefNameDecl *> &Decls) {
7033 for (unsigned I = 0, N = ExtVectorDecls.size(); I != N; ++I) {
7034 TypedefNameDecl *D
7035 = dyn_cast_or_null<TypedefNameDecl>(GetDecl(ExtVectorDecls[I]));
7036 if (D)
7037 Decls.push_back(D);
7038 }
7039 ExtVectorDecls.clear();
7040}
7041
7042void ASTReader::ReadDynamicClasses(SmallVectorImpl<CXXRecordDecl *> &Decls) {
7043 for (unsigned I = 0, N = DynamicClasses.size(); I != N; ++I) {
7044 CXXRecordDecl *D
7045 = dyn_cast_or_null<CXXRecordDecl>(GetDecl(DynamicClasses[I]));
7046 if (D)
7047 Decls.push_back(D);
7048 }
7049 DynamicClasses.clear();
7050}
7051
7052void
Richard Smith78165b52013-01-10 23:43:47 +00007053ASTReader::ReadLocallyScopedExternCDecls(SmallVectorImpl<NamedDecl *> &Decls) {
7054 for (unsigned I = 0, N = LocallyScopedExternCDecls.size(); I != N; ++I) {
7055 NamedDecl *D
7056 = dyn_cast_or_null<NamedDecl>(GetDecl(LocallyScopedExternCDecls[I]));
Guy Benyei11169dd2012-12-18 14:30:41 +00007057 if (D)
7058 Decls.push_back(D);
7059 }
Richard Smith78165b52013-01-10 23:43:47 +00007060 LocallyScopedExternCDecls.clear();
Guy Benyei11169dd2012-12-18 14:30:41 +00007061}
7062
7063void ASTReader::ReadReferencedSelectors(
7064 SmallVectorImpl<std::pair<Selector, SourceLocation> > &Sels) {
7065 if (ReferencedSelectorsData.empty())
7066 return;
7067
7068 // If there are @selector references added them to its pool. This is for
7069 // implementation of -Wselector.
7070 unsigned int DataSize = ReferencedSelectorsData.size()-1;
7071 unsigned I = 0;
7072 while (I < DataSize) {
7073 Selector Sel = DecodeSelector(ReferencedSelectorsData[I++]);
7074 SourceLocation SelLoc
7075 = SourceLocation::getFromRawEncoding(ReferencedSelectorsData[I++]);
7076 Sels.push_back(std::make_pair(Sel, SelLoc));
7077 }
7078 ReferencedSelectorsData.clear();
7079}
7080
7081void ASTReader::ReadWeakUndeclaredIdentifiers(
7082 SmallVectorImpl<std::pair<IdentifierInfo *, WeakInfo> > &WeakIDs) {
7083 if (WeakUndeclaredIdentifiers.empty())
7084 return;
7085
7086 for (unsigned I = 0, N = WeakUndeclaredIdentifiers.size(); I < N; /*none*/) {
7087 IdentifierInfo *WeakId
7088 = DecodeIdentifierInfo(WeakUndeclaredIdentifiers[I++]);
7089 IdentifierInfo *AliasId
7090 = DecodeIdentifierInfo(WeakUndeclaredIdentifiers[I++]);
7091 SourceLocation Loc
7092 = SourceLocation::getFromRawEncoding(WeakUndeclaredIdentifiers[I++]);
7093 bool Used = WeakUndeclaredIdentifiers[I++];
7094 WeakInfo WI(AliasId, Loc);
7095 WI.setUsed(Used);
7096 WeakIDs.push_back(std::make_pair(WeakId, WI));
7097 }
7098 WeakUndeclaredIdentifiers.clear();
7099}
7100
7101void ASTReader::ReadUsedVTables(SmallVectorImpl<ExternalVTableUse> &VTables) {
7102 for (unsigned Idx = 0, N = VTableUses.size(); Idx < N; /* In loop */) {
7103 ExternalVTableUse VT;
7104 VT.Record = dyn_cast_or_null<CXXRecordDecl>(GetDecl(VTableUses[Idx++]));
7105 VT.Location = SourceLocation::getFromRawEncoding(VTableUses[Idx++]);
7106 VT.DefinitionRequired = VTableUses[Idx++];
7107 VTables.push_back(VT);
7108 }
7109
7110 VTableUses.clear();
7111}
7112
7113void ASTReader::ReadPendingInstantiations(
7114 SmallVectorImpl<std::pair<ValueDecl *, SourceLocation> > &Pending) {
7115 for (unsigned Idx = 0, N = PendingInstantiations.size(); Idx < N;) {
7116 ValueDecl *D = cast<ValueDecl>(GetDecl(PendingInstantiations[Idx++]));
7117 SourceLocation Loc
7118 = SourceLocation::getFromRawEncoding(PendingInstantiations[Idx++]);
7119
7120 Pending.push_back(std::make_pair(D, Loc));
7121 }
7122 PendingInstantiations.clear();
7123}
7124
Richard Smithe40f2ba2013-08-07 21:41:30 +00007125void ASTReader::ReadLateParsedTemplates(
7126 llvm::DenseMap<const FunctionDecl *, LateParsedTemplate *> &LPTMap) {
7127 for (unsigned Idx = 0, N = LateParsedTemplates.size(); Idx < N;
7128 /* In loop */) {
7129 FunctionDecl *FD = cast<FunctionDecl>(GetDecl(LateParsedTemplates[Idx++]));
7130
7131 LateParsedTemplate *LT = new LateParsedTemplate;
7132 LT->D = GetDecl(LateParsedTemplates[Idx++]);
7133
7134 ModuleFile *F = getOwningModuleFile(LT->D);
7135 assert(F && "No module");
7136
7137 unsigned TokN = LateParsedTemplates[Idx++];
7138 LT->Toks.reserve(TokN);
7139 for (unsigned T = 0; T < TokN; ++T)
7140 LT->Toks.push_back(ReadToken(*F, LateParsedTemplates, Idx));
7141
7142 LPTMap[FD] = LT;
7143 }
7144
7145 LateParsedTemplates.clear();
7146}
7147
Guy Benyei11169dd2012-12-18 14:30:41 +00007148void ASTReader::LoadSelector(Selector Sel) {
7149 // It would be complicated to avoid reading the methods anyway. So don't.
7150 ReadMethodPool(Sel);
7151}
7152
7153void ASTReader::SetIdentifierInfo(IdentifierID ID, IdentifierInfo *II) {
7154 assert(ID && "Non-zero identifier ID required");
7155 assert(ID <= IdentifiersLoaded.size() && "identifier ID out of range");
7156 IdentifiersLoaded[ID - 1] = II;
7157 if (DeserializationListener)
7158 DeserializationListener->IdentifierRead(ID, II);
7159}
7160
7161/// \brief Set the globally-visible declarations associated with the given
7162/// identifier.
7163///
7164/// If the AST reader is currently in a state where the given declaration IDs
7165/// cannot safely be resolved, they are queued until it is safe to resolve
7166/// them.
7167///
7168/// \param II an IdentifierInfo that refers to one or more globally-visible
7169/// declarations.
7170///
7171/// \param DeclIDs the set of declaration IDs with the name @p II that are
7172/// visible at global scope.
7173///
Douglas Gregor6168bd22013-02-18 15:53:43 +00007174/// \param Decls if non-null, this vector will be populated with the set of
7175/// deserialized declarations. These declarations will not be pushed into
7176/// scope.
Guy Benyei11169dd2012-12-18 14:30:41 +00007177void
7178ASTReader::SetGloballyVisibleDecls(IdentifierInfo *II,
7179 const SmallVectorImpl<uint32_t> &DeclIDs,
Douglas Gregor6168bd22013-02-18 15:53:43 +00007180 SmallVectorImpl<Decl *> *Decls) {
7181 if (NumCurrentElementsDeserializing && !Decls) {
7182 PendingIdentifierInfos[II].append(DeclIDs.begin(), DeclIDs.end());
Guy Benyei11169dd2012-12-18 14:30:41 +00007183 return;
7184 }
7185
7186 for (unsigned I = 0, N = DeclIDs.size(); I != N; ++I) {
7187 NamedDecl *D = cast<NamedDecl>(GetDecl(DeclIDs[I]));
7188 if (SemaObj) {
Douglas Gregor6168bd22013-02-18 15:53:43 +00007189 // If we're simply supposed to record the declarations, do so now.
7190 if (Decls) {
7191 Decls->push_back(D);
7192 continue;
7193 }
7194
Guy Benyei11169dd2012-12-18 14:30:41 +00007195 // Introduce this declaration into the translation-unit scope
7196 // and add it to the declaration chain for this identifier, so
7197 // that (unqualified) name lookup will find it.
Argyrios Kyrtzidise5edbf92013-04-26 21:33:35 +00007198 pushExternalDeclIntoScope(D, II);
Guy Benyei11169dd2012-12-18 14:30:41 +00007199 } else {
7200 // Queue this declaration so that it will be added to the
7201 // translation unit scope and identifier's declaration chain
7202 // once a Sema object is known.
7203 PreloadedDecls.push_back(D);
7204 }
7205 }
7206}
7207
Douglas Gregorc8a992f2013-01-21 16:52:34 +00007208IdentifierInfo *ASTReader::DecodeIdentifierInfo(IdentifierID ID) {
Guy Benyei11169dd2012-12-18 14:30:41 +00007209 if (ID == 0)
7210 return 0;
7211
7212 if (IdentifiersLoaded.empty()) {
7213 Error("no identifier table in AST file");
7214 return 0;
7215 }
7216
7217 ID -= 1;
7218 if (!IdentifiersLoaded[ID]) {
7219 GlobalIdentifierMapType::iterator I = GlobalIdentifierMap.find(ID + 1);
7220 assert(I != GlobalIdentifierMap.end() && "Corrupted global identifier map");
7221 ModuleFile *M = I->second;
7222 unsigned Index = ID - M->BaseIdentifierID;
7223 const char *Str = M->IdentifierTableData + M->IdentifierOffsets[Index];
7224
7225 // All of the strings in the AST file are preceded by a 16-bit length.
7226 // Extract that 16-bit length to avoid having to execute strlen().
7227 // NOTE: 'StrLenPtr' is an 'unsigned char*' so that we load bytes as
7228 // unsigned integers. This is important to avoid integer overflow when
7229 // we cast them to 'unsigned'.
7230 const unsigned char *StrLenPtr = (const unsigned char*) Str - 2;
7231 unsigned StrLen = (((unsigned) StrLenPtr[0])
7232 | (((unsigned) StrLenPtr[1]) << 8)) - 1;
Douglas Gregorc8a992f2013-01-21 16:52:34 +00007233 IdentifiersLoaded[ID]
7234 = &PP.getIdentifierTable().get(StringRef(Str, StrLen));
Guy Benyei11169dd2012-12-18 14:30:41 +00007235 if (DeserializationListener)
7236 DeserializationListener->IdentifierRead(ID + 1, IdentifiersLoaded[ID]);
7237 }
7238
7239 return IdentifiersLoaded[ID];
7240}
7241
Douglas Gregorc8a992f2013-01-21 16:52:34 +00007242IdentifierInfo *ASTReader::getLocalIdentifier(ModuleFile &M, unsigned LocalID) {
7243 return DecodeIdentifierInfo(getGlobalIdentifierID(M, LocalID));
Guy Benyei11169dd2012-12-18 14:30:41 +00007244}
7245
7246IdentifierID ASTReader::getGlobalIdentifierID(ModuleFile &M, unsigned LocalID) {
7247 if (LocalID < NUM_PREDEF_IDENT_IDS)
7248 return LocalID;
7249
7250 ContinuousRangeMap<uint32_t, int, 2>::iterator I
7251 = M.IdentifierRemap.find(LocalID - NUM_PREDEF_IDENT_IDS);
7252 assert(I != M.IdentifierRemap.end()
7253 && "Invalid index into identifier index remap");
7254
7255 return LocalID + I->second;
7256}
7257
Argyrios Kyrtzidiseb663da2013-03-22 21:12:57 +00007258MacroInfo *ASTReader::getMacro(MacroID ID) {
Guy Benyei11169dd2012-12-18 14:30:41 +00007259 if (ID == 0)
7260 return 0;
7261
7262 if (MacrosLoaded.empty()) {
7263 Error("no macro table in AST file");
7264 return 0;
7265 }
7266
7267 ID -= NUM_PREDEF_MACRO_IDS;
7268 if (!MacrosLoaded[ID]) {
7269 GlobalMacroMapType::iterator I
7270 = GlobalMacroMap.find(ID + NUM_PREDEF_MACRO_IDS);
7271 assert(I != GlobalMacroMap.end() && "Corrupted global macro map");
7272 ModuleFile *M = I->second;
7273 unsigned Index = ID - M->BaseMacroID;
Argyrios Kyrtzidiseb663da2013-03-22 21:12:57 +00007274 MacrosLoaded[ID] = ReadMacroRecord(*M, M->MacroOffsets[Index]);
7275
7276 if (DeserializationListener)
7277 DeserializationListener->MacroRead(ID + NUM_PREDEF_MACRO_IDS,
7278 MacrosLoaded[ID]);
Guy Benyei11169dd2012-12-18 14:30:41 +00007279 }
7280
7281 return MacrosLoaded[ID];
7282}
7283
7284MacroID ASTReader::getGlobalMacroID(ModuleFile &M, unsigned LocalID) {
7285 if (LocalID < NUM_PREDEF_MACRO_IDS)
7286 return LocalID;
7287
7288 ContinuousRangeMap<uint32_t, int, 2>::iterator I
7289 = M.MacroRemap.find(LocalID - NUM_PREDEF_MACRO_IDS);
7290 assert(I != M.MacroRemap.end() && "Invalid index into macro index remap");
7291
7292 return LocalID + I->second;
7293}
7294
7295serialization::SubmoduleID
7296ASTReader::getGlobalSubmoduleID(ModuleFile &M, unsigned LocalID) {
7297 if (LocalID < NUM_PREDEF_SUBMODULE_IDS)
7298 return LocalID;
7299
7300 ContinuousRangeMap<uint32_t, int, 2>::iterator I
7301 = M.SubmoduleRemap.find(LocalID - NUM_PREDEF_SUBMODULE_IDS);
7302 assert(I != M.SubmoduleRemap.end()
7303 && "Invalid index into submodule index remap");
7304
7305 return LocalID + I->second;
7306}
7307
7308Module *ASTReader::getSubmodule(SubmoduleID GlobalID) {
7309 if (GlobalID < NUM_PREDEF_SUBMODULE_IDS) {
7310 assert(GlobalID == 0 && "Unhandled global submodule ID");
7311 return 0;
7312 }
7313
7314 if (GlobalID > SubmodulesLoaded.size()) {
7315 Error("submodule ID out of range in AST file");
7316 return 0;
7317 }
7318
7319 return SubmodulesLoaded[GlobalID - NUM_PREDEF_SUBMODULE_IDS];
7320}
Douglas Gregorc147b0b2013-01-12 01:29:50 +00007321
7322Module *ASTReader::getModule(unsigned ID) {
7323 return getSubmodule(ID);
7324}
7325
Guy Benyei11169dd2012-12-18 14:30:41 +00007326Selector ASTReader::getLocalSelector(ModuleFile &M, unsigned LocalID) {
7327 return DecodeSelector(getGlobalSelectorID(M, LocalID));
7328}
7329
7330Selector ASTReader::DecodeSelector(serialization::SelectorID ID) {
7331 if (ID == 0)
7332 return Selector();
7333
7334 if (ID > SelectorsLoaded.size()) {
7335 Error("selector ID out of range in AST file");
7336 return Selector();
7337 }
7338
7339 if (SelectorsLoaded[ID - 1].getAsOpaquePtr() == 0) {
7340 // Load this selector from the selector table.
7341 GlobalSelectorMapType::iterator I = GlobalSelectorMap.find(ID);
7342 assert(I != GlobalSelectorMap.end() && "Corrupted global selector map");
7343 ModuleFile &M = *I->second;
7344 ASTSelectorLookupTrait Trait(*this, M);
7345 unsigned Idx = ID - M.BaseSelectorID - NUM_PREDEF_SELECTOR_IDS;
7346 SelectorsLoaded[ID - 1] =
7347 Trait.ReadKey(M.SelectorLookupTableData + M.SelectorOffsets[Idx], 0);
7348 if (DeserializationListener)
7349 DeserializationListener->SelectorRead(ID, SelectorsLoaded[ID - 1]);
7350 }
7351
7352 return SelectorsLoaded[ID - 1];
7353}
7354
7355Selector ASTReader::GetExternalSelector(serialization::SelectorID ID) {
7356 return DecodeSelector(ID);
7357}
7358
7359uint32_t ASTReader::GetNumExternalSelectors() {
7360 // ID 0 (the null selector) is considered an external selector.
7361 return getTotalNumSelectors() + 1;
7362}
7363
7364serialization::SelectorID
7365ASTReader::getGlobalSelectorID(ModuleFile &M, unsigned LocalID) const {
7366 if (LocalID < NUM_PREDEF_SELECTOR_IDS)
7367 return LocalID;
7368
7369 ContinuousRangeMap<uint32_t, int, 2>::iterator I
7370 = M.SelectorRemap.find(LocalID - NUM_PREDEF_SELECTOR_IDS);
7371 assert(I != M.SelectorRemap.end()
7372 && "Invalid index into selector index remap");
7373
7374 return LocalID + I->second;
7375}
7376
7377DeclarationName
7378ASTReader::ReadDeclarationName(ModuleFile &F,
7379 const RecordData &Record, unsigned &Idx) {
7380 DeclarationName::NameKind Kind = (DeclarationName::NameKind)Record[Idx++];
7381 switch (Kind) {
7382 case DeclarationName::Identifier:
Douglas Gregorc8a992f2013-01-21 16:52:34 +00007383 return DeclarationName(GetIdentifierInfo(F, Record, Idx));
Guy Benyei11169dd2012-12-18 14:30:41 +00007384
7385 case DeclarationName::ObjCZeroArgSelector:
7386 case DeclarationName::ObjCOneArgSelector:
7387 case DeclarationName::ObjCMultiArgSelector:
7388 return DeclarationName(ReadSelector(F, Record, Idx));
7389
7390 case DeclarationName::CXXConstructorName:
7391 return Context.DeclarationNames.getCXXConstructorName(
7392 Context.getCanonicalType(readType(F, Record, Idx)));
7393
7394 case DeclarationName::CXXDestructorName:
7395 return Context.DeclarationNames.getCXXDestructorName(
7396 Context.getCanonicalType(readType(F, Record, Idx)));
7397
7398 case DeclarationName::CXXConversionFunctionName:
7399 return Context.DeclarationNames.getCXXConversionFunctionName(
7400 Context.getCanonicalType(readType(F, Record, Idx)));
7401
7402 case DeclarationName::CXXOperatorName:
7403 return Context.DeclarationNames.getCXXOperatorName(
7404 (OverloadedOperatorKind)Record[Idx++]);
7405
7406 case DeclarationName::CXXLiteralOperatorName:
7407 return Context.DeclarationNames.getCXXLiteralOperatorName(
7408 GetIdentifierInfo(F, Record, Idx));
7409
7410 case DeclarationName::CXXUsingDirective:
7411 return DeclarationName::getUsingDirectiveName();
7412 }
7413
7414 llvm_unreachable("Invalid NameKind!");
7415}
7416
7417void ASTReader::ReadDeclarationNameLoc(ModuleFile &F,
7418 DeclarationNameLoc &DNLoc,
7419 DeclarationName Name,
7420 const RecordData &Record, unsigned &Idx) {
7421 switch (Name.getNameKind()) {
7422 case DeclarationName::CXXConstructorName:
7423 case DeclarationName::CXXDestructorName:
7424 case DeclarationName::CXXConversionFunctionName:
7425 DNLoc.NamedType.TInfo = GetTypeSourceInfo(F, Record, Idx);
7426 break;
7427
7428 case DeclarationName::CXXOperatorName:
7429 DNLoc.CXXOperatorName.BeginOpNameLoc
7430 = ReadSourceLocation(F, Record, Idx).getRawEncoding();
7431 DNLoc.CXXOperatorName.EndOpNameLoc
7432 = ReadSourceLocation(F, Record, Idx).getRawEncoding();
7433 break;
7434
7435 case DeclarationName::CXXLiteralOperatorName:
7436 DNLoc.CXXLiteralOperatorName.OpNameLoc
7437 = ReadSourceLocation(F, Record, Idx).getRawEncoding();
7438 break;
7439
7440 case DeclarationName::Identifier:
7441 case DeclarationName::ObjCZeroArgSelector:
7442 case DeclarationName::ObjCOneArgSelector:
7443 case DeclarationName::ObjCMultiArgSelector:
7444 case DeclarationName::CXXUsingDirective:
7445 break;
7446 }
7447}
7448
7449void ASTReader::ReadDeclarationNameInfo(ModuleFile &F,
7450 DeclarationNameInfo &NameInfo,
7451 const RecordData &Record, unsigned &Idx) {
7452 NameInfo.setName(ReadDeclarationName(F, Record, Idx));
7453 NameInfo.setLoc(ReadSourceLocation(F, Record, Idx));
7454 DeclarationNameLoc DNLoc;
7455 ReadDeclarationNameLoc(F, DNLoc, NameInfo.getName(), Record, Idx);
7456 NameInfo.setInfo(DNLoc);
7457}
7458
7459void ASTReader::ReadQualifierInfo(ModuleFile &F, QualifierInfo &Info,
7460 const RecordData &Record, unsigned &Idx) {
7461 Info.QualifierLoc = ReadNestedNameSpecifierLoc(F, Record, Idx);
7462 unsigned NumTPLists = Record[Idx++];
7463 Info.NumTemplParamLists = NumTPLists;
7464 if (NumTPLists) {
7465 Info.TemplParamLists = new (Context) TemplateParameterList*[NumTPLists];
7466 for (unsigned i=0; i != NumTPLists; ++i)
7467 Info.TemplParamLists[i] = ReadTemplateParameterList(F, Record, Idx);
7468 }
7469}
7470
7471TemplateName
7472ASTReader::ReadTemplateName(ModuleFile &F, const RecordData &Record,
7473 unsigned &Idx) {
7474 TemplateName::NameKind Kind = (TemplateName::NameKind)Record[Idx++];
7475 switch (Kind) {
7476 case TemplateName::Template:
7477 return TemplateName(ReadDeclAs<TemplateDecl>(F, Record, Idx));
7478
7479 case TemplateName::OverloadedTemplate: {
7480 unsigned size = Record[Idx++];
7481 UnresolvedSet<8> Decls;
7482 while (size--)
7483 Decls.addDecl(ReadDeclAs<NamedDecl>(F, Record, Idx));
7484
7485 return Context.getOverloadedTemplateName(Decls.begin(), Decls.end());
7486 }
7487
7488 case TemplateName::QualifiedTemplate: {
7489 NestedNameSpecifier *NNS = ReadNestedNameSpecifier(F, Record, Idx);
7490 bool hasTemplKeyword = Record[Idx++];
7491 TemplateDecl *Template = ReadDeclAs<TemplateDecl>(F, Record, Idx);
7492 return Context.getQualifiedTemplateName(NNS, hasTemplKeyword, Template);
7493 }
7494
7495 case TemplateName::DependentTemplate: {
7496 NestedNameSpecifier *NNS = ReadNestedNameSpecifier(F, Record, Idx);
7497 if (Record[Idx++]) // isIdentifier
7498 return Context.getDependentTemplateName(NNS,
7499 GetIdentifierInfo(F, Record,
7500 Idx));
7501 return Context.getDependentTemplateName(NNS,
7502 (OverloadedOperatorKind)Record[Idx++]);
7503 }
7504
7505 case TemplateName::SubstTemplateTemplateParm: {
7506 TemplateTemplateParmDecl *param
7507 = ReadDeclAs<TemplateTemplateParmDecl>(F, Record, Idx);
7508 if (!param) return TemplateName();
7509 TemplateName replacement = ReadTemplateName(F, Record, Idx);
7510 return Context.getSubstTemplateTemplateParm(param, replacement);
7511 }
7512
7513 case TemplateName::SubstTemplateTemplateParmPack: {
7514 TemplateTemplateParmDecl *Param
7515 = ReadDeclAs<TemplateTemplateParmDecl>(F, Record, Idx);
7516 if (!Param)
7517 return TemplateName();
7518
7519 TemplateArgument ArgPack = ReadTemplateArgument(F, Record, Idx);
7520 if (ArgPack.getKind() != TemplateArgument::Pack)
7521 return TemplateName();
7522
7523 return Context.getSubstTemplateTemplateParmPack(Param, ArgPack);
7524 }
7525 }
7526
7527 llvm_unreachable("Unhandled template name kind!");
7528}
7529
7530TemplateArgument
7531ASTReader::ReadTemplateArgument(ModuleFile &F,
7532 const RecordData &Record, unsigned &Idx) {
7533 TemplateArgument::ArgKind Kind = (TemplateArgument::ArgKind)Record[Idx++];
7534 switch (Kind) {
7535 case TemplateArgument::Null:
7536 return TemplateArgument();
7537 case TemplateArgument::Type:
7538 return TemplateArgument(readType(F, Record, Idx));
7539 case TemplateArgument::Declaration: {
7540 ValueDecl *D = ReadDeclAs<ValueDecl>(F, Record, Idx);
7541 bool ForReferenceParam = Record[Idx++];
7542 return TemplateArgument(D, ForReferenceParam);
7543 }
7544 case TemplateArgument::NullPtr:
7545 return TemplateArgument(readType(F, Record, Idx), /*isNullPtr*/true);
7546 case TemplateArgument::Integral: {
7547 llvm::APSInt Value = ReadAPSInt(Record, Idx);
7548 QualType T = readType(F, Record, Idx);
7549 return TemplateArgument(Context, Value, T);
7550 }
7551 case TemplateArgument::Template:
7552 return TemplateArgument(ReadTemplateName(F, Record, Idx));
7553 case TemplateArgument::TemplateExpansion: {
7554 TemplateName Name = ReadTemplateName(F, Record, Idx);
David Blaikie05785d12013-02-20 22:23:23 +00007555 Optional<unsigned> NumTemplateExpansions;
Guy Benyei11169dd2012-12-18 14:30:41 +00007556 if (unsigned NumExpansions = Record[Idx++])
7557 NumTemplateExpansions = NumExpansions - 1;
7558 return TemplateArgument(Name, NumTemplateExpansions);
7559 }
7560 case TemplateArgument::Expression:
7561 return TemplateArgument(ReadExpr(F));
7562 case TemplateArgument::Pack: {
7563 unsigned NumArgs = Record[Idx++];
7564 TemplateArgument *Args = new (Context) TemplateArgument[NumArgs];
7565 for (unsigned I = 0; I != NumArgs; ++I)
7566 Args[I] = ReadTemplateArgument(F, Record, Idx);
7567 return TemplateArgument(Args, NumArgs);
7568 }
7569 }
7570
7571 llvm_unreachable("Unhandled template argument kind!");
7572}
7573
7574TemplateParameterList *
7575ASTReader::ReadTemplateParameterList(ModuleFile &F,
7576 const RecordData &Record, unsigned &Idx) {
7577 SourceLocation TemplateLoc = ReadSourceLocation(F, Record, Idx);
7578 SourceLocation LAngleLoc = ReadSourceLocation(F, Record, Idx);
7579 SourceLocation RAngleLoc = ReadSourceLocation(F, Record, Idx);
7580
7581 unsigned NumParams = Record[Idx++];
7582 SmallVector<NamedDecl *, 16> Params;
7583 Params.reserve(NumParams);
7584 while (NumParams--)
7585 Params.push_back(ReadDeclAs<NamedDecl>(F, Record, Idx));
7586
7587 TemplateParameterList* TemplateParams =
7588 TemplateParameterList::Create(Context, TemplateLoc, LAngleLoc,
7589 Params.data(), Params.size(), RAngleLoc);
7590 return TemplateParams;
7591}
7592
7593void
7594ASTReader::
Craig Topper5603df42013-07-05 19:34:19 +00007595ReadTemplateArgumentList(SmallVectorImpl<TemplateArgument> &TemplArgs,
Guy Benyei11169dd2012-12-18 14:30:41 +00007596 ModuleFile &F, const RecordData &Record,
7597 unsigned &Idx) {
7598 unsigned NumTemplateArgs = Record[Idx++];
7599 TemplArgs.reserve(NumTemplateArgs);
7600 while (NumTemplateArgs--)
7601 TemplArgs.push_back(ReadTemplateArgument(F, Record, Idx));
7602}
7603
7604/// \brief Read a UnresolvedSet structure.
Richard Smitha4ba74c2013-08-30 04:46:40 +00007605void ASTReader::ReadUnresolvedSet(ModuleFile &F, LazyASTUnresolvedSet &Set,
Guy Benyei11169dd2012-12-18 14:30:41 +00007606 const RecordData &Record, unsigned &Idx) {
7607 unsigned NumDecls = Record[Idx++];
7608 Set.reserve(Context, NumDecls);
7609 while (NumDecls--) {
Richard Smitha4ba74c2013-08-30 04:46:40 +00007610 DeclID ID = ReadDeclID(F, Record, Idx);
Guy Benyei11169dd2012-12-18 14:30:41 +00007611 AccessSpecifier AS = (AccessSpecifier)Record[Idx++];
Richard Smitha4ba74c2013-08-30 04:46:40 +00007612 Set.addLazyDecl(Context, ID, AS);
Guy Benyei11169dd2012-12-18 14:30:41 +00007613 }
7614}
7615
7616CXXBaseSpecifier
7617ASTReader::ReadCXXBaseSpecifier(ModuleFile &F,
7618 const RecordData &Record, unsigned &Idx) {
7619 bool isVirtual = static_cast<bool>(Record[Idx++]);
7620 bool isBaseOfClass = static_cast<bool>(Record[Idx++]);
7621 AccessSpecifier AS = static_cast<AccessSpecifier>(Record[Idx++]);
7622 bool inheritConstructors = static_cast<bool>(Record[Idx++]);
7623 TypeSourceInfo *TInfo = GetTypeSourceInfo(F, Record, Idx);
7624 SourceRange Range = ReadSourceRange(F, Record, Idx);
7625 SourceLocation EllipsisLoc = ReadSourceLocation(F, Record, Idx);
7626 CXXBaseSpecifier Result(Range, isVirtual, isBaseOfClass, AS, TInfo,
7627 EllipsisLoc);
7628 Result.setInheritConstructors(inheritConstructors);
7629 return Result;
7630}
7631
7632std::pair<CXXCtorInitializer **, unsigned>
7633ASTReader::ReadCXXCtorInitializers(ModuleFile &F, const RecordData &Record,
7634 unsigned &Idx) {
7635 CXXCtorInitializer **CtorInitializers = 0;
7636 unsigned NumInitializers = Record[Idx++];
7637 if (NumInitializers) {
7638 CtorInitializers
7639 = new (Context) CXXCtorInitializer*[NumInitializers];
7640 for (unsigned i=0; i != NumInitializers; ++i) {
7641 TypeSourceInfo *TInfo = 0;
7642 bool IsBaseVirtual = false;
7643 FieldDecl *Member = 0;
7644 IndirectFieldDecl *IndirectMember = 0;
7645
7646 CtorInitializerType Type = (CtorInitializerType)Record[Idx++];
7647 switch (Type) {
7648 case CTOR_INITIALIZER_BASE:
7649 TInfo = GetTypeSourceInfo(F, Record, Idx);
7650 IsBaseVirtual = Record[Idx++];
7651 break;
7652
7653 case CTOR_INITIALIZER_DELEGATING:
7654 TInfo = GetTypeSourceInfo(F, Record, Idx);
7655 break;
7656
7657 case CTOR_INITIALIZER_MEMBER:
7658 Member = ReadDeclAs<FieldDecl>(F, Record, Idx);
7659 break;
7660
7661 case CTOR_INITIALIZER_INDIRECT_MEMBER:
7662 IndirectMember = ReadDeclAs<IndirectFieldDecl>(F, Record, Idx);
7663 break;
7664 }
7665
7666 SourceLocation MemberOrEllipsisLoc = ReadSourceLocation(F, Record, Idx);
7667 Expr *Init = ReadExpr(F);
7668 SourceLocation LParenLoc = ReadSourceLocation(F, Record, Idx);
7669 SourceLocation RParenLoc = ReadSourceLocation(F, Record, Idx);
7670 bool IsWritten = Record[Idx++];
7671 unsigned SourceOrderOrNumArrayIndices;
7672 SmallVector<VarDecl *, 8> Indices;
7673 if (IsWritten) {
7674 SourceOrderOrNumArrayIndices = Record[Idx++];
7675 } else {
7676 SourceOrderOrNumArrayIndices = Record[Idx++];
7677 Indices.reserve(SourceOrderOrNumArrayIndices);
7678 for (unsigned i=0; i != SourceOrderOrNumArrayIndices; ++i)
7679 Indices.push_back(ReadDeclAs<VarDecl>(F, Record, Idx));
7680 }
7681
7682 CXXCtorInitializer *BOMInit;
7683 if (Type == CTOR_INITIALIZER_BASE) {
7684 BOMInit = new (Context) CXXCtorInitializer(Context, TInfo, IsBaseVirtual,
7685 LParenLoc, Init, RParenLoc,
7686 MemberOrEllipsisLoc);
7687 } else if (Type == CTOR_INITIALIZER_DELEGATING) {
7688 BOMInit = new (Context) CXXCtorInitializer(Context, TInfo, LParenLoc,
7689 Init, RParenLoc);
7690 } else if (IsWritten) {
7691 if (Member)
7692 BOMInit = new (Context) CXXCtorInitializer(Context, Member, MemberOrEllipsisLoc,
7693 LParenLoc, Init, RParenLoc);
7694 else
7695 BOMInit = new (Context) CXXCtorInitializer(Context, IndirectMember,
7696 MemberOrEllipsisLoc, LParenLoc,
7697 Init, RParenLoc);
7698 } else {
Argyrios Kyrtzidis794671d2013-05-30 23:59:46 +00007699 if (IndirectMember) {
7700 assert(Indices.empty() && "Indirect field improperly initialized");
7701 BOMInit = new (Context) CXXCtorInitializer(Context, IndirectMember,
7702 MemberOrEllipsisLoc, LParenLoc,
7703 Init, RParenLoc);
7704 } else {
7705 BOMInit = CXXCtorInitializer::Create(Context, Member, MemberOrEllipsisLoc,
7706 LParenLoc, Init, RParenLoc,
7707 Indices.data(), Indices.size());
7708 }
Guy Benyei11169dd2012-12-18 14:30:41 +00007709 }
7710
7711 if (IsWritten)
7712 BOMInit->setSourceOrder(SourceOrderOrNumArrayIndices);
7713 CtorInitializers[i] = BOMInit;
7714 }
7715 }
7716
7717 return std::make_pair(CtorInitializers, NumInitializers);
7718}
7719
7720NestedNameSpecifier *
7721ASTReader::ReadNestedNameSpecifier(ModuleFile &F,
7722 const RecordData &Record, unsigned &Idx) {
7723 unsigned N = Record[Idx++];
7724 NestedNameSpecifier *NNS = 0, *Prev = 0;
7725 for (unsigned I = 0; I != N; ++I) {
7726 NestedNameSpecifier::SpecifierKind Kind
7727 = (NestedNameSpecifier::SpecifierKind)Record[Idx++];
7728 switch (Kind) {
7729 case NestedNameSpecifier::Identifier: {
7730 IdentifierInfo *II = GetIdentifierInfo(F, Record, Idx);
7731 NNS = NestedNameSpecifier::Create(Context, Prev, II);
7732 break;
7733 }
7734
7735 case NestedNameSpecifier::Namespace: {
7736 NamespaceDecl *NS = ReadDeclAs<NamespaceDecl>(F, Record, Idx);
7737 NNS = NestedNameSpecifier::Create(Context, Prev, NS);
7738 break;
7739 }
7740
7741 case NestedNameSpecifier::NamespaceAlias: {
7742 NamespaceAliasDecl *Alias =ReadDeclAs<NamespaceAliasDecl>(F, Record, Idx);
7743 NNS = NestedNameSpecifier::Create(Context, Prev, Alias);
7744 break;
7745 }
7746
7747 case NestedNameSpecifier::TypeSpec:
7748 case NestedNameSpecifier::TypeSpecWithTemplate: {
7749 const Type *T = readType(F, Record, Idx).getTypePtrOrNull();
7750 if (!T)
7751 return 0;
7752
7753 bool Template = Record[Idx++];
7754 NNS = NestedNameSpecifier::Create(Context, Prev, Template, T);
7755 break;
7756 }
7757
7758 case NestedNameSpecifier::Global: {
7759 NNS = NestedNameSpecifier::GlobalSpecifier(Context);
7760 // No associated value, and there can't be a prefix.
7761 break;
7762 }
7763 }
7764 Prev = NNS;
7765 }
7766 return NNS;
7767}
7768
7769NestedNameSpecifierLoc
7770ASTReader::ReadNestedNameSpecifierLoc(ModuleFile &F, const RecordData &Record,
7771 unsigned &Idx) {
7772 unsigned N = Record[Idx++];
7773 NestedNameSpecifierLocBuilder Builder;
7774 for (unsigned I = 0; I != N; ++I) {
7775 NestedNameSpecifier::SpecifierKind Kind
7776 = (NestedNameSpecifier::SpecifierKind)Record[Idx++];
7777 switch (Kind) {
7778 case NestedNameSpecifier::Identifier: {
7779 IdentifierInfo *II = GetIdentifierInfo(F, Record, Idx);
7780 SourceRange Range = ReadSourceRange(F, Record, Idx);
7781 Builder.Extend(Context, II, Range.getBegin(), Range.getEnd());
7782 break;
7783 }
7784
7785 case NestedNameSpecifier::Namespace: {
7786 NamespaceDecl *NS = ReadDeclAs<NamespaceDecl>(F, Record, Idx);
7787 SourceRange Range = ReadSourceRange(F, Record, Idx);
7788 Builder.Extend(Context, NS, Range.getBegin(), Range.getEnd());
7789 break;
7790 }
7791
7792 case NestedNameSpecifier::NamespaceAlias: {
7793 NamespaceAliasDecl *Alias =ReadDeclAs<NamespaceAliasDecl>(F, Record, Idx);
7794 SourceRange Range = ReadSourceRange(F, Record, Idx);
7795 Builder.Extend(Context, Alias, Range.getBegin(), Range.getEnd());
7796 break;
7797 }
7798
7799 case NestedNameSpecifier::TypeSpec:
7800 case NestedNameSpecifier::TypeSpecWithTemplate: {
7801 bool Template = Record[Idx++];
7802 TypeSourceInfo *T = GetTypeSourceInfo(F, Record, Idx);
7803 if (!T)
7804 return NestedNameSpecifierLoc();
7805 SourceLocation ColonColonLoc = ReadSourceLocation(F, Record, Idx);
7806
7807 // FIXME: 'template' keyword location not saved anywhere, so we fake it.
7808 Builder.Extend(Context,
7809 Template? T->getTypeLoc().getBeginLoc() : SourceLocation(),
7810 T->getTypeLoc(), ColonColonLoc);
7811 break;
7812 }
7813
7814 case NestedNameSpecifier::Global: {
7815 SourceLocation ColonColonLoc = ReadSourceLocation(F, Record, Idx);
7816 Builder.MakeGlobal(Context, ColonColonLoc);
7817 break;
7818 }
7819 }
7820 }
7821
7822 return Builder.getWithLocInContext(Context);
7823}
7824
7825SourceRange
7826ASTReader::ReadSourceRange(ModuleFile &F, const RecordData &Record,
7827 unsigned &Idx) {
7828 SourceLocation beg = ReadSourceLocation(F, Record, Idx);
7829 SourceLocation end = ReadSourceLocation(F, Record, Idx);
7830 return SourceRange(beg, end);
7831}
7832
7833/// \brief Read an integral value
7834llvm::APInt ASTReader::ReadAPInt(const RecordData &Record, unsigned &Idx) {
7835 unsigned BitWidth = Record[Idx++];
7836 unsigned NumWords = llvm::APInt::getNumWords(BitWidth);
7837 llvm::APInt Result(BitWidth, NumWords, &Record[Idx]);
7838 Idx += NumWords;
7839 return Result;
7840}
7841
7842/// \brief Read a signed integral value
7843llvm::APSInt ASTReader::ReadAPSInt(const RecordData &Record, unsigned &Idx) {
7844 bool isUnsigned = Record[Idx++];
7845 return llvm::APSInt(ReadAPInt(Record, Idx), isUnsigned);
7846}
7847
7848/// \brief Read a floating-point value
Tim Northover178723a2013-01-22 09:46:51 +00007849llvm::APFloat ASTReader::ReadAPFloat(const RecordData &Record,
7850 const llvm::fltSemantics &Sem,
7851 unsigned &Idx) {
7852 return llvm::APFloat(Sem, ReadAPInt(Record, Idx));
Guy Benyei11169dd2012-12-18 14:30:41 +00007853}
7854
7855// \brief Read a string
7856std::string ASTReader::ReadString(const RecordData &Record, unsigned &Idx) {
7857 unsigned Len = Record[Idx++];
7858 std::string Result(Record.data() + Idx, Record.data() + Idx + Len);
7859 Idx += Len;
7860 return Result;
7861}
7862
7863VersionTuple ASTReader::ReadVersionTuple(const RecordData &Record,
7864 unsigned &Idx) {
7865 unsigned Major = Record[Idx++];
7866 unsigned Minor = Record[Idx++];
7867 unsigned Subminor = Record[Idx++];
7868 if (Minor == 0)
7869 return VersionTuple(Major);
7870 if (Subminor == 0)
7871 return VersionTuple(Major, Minor - 1);
7872 return VersionTuple(Major, Minor - 1, Subminor - 1);
7873}
7874
7875CXXTemporary *ASTReader::ReadCXXTemporary(ModuleFile &F,
7876 const RecordData &Record,
7877 unsigned &Idx) {
7878 CXXDestructorDecl *Decl = ReadDeclAs<CXXDestructorDecl>(F, Record, Idx);
7879 return CXXTemporary::Create(Context, Decl);
7880}
7881
7882DiagnosticBuilder ASTReader::Diag(unsigned DiagID) {
Argyrios Kyrtzidisdc9fdaf2013-05-24 05:44:08 +00007883 return Diag(CurrentImportLoc, DiagID);
Guy Benyei11169dd2012-12-18 14:30:41 +00007884}
7885
7886DiagnosticBuilder ASTReader::Diag(SourceLocation Loc, unsigned DiagID) {
7887 return Diags.Report(Loc, DiagID);
7888}
7889
7890/// \brief Retrieve the identifier table associated with the
7891/// preprocessor.
7892IdentifierTable &ASTReader::getIdentifierTable() {
7893 return PP.getIdentifierTable();
7894}
7895
7896/// \brief Record that the given ID maps to the given switch-case
7897/// statement.
7898void ASTReader::RecordSwitchCaseID(SwitchCase *SC, unsigned ID) {
7899 assert((*CurrSwitchCaseStmts)[ID] == 0 &&
7900 "Already have a SwitchCase with this ID");
7901 (*CurrSwitchCaseStmts)[ID] = SC;
7902}
7903
7904/// \brief Retrieve the switch-case statement with the given ID.
7905SwitchCase *ASTReader::getSwitchCaseWithID(unsigned ID) {
7906 assert((*CurrSwitchCaseStmts)[ID] != 0 && "No SwitchCase with this ID");
7907 return (*CurrSwitchCaseStmts)[ID];
7908}
7909
7910void ASTReader::ClearSwitchCaseIDs() {
7911 CurrSwitchCaseStmts->clear();
7912}
7913
7914void ASTReader::ReadComments() {
7915 std::vector<RawComment *> Comments;
Chris Lattner7fb3bef2013-01-20 00:56:42 +00007916 for (SmallVectorImpl<std::pair<BitstreamCursor,
Guy Benyei11169dd2012-12-18 14:30:41 +00007917 serialization::ModuleFile *> >::iterator
7918 I = CommentsCursors.begin(),
7919 E = CommentsCursors.end();
7920 I != E; ++I) {
Dmitri Gribenko9ee0e302014-03-27 15:40:39 +00007921 Comments.clear();
Chris Lattner7fb3bef2013-01-20 00:56:42 +00007922 BitstreamCursor &Cursor = I->first;
Guy Benyei11169dd2012-12-18 14:30:41 +00007923 serialization::ModuleFile &F = *I->second;
7924 SavedStreamPosition SavedPosition(Cursor);
7925
7926 RecordData Record;
7927 while (true) {
Chris Lattner7fb3bef2013-01-20 00:56:42 +00007928 llvm::BitstreamEntry Entry =
7929 Cursor.advanceSkippingSubblocks(BitstreamCursor::AF_DontPopBlockAtEnd);
Dmitri Gribenko9ee0e302014-03-27 15:40:39 +00007930
Chris Lattner7fb3bef2013-01-20 00:56:42 +00007931 switch (Entry.Kind) {
7932 case llvm::BitstreamEntry::SubBlock: // Handled for us already.
7933 case llvm::BitstreamEntry::Error:
7934 Error("malformed block record in AST file");
7935 return;
7936 case llvm::BitstreamEntry::EndBlock:
7937 goto NextCursor;
7938 case llvm::BitstreamEntry::Record:
7939 // The interesting case.
Guy Benyei11169dd2012-12-18 14:30:41 +00007940 break;
Guy Benyei11169dd2012-12-18 14:30:41 +00007941 }
7942
7943 // Read a record.
7944 Record.clear();
Chris Lattner0e6c9402013-01-20 02:38:54 +00007945 switch ((CommentRecordTypes)Cursor.readRecord(Entry.ID, Record)) {
Guy Benyei11169dd2012-12-18 14:30:41 +00007946 case COMMENTS_RAW_COMMENT: {
7947 unsigned Idx = 0;
7948 SourceRange SR = ReadSourceRange(F, Record, Idx);
7949 RawComment::CommentKind Kind =
7950 (RawComment::CommentKind) Record[Idx++];
7951 bool IsTrailingComment = Record[Idx++];
7952 bool IsAlmostTrailingComment = Record[Idx++];
Dmitri Gribenkoa7d16ce2013-04-10 15:35:17 +00007953 Comments.push_back(new (Context) RawComment(
7954 SR, Kind, IsTrailingComment, IsAlmostTrailingComment,
7955 Context.getLangOpts().CommentOpts.ParseAllComments));
Guy Benyei11169dd2012-12-18 14:30:41 +00007956 break;
7957 }
7958 }
7959 }
Dmitri Gribenko9ee0e302014-03-27 15:40:39 +00007960 NextCursor:
7961 Context.Comments.addDeserializedComments(Comments);
Guy Benyei11169dd2012-12-18 14:30:41 +00007962 }
Guy Benyei11169dd2012-12-18 14:30:41 +00007963}
7964
Richard Smithcd45dbc2014-04-19 03:48:30 +00007965std::string ASTReader::getOwningModuleNameForDiagnostic(const Decl *D) {
7966 // If we know the owning module, use it.
7967 if (Module *M = D->getOwningModule())
7968 return M->getFullModuleName();
7969
7970 // Otherwise, use the name of the top-level module the decl is within.
7971 if (ModuleFile *M = getOwningModuleFile(D))
7972 return M->ModuleName;
7973
7974 // Not from a module.
7975 return "";
7976}
7977
Guy Benyei11169dd2012-12-18 14:30:41 +00007978void ASTReader::finishPendingActions() {
7979 while (!PendingIdentifierInfos.empty() || !PendingDeclChains.empty() ||
Richard Smith2b9e3e32013-10-18 06:05:18 +00007980 !PendingMacroIDs.empty() || !PendingDeclContextInfos.empty() ||
Richard Smith93914a92014-05-08 00:25:01 +00007981 !PendingUpdateRecords.empty() || !PendingOdrMergeChecks.empty()) {
Guy Benyei11169dd2012-12-18 14:30:41 +00007982 // If any identifiers with corresponding top-level declarations have
7983 // been loaded, load those declarations now.
Craig Topper79be4cd2013-07-05 04:33:53 +00007984 typedef llvm::DenseMap<IdentifierInfo *, SmallVector<Decl *, 2> >
7985 TopLevelDeclsMap;
7986 TopLevelDeclsMap TopLevelDecls;
7987
Guy Benyei11169dd2012-12-18 14:30:41 +00007988 while (!PendingIdentifierInfos.empty()) {
Douglas Gregor6168bd22013-02-18 15:53:43 +00007989 IdentifierInfo *II = PendingIdentifierInfos.back().first;
Richard Smithf0ae3c2d2014-03-28 17:31:23 +00007990 SmallVector<uint32_t, 4> DeclIDs =
7991 std::move(PendingIdentifierInfos.back().second);
Douglas Gregorcb15f082013-02-19 18:26:28 +00007992 PendingIdentifierInfos.pop_back();
Douglas Gregor6168bd22013-02-18 15:53:43 +00007993
7994 SetGloballyVisibleDecls(II, DeclIDs, &TopLevelDecls[II]);
Guy Benyei11169dd2012-12-18 14:30:41 +00007995 }
Richard Smithf0ae3c2d2014-03-28 17:31:23 +00007996
Guy Benyei11169dd2012-12-18 14:30:41 +00007997 // Load pending declaration chains.
7998 for (unsigned I = 0; I != PendingDeclChains.size(); ++I) {
7999 loadPendingDeclChain(PendingDeclChains[I]);
8000 PendingDeclChainsKnown.erase(PendingDeclChains[I]);
8001 }
8002 PendingDeclChains.clear();
8003
Douglas Gregor6168bd22013-02-18 15:53:43 +00008004 // Make the most recent of the top-level declarations visible.
Craig Topper79be4cd2013-07-05 04:33:53 +00008005 for (TopLevelDeclsMap::iterator TLD = TopLevelDecls.begin(),
8006 TLDEnd = TopLevelDecls.end(); TLD != TLDEnd; ++TLD) {
Douglas Gregor6168bd22013-02-18 15:53:43 +00008007 IdentifierInfo *II = TLD->first;
8008 for (unsigned I = 0, N = TLD->second.size(); I != N; ++I) {
Argyrios Kyrtzidise5edbf92013-04-26 21:33:35 +00008009 pushExternalDeclIntoScope(cast<NamedDecl>(TLD->second[I]), II);
Douglas Gregor6168bd22013-02-18 15:53:43 +00008010 }
8011 }
8012
Guy Benyei11169dd2012-12-18 14:30:41 +00008013 // Load any pending macro definitions.
8014 for (unsigned I = 0; I != PendingMacroIDs.size(); ++I) {
Argyrios Kyrtzidiseb663da2013-03-22 21:12:57 +00008015 IdentifierInfo *II = PendingMacroIDs.begin()[I].first;
8016 SmallVector<PendingMacroInfo, 2> GlobalIDs;
8017 GlobalIDs.swap(PendingMacroIDs.begin()[I].second);
8018 // Initialize the macro history from chained-PCHs ahead of module imports.
Richard Smith49f906a2014-03-01 00:08:04 +00008019 for (unsigned IDIdx = 0, NumIDs = GlobalIDs.size(); IDIdx != NumIDs;
Argyrios Kyrtzidis719736c2013-01-19 03:14:56 +00008020 ++IDIdx) {
Argyrios Kyrtzidiseb663da2013-03-22 21:12:57 +00008021 const PendingMacroInfo &Info = GlobalIDs[IDIdx];
8022 if (Info.M->Kind != MK_Module)
8023 resolvePendingMacro(II, Info);
8024 }
8025 // Handle module imports.
Richard Smith49f906a2014-03-01 00:08:04 +00008026 for (unsigned IDIdx = 0, NumIDs = GlobalIDs.size(); IDIdx != NumIDs;
Argyrios Kyrtzidiseb663da2013-03-22 21:12:57 +00008027 ++IDIdx) {
8028 const PendingMacroInfo &Info = GlobalIDs[IDIdx];
8029 if (Info.M->Kind == MK_Module)
8030 resolvePendingMacro(II, Info);
Guy Benyei11169dd2012-12-18 14:30:41 +00008031 }
8032 }
8033 PendingMacroIDs.clear();
Argyrios Kyrtzidis83a6e3b2013-02-16 00:48:59 +00008034
8035 // Wire up the DeclContexts for Decls that we delayed setting until
8036 // recursive loading is completed.
8037 while (!PendingDeclContextInfos.empty()) {
8038 PendingDeclContextInfo Info = PendingDeclContextInfos.front();
8039 PendingDeclContextInfos.pop_front();
8040 DeclContext *SemaDC = cast<DeclContext>(GetDecl(Info.SemaDC));
8041 DeclContext *LexicalDC = cast<DeclContext>(GetDecl(Info.LexicalDC));
8042 Info.D->setDeclContextsImpl(SemaDC, LexicalDC, getContext());
8043 }
Richard Smith2b9e3e32013-10-18 06:05:18 +00008044
Richard Smithd1c46742014-04-30 02:24:17 +00008045 // Perform any pending declaration updates.
8046 while (!PendingUpdateRecords.empty()) {
8047 auto Update = PendingUpdateRecords.pop_back_val();
8048 ReadingKindTracker ReadingKind(Read_Decl, *this);
8049 loadDeclUpdateRecords(Update.first, Update.second);
8050 }
8051
Richard Smithcd45dbc2014-04-19 03:48:30 +00008052 // Trigger the import of the full definition of each class that had any
8053 // odr-merging problems, so we can produce better diagnostics for them.
8054 for (auto &Merge : PendingOdrMergeFailures) {
8055 Merge.first->buildLookup();
8056 Merge.first->decls_begin();
8057 Merge.first->bases_begin();
8058 Merge.first->vbases_begin();
8059 for (auto *RD : Merge.second) {
8060 RD->decls_begin();
8061 RD->bases_begin();
8062 RD->vbases_begin();
8063 }
8064 }
8065
Richard Smith2b9e3e32013-10-18 06:05:18 +00008066 // For each declaration from a merged context, check that the canonical
8067 // definition of that context also contains a declaration of the same
8068 // entity.
8069 while (!PendingOdrMergeChecks.empty()) {
8070 NamedDecl *D = PendingOdrMergeChecks.pop_back_val();
8071
8072 // FIXME: Skip over implicit declarations for now. This matters for things
8073 // like implicitly-declared special member functions. This isn't entirely
8074 // correct; we can end up with multiple unmerged declarations of the same
8075 // implicit entity.
8076 if (D->isImplicit())
8077 continue;
8078
8079 DeclContext *CanonDef = D->getDeclContext();
8080 DeclContext::lookup_result R = CanonDef->lookup(D->getDeclName());
8081
8082 bool Found = false;
8083 const Decl *DCanon = D->getCanonicalDecl();
8084
8085 llvm::SmallVector<const NamedDecl*, 4> Candidates;
8086 for (DeclContext::lookup_iterator I = R.begin(), E = R.end();
8087 !Found && I != E; ++I) {
Aaron Ballman86c93902014-03-06 23:45:36 +00008088 for (auto RI : (*I)->redecls()) {
8089 if (RI->getLexicalDeclContext() == CanonDef) {
Richard Smith2b9e3e32013-10-18 06:05:18 +00008090 // This declaration is present in the canonical definition. If it's
8091 // in the same redecl chain, it's the one we're looking for.
Aaron Ballman86c93902014-03-06 23:45:36 +00008092 if (RI->getCanonicalDecl() == DCanon)
Richard Smith2b9e3e32013-10-18 06:05:18 +00008093 Found = true;
8094 else
Aaron Ballman86c93902014-03-06 23:45:36 +00008095 Candidates.push_back(cast<NamedDecl>(RI));
Richard Smith2b9e3e32013-10-18 06:05:18 +00008096 break;
8097 }
8098 }
8099 }
8100
8101 if (!Found) {
8102 D->setInvalidDecl();
8103
Richard Smithcd45dbc2014-04-19 03:48:30 +00008104 std::string CanonDefModule =
8105 getOwningModuleNameForDiagnostic(cast<Decl>(CanonDef));
Richard Smith2b9e3e32013-10-18 06:05:18 +00008106 Diag(D->getLocation(), diag::err_module_odr_violation_missing_decl)
Richard Smithcd45dbc2014-04-19 03:48:30 +00008107 << D << getOwningModuleNameForDiagnostic(D)
8108 << CanonDef << CanonDefModule.empty() << CanonDefModule;
Richard Smith2b9e3e32013-10-18 06:05:18 +00008109
8110 if (Candidates.empty())
8111 Diag(cast<Decl>(CanonDef)->getLocation(),
8112 diag::note_module_odr_violation_no_possible_decls) << D;
8113 else {
8114 for (unsigned I = 0, N = Candidates.size(); I != N; ++I)
8115 Diag(Candidates[I]->getLocation(),
8116 diag::note_module_odr_violation_possible_decl)
8117 << Candidates[I];
8118 }
Richard Smithcd45dbc2014-04-19 03:48:30 +00008119
8120 DiagnosedOdrMergeFailures.insert(CanonDef);
Richard Smith2b9e3e32013-10-18 06:05:18 +00008121 }
8122 }
Guy Benyei11169dd2012-12-18 14:30:41 +00008123 }
8124
8125 // If we deserialized any C++ or Objective-C class definitions, any
8126 // Objective-C protocol definitions, or any redeclarable templates, make sure
8127 // that all redeclarations point to the definitions. Note that this can only
8128 // happen now, after the redeclaration chains have been fully wired.
8129 for (llvm::SmallPtrSet<Decl *, 4>::iterator D = PendingDefinitions.begin(),
8130 DEnd = PendingDefinitions.end();
8131 D != DEnd; ++D) {
8132 if (TagDecl *TD = dyn_cast<TagDecl>(*D)) {
Richard Smith5b21db82014-04-23 18:20:42 +00008133 if (const TagType *TagT = dyn_cast<TagType>(TD->getTypeForDecl())) {
Guy Benyei11169dd2012-12-18 14:30:41 +00008134 // Make sure that the TagType points at the definition.
8135 const_cast<TagType*>(TagT)->decl = TD;
8136 }
8137
Aaron Ballman86c93902014-03-06 23:45:36 +00008138 if (auto RD = dyn_cast<CXXRecordDecl>(*D)) {
8139 for (auto R : RD->redecls())
8140 cast<CXXRecordDecl>(R)->DefinitionData = RD->DefinitionData;
Guy Benyei11169dd2012-12-18 14:30:41 +00008141
8142 }
8143
8144 continue;
8145 }
8146
Aaron Ballman86c93902014-03-06 23:45:36 +00008147 if (auto ID = dyn_cast<ObjCInterfaceDecl>(*D)) {
Guy Benyei11169dd2012-12-18 14:30:41 +00008148 // Make sure that the ObjCInterfaceType points at the definition.
8149 const_cast<ObjCInterfaceType *>(cast<ObjCInterfaceType>(ID->TypeForDecl))
8150 ->Decl = ID;
8151
Aaron Ballman86c93902014-03-06 23:45:36 +00008152 for (auto R : ID->redecls())
Guy Benyei11169dd2012-12-18 14:30:41 +00008153 R->Data = ID->Data;
8154
8155 continue;
8156 }
8157
Aaron Ballman86c93902014-03-06 23:45:36 +00008158 if (auto PD = dyn_cast<ObjCProtocolDecl>(*D)) {
8159 for (auto R : PD->redecls())
Guy Benyei11169dd2012-12-18 14:30:41 +00008160 R->Data = PD->Data;
8161
8162 continue;
8163 }
8164
Aaron Ballman86c93902014-03-06 23:45:36 +00008165 auto RTD = cast<RedeclarableTemplateDecl>(*D)->getCanonicalDecl();
8166 for (auto R : RTD->redecls())
Guy Benyei11169dd2012-12-18 14:30:41 +00008167 R->Common = RTD->Common;
8168 }
8169 PendingDefinitions.clear();
8170
8171 // Load the bodies of any functions or methods we've encountered. We do
8172 // this now (delayed) so that we can be sure that the declaration chains
8173 // have been fully wired up.
8174 for (PendingBodiesMap::iterator PB = PendingBodies.begin(),
8175 PBEnd = PendingBodies.end();
8176 PB != PBEnd; ++PB) {
8177 if (FunctionDecl *FD = dyn_cast<FunctionDecl>(PB->first)) {
8178 // FIXME: Check for =delete/=default?
8179 // FIXME: Complain about ODR violations here?
8180 if (!getContext().getLangOpts().Modules || !FD->hasBody())
8181 FD->setLazyBody(PB->second);
8182 continue;
8183 }
8184
8185 ObjCMethodDecl *MD = cast<ObjCMethodDecl>(PB->first);
8186 if (!getContext().getLangOpts().Modules || !MD->hasBody())
8187 MD->setLazyBody(PB->second);
8188 }
8189 PendingBodies.clear();
Richard Smithcd45dbc2014-04-19 03:48:30 +00008190
8191 // Issue any pending ODR-failure diagnostics.
8192 for (auto &Merge : PendingOdrMergeFailures) {
8193 if (!DiagnosedOdrMergeFailures.insert(Merge.first))
8194 continue;
8195
8196 bool Diagnosed = false;
8197 for (auto *RD : Merge.second) {
8198 // Multiple different declarations got merged together; tell the user
8199 // where they came from.
8200 if (Merge.first != RD) {
8201 // FIXME: Walk the definition, figure out what's different,
8202 // and diagnose that.
8203 if (!Diagnosed) {
8204 std::string Module = getOwningModuleNameForDiagnostic(Merge.first);
8205 Diag(Merge.first->getLocation(),
8206 diag::err_module_odr_violation_different_definitions)
8207 << Merge.first << Module.empty() << Module;
8208 Diagnosed = true;
8209 }
8210
8211 Diag(RD->getLocation(),
8212 diag::note_module_odr_violation_different_definitions)
8213 << getOwningModuleNameForDiagnostic(RD);
8214 }
8215 }
8216
8217 if (!Diagnosed) {
8218 // All definitions are updates to the same declaration. This happens if a
8219 // module instantiates the declaration of a class template specialization
8220 // and two or more other modules instantiate its definition.
8221 //
8222 // FIXME: Indicate which modules had instantiations of this definition.
8223 // FIXME: How can this even happen?
8224 Diag(Merge.first->getLocation(),
8225 diag::err_module_odr_violation_different_instantiations)
8226 << Merge.first;
8227 }
8228 }
8229 PendingOdrMergeFailures.clear();
Guy Benyei11169dd2012-12-18 14:30:41 +00008230}
8231
8232void ASTReader::FinishedDeserializing() {
8233 assert(NumCurrentElementsDeserializing &&
8234 "FinishedDeserializing not paired with StartedDeserializing");
8235 if (NumCurrentElementsDeserializing == 1) {
8236 // We decrease NumCurrentElementsDeserializing only after pending actions
8237 // are finished, to avoid recursively re-calling finishPendingActions().
8238 finishPendingActions();
8239 }
8240 --NumCurrentElementsDeserializing;
8241
Richard Smith04d05b52014-03-23 00:27:18 +00008242 if (NumCurrentElementsDeserializing == 0 && Consumer) {
8243 // We are not in recursive loading, so it's safe to pass the "interesting"
8244 // decls to the consumer.
8245 PassInterestingDeclsToConsumer();
Guy Benyei11169dd2012-12-18 14:30:41 +00008246 }
8247}
8248
Argyrios Kyrtzidise5edbf92013-04-26 21:33:35 +00008249void ASTReader::pushExternalDeclIntoScope(NamedDecl *D, DeclarationName Name) {
Rafael Espindola7b56f6c2013-10-19 16:55:03 +00008250 D = D->getMostRecentDecl();
Argyrios Kyrtzidise5edbf92013-04-26 21:33:35 +00008251
8252 if (SemaObj->IdResolver.tryAddTopLevelDecl(D, Name) && SemaObj->TUScope) {
8253 SemaObj->TUScope->AddDecl(D);
8254 } else if (SemaObj->TUScope) {
8255 // Adding the decl to IdResolver may have failed because it was already in
8256 // (even though it was not added in scope). If it is already in, make sure
8257 // it gets in the scope as well.
8258 if (std::find(SemaObj->IdResolver.begin(Name),
8259 SemaObj->IdResolver.end(), D) != SemaObj->IdResolver.end())
8260 SemaObj->TUScope->AddDecl(D);
8261 }
8262}
8263
Nico Weber824285e2014-05-08 04:26:47 +00008264ASTReader::ASTReader(Preprocessor &PP, ASTContext &Context, StringRef isysroot,
8265 bool DisableValidation, bool AllowASTWithCompilerErrors,
8266 bool AllowConfigurationMismatch, bool ValidateSystemInputs,
Ben Langmuir2cb4a782014-02-05 22:21:15 +00008267 bool UseGlobalIndex)
Nico Weber824285e2014-05-08 04:26:47 +00008268 : Listener(new PCHValidator(PP, *this)), DeserializationListener(0),
8269 OwnsDeserializationListener(false), SourceMgr(PP.getSourceManager()),
8270 FileMgr(PP.getFileManager()), Diags(PP.getDiagnostics()), SemaObj(0),
8271 PP(PP), Context(Context), Consumer(0), ModuleMgr(PP.getFileManager()),
8272 isysroot(isysroot), DisableValidation(DisableValidation),
8273 AllowASTWithCompilerErrors(AllowASTWithCompilerErrors),
8274 AllowConfigurationMismatch(AllowConfigurationMismatch),
8275 ValidateSystemInputs(ValidateSystemInputs),
8276 UseGlobalIndex(UseGlobalIndex), TriedLoadingGlobalIndex(false),
8277 CurrentGeneration(0), CurrSwitchCaseStmts(&SwitchCaseStmts),
8278 NumSLocEntriesRead(0), TotalNumSLocEntries(0), NumStatementsRead(0),
8279 TotalNumStatements(0), NumMacrosRead(0), TotalNumMacros(0),
8280 NumIdentifierLookups(0), NumIdentifierLookupHits(0), NumSelectorsRead(0),
8281 NumMethodPoolEntriesRead(0), NumMethodPoolLookups(0),
8282 NumMethodPoolHits(0), NumMethodPoolTableLookups(0),
8283 NumMethodPoolTableHits(0), TotalNumMethodPoolEntries(0),
8284 NumLexicalDeclContextsRead(0), TotalLexicalDeclContexts(0),
8285 NumVisibleDeclContextsRead(0), TotalVisibleDeclContexts(0),
8286 TotalModulesSizeInBits(0), NumCurrentElementsDeserializing(0),
8287 PassingDeclsToConsumer(false), NumCXXBaseSpecifiersLoaded(0),
8288 ReadingKind(Read_None) {
Guy Benyei11169dd2012-12-18 14:30:41 +00008289 SourceMgr.setExternalSLocEntrySource(this);
8290}
8291
8292ASTReader::~ASTReader() {
Nico Weber824285e2014-05-08 04:26:47 +00008293 if (OwnsDeserializationListener)
8294 delete DeserializationListener;
8295
Guy Benyei11169dd2012-12-18 14:30:41 +00008296 for (DeclContextVisibleUpdatesPending::iterator
8297 I = PendingVisibleUpdates.begin(),
8298 E = PendingVisibleUpdates.end();
8299 I != E; ++I) {
8300 for (DeclContextVisibleUpdates::iterator J = I->second.begin(),
8301 F = I->second.end();
8302 J != F; ++J)
8303 delete J->first;
8304 }
8305}