blob: e1daa04647f63b8d9efd149109175b83561f0106 [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"
Benjamin Kramerf3ca26982014-05-10 16:31:55 +000025#include "clang/Basic/DiagnosticOptions.h"
Guy Benyei11169dd2012-12-18 14:30:41 +000026#include "clang/Basic/FileManager.h"
Guy Benyei11169dd2012-12-18 14:30:41 +000027#include "clang/Basic/SourceManager.h"
28#include "clang/Basic/SourceManagerInternals.h"
29#include "clang/Basic/TargetInfo.h"
30#include "clang/Basic/TargetOptions.h"
31#include "clang/Basic/Version.h"
32#include "clang/Basic/VersionTuple.h"
Ben Langmuirb92de022014-04-29 16:25:26 +000033#include "clang/Frontend/Utils.h"
Guy Benyei11169dd2012-12-18 14:30:41 +000034#include "clang/Lex/HeaderSearch.h"
35#include "clang/Lex/HeaderSearchOptions.h"
36#include "clang/Lex/MacroInfo.h"
37#include "clang/Lex/PreprocessingRecord.h"
38#include "clang/Lex/Preprocessor.h"
39#include "clang/Lex/PreprocessorOptions.h"
40#include "clang/Sema/Scope.h"
41#include "clang/Sema/Sema.h"
42#include "clang/Serialization/ASTDeserializationListener.h"
Douglas Gregore060e572013-01-25 01:03:03 +000043#include "clang/Serialization/GlobalModuleIndex.h"
Guy Benyei11169dd2012-12-18 14:30:41 +000044#include "clang/Serialization/ModuleManager.h"
45#include "clang/Serialization/SerializationDiagnostic.h"
Argyrios Kyrtzidis5c2a3452013-03-06 18:12:47 +000046#include "llvm/ADT/Hashing.h"
Guy Benyei11169dd2012-12-18 14:30:41 +000047#include "llvm/ADT/StringExtras.h"
48#include "llvm/Bitcode/BitstreamReader.h"
49#include "llvm/Support/ErrorHandling.h"
50#include "llvm/Support/FileSystem.h"
51#include "llvm/Support/MemoryBuffer.h"
52#include "llvm/Support/Path.h"
53#include "llvm/Support/SaveAndRestore.h"
Dmitri Gribenkof430da42014-02-12 10:33:14 +000054#include "llvm/Support/raw_ostream.h"
Guy Benyei11169dd2012-12-18 14:30:41 +000055#include <algorithm>
Chris Lattner91f373e2013-01-20 00:57:52 +000056#include <cstdio>
Guy Benyei11169dd2012-12-18 14:30:41 +000057#include <iterator>
Rafael Espindola8a8e5542014-06-12 17:19:42 +000058#include <system_error>
Guy Benyei11169dd2012-12-18 14:30:41 +000059
60using namespace clang;
61using namespace clang::serialization;
62using namespace clang::serialization::reader;
Chris Lattner7fb3bef2013-01-20 00:56:42 +000063using llvm::BitstreamCursor;
Guy Benyei11169dd2012-12-18 14:30:41 +000064
Ben Langmuircb69b572014-03-07 06:40:32 +000065
66//===----------------------------------------------------------------------===//
67// ChainedASTReaderListener implementation
68//===----------------------------------------------------------------------===//
69
70bool
71ChainedASTReaderListener::ReadFullVersionInformation(StringRef FullVersion) {
72 return First->ReadFullVersionInformation(FullVersion) ||
73 Second->ReadFullVersionInformation(FullVersion);
74}
Ben Langmuir4f5212a2014-04-14 22:12:44 +000075void ChainedASTReaderListener::ReadModuleName(StringRef ModuleName) {
76 First->ReadModuleName(ModuleName);
77 Second->ReadModuleName(ModuleName);
78}
79void ChainedASTReaderListener::ReadModuleMapFile(StringRef ModuleMapPath) {
80 First->ReadModuleMapFile(ModuleMapPath);
81 Second->ReadModuleMapFile(ModuleMapPath);
82}
Richard Smith1e2cf0d2014-10-31 02:28:58 +000083bool
84ChainedASTReaderListener::ReadLanguageOptions(const LangOptions &LangOpts,
85 bool Complain,
86 bool AllowCompatibleDifferences) {
87 return First->ReadLanguageOptions(LangOpts, Complain,
88 AllowCompatibleDifferences) ||
89 Second->ReadLanguageOptions(LangOpts, Complain,
90 AllowCompatibleDifferences);
Ben Langmuircb69b572014-03-07 06:40:32 +000091}
92bool
93ChainedASTReaderListener::ReadTargetOptions(const TargetOptions &TargetOpts,
94 bool Complain) {
95 return First->ReadTargetOptions(TargetOpts, Complain) ||
96 Second->ReadTargetOptions(TargetOpts, Complain);
97}
98bool ChainedASTReaderListener::ReadDiagnosticOptions(
Ben Langmuirb92de022014-04-29 16:25:26 +000099 IntrusiveRefCntPtr<DiagnosticOptions> DiagOpts, bool Complain) {
Ben Langmuircb69b572014-03-07 06:40:32 +0000100 return First->ReadDiagnosticOptions(DiagOpts, Complain) ||
101 Second->ReadDiagnosticOptions(DiagOpts, Complain);
102}
103bool
104ChainedASTReaderListener::ReadFileSystemOptions(const FileSystemOptions &FSOpts,
105 bool Complain) {
106 return First->ReadFileSystemOptions(FSOpts, Complain) ||
107 Second->ReadFileSystemOptions(FSOpts, Complain);
108}
109
110bool ChainedASTReaderListener::ReadHeaderSearchOptions(
111 const HeaderSearchOptions &HSOpts, bool Complain) {
112 return First->ReadHeaderSearchOptions(HSOpts, Complain) ||
113 Second->ReadHeaderSearchOptions(HSOpts, Complain);
114}
115bool ChainedASTReaderListener::ReadPreprocessorOptions(
116 const PreprocessorOptions &PPOpts, bool Complain,
117 std::string &SuggestedPredefines) {
118 return First->ReadPreprocessorOptions(PPOpts, Complain,
119 SuggestedPredefines) ||
120 Second->ReadPreprocessorOptions(PPOpts, Complain, SuggestedPredefines);
121}
122void ChainedASTReaderListener::ReadCounter(const serialization::ModuleFile &M,
123 unsigned Value) {
124 First->ReadCounter(M, Value);
125 Second->ReadCounter(M, Value);
126}
127bool ChainedASTReaderListener::needsInputFileVisitation() {
128 return First->needsInputFileVisitation() ||
129 Second->needsInputFileVisitation();
130}
131bool ChainedASTReaderListener::needsSystemInputFileVisitation() {
132 return First->needsSystemInputFileVisitation() ||
133 Second->needsSystemInputFileVisitation();
134}
Argyrios Kyrtzidis6d0753d2014-03-14 03:07:38 +0000135void ChainedASTReaderListener::visitModuleFile(StringRef Filename) {
136 First->visitModuleFile(Filename);
137 Second->visitModuleFile(Filename);
138}
Ben Langmuircb69b572014-03-07 06:40:32 +0000139bool ChainedASTReaderListener::visitInputFile(StringRef Filename,
Argyrios Kyrtzidis68ccbe02014-03-14 02:26:31 +0000140 bool isSystem,
141 bool isOverridden) {
Justin Bognerc65a66d2014-05-22 06:04:59 +0000142 bool Continue = false;
143 if (First->needsInputFileVisitation() &&
144 (!isSystem || First->needsSystemInputFileVisitation()))
145 Continue |= First->visitInputFile(Filename, isSystem, isOverridden);
146 if (Second->needsInputFileVisitation() &&
147 (!isSystem || Second->needsSystemInputFileVisitation()))
148 Continue |= Second->visitInputFile(Filename, isSystem, isOverridden);
149 return Continue;
Ben Langmuircb69b572014-03-07 06:40:32 +0000150}
151
Guy Benyei11169dd2012-12-18 14:30:41 +0000152//===----------------------------------------------------------------------===//
153// PCH validator implementation
154//===----------------------------------------------------------------------===//
155
156ASTReaderListener::~ASTReaderListener() {}
157
158/// \brief Compare the given set of language options against an existing set of
159/// language options.
160///
161/// \param Diags If non-NULL, diagnostics will be emitted via this engine.
Richard Smith1e2cf0d2014-10-31 02:28:58 +0000162/// \param AllowCompatibleDifferences If true, differences between compatible
163/// language options will be permitted.
Guy Benyei11169dd2012-12-18 14:30:41 +0000164///
165/// \returns true if the languagae options mis-match, false otherwise.
166static bool checkLanguageOptions(const LangOptions &LangOpts,
167 const LangOptions &ExistingLangOpts,
Richard Smith1e2cf0d2014-10-31 02:28:58 +0000168 DiagnosticsEngine *Diags,
169 bool AllowCompatibleDifferences = true) {
Guy Benyei11169dd2012-12-18 14:30:41 +0000170#define LANGOPT(Name, Bits, Default, Description) \
171 if (ExistingLangOpts.Name != LangOpts.Name) { \
172 if (Diags) \
173 Diags->Report(diag::err_pch_langopt_mismatch) \
174 << Description << LangOpts.Name << ExistingLangOpts.Name; \
175 return true; \
176 }
177
178#define VALUE_LANGOPT(Name, Bits, Default, Description) \
179 if (ExistingLangOpts.Name != LangOpts.Name) { \
180 if (Diags) \
181 Diags->Report(diag::err_pch_langopt_value_mismatch) \
182 << Description; \
183 return true; \
184 }
185
186#define ENUM_LANGOPT(Name, Type, Bits, Default, Description) \
187 if (ExistingLangOpts.get##Name() != LangOpts.get##Name()) { \
188 if (Diags) \
189 Diags->Report(diag::err_pch_langopt_value_mismatch) \
190 << Description; \
191 return true; \
192 }
193
Richard Smith1e2cf0d2014-10-31 02:28:58 +0000194#define COMPATIBLE_LANGOPT(Name, Bits, Default, Description) \
195 if (!AllowCompatibleDifferences) \
196 LANGOPT(Name, Bits, Default, Description)
197
198#define COMPATIBLE_ENUM_LANGOPT(Name, Bits, Default, Description) \
199 if (!AllowCompatibleDifferences) \
200 ENUM_LANGOPT(Name, Bits, Default, Description)
201
Guy Benyei11169dd2012-12-18 14:30:41 +0000202#define BENIGN_LANGOPT(Name, Bits, Default, Description)
203#define BENIGN_ENUM_LANGOPT(Name, Type, Bits, Default, Description)
204#include "clang/Basic/LangOptions.def"
205
206 if (ExistingLangOpts.ObjCRuntime != LangOpts.ObjCRuntime) {
207 if (Diags)
208 Diags->Report(diag::err_pch_langopt_value_mismatch)
209 << "target Objective-C runtime";
210 return true;
211 }
212
Dmitri Gribenkoacf2e782013-02-22 14:21:27 +0000213 if (ExistingLangOpts.CommentOpts.BlockCommandNames !=
214 LangOpts.CommentOpts.BlockCommandNames) {
215 if (Diags)
216 Diags->Report(diag::err_pch_langopt_value_mismatch)
217 << "block command names";
218 return true;
219 }
220
Guy Benyei11169dd2012-12-18 14:30:41 +0000221 return false;
222}
223
224/// \brief Compare the given set of target options against an existing set of
225/// target options.
226///
227/// \param Diags If non-NULL, diagnostics will be emitted via this engine.
228///
229/// \returns true if the target options mis-match, false otherwise.
230static bool checkTargetOptions(const TargetOptions &TargetOpts,
231 const TargetOptions &ExistingTargetOpts,
232 DiagnosticsEngine *Diags) {
233#define CHECK_TARGET_OPT(Field, Name) \
234 if (TargetOpts.Field != ExistingTargetOpts.Field) { \
235 if (Diags) \
236 Diags->Report(diag::err_pch_targetopt_mismatch) \
237 << Name << TargetOpts.Field << ExistingTargetOpts.Field; \
238 return true; \
239 }
240
241 CHECK_TARGET_OPT(Triple, "target");
242 CHECK_TARGET_OPT(CPU, "target CPU");
243 CHECK_TARGET_OPT(ABI, "target ABI");
Guy Benyei11169dd2012-12-18 14:30:41 +0000244#undef CHECK_TARGET_OPT
245
246 // Compare feature sets.
247 SmallVector<StringRef, 4> ExistingFeatures(
248 ExistingTargetOpts.FeaturesAsWritten.begin(),
249 ExistingTargetOpts.FeaturesAsWritten.end());
250 SmallVector<StringRef, 4> ReadFeatures(TargetOpts.FeaturesAsWritten.begin(),
251 TargetOpts.FeaturesAsWritten.end());
252 std::sort(ExistingFeatures.begin(), ExistingFeatures.end());
253 std::sort(ReadFeatures.begin(), ReadFeatures.end());
254
255 unsigned ExistingIdx = 0, ExistingN = ExistingFeatures.size();
256 unsigned ReadIdx = 0, ReadN = ReadFeatures.size();
257 while (ExistingIdx < ExistingN && ReadIdx < ReadN) {
258 if (ExistingFeatures[ExistingIdx] == ReadFeatures[ReadIdx]) {
259 ++ExistingIdx;
260 ++ReadIdx;
261 continue;
262 }
263
264 if (ReadFeatures[ReadIdx] < ExistingFeatures[ExistingIdx]) {
265 if (Diags)
266 Diags->Report(diag::err_pch_targetopt_feature_mismatch)
267 << false << ReadFeatures[ReadIdx];
268 return true;
269 }
270
271 if (Diags)
272 Diags->Report(diag::err_pch_targetopt_feature_mismatch)
273 << true << ExistingFeatures[ExistingIdx];
274 return true;
275 }
276
277 if (ExistingIdx < ExistingN) {
278 if (Diags)
279 Diags->Report(diag::err_pch_targetopt_feature_mismatch)
280 << true << ExistingFeatures[ExistingIdx];
281 return true;
282 }
283
284 if (ReadIdx < ReadN) {
285 if (Diags)
286 Diags->Report(diag::err_pch_targetopt_feature_mismatch)
287 << false << ReadFeatures[ReadIdx];
288 return true;
289 }
290
291 return false;
292}
293
294bool
295PCHValidator::ReadLanguageOptions(const LangOptions &LangOpts,
Richard Smith1e2cf0d2014-10-31 02:28:58 +0000296 bool Complain,
297 bool AllowCompatibleDifferences) {
Guy Benyei11169dd2012-12-18 14:30:41 +0000298 const LangOptions &ExistingLangOpts = PP.getLangOpts();
299 return checkLanguageOptions(LangOpts, ExistingLangOpts,
Richard Smith1e2cf0d2014-10-31 02:28:58 +0000300 Complain ? &Reader.Diags : nullptr,
301 AllowCompatibleDifferences);
Guy Benyei11169dd2012-12-18 14:30:41 +0000302}
303
304bool PCHValidator::ReadTargetOptions(const TargetOptions &TargetOpts,
305 bool Complain) {
306 const TargetOptions &ExistingTargetOpts = PP.getTargetInfo().getTargetOpts();
307 return checkTargetOptions(TargetOpts, ExistingTargetOpts,
Craig Toppera13603a2014-05-22 05:54:18 +0000308 Complain? &Reader.Diags : nullptr);
Guy Benyei11169dd2012-12-18 14:30:41 +0000309}
310
311namespace {
312 typedef llvm::StringMap<std::pair<StringRef, bool /*IsUndef*/> >
313 MacroDefinitionsMap;
Craig Topper3598eb72013-07-05 04:43:31 +0000314 typedef llvm::DenseMap<DeclarationName, SmallVector<NamedDecl *, 8> >
315 DeclsMap;
Guy Benyei11169dd2012-12-18 14:30:41 +0000316}
317
Ben Langmuirb92de022014-04-29 16:25:26 +0000318static bool checkDiagnosticGroupMappings(DiagnosticsEngine &StoredDiags,
319 DiagnosticsEngine &Diags,
320 bool Complain) {
321 typedef DiagnosticsEngine::Level Level;
322
323 // Check current mappings for new -Werror mappings, and the stored mappings
324 // for cases that were explicitly mapped to *not* be errors that are now
325 // errors because of options like -Werror.
326 DiagnosticsEngine *MappingSources[] = { &Diags, &StoredDiags };
327
328 for (DiagnosticsEngine *MappingSource : MappingSources) {
329 for (auto DiagIDMappingPair : MappingSource->getDiagnosticMappings()) {
330 diag::kind DiagID = DiagIDMappingPair.first;
331 Level CurLevel = Diags.getDiagnosticLevel(DiagID, SourceLocation());
332 if (CurLevel < DiagnosticsEngine::Error)
333 continue; // not significant
334 Level StoredLevel =
335 StoredDiags.getDiagnosticLevel(DiagID, SourceLocation());
336 if (StoredLevel < DiagnosticsEngine::Error) {
337 if (Complain)
338 Diags.Report(diag::err_pch_diagopt_mismatch) << "-Werror=" +
339 Diags.getDiagnosticIDs()->getWarningOptionForDiag(DiagID).str();
340 return true;
341 }
342 }
343 }
344
345 return false;
346}
347
Alp Tokerac4e8e52014-06-22 21:58:33 +0000348static bool isExtHandlingFromDiagsError(DiagnosticsEngine &Diags) {
349 diag::Severity Ext = Diags.getExtensionHandlingBehavior();
350 if (Ext == diag::Severity::Warning && Diags.getWarningsAsErrors())
351 return true;
352 return Ext >= diag::Severity::Error;
Ben Langmuirb92de022014-04-29 16:25:26 +0000353}
354
355static bool checkDiagnosticMappings(DiagnosticsEngine &StoredDiags,
356 DiagnosticsEngine &Diags,
357 bool IsSystem, bool Complain) {
358 // Top-level options
359 if (IsSystem) {
360 if (Diags.getSuppressSystemWarnings())
361 return false;
362 // If -Wsystem-headers was not enabled before, be conservative
363 if (StoredDiags.getSuppressSystemWarnings()) {
364 if (Complain)
365 Diags.Report(diag::err_pch_diagopt_mismatch) << "-Wsystem-headers";
366 return true;
367 }
368 }
369
370 if (Diags.getWarningsAsErrors() && !StoredDiags.getWarningsAsErrors()) {
371 if (Complain)
372 Diags.Report(diag::err_pch_diagopt_mismatch) << "-Werror";
373 return true;
374 }
375
376 if (Diags.getWarningsAsErrors() && Diags.getEnableAllWarnings() &&
377 !StoredDiags.getEnableAllWarnings()) {
378 if (Complain)
379 Diags.Report(diag::err_pch_diagopt_mismatch) << "-Weverything -Werror";
380 return true;
381 }
382
383 if (isExtHandlingFromDiagsError(Diags) &&
384 !isExtHandlingFromDiagsError(StoredDiags)) {
385 if (Complain)
386 Diags.Report(diag::err_pch_diagopt_mismatch) << "-pedantic-errors";
387 return true;
388 }
389
390 return checkDiagnosticGroupMappings(StoredDiags, Diags, Complain);
391}
392
393bool PCHValidator::ReadDiagnosticOptions(
394 IntrusiveRefCntPtr<DiagnosticOptions> DiagOpts, bool Complain) {
395 DiagnosticsEngine &ExistingDiags = PP.getDiagnostics();
396 IntrusiveRefCntPtr<DiagnosticIDs> DiagIDs(ExistingDiags.getDiagnosticIDs());
397 IntrusiveRefCntPtr<DiagnosticsEngine> Diags(
Alp Tokerf994cef2014-07-05 03:08:06 +0000398 new DiagnosticsEngine(DiagIDs, DiagOpts.get()));
Ben Langmuirb92de022014-04-29 16:25:26 +0000399 // This should never fail, because we would have processed these options
400 // before writing them to an ASTFile.
401 ProcessWarningOptions(*Diags, *DiagOpts, /*Report*/false);
402
403 ModuleManager &ModuleMgr = Reader.getModuleManager();
404 assert(ModuleMgr.size() >= 1 && "what ASTFile is this then");
405
406 // If the original import came from a file explicitly generated by the user,
407 // don't check the diagnostic mappings.
408 // FIXME: currently this is approximated by checking whether this is not a
Richard Smithe842a472014-10-22 02:05:46 +0000409 // module import of an implicitly-loaded module file.
Ben Langmuirb92de022014-04-29 16:25:26 +0000410 // Note: ModuleMgr.rbegin() may not be the current module, but it must be in
411 // the transitive closure of its imports, since unrelated modules cannot be
412 // imported until after this module finishes validation.
413 ModuleFile *TopImport = *ModuleMgr.rbegin();
414 while (!TopImport->ImportedBy.empty())
415 TopImport = TopImport->ImportedBy[0];
Richard Smithe842a472014-10-22 02:05:46 +0000416 if (TopImport->Kind != MK_ImplicitModule)
Ben Langmuirb92de022014-04-29 16:25:26 +0000417 return false;
418
419 StringRef ModuleName = TopImport->ModuleName;
420 assert(!ModuleName.empty() && "diagnostic options read before module name");
421
422 Module *M = PP.getHeaderSearchInfo().lookupModule(ModuleName);
423 assert(M && "missing module");
424
425 // FIXME: if the diagnostics are incompatible, save a DiagnosticOptions that
426 // contains the union of their flags.
427 return checkDiagnosticMappings(*Diags, ExistingDiags, M->IsSystem, Complain);
428}
429
Guy Benyei11169dd2012-12-18 14:30:41 +0000430/// \brief Collect the macro definitions provided by the given preprocessor
431/// options.
Craig Toppera13603a2014-05-22 05:54:18 +0000432static void
433collectMacroDefinitions(const PreprocessorOptions &PPOpts,
434 MacroDefinitionsMap &Macros,
435 SmallVectorImpl<StringRef> *MacroNames = nullptr) {
Guy Benyei11169dd2012-12-18 14:30:41 +0000436 for (unsigned I = 0, N = PPOpts.Macros.size(); I != N; ++I) {
437 StringRef Macro = PPOpts.Macros[I].first;
438 bool IsUndef = PPOpts.Macros[I].second;
439
440 std::pair<StringRef, StringRef> MacroPair = Macro.split('=');
441 StringRef MacroName = MacroPair.first;
442 StringRef MacroBody = MacroPair.second;
443
444 // For an #undef'd macro, we only care about the name.
445 if (IsUndef) {
446 if (MacroNames && !Macros.count(MacroName))
447 MacroNames->push_back(MacroName);
448
449 Macros[MacroName] = std::make_pair("", true);
450 continue;
451 }
452
453 // For a #define'd macro, figure out the actual definition.
454 if (MacroName.size() == Macro.size())
455 MacroBody = "1";
456 else {
457 // Note: GCC drops anything following an end-of-line character.
458 StringRef::size_type End = MacroBody.find_first_of("\n\r");
459 MacroBody = MacroBody.substr(0, End);
460 }
461
462 if (MacroNames && !Macros.count(MacroName))
463 MacroNames->push_back(MacroName);
464 Macros[MacroName] = std::make_pair(MacroBody, false);
465 }
466}
467
468/// \brief Check the preprocessor options deserialized from the control block
469/// against the preprocessor options in an existing preprocessor.
470///
471/// \param Diags If non-null, produce diagnostics for any mismatches incurred.
472static bool checkPreprocessorOptions(const PreprocessorOptions &PPOpts,
473 const PreprocessorOptions &ExistingPPOpts,
474 DiagnosticsEngine *Diags,
475 FileManager &FileMgr,
Argyrios Kyrtzidisd3afa0c2013-04-26 21:33:40 +0000476 std::string &SuggestedPredefines,
477 const LangOptions &LangOpts) {
Guy Benyei11169dd2012-12-18 14:30:41 +0000478 // Check macro definitions.
479 MacroDefinitionsMap ASTFileMacros;
480 collectMacroDefinitions(PPOpts, ASTFileMacros);
481 MacroDefinitionsMap ExistingMacros;
482 SmallVector<StringRef, 4> ExistingMacroNames;
483 collectMacroDefinitions(ExistingPPOpts, ExistingMacros, &ExistingMacroNames);
484
485 for (unsigned I = 0, N = ExistingMacroNames.size(); I != N; ++I) {
486 // Dig out the macro definition in the existing preprocessor options.
487 StringRef MacroName = ExistingMacroNames[I];
488 std::pair<StringRef, bool> Existing = ExistingMacros[MacroName];
489
490 // Check whether we know anything about this macro name or not.
491 llvm::StringMap<std::pair<StringRef, bool /*IsUndef*/> >::iterator Known
492 = ASTFileMacros.find(MacroName);
493 if (Known == ASTFileMacros.end()) {
494 // FIXME: Check whether this identifier was referenced anywhere in the
495 // AST file. If so, we should reject the AST file. Unfortunately, this
496 // information isn't in the control block. What shall we do about it?
497
498 if (Existing.second) {
499 SuggestedPredefines += "#undef ";
500 SuggestedPredefines += MacroName.str();
501 SuggestedPredefines += '\n';
502 } else {
503 SuggestedPredefines += "#define ";
504 SuggestedPredefines += MacroName.str();
505 SuggestedPredefines += ' ';
506 SuggestedPredefines += Existing.first.str();
507 SuggestedPredefines += '\n';
508 }
509 continue;
510 }
511
512 // If the macro was defined in one but undef'd in the other, we have a
513 // conflict.
514 if (Existing.second != Known->second.second) {
515 if (Diags) {
516 Diags->Report(diag::err_pch_macro_def_undef)
517 << MacroName << Known->second.second;
518 }
519 return true;
520 }
521
522 // If the macro was #undef'd in both, or if the macro bodies are identical,
523 // it's fine.
524 if (Existing.second || Existing.first == Known->second.first)
525 continue;
526
527 // The macro bodies differ; complain.
528 if (Diags) {
529 Diags->Report(diag::err_pch_macro_def_conflict)
530 << MacroName << Known->second.first << Existing.first;
531 }
532 return true;
533 }
534
535 // Check whether we're using predefines.
536 if (PPOpts.UsePredefines != ExistingPPOpts.UsePredefines) {
537 if (Diags) {
538 Diags->Report(diag::err_pch_undef) << ExistingPPOpts.UsePredefines;
539 }
540 return true;
541 }
542
Argyrios Kyrtzidisd3afa0c2013-04-26 21:33:40 +0000543 // Detailed record is important since it is used for the module cache hash.
544 if (LangOpts.Modules &&
545 PPOpts.DetailedRecord != ExistingPPOpts.DetailedRecord) {
546 if (Diags) {
547 Diags->Report(diag::err_pch_pp_detailed_record) << PPOpts.DetailedRecord;
548 }
549 return true;
550 }
551
Guy Benyei11169dd2012-12-18 14:30:41 +0000552 // Compute the #include and #include_macros lines we need.
553 for (unsigned I = 0, N = ExistingPPOpts.Includes.size(); I != N; ++I) {
554 StringRef File = ExistingPPOpts.Includes[I];
555 if (File == ExistingPPOpts.ImplicitPCHInclude)
556 continue;
557
558 if (std::find(PPOpts.Includes.begin(), PPOpts.Includes.end(), File)
559 != PPOpts.Includes.end())
560 continue;
561
562 SuggestedPredefines += "#include \"";
Manuel Klimek9af34ae2014-08-12 08:25:57 +0000563 SuggestedPredefines += File;
Guy Benyei11169dd2012-12-18 14:30:41 +0000564 SuggestedPredefines += "\"\n";
565 }
566
567 for (unsigned I = 0, N = ExistingPPOpts.MacroIncludes.size(); I != N; ++I) {
568 StringRef File = ExistingPPOpts.MacroIncludes[I];
569 if (std::find(PPOpts.MacroIncludes.begin(), PPOpts.MacroIncludes.end(),
570 File)
571 != PPOpts.MacroIncludes.end())
572 continue;
573
574 SuggestedPredefines += "#__include_macros \"";
Manuel Klimek9af34ae2014-08-12 08:25:57 +0000575 SuggestedPredefines += File;
Guy Benyei11169dd2012-12-18 14:30:41 +0000576 SuggestedPredefines += "\"\n##\n";
577 }
578
579 return false;
580}
581
582bool PCHValidator::ReadPreprocessorOptions(const PreprocessorOptions &PPOpts,
583 bool Complain,
584 std::string &SuggestedPredefines) {
585 const PreprocessorOptions &ExistingPPOpts = PP.getPreprocessorOpts();
586
587 return checkPreprocessorOptions(PPOpts, ExistingPPOpts,
Craig Toppera13603a2014-05-22 05:54:18 +0000588 Complain? &Reader.Diags : nullptr,
Guy Benyei11169dd2012-12-18 14:30:41 +0000589 PP.getFileManager(),
Argyrios Kyrtzidisd3afa0c2013-04-26 21:33:40 +0000590 SuggestedPredefines,
591 PP.getLangOpts());
Guy Benyei11169dd2012-12-18 14:30:41 +0000592}
593
Guy Benyei11169dd2012-12-18 14:30:41 +0000594void PCHValidator::ReadCounter(const ModuleFile &M, unsigned Value) {
595 PP.setCounterValue(Value);
596}
597
598//===----------------------------------------------------------------------===//
599// AST reader implementation
600//===----------------------------------------------------------------------===//
601
Nico Weber824285e2014-05-08 04:26:47 +0000602void ASTReader::setDeserializationListener(ASTDeserializationListener *Listener,
603 bool TakeOwnership) {
Guy Benyei11169dd2012-12-18 14:30:41 +0000604 DeserializationListener = Listener;
Nico Weber824285e2014-05-08 04:26:47 +0000605 OwnsDeserializationListener = TakeOwnership;
Guy Benyei11169dd2012-12-18 14:30:41 +0000606}
607
608
609
610unsigned ASTSelectorLookupTrait::ComputeHash(Selector Sel) {
611 return serialization::ComputeHash(Sel);
612}
613
614
615std::pair<unsigned, unsigned>
616ASTSelectorLookupTrait::ReadKeyDataLength(const unsigned char*& d) {
Justin Bogner57ba0b22014-03-28 22:03:24 +0000617 using namespace llvm::support;
618 unsigned KeyLen = endian::readNext<uint16_t, little, unaligned>(d);
619 unsigned DataLen = endian::readNext<uint16_t, little, unaligned>(d);
Guy Benyei11169dd2012-12-18 14:30:41 +0000620 return std::make_pair(KeyLen, DataLen);
621}
622
623ASTSelectorLookupTrait::internal_key_type
624ASTSelectorLookupTrait::ReadKey(const unsigned char* d, unsigned) {
Justin Bogner57ba0b22014-03-28 22:03:24 +0000625 using namespace llvm::support;
Guy Benyei11169dd2012-12-18 14:30:41 +0000626 SelectorTable &SelTable = Reader.getContext().Selectors;
Justin Bogner57ba0b22014-03-28 22:03:24 +0000627 unsigned N = endian::readNext<uint16_t, little, unaligned>(d);
628 IdentifierInfo *FirstII = Reader.getLocalIdentifier(
629 F, endian::readNext<uint32_t, little, unaligned>(d));
Guy Benyei11169dd2012-12-18 14:30:41 +0000630 if (N == 0)
631 return SelTable.getNullarySelector(FirstII);
632 else if (N == 1)
633 return SelTable.getUnarySelector(FirstII);
634
635 SmallVector<IdentifierInfo *, 16> Args;
636 Args.push_back(FirstII);
637 for (unsigned I = 1; I != N; ++I)
Justin Bogner57ba0b22014-03-28 22:03:24 +0000638 Args.push_back(Reader.getLocalIdentifier(
639 F, endian::readNext<uint32_t, little, unaligned>(d)));
Guy Benyei11169dd2012-12-18 14:30:41 +0000640
641 return SelTable.getSelector(N, Args.data());
642}
643
644ASTSelectorLookupTrait::data_type
645ASTSelectorLookupTrait::ReadData(Selector, const unsigned char* d,
646 unsigned DataLen) {
Justin Bogner57ba0b22014-03-28 22:03:24 +0000647 using namespace llvm::support;
Guy Benyei11169dd2012-12-18 14:30:41 +0000648
649 data_type Result;
650
Justin Bogner57ba0b22014-03-28 22:03:24 +0000651 Result.ID = Reader.getGlobalSelectorID(
652 F, endian::readNext<uint32_t, little, unaligned>(d));
653 unsigned NumInstanceMethodsAndBits =
654 endian::readNext<uint16_t, little, unaligned>(d);
655 unsigned NumFactoryMethodsAndBits =
656 endian::readNext<uint16_t, little, unaligned>(d);
Argyrios Kyrtzidisd3da6e02013-04-17 00:08:58 +0000657 Result.InstanceBits = NumInstanceMethodsAndBits & 0x3;
658 Result.FactoryBits = NumFactoryMethodsAndBits & 0x3;
659 unsigned NumInstanceMethods = NumInstanceMethodsAndBits >> 2;
660 unsigned NumFactoryMethods = NumFactoryMethodsAndBits >> 2;
Guy Benyei11169dd2012-12-18 14:30:41 +0000661
662 // Load instance methods
663 for (unsigned I = 0; I != NumInstanceMethods; ++I) {
Justin Bogner57ba0b22014-03-28 22:03:24 +0000664 if (ObjCMethodDecl *Method = Reader.GetLocalDeclAs<ObjCMethodDecl>(
665 F, endian::readNext<uint32_t, little, unaligned>(d)))
Guy Benyei11169dd2012-12-18 14:30:41 +0000666 Result.Instance.push_back(Method);
667 }
668
669 // Load factory methods
670 for (unsigned I = 0; I != NumFactoryMethods; ++I) {
Justin Bogner57ba0b22014-03-28 22:03:24 +0000671 if (ObjCMethodDecl *Method = Reader.GetLocalDeclAs<ObjCMethodDecl>(
672 F, endian::readNext<uint32_t, little, unaligned>(d)))
Guy Benyei11169dd2012-12-18 14:30:41 +0000673 Result.Factory.push_back(Method);
674 }
675
676 return Result;
677}
678
Douglas Gregorbfd73d72013-01-23 18:53:14 +0000679unsigned ASTIdentifierLookupTraitBase::ComputeHash(const internal_key_type& a) {
680 return llvm::HashString(a);
Guy Benyei11169dd2012-12-18 14:30:41 +0000681}
682
683std::pair<unsigned, unsigned>
Douglas Gregorbfd73d72013-01-23 18:53:14 +0000684ASTIdentifierLookupTraitBase::ReadKeyDataLength(const unsigned char*& d) {
Justin Bogner57ba0b22014-03-28 22:03:24 +0000685 using namespace llvm::support;
686 unsigned DataLen = endian::readNext<uint16_t, little, unaligned>(d);
687 unsigned KeyLen = endian::readNext<uint16_t, little, unaligned>(d);
Guy Benyei11169dd2012-12-18 14:30:41 +0000688 return std::make_pair(KeyLen, DataLen);
689}
690
Douglas Gregorbfd73d72013-01-23 18:53:14 +0000691ASTIdentifierLookupTraitBase::internal_key_type
692ASTIdentifierLookupTraitBase::ReadKey(const unsigned char* d, unsigned n) {
Guy Benyei11169dd2012-12-18 14:30:41 +0000693 assert(n >= 2 && d[n-1] == '\0');
Douglas Gregorbfd73d72013-01-23 18:53:14 +0000694 return StringRef((const char*) d, n-1);
Guy Benyei11169dd2012-12-18 14:30:41 +0000695}
696
Douglas Gregordcf25082013-02-11 18:16:18 +0000697/// \brief Whether the given identifier is "interesting".
698static bool isInterestingIdentifier(IdentifierInfo &II) {
699 return II.isPoisoned() ||
700 II.isExtensionToken() ||
701 II.getObjCOrBuiltinID() ||
702 II.hasRevertedTokenIDToIdentifier() ||
703 II.hadMacroDefinition() ||
704 II.getFETokenInfo<void>();
705}
706
Guy Benyei11169dd2012-12-18 14:30:41 +0000707IdentifierInfo *ASTIdentifierLookupTrait::ReadData(const internal_key_type& k,
708 const unsigned char* d,
709 unsigned DataLen) {
Justin Bogner57ba0b22014-03-28 22:03:24 +0000710 using namespace llvm::support;
711 unsigned RawID = endian::readNext<uint32_t, little, unaligned>(d);
Guy Benyei11169dd2012-12-18 14:30:41 +0000712 bool IsInteresting = RawID & 0x01;
713
714 // Wipe out the "is interesting" bit.
715 RawID = RawID >> 1;
716
717 IdentID ID = Reader.getGlobalIdentifierID(F, RawID);
718 if (!IsInteresting) {
719 // For uninteresting identifiers, just build the IdentifierInfo
720 // and associate it with the persistent ID.
721 IdentifierInfo *II = KnownII;
722 if (!II) {
Douglas Gregorbfd73d72013-01-23 18:53:14 +0000723 II = &Reader.getIdentifierTable().getOwn(k);
Guy Benyei11169dd2012-12-18 14:30:41 +0000724 KnownII = II;
725 }
726 Reader.SetIdentifierInfo(ID, II);
Douglas Gregordcf25082013-02-11 18:16:18 +0000727 if (!II->isFromAST()) {
728 bool WasInteresting = isInterestingIdentifier(*II);
729 II->setIsFromAST();
730 if (WasInteresting)
731 II->setChangedSinceDeserialization();
732 }
733 Reader.markIdentifierUpToDate(II);
Guy Benyei11169dd2012-12-18 14:30:41 +0000734 return II;
735 }
736
Justin Bogner57ba0b22014-03-28 22:03:24 +0000737 unsigned ObjCOrBuiltinID = endian::readNext<uint16_t, little, unaligned>(d);
738 unsigned Bits = endian::readNext<uint16_t, little, unaligned>(d);
Guy Benyei11169dd2012-12-18 14:30:41 +0000739 bool CPlusPlusOperatorKeyword = Bits & 0x01;
740 Bits >>= 1;
741 bool HasRevertedTokenIDToIdentifier = Bits & 0x01;
742 Bits >>= 1;
743 bool Poisoned = Bits & 0x01;
744 Bits >>= 1;
745 bool ExtensionToken = Bits & 0x01;
746 Bits >>= 1;
Argyrios Kyrtzidiseb663da2013-03-22 21:12:57 +0000747 bool hasSubmoduleMacros = Bits & 0x01;
748 Bits >>= 1;
Guy Benyei11169dd2012-12-18 14:30:41 +0000749 bool hadMacroDefinition = Bits & 0x01;
750 Bits >>= 1;
751
752 assert(Bits == 0 && "Extra bits in the identifier?");
753 DataLen -= 8;
754
755 // Build the IdentifierInfo itself and link the identifier ID with
756 // the new IdentifierInfo.
757 IdentifierInfo *II = KnownII;
758 if (!II) {
Douglas Gregorbfd73d72013-01-23 18:53:14 +0000759 II = &Reader.getIdentifierTable().getOwn(StringRef(k));
Guy Benyei11169dd2012-12-18 14:30:41 +0000760 KnownII = II;
761 }
762 Reader.markIdentifierUpToDate(II);
Douglas Gregordcf25082013-02-11 18:16:18 +0000763 if (!II->isFromAST()) {
764 bool WasInteresting = isInterestingIdentifier(*II);
765 II->setIsFromAST();
766 if (WasInteresting)
767 II->setChangedSinceDeserialization();
768 }
Guy Benyei11169dd2012-12-18 14:30:41 +0000769
770 // Set or check the various bits in the IdentifierInfo structure.
771 // Token IDs are read-only.
Argyrios Kyrtzidisddee8c92013-02-27 01:13:51 +0000772 if (HasRevertedTokenIDToIdentifier && II->getTokenID() != tok::identifier)
Guy Benyei11169dd2012-12-18 14:30:41 +0000773 II->RevertTokenIDToIdentifier();
774 II->setObjCOrBuiltinID(ObjCOrBuiltinID);
775 assert(II->isExtensionToken() == ExtensionToken &&
776 "Incorrect extension token flag");
777 (void)ExtensionToken;
778 if (Poisoned)
779 II->setIsPoisoned(true);
780 assert(II->isCPlusPlusOperatorKeyword() == CPlusPlusOperatorKeyword &&
781 "Incorrect C++ operator keyword flag");
782 (void)CPlusPlusOperatorKeyword;
783
784 // If this identifier is a macro, deserialize the macro
785 // definition.
786 if (hadMacroDefinition) {
Justin Bogner57ba0b22014-03-28 22:03:24 +0000787 uint32_t MacroDirectivesOffset =
788 endian::readNext<uint32_t, little, unaligned>(d);
Argyrios Kyrtzidiseb663da2013-03-22 21:12:57 +0000789 DataLen -= 4;
790 SmallVector<uint32_t, 8> LocalMacroIDs;
791 if (hasSubmoduleMacros) {
Richard Smithdaa69e02014-07-25 04:40:03 +0000792 while (true) {
793 uint32_t LocalMacroID =
794 endian::readNext<uint32_t, little, unaligned>(d);
Argyrios Kyrtzidiseb663da2013-03-22 21:12:57 +0000795 DataLen -= 4;
Richard Smithdaa69e02014-07-25 04:40:03 +0000796 if (LocalMacroID == 0xdeadbeef) break;
Argyrios Kyrtzidiseb663da2013-03-22 21:12:57 +0000797 LocalMacroIDs.push_back(LocalMacroID);
798 }
Argyrios Kyrtzidis719736c2013-01-19 03:14:56 +0000799 }
Argyrios Kyrtzidiseb663da2013-03-22 21:12:57 +0000800
Richard Smithe842a472014-10-22 02:05:46 +0000801 if (F.Kind == MK_ImplicitModule || F.Kind == MK_ExplicitModule) {
Richard Smith49f906a2014-03-01 00:08:04 +0000802 // Macro definitions are stored from newest to oldest, so reverse them
803 // before registering them.
804 llvm::SmallVector<unsigned, 8> MacroSizes;
Argyrios Kyrtzidiseb663da2013-03-22 21:12:57 +0000805 for (SmallVectorImpl<uint32_t>::iterator
Richard Smith49f906a2014-03-01 00:08:04 +0000806 I = LocalMacroIDs.begin(), E = LocalMacroIDs.end(); I != E; /**/) {
807 unsigned Size = 1;
808
809 static const uint32_t HasOverridesFlag = 0x80000000U;
810 if (I + 1 != E && (I[1] & HasOverridesFlag))
811 Size += 1 + (I[1] & ~HasOverridesFlag);
812
813 MacroSizes.push_back(Size);
814 I += Size;
Argyrios Kyrtzidiseb663da2013-03-22 21:12:57 +0000815 }
Richard Smith49f906a2014-03-01 00:08:04 +0000816
817 SmallVectorImpl<uint32_t>::iterator I = LocalMacroIDs.end();
818 for (SmallVectorImpl<unsigned>::reverse_iterator SI = MacroSizes.rbegin(),
819 SE = MacroSizes.rend();
820 SI != SE; ++SI) {
821 I -= *SI;
822
823 uint32_t LocalMacroID = *I;
Craig Topper00bbdcf2014-06-28 23:22:23 +0000824 ArrayRef<uint32_t> Overrides;
Richard Smith49f906a2014-03-01 00:08:04 +0000825 if (*SI != 1)
826 Overrides = llvm::makeArrayRef(&I[2], *SI - 2);
827 Reader.addPendingMacroFromModule(II, &F, LocalMacroID, Overrides);
828 }
829 assert(I == LocalMacroIDs.begin());
Argyrios Kyrtzidiseb663da2013-03-22 21:12:57 +0000830 } else {
831 Reader.addPendingMacroFromPCH(II, &F, MacroDirectivesOffset);
832 }
Guy Benyei11169dd2012-12-18 14:30:41 +0000833 }
834
835 Reader.SetIdentifierInfo(ID, II);
836
837 // Read all of the declarations visible at global scope with this
838 // name.
839 if (DataLen > 0) {
840 SmallVector<uint32_t, 4> DeclIDs;
841 for (; DataLen > 0; DataLen -= 4)
Justin Bogner57ba0b22014-03-28 22:03:24 +0000842 DeclIDs.push_back(Reader.getGlobalDeclID(
843 F, endian::readNext<uint32_t, little, unaligned>(d)));
Guy Benyei11169dd2012-12-18 14:30:41 +0000844 Reader.SetGloballyVisibleDecls(II, DeclIDs);
845 }
846
847 return II;
848}
849
850unsigned
851ASTDeclContextNameLookupTrait::ComputeHash(const DeclNameKey &Key) const {
852 llvm::FoldingSetNodeID ID;
853 ID.AddInteger(Key.Kind);
854
855 switch (Key.Kind) {
856 case DeclarationName::Identifier:
857 case DeclarationName::CXXLiteralOperatorName:
858 ID.AddString(((IdentifierInfo*)Key.Data)->getName());
859 break;
860 case DeclarationName::ObjCZeroArgSelector:
861 case DeclarationName::ObjCOneArgSelector:
862 case DeclarationName::ObjCMultiArgSelector:
863 ID.AddInteger(serialization::ComputeHash(Selector(Key.Data)));
864 break;
865 case DeclarationName::CXXOperatorName:
866 ID.AddInteger((OverloadedOperatorKind)Key.Data);
867 break;
868 case DeclarationName::CXXConstructorName:
869 case DeclarationName::CXXDestructorName:
870 case DeclarationName::CXXConversionFunctionName:
871 case DeclarationName::CXXUsingDirective:
872 break;
873 }
874
875 return ID.ComputeHash();
876}
877
878ASTDeclContextNameLookupTrait::internal_key_type
879ASTDeclContextNameLookupTrait::GetInternalKey(
880 const external_key_type& Name) const {
881 DeclNameKey Key;
882 Key.Kind = Name.getNameKind();
883 switch (Name.getNameKind()) {
884 case DeclarationName::Identifier:
885 Key.Data = (uint64_t)Name.getAsIdentifierInfo();
886 break;
887 case DeclarationName::ObjCZeroArgSelector:
888 case DeclarationName::ObjCOneArgSelector:
889 case DeclarationName::ObjCMultiArgSelector:
890 Key.Data = (uint64_t)Name.getObjCSelector().getAsOpaquePtr();
891 break;
892 case DeclarationName::CXXOperatorName:
893 Key.Data = Name.getCXXOverloadedOperator();
894 break;
895 case DeclarationName::CXXLiteralOperatorName:
896 Key.Data = (uint64_t)Name.getCXXLiteralIdentifier();
897 break;
898 case DeclarationName::CXXConstructorName:
899 case DeclarationName::CXXDestructorName:
900 case DeclarationName::CXXConversionFunctionName:
901 case DeclarationName::CXXUsingDirective:
902 Key.Data = 0;
903 break;
904 }
905
906 return Key;
907}
908
909std::pair<unsigned, unsigned>
910ASTDeclContextNameLookupTrait::ReadKeyDataLength(const unsigned char*& d) {
Justin Bogner57ba0b22014-03-28 22:03:24 +0000911 using namespace llvm::support;
912 unsigned KeyLen = endian::readNext<uint16_t, little, unaligned>(d);
913 unsigned DataLen = endian::readNext<uint16_t, little, unaligned>(d);
Guy Benyei11169dd2012-12-18 14:30:41 +0000914 return std::make_pair(KeyLen, DataLen);
915}
916
917ASTDeclContextNameLookupTrait::internal_key_type
918ASTDeclContextNameLookupTrait::ReadKey(const unsigned char* d, unsigned) {
Justin Bogner57ba0b22014-03-28 22:03:24 +0000919 using namespace llvm::support;
Guy Benyei11169dd2012-12-18 14:30:41 +0000920
921 DeclNameKey Key;
922 Key.Kind = (DeclarationName::NameKind)*d++;
923 switch (Key.Kind) {
924 case DeclarationName::Identifier:
Justin Bogner57ba0b22014-03-28 22:03:24 +0000925 Key.Data = (uint64_t)Reader.getLocalIdentifier(
926 F, endian::readNext<uint32_t, little, unaligned>(d));
Guy Benyei11169dd2012-12-18 14:30:41 +0000927 break;
928 case DeclarationName::ObjCZeroArgSelector:
929 case DeclarationName::ObjCOneArgSelector:
930 case DeclarationName::ObjCMultiArgSelector:
931 Key.Data =
Justin Bogner57ba0b22014-03-28 22:03:24 +0000932 (uint64_t)Reader.getLocalSelector(
933 F, endian::readNext<uint32_t, little, unaligned>(
934 d)).getAsOpaquePtr();
Guy Benyei11169dd2012-12-18 14:30:41 +0000935 break;
936 case DeclarationName::CXXOperatorName:
937 Key.Data = *d++; // OverloadedOperatorKind
938 break;
939 case DeclarationName::CXXLiteralOperatorName:
Justin Bogner57ba0b22014-03-28 22:03:24 +0000940 Key.Data = (uint64_t)Reader.getLocalIdentifier(
941 F, endian::readNext<uint32_t, little, unaligned>(d));
Guy Benyei11169dd2012-12-18 14:30:41 +0000942 break;
943 case DeclarationName::CXXConstructorName:
944 case DeclarationName::CXXDestructorName:
945 case DeclarationName::CXXConversionFunctionName:
946 case DeclarationName::CXXUsingDirective:
947 Key.Data = 0;
948 break;
949 }
950
951 return Key;
952}
953
954ASTDeclContextNameLookupTrait::data_type
955ASTDeclContextNameLookupTrait::ReadData(internal_key_type,
956 const unsigned char* d,
957 unsigned DataLen) {
Justin Bogner57ba0b22014-03-28 22:03:24 +0000958 using namespace llvm::support;
959 unsigned NumDecls = endian::readNext<uint16_t, little, unaligned>(d);
Argyrios Kyrtzidisc57e5032013-01-11 22:29:49 +0000960 LE32DeclID *Start = reinterpret_cast<LE32DeclID *>(
961 const_cast<unsigned char *>(d));
Guy Benyei11169dd2012-12-18 14:30:41 +0000962 return std::make_pair(Start, Start + NumDecls);
963}
964
965bool ASTReader::ReadDeclContextStorage(ModuleFile &M,
Chris Lattner7fb3bef2013-01-20 00:56:42 +0000966 BitstreamCursor &Cursor,
Guy Benyei11169dd2012-12-18 14:30:41 +0000967 const std::pair<uint64_t, uint64_t> &Offsets,
968 DeclContextInfo &Info) {
969 SavedStreamPosition SavedPosition(Cursor);
970 // First the lexical decls.
971 if (Offsets.first != 0) {
972 Cursor.JumpToBit(Offsets.first);
973
974 RecordData Record;
Chris Lattner0e6c9402013-01-20 02:38:54 +0000975 StringRef Blob;
Guy Benyei11169dd2012-12-18 14:30:41 +0000976 unsigned Code = Cursor.ReadCode();
Chris Lattner0e6c9402013-01-20 02:38:54 +0000977 unsigned RecCode = Cursor.readRecord(Code, Record, &Blob);
Guy Benyei11169dd2012-12-18 14:30:41 +0000978 if (RecCode != DECL_CONTEXT_LEXICAL) {
979 Error("Expected lexical block");
980 return true;
981 }
982
Chris Lattner0e6c9402013-01-20 02:38:54 +0000983 Info.LexicalDecls = reinterpret_cast<const KindDeclIDPair*>(Blob.data());
984 Info.NumLexicalDecls = Blob.size() / sizeof(KindDeclIDPair);
Guy Benyei11169dd2012-12-18 14:30:41 +0000985 }
986
987 // Now the lookup table.
988 if (Offsets.second != 0) {
989 Cursor.JumpToBit(Offsets.second);
990
991 RecordData Record;
Chris Lattner0e6c9402013-01-20 02:38:54 +0000992 StringRef Blob;
Guy Benyei11169dd2012-12-18 14:30:41 +0000993 unsigned Code = Cursor.ReadCode();
Chris Lattner0e6c9402013-01-20 02:38:54 +0000994 unsigned RecCode = Cursor.readRecord(Code, Record, &Blob);
Guy Benyei11169dd2012-12-18 14:30:41 +0000995 if (RecCode != DECL_CONTEXT_VISIBLE) {
996 Error("Expected visible lookup table block");
997 return true;
998 }
Justin Bognerda4e6502014-04-14 16:34:29 +0000999 Info.NameLookupTableData = ASTDeclContextNameLookupTable::Create(
1000 (const unsigned char *)Blob.data() + Record[0],
1001 (const unsigned char *)Blob.data() + sizeof(uint32_t),
1002 (const unsigned char *)Blob.data(),
1003 ASTDeclContextNameLookupTrait(*this, M));
Guy Benyei11169dd2012-12-18 14:30:41 +00001004 }
1005
1006 return false;
1007}
1008
1009void ASTReader::Error(StringRef Msg) {
1010 Error(diag::err_fe_pch_malformed, Msg);
Douglas Gregor940e8052013-05-10 22:15:13 +00001011 if (Context.getLangOpts().Modules && !Diags.isDiagnosticInFlight()) {
1012 Diag(diag::note_module_cache_path)
1013 << PP.getHeaderSearchInfo().getModuleCachePath();
1014 }
Guy Benyei11169dd2012-12-18 14:30:41 +00001015}
1016
1017void ASTReader::Error(unsigned DiagID,
1018 StringRef Arg1, StringRef Arg2) {
1019 if (Diags.isDiagnosticInFlight())
1020 Diags.SetDelayedDiagnostic(DiagID, Arg1, Arg2);
1021 else
1022 Diag(DiagID) << Arg1 << Arg2;
1023}
1024
1025//===----------------------------------------------------------------------===//
1026// Source Manager Deserialization
1027//===----------------------------------------------------------------------===//
1028
1029/// \brief Read the line table in the source manager block.
1030/// \returns true if there was an error.
1031bool ASTReader::ParseLineTable(ModuleFile &F,
1032 SmallVectorImpl<uint64_t> &Record) {
1033 unsigned Idx = 0;
1034 LineTableInfo &LineTable = SourceMgr.getLineTable();
1035
1036 // Parse the file names
1037 std::map<int, int> FileIDs;
1038 for (int I = 0, N = Record[Idx++]; I != N; ++I) {
1039 // Extract the file name
1040 unsigned FilenameLen = Record[Idx++];
1041 std::string Filename(&Record[Idx], &Record[Idx] + FilenameLen);
1042 Idx += FilenameLen;
1043 MaybeAddSystemRootToFilename(F, Filename);
1044 FileIDs[I] = LineTable.getLineTableFilenameID(Filename);
1045 }
1046
1047 // Parse the line entries
1048 std::vector<LineEntry> Entries;
1049 while (Idx < Record.size()) {
1050 int FID = Record[Idx++];
1051 assert(FID >= 0 && "Serialized line entries for non-local file.");
1052 // Remap FileID from 1-based old view.
1053 FID += F.SLocEntryBaseID - 1;
1054
1055 // Extract the line entries
1056 unsigned NumEntries = Record[Idx++];
1057 assert(NumEntries && "Numentries is 00000");
1058 Entries.clear();
1059 Entries.reserve(NumEntries);
1060 for (unsigned I = 0; I != NumEntries; ++I) {
1061 unsigned FileOffset = Record[Idx++];
1062 unsigned LineNo = Record[Idx++];
1063 int FilenameID = FileIDs[Record[Idx++]];
1064 SrcMgr::CharacteristicKind FileKind
1065 = (SrcMgr::CharacteristicKind)Record[Idx++];
1066 unsigned IncludeOffset = Record[Idx++];
1067 Entries.push_back(LineEntry::get(FileOffset, LineNo, FilenameID,
1068 FileKind, IncludeOffset));
1069 }
1070 LineTable.AddEntry(FileID::get(FID), Entries);
1071 }
1072
1073 return false;
1074}
1075
1076/// \brief Read a source manager block
1077bool ASTReader::ReadSourceManagerBlock(ModuleFile &F) {
1078 using namespace SrcMgr;
1079
Chris Lattner7fb3bef2013-01-20 00:56:42 +00001080 BitstreamCursor &SLocEntryCursor = F.SLocEntryCursor;
Guy Benyei11169dd2012-12-18 14:30:41 +00001081
1082 // Set the source-location entry cursor to the current position in
1083 // the stream. This cursor will be used to read the contents of the
1084 // source manager block initially, and then lazily read
1085 // source-location entries as needed.
1086 SLocEntryCursor = F.Stream;
1087
1088 // The stream itself is going to skip over the source manager block.
1089 if (F.Stream.SkipBlock()) {
1090 Error("malformed block record in AST file");
1091 return true;
1092 }
1093
1094 // Enter the source manager block.
1095 if (SLocEntryCursor.EnterSubBlock(SOURCE_MANAGER_BLOCK_ID)) {
1096 Error("malformed source manager block record in AST file");
1097 return true;
1098 }
1099
1100 RecordData Record;
1101 while (true) {
Chris Lattnere7b154b2013-01-19 21:39:22 +00001102 llvm::BitstreamEntry E = SLocEntryCursor.advanceSkippingSubblocks();
1103
1104 switch (E.Kind) {
1105 case llvm::BitstreamEntry::SubBlock: // Handled for us already.
1106 case llvm::BitstreamEntry::Error:
1107 Error("malformed block record in AST file");
1108 return true;
1109 case llvm::BitstreamEntry::EndBlock:
Guy Benyei11169dd2012-12-18 14:30:41 +00001110 return false;
Chris Lattnere7b154b2013-01-19 21:39:22 +00001111 case llvm::BitstreamEntry::Record:
1112 // The interesting case.
1113 break;
Guy Benyei11169dd2012-12-18 14:30:41 +00001114 }
Chris Lattnere7b154b2013-01-19 21:39:22 +00001115
Guy Benyei11169dd2012-12-18 14:30:41 +00001116 // Read a record.
Guy Benyei11169dd2012-12-18 14:30:41 +00001117 Record.clear();
Chris Lattner15c3e7d2013-01-21 18:28:26 +00001118 StringRef Blob;
1119 switch (SLocEntryCursor.readRecord(E.ID, Record, &Blob)) {
Guy Benyei11169dd2012-12-18 14:30:41 +00001120 default: // Default behavior: ignore.
1121 break;
1122
1123 case SM_SLOC_FILE_ENTRY:
1124 case SM_SLOC_BUFFER_ENTRY:
1125 case SM_SLOC_EXPANSION_ENTRY:
1126 // Once we hit one of the source location entries, we're done.
1127 return false;
1128 }
1129 }
1130}
1131
1132/// \brief If a header file is not found at the path that we expect it to be
1133/// and the PCH file was moved from its original location, try to resolve the
1134/// file by assuming that header+PCH were moved together and the header is in
1135/// the same place relative to the PCH.
1136static std::string
1137resolveFileRelativeToOriginalDir(const std::string &Filename,
1138 const std::string &OriginalDir,
1139 const std::string &CurrDir) {
1140 assert(OriginalDir != CurrDir &&
1141 "No point trying to resolve the file if the PCH dir didn't change");
1142 using namespace llvm::sys;
1143 SmallString<128> filePath(Filename);
1144 fs::make_absolute(filePath);
1145 assert(path::is_absolute(OriginalDir));
1146 SmallString<128> currPCHPath(CurrDir);
1147
1148 path::const_iterator fileDirI = path::begin(path::parent_path(filePath)),
1149 fileDirE = path::end(path::parent_path(filePath));
1150 path::const_iterator origDirI = path::begin(OriginalDir),
1151 origDirE = path::end(OriginalDir);
1152 // Skip the common path components from filePath and OriginalDir.
1153 while (fileDirI != fileDirE && origDirI != origDirE &&
1154 *fileDirI == *origDirI) {
1155 ++fileDirI;
1156 ++origDirI;
1157 }
1158 for (; origDirI != origDirE; ++origDirI)
1159 path::append(currPCHPath, "..");
1160 path::append(currPCHPath, fileDirI, fileDirE);
1161 path::append(currPCHPath, path::filename(Filename));
1162 return currPCHPath.str();
1163}
1164
1165bool ASTReader::ReadSLocEntry(int ID) {
1166 if (ID == 0)
1167 return false;
1168
1169 if (unsigned(-ID) - 2 >= getTotalNumSLocs() || ID > 0) {
1170 Error("source location entry ID out-of-range for AST file");
1171 return true;
1172 }
1173
1174 ModuleFile *F = GlobalSLocEntryMap.find(-ID)->second;
1175 F->SLocEntryCursor.JumpToBit(F->SLocEntryOffsets[ID - F->SLocEntryBaseID]);
Chris Lattner7fb3bef2013-01-20 00:56:42 +00001176 BitstreamCursor &SLocEntryCursor = F->SLocEntryCursor;
Guy Benyei11169dd2012-12-18 14:30:41 +00001177 unsigned BaseOffset = F->SLocEntryBaseOffset;
1178
1179 ++NumSLocEntriesRead;
Chris Lattnere7b154b2013-01-19 21:39:22 +00001180 llvm::BitstreamEntry Entry = SLocEntryCursor.advance();
1181 if (Entry.Kind != llvm::BitstreamEntry::Record) {
Guy Benyei11169dd2012-12-18 14:30:41 +00001182 Error("incorrectly-formatted source location entry in AST file");
1183 return true;
1184 }
Chris Lattnere7b154b2013-01-19 21:39:22 +00001185
Guy Benyei11169dd2012-12-18 14:30:41 +00001186 RecordData Record;
Chris Lattner0e6c9402013-01-20 02:38:54 +00001187 StringRef Blob;
1188 switch (SLocEntryCursor.readRecord(Entry.ID, Record, &Blob)) {
Guy Benyei11169dd2012-12-18 14:30:41 +00001189 default:
1190 Error("incorrectly-formatted source location entry in AST file");
1191 return true;
1192
1193 case SM_SLOC_FILE_ENTRY: {
1194 // We will detect whether a file changed and return 'Failure' for it, but
1195 // we will also try to fail gracefully by setting up the SLocEntry.
1196 unsigned InputID = Record[4];
1197 InputFile IF = getInputFile(*F, InputID);
Argyrios Kyrtzidis61c3d872013-03-01 03:26:04 +00001198 const FileEntry *File = IF.getFile();
1199 bool OverriddenBuffer = IF.isOverridden();
Guy Benyei11169dd2012-12-18 14:30:41 +00001200
Argyrios Kyrtzidis61c3d872013-03-01 03:26:04 +00001201 // Note that we only check if a File was returned. If it was out-of-date
1202 // we have complained but we will continue creating a FileID to recover
1203 // gracefully.
1204 if (!File)
Guy Benyei11169dd2012-12-18 14:30:41 +00001205 return true;
1206
1207 SourceLocation IncludeLoc = ReadSourceLocation(*F, Record[1]);
1208 if (IncludeLoc.isInvalid() && F->Kind != MK_MainFile) {
1209 // This is the module's main file.
1210 IncludeLoc = getImportLocation(F);
1211 }
1212 SrcMgr::CharacteristicKind
1213 FileCharacter = (SrcMgr::CharacteristicKind)Record[2];
1214 FileID FID = SourceMgr.createFileID(File, IncludeLoc, FileCharacter,
1215 ID, BaseOffset + Record[0]);
1216 SrcMgr::FileInfo &FileInfo =
1217 const_cast<SrcMgr::FileInfo&>(SourceMgr.getSLocEntry(FID).getFile());
1218 FileInfo.NumCreatedFIDs = Record[5];
1219 if (Record[3])
1220 FileInfo.setHasLineDirectives();
1221
1222 const DeclID *FirstDecl = F->FileSortedDecls + Record[6];
1223 unsigned NumFileDecls = Record[7];
1224 if (NumFileDecls) {
1225 assert(F->FileSortedDecls && "FILE_SORTED_DECLS not encountered yet ?");
1226 FileDeclIDs[FID] = FileDeclsInfo(F, llvm::makeArrayRef(FirstDecl,
1227 NumFileDecls));
1228 }
1229
1230 const SrcMgr::ContentCache *ContentCache
1231 = SourceMgr.getOrCreateContentCache(File,
1232 /*isSystemFile=*/FileCharacter != SrcMgr::C_User);
1233 if (OverriddenBuffer && !ContentCache->BufferOverridden &&
1234 ContentCache->ContentsEntry == ContentCache->OrigEntry) {
1235 unsigned Code = SLocEntryCursor.ReadCode();
1236 Record.clear();
Chris Lattner0e6c9402013-01-20 02:38:54 +00001237 unsigned RecCode = SLocEntryCursor.readRecord(Code, Record, &Blob);
Guy Benyei11169dd2012-12-18 14:30:41 +00001238
1239 if (RecCode != SM_SLOC_BUFFER_BLOB) {
1240 Error("AST record has invalid code");
1241 return true;
1242 }
1243
Rafael Espindolad87f8d72014-08-27 20:03:29 +00001244 std::unique_ptr<llvm::MemoryBuffer> Buffer
Chris Lattner0e6c9402013-01-20 02:38:54 +00001245 = llvm::MemoryBuffer::getMemBuffer(Blob.drop_back(1), File->getName());
David Blaikie49cc3182014-08-27 20:54:45 +00001246 SourceMgr.overrideFileContents(File, std::move(Buffer));
Guy Benyei11169dd2012-12-18 14:30:41 +00001247 }
1248
1249 break;
1250 }
1251
1252 case SM_SLOC_BUFFER_ENTRY: {
Chris Lattner0e6c9402013-01-20 02:38:54 +00001253 const char *Name = Blob.data();
Guy Benyei11169dd2012-12-18 14:30:41 +00001254 unsigned Offset = Record[0];
1255 SrcMgr::CharacteristicKind
1256 FileCharacter = (SrcMgr::CharacteristicKind)Record[2];
1257 SourceLocation IncludeLoc = ReadSourceLocation(*F, Record[1]);
Richard Smithe842a472014-10-22 02:05:46 +00001258 if (IncludeLoc.isInvalid() &&
1259 (F->Kind == MK_ImplicitModule || F->Kind == MK_ExplicitModule)) {
Guy Benyei11169dd2012-12-18 14:30:41 +00001260 IncludeLoc = getImportLocation(F);
1261 }
1262 unsigned Code = SLocEntryCursor.ReadCode();
1263 Record.clear();
1264 unsigned RecCode
Chris Lattner0e6c9402013-01-20 02:38:54 +00001265 = SLocEntryCursor.readRecord(Code, Record, &Blob);
Guy Benyei11169dd2012-12-18 14:30:41 +00001266
1267 if (RecCode != SM_SLOC_BUFFER_BLOB) {
1268 Error("AST record has invalid code");
1269 return true;
1270 }
1271
Rafael Espindolad87f8d72014-08-27 20:03:29 +00001272 std::unique_ptr<llvm::MemoryBuffer> Buffer =
1273 llvm::MemoryBuffer::getMemBuffer(Blob.drop_back(1), Name);
David Blaikie50a5f972014-08-29 07:59:55 +00001274 SourceMgr.createFileID(std::move(Buffer), FileCharacter, ID,
Rafael Espindolad87f8d72014-08-27 20:03:29 +00001275 BaseOffset + Offset, IncludeLoc);
Guy Benyei11169dd2012-12-18 14:30:41 +00001276 break;
1277 }
1278
1279 case SM_SLOC_EXPANSION_ENTRY: {
1280 SourceLocation SpellingLoc = ReadSourceLocation(*F, Record[1]);
1281 SourceMgr.createExpansionLoc(SpellingLoc,
1282 ReadSourceLocation(*F, Record[2]),
1283 ReadSourceLocation(*F, Record[3]),
1284 Record[4],
1285 ID,
1286 BaseOffset + Record[0]);
1287 break;
1288 }
1289 }
1290
1291 return false;
1292}
1293
1294std::pair<SourceLocation, StringRef> ASTReader::getModuleImportLoc(int ID) {
1295 if (ID == 0)
1296 return std::make_pair(SourceLocation(), "");
1297
1298 if (unsigned(-ID) - 2 >= getTotalNumSLocs() || ID > 0) {
1299 Error("source location entry ID out-of-range for AST file");
1300 return std::make_pair(SourceLocation(), "");
1301 }
1302
1303 // Find which module file this entry lands in.
1304 ModuleFile *M = GlobalSLocEntryMap.find(-ID)->second;
Richard Smithe842a472014-10-22 02:05:46 +00001305 if (M->Kind != MK_ImplicitModule && M->Kind != MK_ExplicitModule)
Guy Benyei11169dd2012-12-18 14:30:41 +00001306 return std::make_pair(SourceLocation(), "");
1307
1308 // FIXME: Can we map this down to a particular submodule? That would be
1309 // ideal.
Ben Langmuirbeee15e2014-04-14 18:00:01 +00001310 return std::make_pair(M->ImportLoc, StringRef(M->ModuleName));
Guy Benyei11169dd2012-12-18 14:30:41 +00001311}
1312
1313/// \brief Find the location where the module F is imported.
1314SourceLocation ASTReader::getImportLocation(ModuleFile *F) {
1315 if (F->ImportLoc.isValid())
1316 return F->ImportLoc;
1317
1318 // Otherwise we have a PCH. It's considered to be "imported" at the first
1319 // location of its includer.
1320 if (F->ImportedBy.empty() || !F->ImportedBy[0]) {
Ben Langmuirbeee15e2014-04-14 18:00:01 +00001321 // Main file is the importer.
1322 assert(!SourceMgr.getMainFileID().isInvalid() && "missing main file");
1323 return SourceMgr.getLocForStartOfFile(SourceMgr.getMainFileID());
Guy Benyei11169dd2012-12-18 14:30:41 +00001324 }
Guy Benyei11169dd2012-12-18 14:30:41 +00001325 return F->ImportedBy[0]->FirstLoc;
1326}
1327
1328/// ReadBlockAbbrevs - Enter a subblock of the specified BlockID with the
1329/// specified cursor. Read the abbreviations that are at the top of the block
1330/// and then leave the cursor pointing into the block.
Chris Lattner7fb3bef2013-01-20 00:56:42 +00001331bool ASTReader::ReadBlockAbbrevs(BitstreamCursor &Cursor, unsigned BlockID) {
Guy Benyei11169dd2012-12-18 14:30:41 +00001332 if (Cursor.EnterSubBlock(BlockID)) {
1333 Error("malformed block record in AST file");
1334 return Failure;
1335 }
1336
1337 while (true) {
1338 uint64_t Offset = Cursor.GetCurrentBitNo();
1339 unsigned Code = Cursor.ReadCode();
1340
1341 // We expect all abbrevs to be at the start of the block.
1342 if (Code != llvm::bitc::DEFINE_ABBREV) {
1343 Cursor.JumpToBit(Offset);
1344 return false;
1345 }
1346 Cursor.ReadAbbrevRecord();
1347 }
1348}
1349
Richard Smithe40f2ba2013-08-07 21:41:30 +00001350Token ASTReader::ReadToken(ModuleFile &F, const RecordDataImpl &Record,
John McCallf413f5e2013-05-03 00:10:13 +00001351 unsigned &Idx) {
1352 Token Tok;
1353 Tok.startToken();
1354 Tok.setLocation(ReadSourceLocation(F, Record, Idx));
1355 Tok.setLength(Record[Idx++]);
1356 if (IdentifierInfo *II = getLocalIdentifier(F, Record[Idx++]))
1357 Tok.setIdentifierInfo(II);
1358 Tok.setKind((tok::TokenKind)Record[Idx++]);
1359 Tok.setFlag((Token::TokenFlags)Record[Idx++]);
1360 return Tok;
1361}
1362
Argyrios Kyrtzidiseb663da2013-03-22 21:12:57 +00001363MacroInfo *ASTReader::ReadMacroRecord(ModuleFile &F, uint64_t Offset) {
Chris Lattner7fb3bef2013-01-20 00:56:42 +00001364 BitstreamCursor &Stream = F.MacroCursor;
Guy Benyei11169dd2012-12-18 14:30:41 +00001365
1366 // Keep track of where we are in the stream, then jump back there
1367 // after reading this macro.
1368 SavedStreamPosition SavedPosition(Stream);
1369
1370 Stream.JumpToBit(Offset);
1371 RecordData Record;
1372 SmallVector<IdentifierInfo*, 16> MacroArgs;
Craig Toppera13603a2014-05-22 05:54:18 +00001373 MacroInfo *Macro = nullptr;
Guy Benyei11169dd2012-12-18 14:30:41 +00001374
Guy Benyei11169dd2012-12-18 14:30:41 +00001375 while (true) {
Chris Lattnerefa77172013-01-20 00:00:22 +00001376 // Advance to the next record, but if we get to the end of the block, don't
1377 // pop it (removing all the abbreviations from the cursor) since we want to
1378 // be able to reseek within the block and read entries.
Chris Lattner7fb3bef2013-01-20 00:56:42 +00001379 unsigned Flags = BitstreamCursor::AF_DontPopBlockAtEnd;
Chris Lattnerefa77172013-01-20 00:00:22 +00001380 llvm::BitstreamEntry Entry = Stream.advanceSkippingSubblocks(Flags);
1381
1382 switch (Entry.Kind) {
1383 case llvm::BitstreamEntry::SubBlock: // Handled for us already.
1384 case llvm::BitstreamEntry::Error:
1385 Error("malformed block record in AST file");
Argyrios Kyrtzidiseb663da2013-03-22 21:12:57 +00001386 return Macro;
Chris Lattnerefa77172013-01-20 00:00:22 +00001387 case llvm::BitstreamEntry::EndBlock:
Argyrios Kyrtzidiseb663da2013-03-22 21:12:57 +00001388 return Macro;
Chris Lattnerefa77172013-01-20 00:00:22 +00001389 case llvm::BitstreamEntry::Record:
1390 // The interesting case.
1391 break;
Guy Benyei11169dd2012-12-18 14:30:41 +00001392 }
1393
1394 // Read a record.
Guy Benyei11169dd2012-12-18 14:30:41 +00001395 Record.clear();
1396 PreprocessorRecordTypes RecType =
Chris Lattner0e6c9402013-01-20 02:38:54 +00001397 (PreprocessorRecordTypes)Stream.readRecord(Entry.ID, Record);
Guy Benyei11169dd2012-12-18 14:30:41 +00001398 switch (RecType) {
Argyrios Kyrtzidiseb663da2013-03-22 21:12:57 +00001399 case PP_MACRO_DIRECTIVE_HISTORY:
1400 return Macro;
1401
Guy Benyei11169dd2012-12-18 14:30:41 +00001402 case PP_MACRO_OBJECT_LIKE:
1403 case PP_MACRO_FUNCTION_LIKE: {
1404 // If we already have a macro, that means that we've hit the end
1405 // of the definition of the macro we were looking for. We're
1406 // done.
1407 if (Macro)
Argyrios Kyrtzidiseb663da2013-03-22 21:12:57 +00001408 return Macro;
Guy Benyei11169dd2012-12-18 14:30:41 +00001409
Argyrios Kyrtzidiseb663da2013-03-22 21:12:57 +00001410 unsigned NextIndex = 1; // Skip identifier ID.
1411 SubmoduleID SubModID = getGlobalSubmoduleID(F, Record[NextIndex++]);
Guy Benyei11169dd2012-12-18 14:30:41 +00001412 SourceLocation Loc = ReadSourceLocation(F, Record, NextIndex);
Argyrios Kyrtzidiseb663da2013-03-22 21:12:57 +00001413 MacroInfo *MI = PP.AllocateDeserializedMacroInfo(Loc, SubModID);
Argyrios Kyrtzidis7572be22013-01-07 19:16:23 +00001414 MI->setDefinitionEndLoc(ReadSourceLocation(F, Record, NextIndex));
Guy Benyei11169dd2012-12-18 14:30:41 +00001415 MI->setIsUsed(Record[NextIndex++]);
Argyrios Kyrtzidis9ef53ce2014-04-09 18:21:23 +00001416 MI->setUsedForHeaderGuard(Record[NextIndex++]);
Guy Benyei11169dd2012-12-18 14:30:41 +00001417
Guy Benyei11169dd2012-12-18 14:30:41 +00001418 if (RecType == PP_MACRO_FUNCTION_LIKE) {
1419 // Decode function-like macro info.
1420 bool isC99VarArgs = Record[NextIndex++];
1421 bool isGNUVarArgs = Record[NextIndex++];
1422 bool hasCommaPasting = Record[NextIndex++];
1423 MacroArgs.clear();
1424 unsigned NumArgs = Record[NextIndex++];
1425 for (unsigned i = 0; i != NumArgs; ++i)
1426 MacroArgs.push_back(getLocalIdentifier(F, Record[NextIndex++]));
1427
1428 // Install function-like macro info.
1429 MI->setIsFunctionLike();
1430 if (isC99VarArgs) MI->setIsC99Varargs();
1431 if (isGNUVarArgs) MI->setIsGNUVarargs();
1432 if (hasCommaPasting) MI->setHasCommaPasting();
1433 MI->setArgumentList(MacroArgs.data(), MacroArgs.size(),
1434 PP.getPreprocessorAllocator());
1435 }
1436
Guy Benyei11169dd2012-12-18 14:30:41 +00001437 // Remember that we saw this macro last so that we add the tokens that
1438 // form its body to it.
1439 Macro = MI;
1440
1441 if (NextIndex + 1 == Record.size() && PP.getPreprocessingRecord() &&
1442 Record[NextIndex]) {
1443 // We have a macro definition. Register the association
1444 PreprocessedEntityID
1445 GlobalID = getGlobalPreprocessedEntityID(F, Record[NextIndex]);
1446 PreprocessingRecord &PPRec = *PP.getPreprocessingRecord();
Argyrios Kyrtzidis832de9f2013-02-22 18:35:59 +00001447 PreprocessingRecord::PPEntityID
1448 PPID = PPRec.getPPEntityID(GlobalID-1, /*isLoaded=*/true);
1449 MacroDefinition *PPDef =
1450 cast_or_null<MacroDefinition>(PPRec.getPreprocessedEntity(PPID));
1451 if (PPDef)
1452 PPRec.RegisterMacroDefinition(Macro, PPDef);
Guy Benyei11169dd2012-12-18 14:30:41 +00001453 }
1454
1455 ++NumMacrosRead;
1456 break;
1457 }
1458
1459 case PP_TOKEN: {
1460 // If we see a TOKEN before a PP_MACRO_*, then the file is
1461 // erroneous, just pretend we didn't see this.
Craig Toppera13603a2014-05-22 05:54:18 +00001462 if (!Macro) break;
Guy Benyei11169dd2012-12-18 14:30:41 +00001463
John McCallf413f5e2013-05-03 00:10:13 +00001464 unsigned Idx = 0;
1465 Token Tok = ReadToken(F, Record, Idx);
Guy Benyei11169dd2012-12-18 14:30:41 +00001466 Macro->AddTokenToBody(Tok);
1467 break;
1468 }
1469 }
1470 }
1471}
1472
1473PreprocessedEntityID
1474ASTReader::getGlobalPreprocessedEntityID(ModuleFile &M, unsigned LocalID) const {
1475 ContinuousRangeMap<uint32_t, int, 2>::const_iterator
1476 I = M.PreprocessedEntityRemap.find(LocalID - NUM_PREDEF_PP_ENTITY_IDS);
1477 assert(I != M.PreprocessedEntityRemap.end()
1478 && "Invalid index into preprocessed entity index remap");
1479
1480 return LocalID + I->second;
1481}
1482
Argyrios Kyrtzidis5c2a3452013-03-06 18:12:47 +00001483unsigned HeaderFileInfoTrait::ComputeHash(internal_key_ref ikey) {
1484 return llvm::hash_combine(ikey.Size, ikey.ModTime);
Guy Benyei11169dd2012-12-18 14:30:41 +00001485}
1486
1487HeaderFileInfoTrait::internal_key_type
Argyrios Kyrtzidis5c2a3452013-03-06 18:12:47 +00001488HeaderFileInfoTrait::GetInternalKey(const FileEntry *FE) {
1489 internal_key_type ikey = { FE->getSize(), FE->getModificationTime(),
1490 FE->getName() };
1491 return ikey;
1492}
Guy Benyei11169dd2012-12-18 14:30:41 +00001493
Argyrios Kyrtzidis5c2a3452013-03-06 18:12:47 +00001494bool HeaderFileInfoTrait::EqualKey(internal_key_ref a, internal_key_ref b) {
1495 if (a.Size != b.Size || a.ModTime != b.ModTime)
Guy Benyei11169dd2012-12-18 14:30:41 +00001496 return false;
1497
Argyrios Kyrtzidis5c2a3452013-03-06 18:12:47 +00001498 if (strcmp(a.Filename, b.Filename) == 0)
1499 return true;
1500
Guy Benyei11169dd2012-12-18 14:30:41 +00001501 // Determine whether the actual files are equivalent.
Argyrios Kyrtzidis2a513e82013-03-04 20:33:40 +00001502 FileManager &FileMgr = Reader.getFileManager();
Argyrios Kyrtzidis5c2a3452013-03-06 18:12:47 +00001503 const FileEntry *FEA = FileMgr.getFile(a.Filename);
1504 const FileEntry *FEB = FileMgr.getFile(b.Filename);
Argyrios Kyrtzidis2a513e82013-03-04 20:33:40 +00001505 return (FEA && FEA == FEB);
Guy Benyei11169dd2012-12-18 14:30:41 +00001506}
1507
1508std::pair<unsigned, unsigned>
1509HeaderFileInfoTrait::ReadKeyDataLength(const unsigned char*& d) {
Justin Bogner57ba0b22014-03-28 22:03:24 +00001510 using namespace llvm::support;
1511 unsigned KeyLen = (unsigned) endian::readNext<uint16_t, little, unaligned>(d);
Guy Benyei11169dd2012-12-18 14:30:41 +00001512 unsigned DataLen = (unsigned) *d++;
Argyrios Kyrtzidis5c2a3452013-03-06 18:12:47 +00001513 return std::make_pair(KeyLen, DataLen);
Guy Benyei11169dd2012-12-18 14:30:41 +00001514}
Argyrios Kyrtzidis5c2a3452013-03-06 18:12:47 +00001515
1516HeaderFileInfoTrait::internal_key_type
1517HeaderFileInfoTrait::ReadKey(const unsigned char *d, unsigned) {
Justin Bogner57ba0b22014-03-28 22:03:24 +00001518 using namespace llvm::support;
Argyrios Kyrtzidis5c2a3452013-03-06 18:12:47 +00001519 internal_key_type ikey;
Justin Bogner57ba0b22014-03-28 22:03:24 +00001520 ikey.Size = off_t(endian::readNext<uint64_t, little, unaligned>(d));
1521 ikey.ModTime = time_t(endian::readNext<uint64_t, little, unaligned>(d));
Argyrios Kyrtzidis5c2a3452013-03-06 18:12:47 +00001522 ikey.Filename = (const char *)d;
1523 return ikey;
1524}
1525
Guy Benyei11169dd2012-12-18 14:30:41 +00001526HeaderFileInfoTrait::data_type
Argyrios Kyrtzidisb146baa2013-03-13 21:13:51 +00001527HeaderFileInfoTrait::ReadData(internal_key_ref key, const unsigned char *d,
Guy Benyei11169dd2012-12-18 14:30:41 +00001528 unsigned DataLen) {
1529 const unsigned char *End = d + DataLen;
Justin Bogner57ba0b22014-03-28 22:03:24 +00001530 using namespace llvm::support;
Guy Benyei11169dd2012-12-18 14:30:41 +00001531 HeaderFileInfo HFI;
1532 unsigned Flags = *d++;
Lawrence Crowlb53e5482013-06-20 21:14:14 +00001533 HFI.HeaderRole = static_cast<ModuleMap::ModuleHeaderRole>
1534 ((Flags >> 6) & 0x03);
Guy Benyei11169dd2012-12-18 14:30:41 +00001535 HFI.isImport = (Flags >> 5) & 0x01;
1536 HFI.isPragmaOnce = (Flags >> 4) & 0x01;
1537 HFI.DirInfo = (Flags >> 2) & 0x03;
1538 HFI.Resolved = (Flags >> 1) & 0x01;
1539 HFI.IndexHeaderMapHeader = Flags & 0x01;
Justin Bogner57ba0b22014-03-28 22:03:24 +00001540 HFI.NumIncludes = endian::readNext<uint16_t, little, unaligned>(d);
1541 HFI.ControllingMacroID = Reader.getGlobalIdentifierID(
1542 M, endian::readNext<uint32_t, little, unaligned>(d));
1543 if (unsigned FrameworkOffset =
1544 endian::readNext<uint32_t, little, unaligned>(d)) {
Guy Benyei11169dd2012-12-18 14:30:41 +00001545 // The framework offset is 1 greater than the actual offset,
1546 // since 0 is used as an indicator for "no framework name".
1547 StringRef FrameworkName(FrameworkStrings + FrameworkOffset - 1);
1548 HFI.Framework = HS->getUniqueFrameworkName(FrameworkName);
1549 }
1550
Argyrios Kyrtzidisb146baa2013-03-13 21:13:51 +00001551 if (d != End) {
Justin Bogner57ba0b22014-03-28 22:03:24 +00001552 uint32_t LocalSMID = endian::readNext<uint32_t, little, unaligned>(d);
Argyrios Kyrtzidisb146baa2013-03-13 21:13:51 +00001553 if (LocalSMID) {
1554 // This header is part of a module. Associate it with the module to enable
1555 // implicit module import.
1556 SubmoduleID GlobalSMID = Reader.getGlobalSubmoduleID(M, LocalSMID);
1557 Module *Mod = Reader.getSubmodule(GlobalSMID);
1558 HFI.isModuleHeader = true;
1559 FileManager &FileMgr = Reader.getFileManager();
1560 ModuleMap &ModMap =
1561 Reader.getPreprocessor().getHeaderSearchInfo().getModuleMap();
Richard Smith3c1a41a2014-12-02 00:08:08 +00001562 // FIXME: This is wrong. We should track the filename as written; this
1563 // information should be propagated through the SUBMODULE_HEADER etc
1564 // records rather than from here.
1565 // FIXME: We don't ever mark excluded headers.
1566 ModMap.addHeader(
1567 Mod, Module::Header{key.Filename, FileMgr.getFile(key.Filename)},
1568 HFI.getHeaderRole());
Argyrios Kyrtzidisb146baa2013-03-13 21:13:51 +00001569 }
1570 }
1571
Guy Benyei11169dd2012-12-18 14:30:41 +00001572 assert(End == d && "Wrong data length in HeaderFileInfo deserialization");
1573 (void)End;
1574
1575 // This HeaderFileInfo was externally loaded.
1576 HFI.External = true;
1577 return HFI;
1578}
1579
Richard Smith49f906a2014-03-01 00:08:04 +00001580void
1581ASTReader::addPendingMacroFromModule(IdentifierInfo *II, ModuleFile *M,
1582 GlobalMacroID GMacID,
Craig Topper00bbdcf2014-06-28 23:22:23 +00001583 ArrayRef<SubmoduleID> Overrides) {
Guy Benyei11169dd2012-12-18 14:30:41 +00001584 assert(NumCurrentElementsDeserializing > 0 &&"Missing deserialization guard");
Craig Toppera13603a2014-05-22 05:54:18 +00001585 SubmoduleID *OverrideData = nullptr;
Richard Smith49f906a2014-03-01 00:08:04 +00001586 if (!Overrides.empty()) {
1587 OverrideData = new (Context) SubmoduleID[Overrides.size() + 1];
1588 OverrideData[0] = Overrides.size();
1589 for (unsigned I = 0; I != Overrides.size(); ++I)
1590 OverrideData[I + 1] = getGlobalSubmoduleID(*M, Overrides[I]);
1591 }
1592 PendingMacroIDs[II].push_back(PendingMacroInfo(M, GMacID, OverrideData));
Argyrios Kyrtzidiseb663da2013-03-22 21:12:57 +00001593}
1594
1595void ASTReader::addPendingMacroFromPCH(IdentifierInfo *II,
1596 ModuleFile *M,
1597 uint64_t MacroDirectivesOffset) {
1598 assert(NumCurrentElementsDeserializing > 0 &&"Missing deserialization guard");
1599 PendingMacroIDs[II].push_back(PendingMacroInfo(M, MacroDirectivesOffset));
Guy Benyei11169dd2012-12-18 14:30:41 +00001600}
1601
1602void ASTReader::ReadDefinedMacros() {
1603 // Note that we are loading defined macros.
1604 Deserializing Macros(this);
1605
1606 for (ModuleReverseIterator I = ModuleMgr.rbegin(),
1607 E = ModuleMgr.rend(); I != E; ++I) {
Chris Lattner7fb3bef2013-01-20 00:56:42 +00001608 BitstreamCursor &MacroCursor = (*I)->MacroCursor;
Guy Benyei11169dd2012-12-18 14:30:41 +00001609
1610 // If there was no preprocessor block, skip this file.
1611 if (!MacroCursor.getBitStreamReader())
1612 continue;
1613
Chris Lattner7fb3bef2013-01-20 00:56:42 +00001614 BitstreamCursor Cursor = MacroCursor;
Guy Benyei11169dd2012-12-18 14:30:41 +00001615 Cursor.JumpToBit((*I)->MacroStartOffset);
1616
1617 RecordData Record;
1618 while (true) {
Chris Lattnere7b154b2013-01-19 21:39:22 +00001619 llvm::BitstreamEntry E = Cursor.advanceSkippingSubblocks();
1620
1621 switch (E.Kind) {
1622 case llvm::BitstreamEntry::SubBlock: // Handled for us already.
1623 case llvm::BitstreamEntry::Error:
1624 Error("malformed block record in AST file");
1625 return;
1626 case llvm::BitstreamEntry::EndBlock:
1627 goto NextCursor;
1628
1629 case llvm::BitstreamEntry::Record:
Chris Lattnere7b154b2013-01-19 21:39:22 +00001630 Record.clear();
Chris Lattner0e6c9402013-01-20 02:38:54 +00001631 switch (Cursor.readRecord(E.ID, Record)) {
Chris Lattnere7b154b2013-01-19 21:39:22 +00001632 default: // Default behavior: ignore.
1633 break;
1634
1635 case PP_MACRO_OBJECT_LIKE:
1636 case PP_MACRO_FUNCTION_LIKE:
1637 getLocalIdentifier(**I, Record[0]);
1638 break;
1639
1640 case PP_TOKEN:
1641 // Ignore tokens.
1642 break;
Guy Benyei11169dd2012-12-18 14:30:41 +00001643 }
Guy Benyei11169dd2012-12-18 14:30:41 +00001644 break;
1645 }
1646 }
Chris Lattnere7b154b2013-01-19 21:39:22 +00001647 NextCursor: ;
Guy Benyei11169dd2012-12-18 14:30:41 +00001648 }
1649}
1650
1651namespace {
1652 /// \brief Visitor class used to look up identifirs in an AST file.
1653 class IdentifierLookupVisitor {
1654 StringRef Name;
1655 unsigned PriorGeneration;
Douglas Gregor00a50f72013-01-25 00:38:33 +00001656 unsigned &NumIdentifierLookups;
1657 unsigned &NumIdentifierLookupHits;
Guy Benyei11169dd2012-12-18 14:30:41 +00001658 IdentifierInfo *Found;
Douglas Gregor00a50f72013-01-25 00:38:33 +00001659
Guy Benyei11169dd2012-12-18 14:30:41 +00001660 public:
Douglas Gregor00a50f72013-01-25 00:38:33 +00001661 IdentifierLookupVisitor(StringRef Name, unsigned PriorGeneration,
1662 unsigned &NumIdentifierLookups,
1663 unsigned &NumIdentifierLookupHits)
Douglas Gregor7211ac12013-01-25 23:32:03 +00001664 : Name(Name), PriorGeneration(PriorGeneration),
Douglas Gregor00a50f72013-01-25 00:38:33 +00001665 NumIdentifierLookups(NumIdentifierLookups),
1666 NumIdentifierLookupHits(NumIdentifierLookupHits),
1667 Found()
1668 {
1669 }
Guy Benyei11169dd2012-12-18 14:30:41 +00001670
1671 static bool visit(ModuleFile &M, void *UserData) {
1672 IdentifierLookupVisitor *This
1673 = static_cast<IdentifierLookupVisitor *>(UserData);
1674
1675 // If we've already searched this module file, skip it now.
1676 if (M.Generation <= This->PriorGeneration)
1677 return true;
Douglas Gregore060e572013-01-25 01:03:03 +00001678
Guy Benyei11169dd2012-12-18 14:30:41 +00001679 ASTIdentifierLookupTable *IdTable
1680 = (ASTIdentifierLookupTable *)M.IdentifierLookupTable;
1681 if (!IdTable)
1682 return false;
1683
1684 ASTIdentifierLookupTrait Trait(IdTable->getInfoObj().getReader(),
1685 M, This->Found);
Douglas Gregor00a50f72013-01-25 00:38:33 +00001686 ++This->NumIdentifierLookups;
1687 ASTIdentifierLookupTable::iterator Pos = IdTable->find(This->Name,&Trait);
Guy Benyei11169dd2012-12-18 14:30:41 +00001688 if (Pos == IdTable->end())
1689 return false;
1690
1691 // Dereferencing the iterator has the effect of building the
1692 // IdentifierInfo node and populating it with the various
1693 // declarations it needs.
Douglas Gregor00a50f72013-01-25 00:38:33 +00001694 ++This->NumIdentifierLookupHits;
Guy Benyei11169dd2012-12-18 14:30:41 +00001695 This->Found = *Pos;
1696 return true;
1697 }
1698
1699 // \brief Retrieve the identifier info found within the module
1700 // files.
1701 IdentifierInfo *getIdentifierInfo() const { return Found; }
1702 };
1703}
1704
1705void ASTReader::updateOutOfDateIdentifier(IdentifierInfo &II) {
1706 // Note that we are loading an identifier.
1707 Deserializing AnIdentifier(this);
1708
1709 unsigned PriorGeneration = 0;
1710 if (getContext().getLangOpts().Modules)
1711 PriorGeneration = IdentifierGeneration[&II];
Douglas Gregore060e572013-01-25 01:03:03 +00001712
1713 // If there is a global index, look there first to determine which modules
1714 // provably do not have any results for this identifier.
Douglas Gregor7211ac12013-01-25 23:32:03 +00001715 GlobalModuleIndex::HitSet Hits;
Craig Toppera13603a2014-05-22 05:54:18 +00001716 GlobalModuleIndex::HitSet *HitsPtr = nullptr;
Douglas Gregore060e572013-01-25 01:03:03 +00001717 if (!loadGlobalIndex()) {
Douglas Gregor7211ac12013-01-25 23:32:03 +00001718 if (GlobalIndex->lookupIdentifier(II.getName(), Hits)) {
1719 HitsPtr = &Hits;
Douglas Gregore060e572013-01-25 01:03:03 +00001720 }
1721 }
1722
Douglas Gregor7211ac12013-01-25 23:32:03 +00001723 IdentifierLookupVisitor Visitor(II.getName(), PriorGeneration,
Douglas Gregor00a50f72013-01-25 00:38:33 +00001724 NumIdentifierLookups,
1725 NumIdentifierLookupHits);
Douglas Gregor7211ac12013-01-25 23:32:03 +00001726 ModuleMgr.visit(IdentifierLookupVisitor::visit, &Visitor, HitsPtr);
Guy Benyei11169dd2012-12-18 14:30:41 +00001727 markIdentifierUpToDate(&II);
1728}
1729
1730void ASTReader::markIdentifierUpToDate(IdentifierInfo *II) {
1731 if (!II)
1732 return;
1733
1734 II->setOutOfDate(false);
1735
1736 // Update the generation for this identifier.
1737 if (getContext().getLangOpts().Modules)
Richard Smith053f6c62014-05-16 23:01:30 +00001738 IdentifierGeneration[II] = getGeneration();
Guy Benyei11169dd2012-12-18 14:30:41 +00001739}
1740
Richard Smith49f906a2014-03-01 00:08:04 +00001741struct ASTReader::ModuleMacroInfo {
1742 SubmoduleID SubModID;
1743 MacroInfo *MI;
1744 SubmoduleID *Overrides;
1745 // FIXME: Remove this.
1746 ModuleFile *F;
1747
1748 bool isDefine() const { return MI; }
1749
1750 SubmoduleID getSubmoduleID() const { return SubModID; }
1751
Craig Topper00bbdcf2014-06-28 23:22:23 +00001752 ArrayRef<SubmoduleID> getOverriddenSubmodules() const {
Richard Smith49f906a2014-03-01 00:08:04 +00001753 if (!Overrides)
Craig Topper00bbdcf2014-06-28 23:22:23 +00001754 return None;
Richard Smith49f906a2014-03-01 00:08:04 +00001755 return llvm::makeArrayRef(Overrides + 1, *Overrides);
1756 }
1757
Richard Smithdaa69e02014-07-25 04:40:03 +00001758 MacroDirective *import(Preprocessor &PP, SourceLocation ImportLoc) const {
Richard Smith49f906a2014-03-01 00:08:04 +00001759 if (!MI)
Richard Smithdaa69e02014-07-25 04:40:03 +00001760 return PP.AllocateUndefMacroDirective(ImportLoc, SubModID,
1761 getOverriddenSubmodules());
1762 return PP.AllocateDefMacroDirective(MI, ImportLoc, SubModID,
1763 getOverriddenSubmodules());
Richard Smith49f906a2014-03-01 00:08:04 +00001764 }
1765};
1766
1767ASTReader::ModuleMacroInfo *
1768ASTReader::getModuleMacro(const PendingMacroInfo &PMInfo) {
1769 ModuleMacroInfo Info;
1770
1771 uint32_t ID = PMInfo.ModuleMacroData.MacID;
1772 if (ID & 1) {
1773 // Macro undefinition.
1774 Info.SubModID = getGlobalSubmoduleID(*PMInfo.M, ID >> 1);
Craig Toppera13603a2014-05-22 05:54:18 +00001775 Info.MI = nullptr;
Richard Smith49f906a2014-03-01 00:08:04 +00001776 } else {
1777 // Macro definition.
1778 GlobalMacroID GMacID = getGlobalMacroID(*PMInfo.M, ID >> 1);
1779 assert(GMacID);
1780
1781 // If this macro has already been loaded, don't do so again.
1782 // FIXME: This is highly dubious. Multiple macro definitions can have the
1783 // same MacroInfo (and hence the same GMacID) due to #pragma push_macro etc.
1784 if (MacrosLoaded[GMacID - NUM_PREDEF_MACRO_IDS])
Craig Toppera13603a2014-05-22 05:54:18 +00001785 return nullptr;
Richard Smith49f906a2014-03-01 00:08:04 +00001786
1787 Info.MI = getMacro(GMacID);
1788 Info.SubModID = Info.MI->getOwningModuleID();
1789 }
1790 Info.Overrides = PMInfo.ModuleMacroData.Overrides;
1791 Info.F = PMInfo.M;
1792
1793 return new (Context) ModuleMacroInfo(Info);
1794}
1795
Argyrios Kyrtzidiseb663da2013-03-22 21:12:57 +00001796void ASTReader::resolvePendingMacro(IdentifierInfo *II,
1797 const PendingMacroInfo &PMInfo) {
1798 assert(II);
1799
Richard Smithe842a472014-10-22 02:05:46 +00001800 if (PMInfo.M->Kind != MK_ImplicitModule &&
1801 PMInfo.M->Kind != MK_ExplicitModule) {
Argyrios Kyrtzidiseb663da2013-03-22 21:12:57 +00001802 installPCHMacroDirectives(II, *PMInfo.M,
1803 PMInfo.PCHMacroData.MacroDirectivesOffset);
1804 return;
1805 }
Richard Smith49f906a2014-03-01 00:08:04 +00001806
Argyrios Kyrtzidiseb663da2013-03-22 21:12:57 +00001807 // Module Macro.
1808
Richard Smith49f906a2014-03-01 00:08:04 +00001809 ModuleMacroInfo *MMI = getModuleMacro(PMInfo);
1810 if (!MMI)
Argyrios Kyrtzidiseb663da2013-03-22 21:12:57 +00001811 return;
1812
Richard Smith49f906a2014-03-01 00:08:04 +00001813 Module *Owner = getSubmodule(MMI->getSubmoduleID());
1814 if (Owner && Owner->NameVisibility == Module::Hidden) {
1815 // Macros in the owning module are hidden. Just remember this macro to
1816 // install if we make this module visible.
1817 HiddenNamesMap[Owner].HiddenMacros.insert(std::make_pair(II, MMI));
1818 } else {
Richard Smithdaa69e02014-07-25 04:40:03 +00001819 installImportedMacro(II, MMI, Owner);
Argyrios Kyrtzidiseb663da2013-03-22 21:12:57 +00001820 }
Argyrios Kyrtzidiseb663da2013-03-22 21:12:57 +00001821}
1822
1823void ASTReader::installPCHMacroDirectives(IdentifierInfo *II,
1824 ModuleFile &M, uint64_t Offset) {
Richard Smithe842a472014-10-22 02:05:46 +00001825 assert(M.Kind != MK_ImplicitModule && M.Kind != MK_ExplicitModule);
Argyrios Kyrtzidiseb663da2013-03-22 21:12:57 +00001826
1827 BitstreamCursor &Cursor = M.MacroCursor;
1828 SavedStreamPosition SavedPosition(Cursor);
1829 Cursor.JumpToBit(Offset);
1830
1831 llvm::BitstreamEntry Entry =
1832 Cursor.advance(BitstreamCursor::AF_DontPopBlockAtEnd);
1833 if (Entry.Kind != llvm::BitstreamEntry::Record) {
1834 Error("malformed block record in AST file");
1835 return;
1836 }
1837
1838 RecordData Record;
1839 PreprocessorRecordTypes RecType =
1840 (PreprocessorRecordTypes)Cursor.readRecord(Entry.ID, Record);
1841 if (RecType != PP_MACRO_DIRECTIVE_HISTORY) {
1842 Error("malformed block record in AST file");
1843 return;
1844 }
1845
1846 // Deserialize the macro directives history in reverse source-order.
Craig Toppera13603a2014-05-22 05:54:18 +00001847 MacroDirective *Latest = nullptr, *Earliest = nullptr;
Argyrios Kyrtzidiseb663da2013-03-22 21:12:57 +00001848 unsigned Idx = 0, N = Record.size();
1849 while (Idx < N) {
Craig Toppera13603a2014-05-22 05:54:18 +00001850 MacroDirective *MD = nullptr;
Argyrios Kyrtzidiseb663da2013-03-22 21:12:57 +00001851 SourceLocation Loc = ReadSourceLocation(M, Record, Idx);
Argyrios Kyrtzidisb6210df2013-03-26 17:17:01 +00001852 MacroDirective::Kind K = (MacroDirective::Kind)Record[Idx++];
1853 switch (K) {
1854 case MacroDirective::MD_Define: {
1855 GlobalMacroID GMacID = getGlobalMacroID(M, Record[Idx++]);
1856 MacroInfo *MI = getMacro(GMacID);
Richard Smithdaa69e02014-07-25 04:40:03 +00001857 SubmoduleID ImportedFrom = Record[Idx++];
1858 bool IsAmbiguous = Record[Idx++];
1859 llvm::SmallVector<unsigned, 4> Overrides;
1860 if (ImportedFrom) {
1861 Overrides.insert(Overrides.end(),
1862 &Record[Idx] + 1, &Record[Idx] + 1 + Record[Idx]);
1863 Idx += Overrides.size() + 1;
1864 }
Argyrios Kyrtzidisb6210df2013-03-26 17:17:01 +00001865 DefMacroDirective *DefMD =
Richard Smithdaa69e02014-07-25 04:40:03 +00001866 PP.AllocateDefMacroDirective(MI, Loc, ImportedFrom, Overrides);
1867 DefMD->setAmbiguous(IsAmbiguous);
Argyrios Kyrtzidisb6210df2013-03-26 17:17:01 +00001868 MD = DefMD;
1869 break;
1870 }
Richard Smithdaa69e02014-07-25 04:40:03 +00001871 case MacroDirective::MD_Undefine: {
1872 SubmoduleID ImportedFrom = Record[Idx++];
1873 llvm::SmallVector<unsigned, 4> Overrides;
1874 if (ImportedFrom) {
1875 Overrides.insert(Overrides.end(),
1876 &Record[Idx] + 1, &Record[Idx] + 1 + Record[Idx]);
1877 Idx += Overrides.size() + 1;
1878 }
1879 MD = PP.AllocateUndefMacroDirective(Loc, ImportedFrom, Overrides);
Argyrios Kyrtzidisb6210df2013-03-26 17:17:01 +00001880 break;
Richard Smithdaa69e02014-07-25 04:40:03 +00001881 }
1882 case MacroDirective::MD_Visibility:
Argyrios Kyrtzidisb6210df2013-03-26 17:17:01 +00001883 bool isPublic = Record[Idx++];
1884 MD = PP.AllocateVisibilityMacroDirective(Loc, isPublic);
1885 break;
1886 }
Argyrios Kyrtzidiseb663da2013-03-22 21:12:57 +00001887
1888 if (!Latest)
1889 Latest = MD;
1890 if (Earliest)
1891 Earliest->setPrevious(MD);
1892 Earliest = MD;
1893 }
1894
1895 PP.setLoadedMacroDirective(II, Latest);
1896}
1897
Argyrios Kyrtzidis3a9c42c2013-03-27 01:25:34 +00001898/// \brief For the given macro definitions, check if they are both in system
Douglas Gregor0b202052013-04-12 21:00:54 +00001899/// modules.
1900static bool areDefinedInSystemModules(MacroInfo *PrevMI, MacroInfo *NewMI,
Douglas Gregor5e461192013-06-07 22:56:11 +00001901 Module *NewOwner, ASTReader &Reader) {
Argyrios Kyrtzidis3a9c42c2013-03-27 01:25:34 +00001902 assert(PrevMI && NewMI);
Craig Toppera13603a2014-05-22 05:54:18 +00001903 Module *PrevOwner = nullptr;
Argyrios Kyrtzidis3a9c42c2013-03-27 01:25:34 +00001904 if (SubmoduleID PrevModID = PrevMI->getOwningModuleID())
1905 PrevOwner = Reader.getSubmodule(PrevModID);
Douglas Gregor5e461192013-06-07 22:56:11 +00001906 SourceManager &SrcMgr = Reader.getSourceManager();
1907 bool PrevInSystem
1908 = PrevOwner? PrevOwner->IsSystem
1909 : SrcMgr.isInSystemHeader(PrevMI->getDefinitionLoc());
1910 bool NewInSystem
1911 = NewOwner? NewOwner->IsSystem
1912 : SrcMgr.isInSystemHeader(NewMI->getDefinitionLoc());
1913 if (PrevOwner && PrevOwner == NewOwner)
Argyrios Kyrtzidis3a9c42c2013-03-27 01:25:34 +00001914 return false;
Douglas Gregor5e461192013-06-07 22:56:11 +00001915 return PrevInSystem && NewInSystem;
Argyrios Kyrtzidis3a9c42c2013-03-27 01:25:34 +00001916}
1917
Richard Smith49f906a2014-03-01 00:08:04 +00001918void ASTReader::removeOverriddenMacros(IdentifierInfo *II,
Richard Smithdaa69e02014-07-25 04:40:03 +00001919 SourceLocation ImportLoc,
Richard Smith49f906a2014-03-01 00:08:04 +00001920 AmbiguousMacros &Ambig,
Craig Topper00bbdcf2014-06-28 23:22:23 +00001921 ArrayRef<SubmoduleID> Overrides) {
Richard Smith49f906a2014-03-01 00:08:04 +00001922 for (unsigned OI = 0, ON = Overrides.size(); OI != ON; ++OI) {
1923 SubmoduleID OwnerID = Overrides[OI];
Argyrios Kyrtzidiseb663da2013-03-22 21:12:57 +00001924
Richard Smith49f906a2014-03-01 00:08:04 +00001925 // If this macro is not yet visible, remove it from the hidden names list.
Richard Smithbb853c72014-08-13 01:23:33 +00001926 // It won't be there if we're in the middle of making the owner visible.
Richard Smith49f906a2014-03-01 00:08:04 +00001927 Module *Owner = getSubmodule(OwnerID);
Richard Smithbb853c72014-08-13 01:23:33 +00001928 auto HiddenIt = HiddenNamesMap.find(Owner);
1929 if (HiddenIt != HiddenNamesMap.end()) {
1930 HiddenNames &Hidden = HiddenIt->second;
1931 HiddenMacrosMap::iterator HI = Hidden.HiddenMacros.find(II);
1932 if (HI != Hidden.HiddenMacros.end()) {
1933 // Register the macro now so we don't lose it when we re-export.
1934 PP.appendMacroDirective(II, HI->second->import(PP, ImportLoc));
Richard Smithdaa69e02014-07-25 04:40:03 +00001935
Richard Smithbb853c72014-08-13 01:23:33 +00001936 auto SubOverrides = HI->second->getOverriddenSubmodules();
1937 Hidden.HiddenMacros.erase(HI);
1938 removeOverriddenMacros(II, ImportLoc, Ambig, SubOverrides);
1939 }
Richard Smith49f906a2014-03-01 00:08:04 +00001940 }
1941
1942 // If this macro is already in our list of conflicts, remove it from there.
Richard Smithbb29e512014-03-06 00:33:23 +00001943 Ambig.erase(
1944 std::remove_if(Ambig.begin(), Ambig.end(), [&](DefMacroDirective *MD) {
1945 return MD->getInfo()->getOwningModuleID() == OwnerID;
1946 }),
1947 Ambig.end());
Richard Smith49f906a2014-03-01 00:08:04 +00001948 }
1949}
1950
1951ASTReader::AmbiguousMacros *
1952ASTReader::removeOverriddenMacros(IdentifierInfo *II,
Richard Smithdaa69e02014-07-25 04:40:03 +00001953 SourceLocation ImportLoc,
Craig Topper00bbdcf2014-06-28 23:22:23 +00001954 ArrayRef<SubmoduleID> Overrides) {
Argyrios Kyrtzidiseb663da2013-03-22 21:12:57 +00001955 MacroDirective *Prev = PP.getMacroDirective(II);
Richard Smith49f906a2014-03-01 00:08:04 +00001956 if (!Prev && Overrides.empty())
Craig Toppera13603a2014-05-22 05:54:18 +00001957 return nullptr;
Richard Smith49f906a2014-03-01 00:08:04 +00001958
Craig Toppera13603a2014-05-22 05:54:18 +00001959 DefMacroDirective *PrevDef = Prev ? Prev->getDefinition().getDirective()
1960 : nullptr;
Richard Smith49f906a2014-03-01 00:08:04 +00001961 if (PrevDef && PrevDef->isAmbiguous()) {
1962 // We had a prior ambiguity. Check whether we resolve it (or make it worse).
1963 AmbiguousMacros &Ambig = AmbiguousMacroDefs[II];
1964 Ambig.push_back(PrevDef);
1965
Richard Smithdaa69e02014-07-25 04:40:03 +00001966 removeOverriddenMacros(II, ImportLoc, Ambig, Overrides);
Richard Smith49f906a2014-03-01 00:08:04 +00001967
1968 if (!Ambig.empty())
1969 return &Ambig;
1970
1971 AmbiguousMacroDefs.erase(II);
1972 } else {
1973 // There's no ambiguity yet. Maybe we're introducing one.
Benjamin Kramer834652a2014-05-03 18:44:26 +00001974 AmbiguousMacros Ambig;
Richard Smith49f906a2014-03-01 00:08:04 +00001975 if (PrevDef)
1976 Ambig.push_back(PrevDef);
1977
Richard Smithdaa69e02014-07-25 04:40:03 +00001978 removeOverriddenMacros(II, ImportLoc, Ambig, Overrides);
Richard Smith49f906a2014-03-01 00:08:04 +00001979
1980 if (!Ambig.empty()) {
1981 AmbiguousMacros &Result = AmbiguousMacroDefs[II];
Benjamin Kramer834652a2014-05-03 18:44:26 +00001982 std::swap(Result, Ambig);
Richard Smith49f906a2014-03-01 00:08:04 +00001983 return &Result;
Argyrios Kyrtzidisb6210df2013-03-26 17:17:01 +00001984 }
Argyrios Kyrtzidiseb663da2013-03-22 21:12:57 +00001985 }
Richard Smith49f906a2014-03-01 00:08:04 +00001986
1987 // We ended up with no ambiguity.
Craig Toppera13603a2014-05-22 05:54:18 +00001988 return nullptr;
Richard Smith49f906a2014-03-01 00:08:04 +00001989}
1990
1991void ASTReader::installImportedMacro(IdentifierInfo *II, ModuleMacroInfo *MMI,
Richard Smithdaa69e02014-07-25 04:40:03 +00001992 Module *Owner) {
Richard Smith49f906a2014-03-01 00:08:04 +00001993 assert(II && Owner);
1994
1995 SourceLocation ImportLoc = Owner->MacroVisibilityLoc;
Richard Smithdaa69e02014-07-25 04:40:03 +00001996 if (ImportLoc.isInvalid()) {
Richard Smith49f906a2014-03-01 00:08:04 +00001997 // FIXME: If we made macros from this module visible but didn't provide a
1998 // source location for the import, we don't have a location for the macro.
1999 // Use the location at which the containing module file was first imported
2000 // for now.
2001 ImportLoc = MMI->F->DirectImportLoc;
Richard Smith56be7542014-03-21 00:33:59 +00002002 assert(ImportLoc.isValid() && "no import location for a visible macro?");
Richard Smith49f906a2014-03-01 00:08:04 +00002003 }
2004
Benjamin Kramer834652a2014-05-03 18:44:26 +00002005 AmbiguousMacros *Prev =
Richard Smithdaa69e02014-07-25 04:40:03 +00002006 removeOverriddenMacros(II, ImportLoc, MMI->getOverriddenSubmodules());
Richard Smith49f906a2014-03-01 00:08:04 +00002007
Richard Smith49f906a2014-03-01 00:08:04 +00002008 // Create a synthetic macro definition corresponding to the import (or null
2009 // if this was an undefinition of the macro).
Richard Smithdaa69e02014-07-25 04:40:03 +00002010 MacroDirective *Imported = MMI->import(PP, ImportLoc);
2011 DefMacroDirective *MD = dyn_cast<DefMacroDirective>(Imported);
Richard Smith49f906a2014-03-01 00:08:04 +00002012
2013 // If there's no ambiguity, just install the macro.
2014 if (!Prev) {
Richard Smithdaa69e02014-07-25 04:40:03 +00002015 PP.appendMacroDirective(II, Imported);
Richard Smith49f906a2014-03-01 00:08:04 +00002016 return;
2017 }
2018 assert(!Prev->empty());
2019
2020 if (!MD) {
2021 // We imported a #undef that didn't remove all prior definitions. The most
2022 // recent prior definition remains, and we install it in the place of the
Richard Smithdaa69e02014-07-25 04:40:03 +00002023 // imported directive, as if by a local #pragma pop_macro.
Richard Smith49f906a2014-03-01 00:08:04 +00002024 MacroInfo *NewMI = Prev->back()->getInfo();
2025 Prev->pop_back();
Richard Smithdaa69e02014-07-25 04:40:03 +00002026 MD = PP.AllocateDefMacroDirective(NewMI, ImportLoc);
2027
2028 // Install our #undef first so that we don't lose track of it. We'll replace
2029 // this with whichever macro definition ends up winning.
2030 PP.appendMacroDirective(II, Imported);
Richard Smith49f906a2014-03-01 00:08:04 +00002031 }
2032
2033 // We're introducing a macro definition that creates or adds to an ambiguity.
2034 // We can resolve that ambiguity if this macro is token-for-token identical to
2035 // all of the existing definitions.
2036 MacroInfo *NewMI = MD->getInfo();
2037 assert(NewMI && "macro definition with no MacroInfo?");
2038 while (!Prev->empty()) {
2039 MacroInfo *PrevMI = Prev->back()->getInfo();
2040 assert(PrevMI && "macro definition with no MacroInfo?");
2041
2042 // Before marking the macros as ambiguous, check if this is a case where
2043 // both macros are in system headers. If so, we trust that the system
2044 // did not get it wrong. This also handles cases where Clang's own
2045 // headers have a different spelling of certain system macros:
2046 // #define LONG_MAX __LONG_MAX__ (clang's limits.h)
2047 // #define LONG_MAX 0x7fffffffffffffffL (system's limits.h)
2048 //
2049 // FIXME: Remove the defined-in-system-headers check. clang's limits.h
2050 // overrides the system limits.h's macros, so there's no conflict here.
2051 if (NewMI != PrevMI &&
2052 !PrevMI->isIdenticalTo(*NewMI, PP, /*Syntactically=*/true) &&
2053 !areDefinedInSystemModules(PrevMI, NewMI, Owner, *this))
2054 break;
2055
2056 // The previous definition is the same as this one (or both are defined in
2057 // system modules so we can assume they're equivalent); we don't need to
2058 // track it any more.
2059 Prev->pop_back();
2060 }
2061
2062 if (!Prev->empty())
2063 MD->setAmbiguous(true);
2064
Argyrios Kyrtzidisb6210df2013-03-26 17:17:01 +00002065 PP.appendMacroDirective(II, MD);
Argyrios Kyrtzidiseb663da2013-03-22 21:12:57 +00002066}
2067
Argyrios Kyrtzidisce9b49e2014-03-14 02:26:27 +00002068ASTReader::InputFileInfo
2069ASTReader::readInputFileInfo(ModuleFile &F, unsigned ID) {
Ben Langmuir198c1682014-03-07 07:27:49 +00002070 // Go find this input file.
2071 BitstreamCursor &Cursor = F.InputFilesCursor;
2072 SavedStreamPosition SavedPosition(Cursor);
2073 Cursor.JumpToBit(F.InputFileOffsets[ID-1]);
2074
2075 unsigned Code = Cursor.ReadCode();
2076 RecordData Record;
2077 StringRef Blob;
2078
2079 unsigned Result = Cursor.readRecord(Code, Record, &Blob);
2080 assert(static_cast<InputFileRecordTypes>(Result) == INPUT_FILE &&
2081 "invalid record type for input file");
2082 (void)Result;
2083
Argyrios Kyrtzidisce9b49e2014-03-14 02:26:27 +00002084 std::string Filename;
2085 off_t StoredSize;
2086 time_t StoredTime;
2087 bool Overridden;
2088
Ben Langmuir198c1682014-03-07 07:27:49 +00002089 assert(Record[0] == ID && "Bogus stored ID or offset");
2090 StoredSize = static_cast<off_t>(Record[1]);
2091 StoredTime = static_cast<time_t>(Record[2]);
2092 Overridden = static_cast<bool>(Record[3]);
2093 Filename = Blob;
2094 MaybeAddSystemRootToFilename(F, Filename);
Argyrios Kyrtzidisce9b49e2014-03-14 02:26:27 +00002095
Hans Wennborg73945142014-03-14 17:45:06 +00002096 InputFileInfo R = { std::move(Filename), StoredSize, StoredTime, Overridden };
2097 return R;
Ben Langmuir198c1682014-03-07 07:27:49 +00002098}
2099
2100std::string ASTReader::getInputFileName(ModuleFile &F, unsigned int ID) {
Argyrios Kyrtzidisce9b49e2014-03-14 02:26:27 +00002101 return readInputFileInfo(F, ID).Filename;
Ben Langmuir198c1682014-03-07 07:27:49 +00002102}
2103
Argyrios Kyrtzidis61c3d872013-03-01 03:26:04 +00002104InputFile ASTReader::getInputFile(ModuleFile &F, unsigned ID, bool Complain) {
Guy Benyei11169dd2012-12-18 14:30:41 +00002105 // If this ID is bogus, just return an empty input file.
2106 if (ID == 0 || ID > F.InputFilesLoaded.size())
2107 return InputFile();
2108
2109 // If we've already loaded this input file, return it.
Argyrios Kyrtzidis61c3d872013-03-01 03:26:04 +00002110 if (F.InputFilesLoaded[ID-1].getFile())
Guy Benyei11169dd2012-12-18 14:30:41 +00002111 return F.InputFilesLoaded[ID-1];
2112
Argyrios Kyrtzidis9308f0a2014-01-08 19:13:34 +00002113 if (F.InputFilesLoaded[ID-1].isNotFound())
2114 return InputFile();
2115
Guy Benyei11169dd2012-12-18 14:30:41 +00002116 // Go find this input file.
Chris Lattner7fb3bef2013-01-20 00:56:42 +00002117 BitstreamCursor &Cursor = F.InputFilesCursor;
Guy Benyei11169dd2012-12-18 14:30:41 +00002118 SavedStreamPosition SavedPosition(Cursor);
2119 Cursor.JumpToBit(F.InputFileOffsets[ID-1]);
2120
Argyrios Kyrtzidisce9b49e2014-03-14 02:26:27 +00002121 InputFileInfo FI = readInputFileInfo(F, ID);
2122 off_t StoredSize = FI.StoredSize;
2123 time_t StoredTime = FI.StoredTime;
2124 bool Overridden = FI.Overridden;
2125 StringRef Filename = FI.Filename;
Argyrios Kyrtzidis61c3d872013-03-01 03:26:04 +00002126
Ben Langmuir198c1682014-03-07 07:27:49 +00002127 const FileEntry *File
2128 = Overridden? FileMgr.getVirtualFile(Filename, StoredSize, StoredTime)
2129 : FileMgr.getFile(Filename, /*OpenFile=*/false);
2130
2131 // If we didn't find the file, resolve it relative to the
2132 // original directory from which this AST file was created.
Craig Toppera13603a2014-05-22 05:54:18 +00002133 if (File == nullptr && !F.OriginalDir.empty() && !CurrentDir.empty() &&
Ben Langmuir198c1682014-03-07 07:27:49 +00002134 F.OriginalDir != CurrentDir) {
2135 std::string Resolved = resolveFileRelativeToOriginalDir(Filename,
2136 F.OriginalDir,
2137 CurrentDir);
2138 if (!Resolved.empty())
2139 File = FileMgr.getFile(Resolved);
2140 }
2141
2142 // For an overridden file, create a virtual file with the stored
2143 // size/timestamp.
Craig Toppera13603a2014-05-22 05:54:18 +00002144 if (Overridden && File == nullptr) {
Ben Langmuir198c1682014-03-07 07:27:49 +00002145 File = FileMgr.getVirtualFile(Filename, StoredSize, StoredTime);
2146 }
2147
Craig Toppera13603a2014-05-22 05:54:18 +00002148 if (File == nullptr) {
Ben Langmuir198c1682014-03-07 07:27:49 +00002149 if (Complain) {
2150 std::string ErrorStr = "could not find file '";
2151 ErrorStr += Filename;
2152 ErrorStr += "' referenced by AST file";
2153 Error(ErrorStr.c_str());
Guy Benyei11169dd2012-12-18 14:30:41 +00002154 }
Ben Langmuir198c1682014-03-07 07:27:49 +00002155 // Record that we didn't find the file.
2156 F.InputFilesLoaded[ID-1] = InputFile::getNotFound();
2157 return InputFile();
2158 }
Guy Benyei11169dd2012-12-18 14:30:41 +00002159
Ben Langmuir198c1682014-03-07 07:27:49 +00002160 // Check if there was a request to override the contents of the file
2161 // that was part of the precompiled header. Overridding such a file
2162 // can lead to problems when lexing using the source locations from the
2163 // PCH.
2164 SourceManager &SM = getSourceManager();
2165 if (!Overridden && SM.isFileOverridden(File)) {
2166 if (Complain)
2167 Error(diag::err_fe_pch_file_overridden, Filename);
2168 // After emitting the diagnostic, recover by disabling the override so
2169 // that the original file will be used.
2170 SM.disableFileContentsOverride(File);
2171 // The FileEntry is a virtual file entry with the size of the contents
2172 // that would override the original contents. Set it to the original's
2173 // size/time.
2174 FileMgr.modifyFileEntry(const_cast<FileEntry*>(File),
2175 StoredSize, StoredTime);
2176 }
Guy Benyei11169dd2012-12-18 14:30:41 +00002177
Ben Langmuir198c1682014-03-07 07:27:49 +00002178 bool IsOutOfDate = false;
2179
2180 // For an overridden file, there is nothing to validate.
Richard Smith96fdab62014-10-28 16:24:08 +00002181 if (!Overridden && //
2182 (StoredSize != File->getSize() ||
2183#if defined(LLVM_ON_WIN32)
2184 false
2185#else
Ben Langmuir198c1682014-03-07 07:27:49 +00002186 // In our regression testing, the Windows file system seems to
2187 // have inconsistent modification times that sometimes
2188 // erroneously trigger this error-handling path.
Richard Smith96fdab62014-10-28 16:24:08 +00002189 //
2190 // This also happens in networked file systems, so disable this
2191 // check if validation is disabled or if we have an explicitly
2192 // built PCM file.
2193 //
2194 // FIXME: Should we also do this for PCH files? They could also
2195 // reasonably get shared across a network during a distributed build.
2196 (StoredTime != File->getModificationTime() && !DisableValidation &&
2197 F.Kind != MK_ExplicitModule)
Guy Benyei11169dd2012-12-18 14:30:41 +00002198#endif
Ben Langmuir198c1682014-03-07 07:27:49 +00002199 )) {
2200 if (Complain) {
2201 // Build a list of the PCH imports that got us here (in reverse).
2202 SmallVector<ModuleFile *, 4> ImportStack(1, &F);
2203 while (ImportStack.back()->ImportedBy.size() > 0)
2204 ImportStack.push_back(ImportStack.back()->ImportedBy[0]);
Ben Langmuire82630d2014-01-17 00:19:09 +00002205
Ben Langmuir198c1682014-03-07 07:27:49 +00002206 // The top-level PCH is stale.
2207 StringRef TopLevelPCHName(ImportStack.back()->FileName);
2208 Error(diag::err_fe_pch_file_modified, Filename, TopLevelPCHName);
Ben Langmuire82630d2014-01-17 00:19:09 +00002209
Ben Langmuir198c1682014-03-07 07:27:49 +00002210 // Print the import stack.
2211 if (ImportStack.size() > 1 && !Diags.isDiagnosticInFlight()) {
2212 Diag(diag::note_pch_required_by)
2213 << Filename << ImportStack[0]->FileName;
2214 for (unsigned I = 1; I < ImportStack.size(); ++I)
Ben Langmuire82630d2014-01-17 00:19:09 +00002215 Diag(diag::note_pch_required_by)
Ben Langmuir198c1682014-03-07 07:27:49 +00002216 << ImportStack[I-1]->FileName << ImportStack[I]->FileName;
Douglas Gregor7029ce12013-03-19 00:28:20 +00002217 }
2218
Ben Langmuir198c1682014-03-07 07:27:49 +00002219 if (!Diags.isDiagnosticInFlight())
2220 Diag(diag::note_pch_rebuild_required) << TopLevelPCHName;
Guy Benyei11169dd2012-12-18 14:30:41 +00002221 }
2222
Ben Langmuir198c1682014-03-07 07:27:49 +00002223 IsOutOfDate = true;
Guy Benyei11169dd2012-12-18 14:30:41 +00002224 }
2225
Ben Langmuir198c1682014-03-07 07:27:49 +00002226 InputFile IF = InputFile(File, Overridden, IsOutOfDate);
2227
2228 // Note that we've loaded this input file.
2229 F.InputFilesLoaded[ID-1] = IF;
2230 return IF;
Guy Benyei11169dd2012-12-18 14:30:41 +00002231}
2232
2233const FileEntry *ASTReader::getFileEntry(StringRef filenameStrRef) {
2234 ModuleFile &M = ModuleMgr.getPrimaryModule();
2235 std::string Filename = filenameStrRef;
2236 MaybeAddSystemRootToFilename(M, Filename);
2237 const FileEntry *File = FileMgr.getFile(Filename);
Craig Toppera13603a2014-05-22 05:54:18 +00002238 if (File == nullptr && !M.OriginalDir.empty() && !CurrentDir.empty() &&
Guy Benyei11169dd2012-12-18 14:30:41 +00002239 M.OriginalDir != CurrentDir) {
2240 std::string resolved = resolveFileRelativeToOriginalDir(Filename,
2241 M.OriginalDir,
2242 CurrentDir);
2243 if (!resolved.empty())
2244 File = FileMgr.getFile(resolved);
2245 }
2246
2247 return File;
2248}
2249
2250/// \brief If we are loading a relocatable PCH file, and the filename is
2251/// not an absolute path, add the system root to the beginning of the file
2252/// name.
2253void ASTReader::MaybeAddSystemRootToFilename(ModuleFile &M,
2254 std::string &Filename) {
2255 // If this is not a relocatable PCH file, there's nothing to do.
2256 if (!M.RelocatablePCH)
2257 return;
2258
2259 if (Filename.empty() || llvm::sys::path::is_absolute(Filename))
2260 return;
2261
2262 if (isysroot.empty()) {
2263 // If no system root was given, default to '/'
2264 Filename.insert(Filename.begin(), '/');
2265 return;
2266 }
2267
2268 unsigned Length = isysroot.size();
2269 if (isysroot[Length - 1] != '/')
2270 Filename.insert(Filename.begin(), '/');
2271
2272 Filename.insert(Filename.begin(), isysroot.begin(), isysroot.end());
2273}
2274
2275ASTReader::ASTReadResult
2276ASTReader::ReadControlBlock(ModuleFile &F,
Dmitri Gribenkof8579502013-01-12 19:30:44 +00002277 SmallVectorImpl<ImportedModule> &Loaded,
Ben Langmuirbeee15e2014-04-14 18:00:01 +00002278 const ModuleFile *ImportedBy,
Guy Benyei11169dd2012-12-18 14:30:41 +00002279 unsigned ClientLoadCapabilities) {
Chris Lattner7fb3bef2013-01-20 00:56:42 +00002280 BitstreamCursor &Stream = F.Stream;
Guy Benyei11169dd2012-12-18 14:30:41 +00002281
2282 if (Stream.EnterSubBlock(CONTROL_BLOCK_ID)) {
2283 Error("malformed block record in AST file");
2284 return Failure;
2285 }
2286
Richard Smith1e2cf0d2014-10-31 02:28:58 +00002287 // Should we allow the configuration of the module file to differ from the
2288 // configuration of the current translation unit in a compatible way?
2289 //
2290 // FIXME: Allow this for files explicitly specified with -include-pch too.
2291 bool AllowCompatibleConfigurationMismatch = F.Kind == MK_ExplicitModule;
2292
Guy Benyei11169dd2012-12-18 14:30:41 +00002293 // Read all of the records and blocks in the control block.
2294 RecordData Record;
Richard Smitha1825302014-10-23 22:18:29 +00002295 unsigned NumInputs = 0;
2296 unsigned NumUserInputs = 0;
Chris Lattnere7b154b2013-01-19 21:39:22 +00002297 while (1) {
2298 llvm::BitstreamEntry Entry = Stream.advance();
2299
2300 switch (Entry.Kind) {
2301 case llvm::BitstreamEntry::Error:
2302 Error("malformed block record in AST file");
2303 return Failure;
Dmitri Gribenkof430da42014-02-12 10:33:14 +00002304 case llvm::BitstreamEntry::EndBlock: {
2305 // Validate input files.
2306 const HeaderSearchOptions &HSOpts =
2307 PP.getHeaderSearchInfo().getHeaderSearchOpts();
Ben Langmuircb69b572014-03-07 06:40:32 +00002308
Richard Smitha1825302014-10-23 22:18:29 +00002309 // All user input files reside at the index range [0, NumUserInputs), and
2310 // system input files reside at [NumUserInputs, NumInputs).
Ben Langmuiracb803e2014-11-10 22:13:10 +00002311 if (!DisableValidation) {
Guy Benyei11169dd2012-12-18 14:30:41 +00002312 bool Complain = (ClientLoadCapabilities & ARR_OutOfDate) == 0;
Ben Langmuircb69b572014-03-07 06:40:32 +00002313
Dmitri Gribenkof430da42014-02-12 10:33:14 +00002314 // If we are reading a module, we will create a verification timestamp,
2315 // so we verify all input files. Otherwise, verify only user input
2316 // files.
Ben Langmuircb69b572014-03-07 06:40:32 +00002317
2318 unsigned N = NumUserInputs;
2319 if (ValidateSystemInputs ||
Richard Smithe842a472014-10-22 02:05:46 +00002320 (HSOpts.ModulesValidateOncePerBuildSession &&
Ben Langmuiracb803e2014-11-10 22:13:10 +00002321 F.InputFilesValidationTimestamp <= HSOpts.BuildSessionTimestamp &&
Richard Smithe842a472014-10-22 02:05:46 +00002322 F.Kind == MK_ImplicitModule))
Ben Langmuircb69b572014-03-07 06:40:32 +00002323 N = NumInputs;
2324
Ben Langmuir3d4417c2014-02-07 17:31:11 +00002325 for (unsigned I = 0; I < N; ++I) {
Argyrios Kyrtzidis61c3d872013-03-01 03:26:04 +00002326 InputFile IF = getInputFile(F, I+1, Complain);
2327 if (!IF.getFile() || IF.isOutOfDate())
Guy Benyei11169dd2012-12-18 14:30:41 +00002328 return OutOfDate;
Argyrios Kyrtzidis61c3d872013-03-01 03:26:04 +00002329 }
Guy Benyei11169dd2012-12-18 14:30:41 +00002330 }
Ben Langmuircb69b572014-03-07 06:40:32 +00002331
Argyrios Kyrtzidis6d0753d2014-03-14 03:07:38 +00002332 if (Listener)
2333 Listener->visitModuleFile(F.FileName);
2334
Ben Langmuircb69b572014-03-07 06:40:32 +00002335 if (Listener && Listener->needsInputFileVisitation()) {
2336 unsigned N = Listener->needsSystemInputFileVisitation() ? NumInputs
2337 : NumUserInputs;
Argyrios Kyrtzidis68ccbe02014-03-14 02:26:31 +00002338 for (unsigned I = 0; I < N; ++I) {
2339 bool IsSystem = I >= NumUserInputs;
2340 InputFileInfo FI = readInputFileInfo(F, I+1);
2341 Listener->visitInputFile(FI.Filename, IsSystem, FI.Overridden);
2342 }
Ben Langmuircb69b572014-03-07 06:40:32 +00002343 }
2344
Guy Benyei11169dd2012-12-18 14:30:41 +00002345 return Success;
Dmitri Gribenkof430da42014-02-12 10:33:14 +00002346 }
2347
Chris Lattnere7b154b2013-01-19 21:39:22 +00002348 case llvm::BitstreamEntry::SubBlock:
2349 switch (Entry.ID) {
Guy Benyei11169dd2012-12-18 14:30:41 +00002350 case INPUT_FILES_BLOCK_ID:
2351 F.InputFilesCursor = Stream;
2352 if (Stream.SkipBlock() || // Skip with the main cursor
2353 // Read the abbreviations
2354 ReadBlockAbbrevs(F.InputFilesCursor, INPUT_FILES_BLOCK_ID)) {
2355 Error("malformed block record in AST file");
2356 return Failure;
2357 }
2358 continue;
Chris Lattnere7b154b2013-01-19 21:39:22 +00002359
Guy Benyei11169dd2012-12-18 14:30:41 +00002360 default:
Chris Lattnere7b154b2013-01-19 21:39:22 +00002361 if (Stream.SkipBlock()) {
2362 Error("malformed block record in AST file");
2363 return Failure;
2364 }
2365 continue;
Guy Benyei11169dd2012-12-18 14:30:41 +00002366 }
Chris Lattnere7b154b2013-01-19 21:39:22 +00002367
2368 case llvm::BitstreamEntry::Record:
2369 // The interesting case.
2370 break;
Guy Benyei11169dd2012-12-18 14:30:41 +00002371 }
2372
2373 // Read and process a record.
2374 Record.clear();
Chris Lattner0e6c9402013-01-20 02:38:54 +00002375 StringRef Blob;
2376 switch ((ControlRecordTypes)Stream.readRecord(Entry.ID, Record, &Blob)) {
Guy Benyei11169dd2012-12-18 14:30:41 +00002377 case METADATA: {
2378 if (Record[0] != VERSION_MAJOR && !DisableValidation) {
2379 if ((ClientLoadCapabilities & ARR_VersionMismatch) == 0)
Dmitri Gribenko2228cd32014-02-11 15:40:09 +00002380 Diag(Record[0] < VERSION_MAJOR? diag::err_pch_version_too_old
2381 : diag::err_pch_version_too_new);
Guy Benyei11169dd2012-12-18 14:30:41 +00002382 return VersionMismatch;
2383 }
2384
2385 bool hasErrors = Record[5];
2386 if (hasErrors && !DisableValidation && !AllowASTWithCompilerErrors) {
2387 Diag(diag::err_pch_with_compiler_errors);
2388 return HadErrors;
2389 }
2390
2391 F.RelocatablePCH = Record[4];
2392
2393 const std::string &CurBranch = getClangFullRepositoryVersion();
Chris Lattner0e6c9402013-01-20 02:38:54 +00002394 StringRef ASTBranch = Blob;
Guy Benyei11169dd2012-12-18 14:30:41 +00002395 if (StringRef(CurBranch) != ASTBranch && !DisableValidation) {
2396 if ((ClientLoadCapabilities & ARR_VersionMismatch) == 0)
Dmitri Gribenko2228cd32014-02-11 15:40:09 +00002397 Diag(diag::err_pch_different_branch) << ASTBranch << CurBranch;
Guy Benyei11169dd2012-12-18 14:30:41 +00002398 return VersionMismatch;
2399 }
2400 break;
2401 }
2402
Ben Langmuir487ea142014-10-23 18:05:36 +00002403 case SIGNATURE:
2404 assert((!F.Signature || F.Signature == Record[0]) && "signature changed");
2405 F.Signature = Record[0];
2406 break;
2407
Guy Benyei11169dd2012-12-18 14:30:41 +00002408 case IMPORTS: {
2409 // Load each of the imported PCH files.
2410 unsigned Idx = 0, N = Record.size();
2411 while (Idx < N) {
2412 // Read information about the AST file.
2413 ModuleKind ImportedKind = (ModuleKind)Record[Idx++];
2414 // The import location will be the local one for now; we will adjust
2415 // all import locations of module imports after the global source
2416 // location info are setup.
2417 SourceLocation ImportLoc =
2418 SourceLocation::getFromRawEncoding(Record[Idx++]);
Douglas Gregor7029ce12013-03-19 00:28:20 +00002419 off_t StoredSize = (off_t)Record[Idx++];
2420 time_t StoredModTime = (time_t)Record[Idx++];
Ben Langmuir487ea142014-10-23 18:05:36 +00002421 ASTFileSignature StoredSignature = Record[Idx++];
Guy Benyei11169dd2012-12-18 14:30:41 +00002422 unsigned Length = Record[Idx++];
2423 SmallString<128> ImportedFile(Record.begin() + Idx,
2424 Record.begin() + Idx + Length);
2425 Idx += Length;
2426
2427 // Load the AST file.
2428 switch(ReadASTCore(ImportedFile, ImportedKind, ImportLoc, &F, Loaded,
Ben Langmuir487ea142014-10-23 18:05:36 +00002429 StoredSize, StoredModTime, StoredSignature,
Guy Benyei11169dd2012-12-18 14:30:41 +00002430 ClientLoadCapabilities)) {
2431 case Failure: return Failure;
2432 // If we have to ignore the dependency, we'll have to ignore this too.
Douglas Gregor2f1806e2013-03-19 00:38:50 +00002433 case Missing:
Guy Benyei11169dd2012-12-18 14:30:41 +00002434 case OutOfDate: return OutOfDate;
2435 case VersionMismatch: return VersionMismatch;
2436 case ConfigurationMismatch: return ConfigurationMismatch;
2437 case HadErrors: return HadErrors;
2438 case Success: break;
2439 }
2440 }
2441 break;
2442 }
2443
2444 case LANGUAGE_OPTIONS: {
2445 bool Complain = (ClientLoadCapabilities & ARR_ConfigurationMismatch) == 0;
Richard Smith1e2cf0d2014-10-31 02:28:58 +00002446 // FIXME: The &F == *ModuleMgr.begin() check is wrong for modules.
Guy Benyei11169dd2012-12-18 14:30:41 +00002447 if (Listener && &F == *ModuleMgr.begin() &&
Richard Smith1e2cf0d2014-10-31 02:28:58 +00002448 ParseLanguageOptions(Record, Complain, *Listener,
2449 AllowCompatibleConfigurationMismatch) &&
Ben Langmuir2cb4a782014-02-05 22:21:15 +00002450 !DisableValidation && !AllowConfigurationMismatch)
Guy Benyei11169dd2012-12-18 14:30:41 +00002451 return ConfigurationMismatch;
2452 break;
2453 }
2454
2455 case TARGET_OPTIONS: {
2456 bool Complain = (ClientLoadCapabilities & ARR_ConfigurationMismatch)==0;
2457 if (Listener && &F == *ModuleMgr.begin() &&
2458 ParseTargetOptions(Record, Complain, *Listener) &&
Ben Langmuir2cb4a782014-02-05 22:21:15 +00002459 !DisableValidation && !AllowConfigurationMismatch)
Guy Benyei11169dd2012-12-18 14:30:41 +00002460 return ConfigurationMismatch;
2461 break;
2462 }
2463
2464 case DIAGNOSTIC_OPTIONS: {
Ben Langmuirb92de022014-04-29 16:25:26 +00002465 bool Complain = (ClientLoadCapabilities & ARR_OutOfDate)==0;
Guy Benyei11169dd2012-12-18 14:30:41 +00002466 if (Listener && &F == *ModuleMgr.begin() &&
Richard Smith1e2cf0d2014-10-31 02:28:58 +00002467 !AllowCompatibleConfigurationMismatch &&
Guy Benyei11169dd2012-12-18 14:30:41 +00002468 ParseDiagnosticOptions(Record, Complain, *Listener) &&
Ben Langmuirb92de022014-04-29 16:25:26 +00002469 !DisableValidation)
2470 return OutOfDate;
Guy Benyei11169dd2012-12-18 14:30:41 +00002471 break;
2472 }
2473
2474 case FILE_SYSTEM_OPTIONS: {
2475 bool Complain = (ClientLoadCapabilities & ARR_ConfigurationMismatch)==0;
2476 if (Listener && &F == *ModuleMgr.begin() &&
Richard Smith1e2cf0d2014-10-31 02:28:58 +00002477 !AllowCompatibleConfigurationMismatch &&
Guy Benyei11169dd2012-12-18 14:30:41 +00002478 ParseFileSystemOptions(Record, Complain, *Listener) &&
Ben Langmuir2cb4a782014-02-05 22:21:15 +00002479 !DisableValidation && !AllowConfigurationMismatch)
Guy Benyei11169dd2012-12-18 14:30:41 +00002480 return ConfigurationMismatch;
2481 break;
2482 }
2483
2484 case HEADER_SEARCH_OPTIONS: {
2485 bool Complain = (ClientLoadCapabilities & ARR_ConfigurationMismatch)==0;
2486 if (Listener && &F == *ModuleMgr.begin() &&
Richard Smith1e2cf0d2014-10-31 02:28:58 +00002487 !AllowCompatibleConfigurationMismatch &&
Guy Benyei11169dd2012-12-18 14:30:41 +00002488 ParseHeaderSearchOptions(Record, Complain, *Listener) &&
Ben Langmuir2cb4a782014-02-05 22:21:15 +00002489 !DisableValidation && !AllowConfigurationMismatch)
Guy Benyei11169dd2012-12-18 14:30:41 +00002490 return ConfigurationMismatch;
2491 break;
2492 }
2493
2494 case PREPROCESSOR_OPTIONS: {
2495 bool Complain = (ClientLoadCapabilities & ARR_ConfigurationMismatch)==0;
2496 if (Listener && &F == *ModuleMgr.begin() &&
Richard Smith1e2cf0d2014-10-31 02:28:58 +00002497 !AllowCompatibleConfigurationMismatch &&
Guy Benyei11169dd2012-12-18 14:30:41 +00002498 ParsePreprocessorOptions(Record, Complain, *Listener,
2499 SuggestedPredefines) &&
Ben Langmuir2cb4a782014-02-05 22:21:15 +00002500 !DisableValidation && !AllowConfigurationMismatch)
Guy Benyei11169dd2012-12-18 14:30:41 +00002501 return ConfigurationMismatch;
2502 break;
2503 }
2504
2505 case ORIGINAL_FILE:
2506 F.OriginalSourceFileID = FileID::get(Record[0]);
Chris Lattner0e6c9402013-01-20 02:38:54 +00002507 F.ActualOriginalSourceFileName = Blob;
Guy Benyei11169dd2012-12-18 14:30:41 +00002508 F.OriginalSourceFileName = F.ActualOriginalSourceFileName;
2509 MaybeAddSystemRootToFilename(F, F.OriginalSourceFileName);
2510 break;
2511
2512 case ORIGINAL_FILE_ID:
2513 F.OriginalSourceFileID = FileID::get(Record[0]);
2514 break;
2515
2516 case ORIGINAL_PCH_DIR:
Chris Lattner0e6c9402013-01-20 02:38:54 +00002517 F.OriginalDir = Blob;
Guy Benyei11169dd2012-12-18 14:30:41 +00002518 break;
2519
Ben Langmuirbeee15e2014-04-14 18:00:01 +00002520 case MODULE_NAME:
2521 F.ModuleName = Blob;
Ben Langmuir4f5212a2014-04-14 22:12:44 +00002522 if (Listener)
2523 Listener->ReadModuleName(F.ModuleName);
Ben Langmuirbeee15e2014-04-14 18:00:01 +00002524 break;
2525
2526 case MODULE_MAP_FILE:
Ben Langmuir4b8a9e92014-08-12 16:42:33 +00002527 if (ASTReadResult Result =
2528 ReadModuleMapFileBlock(Record, F, ImportedBy, ClientLoadCapabilities))
2529 return Result;
Ben Langmuir264ea152014-11-08 00:06:39 +00002530 break;
2531
Guy Benyei11169dd2012-12-18 14:30:41 +00002532 case INPUT_FILE_OFFSETS:
Richard Smitha1825302014-10-23 22:18:29 +00002533 NumInputs = Record[0];
2534 NumUserInputs = Record[1];
Chris Lattner0e6c9402013-01-20 02:38:54 +00002535 F.InputFileOffsets = (const uint32_t *)Blob.data();
Richard Smitha1825302014-10-23 22:18:29 +00002536 F.InputFilesLoaded.resize(NumInputs);
Guy Benyei11169dd2012-12-18 14:30:41 +00002537 break;
2538 }
2539 }
Guy Benyei11169dd2012-12-18 14:30:41 +00002540}
2541
Ben Langmuir2c9af442014-04-10 17:57:43 +00002542ASTReader::ASTReadResult
2543ASTReader::ReadASTBlock(ModuleFile &F, unsigned ClientLoadCapabilities) {
Chris Lattner7fb3bef2013-01-20 00:56:42 +00002544 BitstreamCursor &Stream = F.Stream;
Guy Benyei11169dd2012-12-18 14:30:41 +00002545
2546 if (Stream.EnterSubBlock(AST_BLOCK_ID)) {
2547 Error("malformed block record in AST file");
Ben Langmuir2c9af442014-04-10 17:57:43 +00002548 return Failure;
Guy Benyei11169dd2012-12-18 14:30:41 +00002549 }
2550
2551 // Read all of the records and blocks for the AST file.
2552 RecordData Record;
Chris Lattnere7b154b2013-01-19 21:39:22 +00002553 while (1) {
2554 llvm::BitstreamEntry Entry = Stream.advance();
2555
2556 switch (Entry.Kind) {
2557 case llvm::BitstreamEntry::Error:
2558 Error("error at end of module block in AST file");
Ben Langmuir2c9af442014-04-10 17:57:43 +00002559 return Failure;
Chris Lattnere7b154b2013-01-19 21:39:22 +00002560 case llvm::BitstreamEntry::EndBlock: {
Richard Smithc0fbba72013-04-03 22:49:41 +00002561 // Outside of C++, we do not store a lookup map for the translation unit.
2562 // Instead, mark it as needing a lookup map to be built if this module
2563 // contains any declarations lexically within it (which it always does!).
2564 // This usually has no cost, since we very rarely need the lookup map for
2565 // the translation unit outside C++.
Guy Benyei11169dd2012-12-18 14:30:41 +00002566 DeclContext *DC = Context.getTranslationUnitDecl();
Richard Smithc0fbba72013-04-03 22:49:41 +00002567 if (DC->hasExternalLexicalStorage() &&
2568 !getContext().getLangOpts().CPlusPlus)
Guy Benyei11169dd2012-12-18 14:30:41 +00002569 DC->setMustBuildLookupTable();
Chris Lattnere7b154b2013-01-19 21:39:22 +00002570
Ben Langmuir2c9af442014-04-10 17:57:43 +00002571 return Success;
Guy Benyei11169dd2012-12-18 14:30:41 +00002572 }
Chris Lattnere7b154b2013-01-19 21:39:22 +00002573 case llvm::BitstreamEntry::SubBlock:
2574 switch (Entry.ID) {
Guy Benyei11169dd2012-12-18 14:30:41 +00002575 case DECLTYPES_BLOCK_ID:
2576 // We lazily load the decls block, but we want to set up the
2577 // DeclsCursor cursor to point into it. Clone our current bitcode
2578 // cursor to it, enter the block and read the abbrevs in that block.
2579 // With the main cursor, we just skip over it.
2580 F.DeclsCursor = Stream;
2581 if (Stream.SkipBlock() || // Skip with the main cursor.
2582 // Read the abbrevs.
2583 ReadBlockAbbrevs(F.DeclsCursor, DECLTYPES_BLOCK_ID)) {
2584 Error("malformed block record in AST file");
Ben Langmuir2c9af442014-04-10 17:57:43 +00002585 return Failure;
Guy Benyei11169dd2012-12-18 14:30:41 +00002586 }
2587 break;
Richard Smithb9eab6d2014-03-20 19:44:17 +00002588
Guy Benyei11169dd2012-12-18 14:30:41 +00002589 case PREPROCESSOR_BLOCK_ID:
2590 F.MacroCursor = Stream;
2591 if (!PP.getExternalSource())
2592 PP.setExternalSource(this);
Chris Lattnere7b154b2013-01-19 21:39:22 +00002593
Guy Benyei11169dd2012-12-18 14:30:41 +00002594 if (Stream.SkipBlock() ||
2595 ReadBlockAbbrevs(F.MacroCursor, PREPROCESSOR_BLOCK_ID)) {
2596 Error("malformed block record in AST file");
Ben Langmuir2c9af442014-04-10 17:57:43 +00002597 return Failure;
Guy Benyei11169dd2012-12-18 14:30:41 +00002598 }
2599 F.MacroStartOffset = F.MacroCursor.GetCurrentBitNo();
2600 break;
Chris Lattnere7b154b2013-01-19 21:39:22 +00002601
Guy Benyei11169dd2012-12-18 14:30:41 +00002602 case PREPROCESSOR_DETAIL_BLOCK_ID:
2603 F.PreprocessorDetailCursor = Stream;
2604 if (Stream.SkipBlock() ||
Chris Lattnere7b154b2013-01-19 21:39:22 +00002605 ReadBlockAbbrevs(F.PreprocessorDetailCursor,
Guy Benyei11169dd2012-12-18 14:30:41 +00002606 PREPROCESSOR_DETAIL_BLOCK_ID)) {
Chris Lattnere7b154b2013-01-19 21:39:22 +00002607 Error("malformed preprocessor detail record in AST file");
Ben Langmuir2c9af442014-04-10 17:57:43 +00002608 return Failure;
Chris Lattnere7b154b2013-01-19 21:39:22 +00002609 }
Guy Benyei11169dd2012-12-18 14:30:41 +00002610 F.PreprocessorDetailStartOffset
Chris Lattnere7b154b2013-01-19 21:39:22 +00002611 = F.PreprocessorDetailCursor.GetCurrentBitNo();
2612
Guy Benyei11169dd2012-12-18 14:30:41 +00002613 if (!PP.getPreprocessingRecord())
2614 PP.createPreprocessingRecord();
2615 if (!PP.getPreprocessingRecord()->getExternalSource())
2616 PP.getPreprocessingRecord()->SetExternalSource(*this);
2617 break;
2618
2619 case SOURCE_MANAGER_BLOCK_ID:
2620 if (ReadSourceManagerBlock(F))
Ben Langmuir2c9af442014-04-10 17:57:43 +00002621 return Failure;
Guy Benyei11169dd2012-12-18 14:30:41 +00002622 break;
Chris Lattnere7b154b2013-01-19 21:39:22 +00002623
Guy Benyei11169dd2012-12-18 14:30:41 +00002624 case SUBMODULE_BLOCK_ID:
Ben Langmuir2c9af442014-04-10 17:57:43 +00002625 if (ASTReadResult Result = ReadSubmoduleBlock(F, ClientLoadCapabilities))
2626 return Result;
Guy Benyei11169dd2012-12-18 14:30:41 +00002627 break;
Chris Lattnere7b154b2013-01-19 21:39:22 +00002628
Guy Benyei11169dd2012-12-18 14:30:41 +00002629 case COMMENTS_BLOCK_ID: {
Chris Lattner7fb3bef2013-01-20 00:56:42 +00002630 BitstreamCursor C = Stream;
Guy Benyei11169dd2012-12-18 14:30:41 +00002631 if (Stream.SkipBlock() ||
2632 ReadBlockAbbrevs(C, COMMENTS_BLOCK_ID)) {
2633 Error("malformed comments block in AST file");
Ben Langmuir2c9af442014-04-10 17:57:43 +00002634 return Failure;
Guy Benyei11169dd2012-12-18 14:30:41 +00002635 }
2636 CommentsCursors.push_back(std::make_pair(C, &F));
2637 break;
2638 }
Chris Lattnere7b154b2013-01-19 21:39:22 +00002639
Guy Benyei11169dd2012-12-18 14:30:41 +00002640 default:
Chris Lattnere7b154b2013-01-19 21:39:22 +00002641 if (Stream.SkipBlock()) {
2642 Error("malformed block record in AST file");
Ben Langmuir2c9af442014-04-10 17:57:43 +00002643 return Failure;
Chris Lattnere7b154b2013-01-19 21:39:22 +00002644 }
2645 break;
Guy Benyei11169dd2012-12-18 14:30:41 +00002646 }
2647 continue;
Chris Lattnere7b154b2013-01-19 21:39:22 +00002648
2649 case llvm::BitstreamEntry::Record:
2650 // The interesting case.
2651 break;
Guy Benyei11169dd2012-12-18 14:30:41 +00002652 }
2653
2654 // Read and process a record.
2655 Record.clear();
Chris Lattner0e6c9402013-01-20 02:38:54 +00002656 StringRef Blob;
2657 switch ((ASTRecordTypes)Stream.readRecord(Entry.ID, Record, &Blob)) {
Guy Benyei11169dd2012-12-18 14:30:41 +00002658 default: // Default behavior: ignore.
2659 break;
2660
2661 case TYPE_OFFSET: {
2662 if (F.LocalNumTypes != 0) {
2663 Error("duplicate TYPE_OFFSET record in AST file");
Ben Langmuir2c9af442014-04-10 17:57:43 +00002664 return Failure;
Guy Benyei11169dd2012-12-18 14:30:41 +00002665 }
Chris Lattner0e6c9402013-01-20 02:38:54 +00002666 F.TypeOffsets = (const uint32_t *)Blob.data();
Guy Benyei11169dd2012-12-18 14:30:41 +00002667 F.LocalNumTypes = Record[0];
2668 unsigned LocalBaseTypeIndex = Record[1];
2669 F.BaseTypeIndex = getTotalNumTypes();
2670
2671 if (F.LocalNumTypes > 0) {
2672 // Introduce the global -> local mapping for types within this module.
2673 GlobalTypeMap.insert(std::make_pair(getTotalNumTypes(), &F));
2674
2675 // Introduce the local -> global mapping for types within this module.
2676 F.TypeRemap.insertOrReplace(
2677 std::make_pair(LocalBaseTypeIndex,
2678 F.BaseTypeIndex - LocalBaseTypeIndex));
Ben Langmuir52ca6782014-10-20 16:27:32 +00002679
2680 TypesLoaded.resize(TypesLoaded.size() + F.LocalNumTypes);
Guy Benyei11169dd2012-12-18 14:30:41 +00002681 }
2682 break;
2683 }
2684
2685 case DECL_OFFSET: {
2686 if (F.LocalNumDecls != 0) {
2687 Error("duplicate DECL_OFFSET record in AST file");
Ben Langmuir2c9af442014-04-10 17:57:43 +00002688 return Failure;
Guy Benyei11169dd2012-12-18 14:30:41 +00002689 }
Chris Lattner0e6c9402013-01-20 02:38:54 +00002690 F.DeclOffsets = (const DeclOffset *)Blob.data();
Guy Benyei11169dd2012-12-18 14:30:41 +00002691 F.LocalNumDecls = Record[0];
2692 unsigned LocalBaseDeclID = Record[1];
2693 F.BaseDeclID = getTotalNumDecls();
2694
2695 if (F.LocalNumDecls > 0) {
2696 // Introduce the global -> local mapping for declarations within this
2697 // module.
2698 GlobalDeclMap.insert(
2699 std::make_pair(getTotalNumDecls() + NUM_PREDEF_DECL_IDS, &F));
2700
2701 // Introduce the local -> global mapping for declarations within this
2702 // module.
2703 F.DeclRemap.insertOrReplace(
2704 std::make_pair(LocalBaseDeclID, F.BaseDeclID - LocalBaseDeclID));
2705
2706 // Introduce the global -> local mapping for declarations within this
2707 // module.
2708 F.GlobalToLocalDeclIDs[&F] = LocalBaseDeclID;
Ben Langmuirfe971d92014-08-16 04:54:18 +00002709
Ben Langmuir52ca6782014-10-20 16:27:32 +00002710 DeclsLoaded.resize(DeclsLoaded.size() + F.LocalNumDecls);
2711 }
Guy Benyei11169dd2012-12-18 14:30:41 +00002712 break;
2713 }
2714
2715 case TU_UPDATE_LEXICAL: {
2716 DeclContext *TU = Context.getTranslationUnitDecl();
2717 DeclContextInfo &Info = F.DeclContextInfos[TU];
Chris Lattner0e6c9402013-01-20 02:38:54 +00002718 Info.LexicalDecls = reinterpret_cast<const KindDeclIDPair *>(Blob.data());
Guy Benyei11169dd2012-12-18 14:30:41 +00002719 Info.NumLexicalDecls
Chris Lattner0e6c9402013-01-20 02:38:54 +00002720 = static_cast<unsigned int>(Blob.size() / sizeof(KindDeclIDPair));
Guy Benyei11169dd2012-12-18 14:30:41 +00002721 TU->setHasExternalLexicalStorage(true);
2722 break;
2723 }
2724
2725 case UPDATE_VISIBLE: {
2726 unsigned Idx = 0;
2727 serialization::DeclID ID = ReadDeclID(F, Record, Idx);
2728 ASTDeclContextNameLookupTable *Table =
Justin Bognerda4e6502014-04-14 16:34:29 +00002729 ASTDeclContextNameLookupTable::Create(
2730 (const unsigned char *)Blob.data() + Record[Idx++],
2731 (const unsigned char *)Blob.data() + sizeof(uint32_t),
2732 (const unsigned char *)Blob.data(),
2733 ASTDeclContextNameLookupTrait(*this, F));
Richard Smithcd45dbc2014-04-19 03:48:30 +00002734 if (Decl *D = GetExistingDecl(ID)) {
Richard Smithd9174792014-03-11 03:10:46 +00002735 auto *DC = cast<DeclContext>(D);
2736 DC->getPrimaryContext()->setHasExternalVisibleStorage(true);
Richard Smith52e3fba2014-03-11 07:17:35 +00002737 auto *&LookupTable = F.DeclContextInfos[DC].NameLookupTableData;
2738 delete LookupTable;
2739 LookupTable = Table;
Guy Benyei11169dd2012-12-18 14:30:41 +00002740 } else
2741 PendingVisibleUpdates[ID].push_back(std::make_pair(Table, &F));
2742 break;
2743 }
2744
2745 case IDENTIFIER_TABLE:
Chris Lattner0e6c9402013-01-20 02:38:54 +00002746 F.IdentifierTableData = Blob.data();
Guy Benyei11169dd2012-12-18 14:30:41 +00002747 if (Record[0]) {
Justin Bognerda4e6502014-04-14 16:34:29 +00002748 F.IdentifierLookupTable = ASTIdentifierLookupTable::Create(
2749 (const unsigned char *)F.IdentifierTableData + Record[0],
2750 (const unsigned char *)F.IdentifierTableData + sizeof(uint32_t),
2751 (const unsigned char *)F.IdentifierTableData,
2752 ASTIdentifierLookupTrait(*this, F));
Guy Benyei11169dd2012-12-18 14:30:41 +00002753
2754 PP.getIdentifierTable().setExternalIdentifierLookup(this);
2755 }
2756 break;
2757
2758 case IDENTIFIER_OFFSET: {
2759 if (F.LocalNumIdentifiers != 0) {
2760 Error("duplicate IDENTIFIER_OFFSET record in AST file");
Ben Langmuir2c9af442014-04-10 17:57:43 +00002761 return Failure;
Guy Benyei11169dd2012-12-18 14:30:41 +00002762 }
Chris Lattner0e6c9402013-01-20 02:38:54 +00002763 F.IdentifierOffsets = (const uint32_t *)Blob.data();
Guy Benyei11169dd2012-12-18 14:30:41 +00002764 F.LocalNumIdentifiers = Record[0];
2765 unsigned LocalBaseIdentifierID = Record[1];
2766 F.BaseIdentifierID = getTotalNumIdentifiers();
2767
2768 if (F.LocalNumIdentifiers > 0) {
2769 // Introduce the global -> local mapping for identifiers within this
2770 // module.
2771 GlobalIdentifierMap.insert(std::make_pair(getTotalNumIdentifiers() + 1,
2772 &F));
2773
2774 // Introduce the local -> global mapping for identifiers within this
2775 // module.
2776 F.IdentifierRemap.insertOrReplace(
2777 std::make_pair(LocalBaseIdentifierID,
2778 F.BaseIdentifierID - LocalBaseIdentifierID));
Ben Langmuirfe971d92014-08-16 04:54:18 +00002779
Ben Langmuir52ca6782014-10-20 16:27:32 +00002780 IdentifiersLoaded.resize(IdentifiersLoaded.size()
2781 + F.LocalNumIdentifiers);
2782 }
Guy Benyei11169dd2012-12-18 14:30:41 +00002783 break;
2784 }
2785
Ben Langmuir332aafe2014-01-31 01:06:56 +00002786 case EAGERLY_DESERIALIZED_DECLS:
Guy Benyei11169dd2012-12-18 14:30:41 +00002787 for (unsigned I = 0, N = Record.size(); I != N; ++I)
Ben Langmuir332aafe2014-01-31 01:06:56 +00002788 EagerlyDeserializedDecls.push_back(getGlobalDeclID(F, Record[I]));
Guy Benyei11169dd2012-12-18 14:30:41 +00002789 break;
2790
2791 case SPECIAL_TYPES:
Douglas Gregor44180f82013-02-01 23:45:03 +00002792 if (SpecialTypes.empty()) {
2793 for (unsigned I = 0, N = Record.size(); I != N; ++I)
2794 SpecialTypes.push_back(getGlobalTypeID(F, Record[I]));
2795 break;
2796 }
2797
2798 if (SpecialTypes.size() != Record.size()) {
2799 Error("invalid special-types record");
Ben Langmuir2c9af442014-04-10 17:57:43 +00002800 return Failure;
Douglas Gregor44180f82013-02-01 23:45:03 +00002801 }
2802
2803 for (unsigned I = 0, N = Record.size(); I != N; ++I) {
2804 serialization::TypeID ID = getGlobalTypeID(F, Record[I]);
2805 if (!SpecialTypes[I])
2806 SpecialTypes[I] = ID;
2807 // FIXME: If ID && SpecialTypes[I] != ID, do we need a separate
2808 // merge step?
2809 }
Guy Benyei11169dd2012-12-18 14:30:41 +00002810 break;
2811
2812 case STATISTICS:
2813 TotalNumStatements += Record[0];
2814 TotalNumMacros += Record[1];
2815 TotalLexicalDeclContexts += Record[2];
2816 TotalVisibleDeclContexts += Record[3];
2817 break;
2818
2819 case UNUSED_FILESCOPED_DECLS:
2820 for (unsigned I = 0, N = Record.size(); I != N; ++I)
2821 UnusedFileScopedDecls.push_back(getGlobalDeclID(F, Record[I]));
2822 break;
2823
2824 case DELEGATING_CTORS:
2825 for (unsigned I = 0, N = Record.size(); I != N; ++I)
2826 DelegatingCtorDecls.push_back(getGlobalDeclID(F, Record[I]));
2827 break;
2828
2829 case WEAK_UNDECLARED_IDENTIFIERS:
2830 if (Record.size() % 4 != 0) {
2831 Error("invalid weak identifiers record");
Ben Langmuir2c9af442014-04-10 17:57:43 +00002832 return Failure;
Guy Benyei11169dd2012-12-18 14:30:41 +00002833 }
2834
2835 // FIXME: Ignore weak undeclared identifiers from non-original PCH
2836 // files. This isn't the way to do it :)
2837 WeakUndeclaredIdentifiers.clear();
2838
2839 // Translate the weak, undeclared identifiers into global IDs.
2840 for (unsigned I = 0, N = Record.size(); I < N; /* in loop */) {
2841 WeakUndeclaredIdentifiers.push_back(
2842 getGlobalIdentifierID(F, Record[I++]));
2843 WeakUndeclaredIdentifiers.push_back(
2844 getGlobalIdentifierID(F, Record[I++]));
2845 WeakUndeclaredIdentifiers.push_back(
2846 ReadSourceLocation(F, Record, I).getRawEncoding());
2847 WeakUndeclaredIdentifiers.push_back(Record[I++]);
2848 }
2849 break;
2850
Richard Smith78165b52013-01-10 23:43:47 +00002851 case LOCALLY_SCOPED_EXTERN_C_DECLS:
Guy Benyei11169dd2012-12-18 14:30:41 +00002852 for (unsigned I = 0, N = Record.size(); I != N; ++I)
Richard Smith78165b52013-01-10 23:43:47 +00002853 LocallyScopedExternCDecls.push_back(getGlobalDeclID(F, Record[I]));
Guy Benyei11169dd2012-12-18 14:30:41 +00002854 break;
2855
2856 case SELECTOR_OFFSETS: {
Chris Lattner0e6c9402013-01-20 02:38:54 +00002857 F.SelectorOffsets = (const uint32_t *)Blob.data();
Guy Benyei11169dd2012-12-18 14:30:41 +00002858 F.LocalNumSelectors = Record[0];
2859 unsigned LocalBaseSelectorID = Record[1];
2860 F.BaseSelectorID = getTotalNumSelectors();
2861
2862 if (F.LocalNumSelectors > 0) {
2863 // Introduce the global -> local mapping for selectors within this
2864 // module.
2865 GlobalSelectorMap.insert(std::make_pair(getTotalNumSelectors()+1, &F));
2866
2867 // Introduce the local -> global mapping for selectors within this
2868 // module.
2869 F.SelectorRemap.insertOrReplace(
2870 std::make_pair(LocalBaseSelectorID,
2871 F.BaseSelectorID - LocalBaseSelectorID));
Ben Langmuir52ca6782014-10-20 16:27:32 +00002872
2873 SelectorsLoaded.resize(SelectorsLoaded.size() + F.LocalNumSelectors);
Guy Benyei11169dd2012-12-18 14:30:41 +00002874 }
2875 break;
2876 }
2877
2878 case METHOD_POOL:
Chris Lattner0e6c9402013-01-20 02:38:54 +00002879 F.SelectorLookupTableData = (const unsigned char *)Blob.data();
Guy Benyei11169dd2012-12-18 14:30:41 +00002880 if (Record[0])
2881 F.SelectorLookupTable
2882 = ASTSelectorLookupTable::Create(
2883 F.SelectorLookupTableData + Record[0],
2884 F.SelectorLookupTableData,
2885 ASTSelectorLookupTrait(*this, F));
2886 TotalNumMethodPoolEntries += Record[1];
2887 break;
2888
2889 case REFERENCED_SELECTOR_POOL:
2890 if (!Record.empty()) {
2891 for (unsigned Idx = 0, N = Record.size() - 1; Idx < N; /* in loop */) {
2892 ReferencedSelectorsData.push_back(getGlobalSelectorID(F,
2893 Record[Idx++]));
2894 ReferencedSelectorsData.push_back(ReadSourceLocation(F, Record, Idx).
2895 getRawEncoding());
2896 }
2897 }
2898 break;
2899
2900 case PP_COUNTER_VALUE:
2901 if (!Record.empty() && Listener)
2902 Listener->ReadCounter(F, Record[0]);
2903 break;
2904
2905 case FILE_SORTED_DECLS:
Chris Lattner0e6c9402013-01-20 02:38:54 +00002906 F.FileSortedDecls = (const DeclID *)Blob.data();
Guy Benyei11169dd2012-12-18 14:30:41 +00002907 F.NumFileSortedDecls = Record[0];
2908 break;
2909
2910 case SOURCE_LOCATION_OFFSETS: {
Chris Lattner0e6c9402013-01-20 02:38:54 +00002911 F.SLocEntryOffsets = (const uint32_t *)Blob.data();
Guy Benyei11169dd2012-12-18 14:30:41 +00002912 F.LocalNumSLocEntries = Record[0];
2913 unsigned SLocSpaceSize = Record[1];
Benjamin Kramer867ea1d2014-03-02 13:01:17 +00002914 std::tie(F.SLocEntryBaseID, F.SLocEntryBaseOffset) =
Ben Langmuir52ca6782014-10-20 16:27:32 +00002915 SourceMgr.AllocateLoadedSLocEntries(F.LocalNumSLocEntries,
Guy Benyei11169dd2012-12-18 14:30:41 +00002916 SLocSpaceSize);
2917 // Make our entry in the range map. BaseID is negative and growing, so
2918 // we invert it. Because we invert it, though, we need the other end of
2919 // the range.
2920 unsigned RangeStart =
2921 unsigned(-F.SLocEntryBaseID) - F.LocalNumSLocEntries + 1;
2922 GlobalSLocEntryMap.insert(std::make_pair(RangeStart, &F));
2923 F.FirstLoc = SourceLocation::getFromRawEncoding(F.SLocEntryBaseOffset);
2924
2925 // SLocEntryBaseOffset is lower than MaxLoadedOffset and decreasing.
2926 assert((F.SLocEntryBaseOffset & (1U << 31U)) == 0);
2927 GlobalSLocOffsetMap.insert(
2928 std::make_pair(SourceManager::MaxLoadedOffset - F.SLocEntryBaseOffset
2929 - SLocSpaceSize,&F));
2930
2931 // Initialize the remapping table.
2932 // Invalid stays invalid.
Richard Smithb9eab6d2014-03-20 19:44:17 +00002933 F.SLocRemap.insertOrReplace(std::make_pair(0U, 0));
Guy Benyei11169dd2012-12-18 14:30:41 +00002934 // This module. Base was 2 when being compiled.
Richard Smithb9eab6d2014-03-20 19:44:17 +00002935 F.SLocRemap.insertOrReplace(std::make_pair(2U,
Guy Benyei11169dd2012-12-18 14:30:41 +00002936 static_cast<int>(F.SLocEntryBaseOffset - 2)));
2937
2938 TotalNumSLocEntries += F.LocalNumSLocEntries;
2939 break;
2940 }
2941
2942 case MODULE_OFFSET_MAP: {
2943 // Additional remapping information.
Chris Lattner0e6c9402013-01-20 02:38:54 +00002944 const unsigned char *Data = (const unsigned char*)Blob.data();
2945 const unsigned char *DataEnd = Data + Blob.size();
Richard Smithb9eab6d2014-03-20 19:44:17 +00002946
2947 // If we see this entry before SOURCE_LOCATION_OFFSETS, add placeholders.
2948 if (F.SLocRemap.find(0) == F.SLocRemap.end()) {
2949 F.SLocRemap.insert(std::make_pair(0U, 0));
2950 F.SLocRemap.insert(std::make_pair(2U, 1));
2951 }
2952
Guy Benyei11169dd2012-12-18 14:30:41 +00002953 // Continuous range maps we may be updating in our module.
Ben Langmuir785180e2014-10-20 16:27:30 +00002954 typedef ContinuousRangeMap<uint32_t, int, 2>::Builder
2955 RemapBuilder;
2956 RemapBuilder SLocRemap(F.SLocRemap);
2957 RemapBuilder IdentifierRemap(F.IdentifierRemap);
2958 RemapBuilder MacroRemap(F.MacroRemap);
2959 RemapBuilder PreprocessedEntityRemap(F.PreprocessedEntityRemap);
2960 RemapBuilder SubmoduleRemap(F.SubmoduleRemap);
2961 RemapBuilder SelectorRemap(F.SelectorRemap);
2962 RemapBuilder DeclRemap(F.DeclRemap);
2963 RemapBuilder TypeRemap(F.TypeRemap);
Guy Benyei11169dd2012-12-18 14:30:41 +00002964
2965 while(Data < DataEnd) {
Justin Bogner57ba0b22014-03-28 22:03:24 +00002966 using namespace llvm::support;
2967 uint16_t Len = endian::readNext<uint16_t, little, unaligned>(Data);
Guy Benyei11169dd2012-12-18 14:30:41 +00002968 StringRef Name = StringRef((const char*)Data, Len);
2969 Data += Len;
2970 ModuleFile *OM = ModuleMgr.lookup(Name);
2971 if (!OM) {
2972 Error("SourceLocation remap refers to unknown module");
Ben Langmuir2c9af442014-04-10 17:57:43 +00002973 return Failure;
Guy Benyei11169dd2012-12-18 14:30:41 +00002974 }
2975
Justin Bogner57ba0b22014-03-28 22:03:24 +00002976 uint32_t SLocOffset =
2977 endian::readNext<uint32_t, little, unaligned>(Data);
2978 uint32_t IdentifierIDOffset =
2979 endian::readNext<uint32_t, little, unaligned>(Data);
2980 uint32_t MacroIDOffset =
2981 endian::readNext<uint32_t, little, unaligned>(Data);
2982 uint32_t PreprocessedEntityIDOffset =
2983 endian::readNext<uint32_t, little, unaligned>(Data);
2984 uint32_t SubmoduleIDOffset =
2985 endian::readNext<uint32_t, little, unaligned>(Data);
2986 uint32_t SelectorIDOffset =
2987 endian::readNext<uint32_t, little, unaligned>(Data);
2988 uint32_t DeclIDOffset =
2989 endian::readNext<uint32_t, little, unaligned>(Data);
2990 uint32_t TypeIndexOffset =
2991 endian::readNext<uint32_t, little, unaligned>(Data);
2992
Ben Langmuir785180e2014-10-20 16:27:30 +00002993 uint32_t None = std::numeric_limits<uint32_t>::max();
2994
2995 auto mapOffset = [&](uint32_t Offset, uint32_t BaseOffset,
2996 RemapBuilder &Remap) {
2997 if (Offset != None)
2998 Remap.insert(std::make_pair(Offset,
2999 static_cast<int>(BaseOffset - Offset)));
3000 };
3001 mapOffset(SLocOffset, OM->SLocEntryBaseOffset, SLocRemap);
3002 mapOffset(IdentifierIDOffset, OM->BaseIdentifierID, IdentifierRemap);
3003 mapOffset(MacroIDOffset, OM->BaseMacroID, MacroRemap);
3004 mapOffset(PreprocessedEntityIDOffset, OM->BasePreprocessedEntityID,
3005 PreprocessedEntityRemap);
3006 mapOffset(SubmoduleIDOffset, OM->BaseSubmoduleID, SubmoduleRemap);
3007 mapOffset(SelectorIDOffset, OM->BaseSelectorID, SelectorRemap);
3008 mapOffset(DeclIDOffset, OM->BaseDeclID, DeclRemap);
3009 mapOffset(TypeIndexOffset, OM->BaseTypeIndex, TypeRemap);
Guy Benyei11169dd2012-12-18 14:30:41 +00003010
3011 // Global -> local mappings.
3012 F.GlobalToLocalDeclIDs[OM] = DeclIDOffset;
3013 }
3014 break;
3015 }
3016
3017 case SOURCE_MANAGER_LINE_TABLE:
3018 if (ParseLineTable(F, Record))
Ben Langmuir2c9af442014-04-10 17:57:43 +00003019 return Failure;
Guy Benyei11169dd2012-12-18 14:30:41 +00003020 break;
3021
3022 case SOURCE_LOCATION_PRELOADS: {
3023 // Need to transform from the local view (1-based IDs) to the global view,
3024 // which is based off F.SLocEntryBaseID.
3025 if (!F.PreloadSLocEntries.empty()) {
3026 Error("Multiple SOURCE_LOCATION_PRELOADS records in AST file");
Ben Langmuir2c9af442014-04-10 17:57:43 +00003027 return Failure;
Guy Benyei11169dd2012-12-18 14:30:41 +00003028 }
3029
3030 F.PreloadSLocEntries.swap(Record);
3031 break;
3032 }
3033
3034 case EXT_VECTOR_DECLS:
3035 for (unsigned I = 0, N = Record.size(); I != N; ++I)
3036 ExtVectorDecls.push_back(getGlobalDeclID(F, Record[I]));
3037 break;
3038
3039 case VTABLE_USES:
3040 if (Record.size() % 3 != 0) {
3041 Error("Invalid VTABLE_USES record");
Ben Langmuir2c9af442014-04-10 17:57:43 +00003042 return Failure;
Guy Benyei11169dd2012-12-18 14:30:41 +00003043 }
3044
3045 // Later tables overwrite earlier ones.
3046 // FIXME: Modules will have some trouble with this. This is clearly not
3047 // the right way to do this.
3048 VTableUses.clear();
3049
3050 for (unsigned Idx = 0, N = Record.size(); Idx != N; /* In loop */) {
3051 VTableUses.push_back(getGlobalDeclID(F, Record[Idx++]));
3052 VTableUses.push_back(
3053 ReadSourceLocation(F, Record, Idx).getRawEncoding());
3054 VTableUses.push_back(Record[Idx++]);
3055 }
3056 break;
3057
3058 case DYNAMIC_CLASSES:
3059 for (unsigned I = 0, N = Record.size(); I != N; ++I)
3060 DynamicClasses.push_back(getGlobalDeclID(F, Record[I]));
3061 break;
3062
3063 case PENDING_IMPLICIT_INSTANTIATIONS:
3064 if (PendingInstantiations.size() % 2 != 0) {
3065 Error("Invalid existing PendingInstantiations");
Ben Langmuir2c9af442014-04-10 17:57:43 +00003066 return Failure;
Guy Benyei11169dd2012-12-18 14:30:41 +00003067 }
3068
3069 if (Record.size() % 2 != 0) {
3070 Error("Invalid PENDING_IMPLICIT_INSTANTIATIONS block");
Ben Langmuir2c9af442014-04-10 17:57:43 +00003071 return Failure;
Guy Benyei11169dd2012-12-18 14:30:41 +00003072 }
3073
3074 for (unsigned I = 0, N = Record.size(); I != N; /* in loop */) {
3075 PendingInstantiations.push_back(getGlobalDeclID(F, Record[I++]));
3076 PendingInstantiations.push_back(
3077 ReadSourceLocation(F, Record, I).getRawEncoding());
3078 }
3079 break;
3080
3081 case SEMA_DECL_REFS:
Richard Smith3d8e97e2013-10-18 06:54:39 +00003082 if (Record.size() != 2) {
3083 Error("Invalid SEMA_DECL_REFS block");
Ben Langmuir2c9af442014-04-10 17:57:43 +00003084 return Failure;
Richard Smith3d8e97e2013-10-18 06:54:39 +00003085 }
Guy Benyei11169dd2012-12-18 14:30:41 +00003086 for (unsigned I = 0, N = Record.size(); I != N; ++I)
3087 SemaDeclRefs.push_back(getGlobalDeclID(F, Record[I]));
3088 break;
3089
3090 case PPD_ENTITIES_OFFSETS: {
Chris Lattner0e6c9402013-01-20 02:38:54 +00003091 F.PreprocessedEntityOffsets = (const PPEntityOffset *)Blob.data();
3092 assert(Blob.size() % sizeof(PPEntityOffset) == 0);
3093 F.NumPreprocessedEntities = Blob.size() / sizeof(PPEntityOffset);
Guy Benyei11169dd2012-12-18 14:30:41 +00003094
3095 unsigned LocalBasePreprocessedEntityID = Record[0];
3096
3097 unsigned StartingID;
3098 if (!PP.getPreprocessingRecord())
3099 PP.createPreprocessingRecord();
3100 if (!PP.getPreprocessingRecord()->getExternalSource())
3101 PP.getPreprocessingRecord()->SetExternalSource(*this);
3102 StartingID
3103 = PP.getPreprocessingRecord()
Ben Langmuir52ca6782014-10-20 16:27:32 +00003104 ->allocateLoadedEntities(F.NumPreprocessedEntities);
Guy Benyei11169dd2012-12-18 14:30:41 +00003105 F.BasePreprocessedEntityID = StartingID;
3106
3107 if (F.NumPreprocessedEntities > 0) {
3108 // Introduce the global -> local mapping for preprocessed entities in
3109 // this module.
3110 GlobalPreprocessedEntityMap.insert(std::make_pair(StartingID, &F));
3111
3112 // Introduce the local -> global mapping for preprocessed entities in
3113 // this module.
3114 F.PreprocessedEntityRemap.insertOrReplace(
3115 std::make_pair(LocalBasePreprocessedEntityID,
3116 F.BasePreprocessedEntityID - LocalBasePreprocessedEntityID));
3117 }
3118
3119 break;
3120 }
3121
3122 case DECL_UPDATE_OFFSETS: {
3123 if (Record.size() % 2 != 0) {
3124 Error("invalid DECL_UPDATE_OFFSETS block in AST file");
Ben Langmuir2c9af442014-04-10 17:57:43 +00003125 return Failure;
Guy Benyei11169dd2012-12-18 14:30:41 +00003126 }
Richard Smithcd45dbc2014-04-19 03:48:30 +00003127 for (unsigned I = 0, N = Record.size(); I != N; I += 2) {
3128 GlobalDeclID ID = getGlobalDeclID(F, Record[I]);
3129 DeclUpdateOffsets[ID].push_back(std::make_pair(&F, Record[I + 1]));
3130
3131 // If we've already loaded the decl, perform the updates when we finish
3132 // loading this block.
3133 if (Decl *D = GetExistingDecl(ID))
3134 PendingUpdateRecords.push_back(std::make_pair(ID, D));
3135 }
Guy Benyei11169dd2012-12-18 14:30:41 +00003136 break;
3137 }
3138
3139 case DECL_REPLACEMENTS: {
3140 if (Record.size() % 3 != 0) {
3141 Error("invalid DECL_REPLACEMENTS block in AST file");
Ben Langmuir2c9af442014-04-10 17:57:43 +00003142 return Failure;
Guy Benyei11169dd2012-12-18 14:30:41 +00003143 }
3144 for (unsigned I = 0, N = Record.size(); I != N; I += 3)
3145 ReplacedDecls[getGlobalDeclID(F, Record[I])]
3146 = ReplacedDeclInfo(&F, Record[I+1], Record[I+2]);
3147 break;
3148 }
3149
3150 case OBJC_CATEGORIES_MAP: {
3151 if (F.LocalNumObjCCategoriesInMap != 0) {
3152 Error("duplicate OBJC_CATEGORIES_MAP record in AST file");
Ben Langmuir2c9af442014-04-10 17:57:43 +00003153 return Failure;
Guy Benyei11169dd2012-12-18 14:30:41 +00003154 }
3155
3156 F.LocalNumObjCCategoriesInMap = Record[0];
Chris Lattner0e6c9402013-01-20 02:38:54 +00003157 F.ObjCCategoriesMap = (const ObjCCategoriesInfo *)Blob.data();
Guy Benyei11169dd2012-12-18 14:30:41 +00003158 break;
3159 }
3160
3161 case OBJC_CATEGORIES:
3162 F.ObjCCategories.swap(Record);
3163 break;
3164
3165 case CXX_BASE_SPECIFIER_OFFSETS: {
3166 if (F.LocalNumCXXBaseSpecifiers != 0) {
3167 Error("duplicate CXX_BASE_SPECIFIER_OFFSETS record in AST file");
Ben Langmuir2c9af442014-04-10 17:57:43 +00003168 return Failure;
Guy Benyei11169dd2012-12-18 14:30:41 +00003169 }
3170
3171 F.LocalNumCXXBaseSpecifiers = Record[0];
Chris Lattner0e6c9402013-01-20 02:38:54 +00003172 F.CXXBaseSpecifiersOffsets = (const uint32_t *)Blob.data();
Guy Benyei11169dd2012-12-18 14:30:41 +00003173 NumCXXBaseSpecifiersLoaded += F.LocalNumCXXBaseSpecifiers;
3174 break;
3175 }
3176
3177 case DIAG_PRAGMA_MAPPINGS:
3178 if (F.PragmaDiagMappings.empty())
3179 F.PragmaDiagMappings.swap(Record);
3180 else
3181 F.PragmaDiagMappings.insert(F.PragmaDiagMappings.end(),
3182 Record.begin(), Record.end());
3183 break;
3184
3185 case CUDA_SPECIAL_DECL_REFS:
3186 // Later tables overwrite earlier ones.
3187 // FIXME: Modules will have trouble with this.
3188 CUDASpecialDeclRefs.clear();
3189 for (unsigned I = 0, N = Record.size(); I != N; ++I)
3190 CUDASpecialDeclRefs.push_back(getGlobalDeclID(F, Record[I]));
3191 break;
3192
3193 case HEADER_SEARCH_TABLE: {
Chris Lattner0e6c9402013-01-20 02:38:54 +00003194 F.HeaderFileInfoTableData = Blob.data();
Guy Benyei11169dd2012-12-18 14:30:41 +00003195 F.LocalNumHeaderFileInfos = Record[1];
Guy Benyei11169dd2012-12-18 14:30:41 +00003196 if (Record[0]) {
3197 F.HeaderFileInfoTable
3198 = HeaderFileInfoLookupTable::Create(
3199 (const unsigned char *)F.HeaderFileInfoTableData + Record[0],
3200 (const unsigned char *)F.HeaderFileInfoTableData,
3201 HeaderFileInfoTrait(*this, F,
3202 &PP.getHeaderSearchInfo(),
Chris Lattner0e6c9402013-01-20 02:38:54 +00003203 Blob.data() + Record[2]));
Guy Benyei11169dd2012-12-18 14:30:41 +00003204
3205 PP.getHeaderSearchInfo().SetExternalSource(this);
3206 if (!PP.getHeaderSearchInfo().getExternalLookup())
3207 PP.getHeaderSearchInfo().SetExternalLookup(this);
3208 }
3209 break;
3210 }
3211
3212 case FP_PRAGMA_OPTIONS:
3213 // Later tables overwrite earlier ones.
3214 FPPragmaOptions.swap(Record);
3215 break;
3216
3217 case OPENCL_EXTENSIONS:
3218 // Later tables overwrite earlier ones.
3219 OpenCLExtensions.swap(Record);
3220 break;
3221
3222 case TENTATIVE_DEFINITIONS:
3223 for (unsigned I = 0, N = Record.size(); I != N; ++I)
3224 TentativeDefinitions.push_back(getGlobalDeclID(F, Record[I]));
3225 break;
3226
3227 case KNOWN_NAMESPACES:
3228 for (unsigned I = 0, N = Record.size(); I != N; ++I)
3229 KnownNamespaces.push_back(getGlobalDeclID(F, Record[I]));
3230 break;
Nick Lewycky8334af82013-01-26 00:35:08 +00003231
Nick Lewycky9c7eb1d2013-02-01 08:13:20 +00003232 case UNDEFINED_BUT_USED:
3233 if (UndefinedButUsed.size() % 2 != 0) {
3234 Error("Invalid existing UndefinedButUsed");
Ben Langmuir2c9af442014-04-10 17:57:43 +00003235 return Failure;
Nick Lewycky8334af82013-01-26 00:35:08 +00003236 }
3237
3238 if (Record.size() % 2 != 0) {
Nick Lewycky9c7eb1d2013-02-01 08:13:20 +00003239 Error("invalid undefined-but-used record");
Ben Langmuir2c9af442014-04-10 17:57:43 +00003240 return Failure;
Nick Lewycky8334af82013-01-26 00:35:08 +00003241 }
3242 for (unsigned I = 0, N = Record.size(); I != N; /* in loop */) {
Nick Lewycky9c7eb1d2013-02-01 08:13:20 +00003243 UndefinedButUsed.push_back(getGlobalDeclID(F, Record[I++]));
3244 UndefinedButUsed.push_back(
Nick Lewycky8334af82013-01-26 00:35:08 +00003245 ReadSourceLocation(F, Record, I).getRawEncoding());
3246 }
3247 break;
3248
Guy Benyei11169dd2012-12-18 14:30:41 +00003249 case IMPORTED_MODULES: {
Richard Smithe842a472014-10-22 02:05:46 +00003250 if (F.Kind != MK_ImplicitModule && F.Kind != MK_ExplicitModule) {
Guy Benyei11169dd2012-12-18 14:30:41 +00003251 // If we aren't loading a module (which has its own exports), make
3252 // all of the imported modules visible.
3253 // FIXME: Deal with macros-only imports.
Richard Smith56be7542014-03-21 00:33:59 +00003254 for (unsigned I = 0, N = Record.size(); I != N; /**/) {
3255 unsigned GlobalID = getGlobalSubmoduleID(F, Record[I++]);
3256 SourceLocation Loc = ReadSourceLocation(F, Record, I);
3257 if (GlobalID)
Aaron Ballman4f45b712014-03-21 15:22:56 +00003258 ImportedModules.push_back(ImportedSubmodule(GlobalID, Loc));
Guy Benyei11169dd2012-12-18 14:30:41 +00003259 }
3260 }
3261 break;
3262 }
3263
3264 case LOCAL_REDECLARATIONS: {
3265 F.RedeclarationChains.swap(Record);
3266 break;
3267 }
3268
3269 case LOCAL_REDECLARATIONS_MAP: {
3270 if (F.LocalNumRedeclarationsInMap != 0) {
3271 Error("duplicate LOCAL_REDECLARATIONS_MAP record in AST file");
Ben Langmuir2c9af442014-04-10 17:57:43 +00003272 return Failure;
Guy Benyei11169dd2012-12-18 14:30:41 +00003273 }
3274
3275 F.LocalNumRedeclarationsInMap = Record[0];
Chris Lattner0e6c9402013-01-20 02:38:54 +00003276 F.RedeclarationsMap = (const LocalRedeclarationsInfo *)Blob.data();
Guy Benyei11169dd2012-12-18 14:30:41 +00003277 break;
3278 }
3279
3280 case MERGED_DECLARATIONS: {
3281 for (unsigned Idx = 0; Idx < Record.size(); /* increment in loop */) {
3282 GlobalDeclID CanonID = getGlobalDeclID(F, Record[Idx++]);
3283 SmallVectorImpl<GlobalDeclID> &Decls = StoredMergedDecls[CanonID];
3284 for (unsigned N = Record[Idx++]; N > 0; --N)
3285 Decls.push_back(getGlobalDeclID(F, Record[Idx++]));
3286 }
3287 break;
3288 }
3289
3290 case MACRO_OFFSET: {
3291 if (F.LocalNumMacros != 0) {
3292 Error("duplicate MACRO_OFFSET record in AST file");
Ben Langmuir2c9af442014-04-10 17:57:43 +00003293 return Failure;
Guy Benyei11169dd2012-12-18 14:30:41 +00003294 }
Chris Lattner0e6c9402013-01-20 02:38:54 +00003295 F.MacroOffsets = (const uint32_t *)Blob.data();
Guy Benyei11169dd2012-12-18 14:30:41 +00003296 F.LocalNumMacros = Record[0];
3297 unsigned LocalBaseMacroID = Record[1];
3298 F.BaseMacroID = getTotalNumMacros();
3299
3300 if (F.LocalNumMacros > 0) {
3301 // Introduce the global -> local mapping for macros within this module.
3302 GlobalMacroMap.insert(std::make_pair(getTotalNumMacros() + 1, &F));
3303
3304 // Introduce the local -> global mapping for macros within this module.
3305 F.MacroRemap.insertOrReplace(
3306 std::make_pair(LocalBaseMacroID,
3307 F.BaseMacroID - LocalBaseMacroID));
Ben Langmuir52ca6782014-10-20 16:27:32 +00003308
3309 MacrosLoaded.resize(MacrosLoaded.size() + F.LocalNumMacros);
Guy Benyei11169dd2012-12-18 14:30:41 +00003310 }
3311 break;
3312 }
3313
Argyrios Kyrtzidiseb663da2013-03-22 21:12:57 +00003314 case MACRO_TABLE: {
3315 // FIXME: Not used yet.
Guy Benyei11169dd2012-12-18 14:30:41 +00003316 break;
3317 }
Richard Smithe40f2ba2013-08-07 21:41:30 +00003318
3319 case LATE_PARSED_TEMPLATE: {
3320 LateParsedTemplates.append(Record.begin(), Record.end());
3321 break;
3322 }
Dario Domizioli13a0a382014-05-23 12:13:25 +00003323
3324 case OPTIMIZE_PRAGMA_OPTIONS:
3325 if (Record.size() != 1) {
3326 Error("invalid pragma optimize record");
3327 return Failure;
3328 }
3329 OptimizeOffPragmaLocation = ReadSourceLocation(F, Record[0]);
3330 break;
Nico Weber72889432014-09-06 01:25:55 +00003331
3332 case UNUSED_LOCAL_TYPEDEF_NAME_CANDIDATES:
3333 for (unsigned I = 0, N = Record.size(); I != N; ++I)
3334 UnusedLocalTypedefNameCandidates.push_back(
3335 getGlobalDeclID(F, Record[I]));
3336 break;
Guy Benyei11169dd2012-12-18 14:30:41 +00003337 }
3338 }
Guy Benyei11169dd2012-12-18 14:30:41 +00003339}
3340
Ben Langmuir4b8a9e92014-08-12 16:42:33 +00003341ASTReader::ASTReadResult
3342ASTReader::ReadModuleMapFileBlock(RecordData &Record, ModuleFile &F,
3343 const ModuleFile *ImportedBy,
3344 unsigned ClientLoadCapabilities) {
3345 unsigned Idx = 0;
3346 F.ModuleMapPath = ReadString(Record, Idx);
3347
Richard Smithe842a472014-10-22 02:05:46 +00003348 if (F.Kind == MK_ExplicitModule) {
3349 // For an explicitly-loaded module, we don't care whether the original
3350 // module map file exists or matches.
3351 return Success;
3352 }
3353
Ben Langmuir4b8a9e92014-08-12 16:42:33 +00003354 // Try to resolve ModuleName in the current header search context and
3355 // verify that it is found in the same module map file as we saved. If the
3356 // top-level AST file is a main file, skip this check because there is no
3357 // usable header search context.
3358 assert(!F.ModuleName.empty() &&
Richard Smithe842a472014-10-22 02:05:46 +00003359 "MODULE_NAME should come before MODULE_MAP_FILE");
3360 if (F.Kind == MK_ImplicitModule &&
3361 (*ModuleMgr.begin())->Kind != MK_MainFile) {
3362 // An implicitly-loaded module file should have its module listed in some
3363 // module map file that we've already loaded.
Ben Langmuir4b8a9e92014-08-12 16:42:33 +00003364 Module *M = PP.getHeaderSearchInfo().lookupModule(F.ModuleName);
Richard Smithe842a472014-10-22 02:05:46 +00003365 auto &Map = PP.getHeaderSearchInfo().getModuleMap();
3366 const FileEntry *ModMap = M ? Map.getModuleMapFileForUniquing(M) : nullptr;
3367 if (!ModMap) {
Ben Langmuir4b8a9e92014-08-12 16:42:33 +00003368 assert(ImportedBy && "top-level import should be verified");
3369 if ((ClientLoadCapabilities & ARR_Missing) == 0)
Richard Smithe842a472014-10-22 02:05:46 +00003370 Diag(diag::err_imported_module_not_found) << F.ModuleName << F.FileName
3371 << ImportedBy->FileName
3372 << F.ModuleMapPath;
Ben Langmuir4b8a9e92014-08-12 16:42:33 +00003373 return Missing;
3374 }
3375
Richard Smithe842a472014-10-22 02:05:46 +00003376 assert(M->Name == F.ModuleName && "found module with different name");
3377
Ben Langmuir4b8a9e92014-08-12 16:42:33 +00003378 // Check the primary module map file.
Ben Langmuir4b8a9e92014-08-12 16:42:33 +00003379 const FileEntry *StoredModMap = FileMgr.getFile(F.ModuleMapPath);
Ben Langmuir4b8a9e92014-08-12 16:42:33 +00003380 if (StoredModMap == nullptr || StoredModMap != ModMap) {
3381 assert(ModMap && "found module is missing module map file");
Ben Langmuir4b8a9e92014-08-12 16:42:33 +00003382 assert(ImportedBy && "top-level import should be verified");
3383 if ((ClientLoadCapabilities & ARR_OutOfDate) == 0)
3384 Diag(diag::err_imported_module_modmap_changed)
3385 << F.ModuleName << ImportedBy->FileName
3386 << ModMap->getName() << F.ModuleMapPath;
3387 return OutOfDate;
3388 }
3389
3390 llvm::SmallPtrSet<const FileEntry *, 1> AdditionalStoredMaps;
3391 for (unsigned I = 0, N = Record[Idx++]; I < N; ++I) {
3392 // FIXME: we should use input files rather than storing names.
3393 std::string Filename = ReadString(Record, Idx);
3394 const FileEntry *F =
3395 FileMgr.getFile(Filename, false, false);
3396 if (F == nullptr) {
3397 if ((ClientLoadCapabilities & ARR_OutOfDate) == 0)
3398 Error("could not find file '" + Filename +"' referenced by AST file");
3399 return OutOfDate;
3400 }
3401 AdditionalStoredMaps.insert(F);
3402 }
3403
3404 // Check any additional module map files (e.g. module.private.modulemap)
3405 // that are not in the pcm.
3406 if (auto *AdditionalModuleMaps = Map.getAdditionalModuleMapFiles(M)) {
3407 for (const FileEntry *ModMap : *AdditionalModuleMaps) {
3408 // Remove files that match
3409 // Note: SmallPtrSet::erase is really remove
3410 if (!AdditionalStoredMaps.erase(ModMap)) {
3411 if ((ClientLoadCapabilities & ARR_OutOfDate) == 0)
3412 Diag(diag::err_module_different_modmap)
3413 << F.ModuleName << /*new*/0 << ModMap->getName();
3414 return OutOfDate;
3415 }
3416 }
3417 }
3418
3419 // Check any additional module map files that are in the pcm, but not
3420 // found in header search. Cases that match are already removed.
3421 for (const FileEntry *ModMap : AdditionalStoredMaps) {
3422 if ((ClientLoadCapabilities & ARR_OutOfDate) == 0)
3423 Diag(diag::err_module_different_modmap)
3424 << F.ModuleName << /*not new*/1 << ModMap->getName();
3425 return OutOfDate;
3426 }
3427 }
3428
3429 if (Listener)
3430 Listener->ReadModuleMapFile(F.ModuleMapPath);
3431 return Success;
3432}
3433
3434
Douglas Gregorc1489562013-02-12 23:36:21 +00003435/// \brief Move the given method to the back of the global list of methods.
3436static void moveMethodToBackOfGlobalList(Sema &S, ObjCMethodDecl *Method) {
3437 // Find the entry for this selector in the method pool.
3438 Sema::GlobalMethodPool::iterator Known
3439 = S.MethodPool.find(Method->getSelector());
3440 if (Known == S.MethodPool.end())
3441 return;
3442
3443 // Retrieve the appropriate method list.
3444 ObjCMethodList &Start = Method->isInstanceMethod()? Known->second.first
3445 : Known->second.second;
3446 bool Found = false;
Argyrios Kyrtzidisd3da6e02013-04-17 00:08:58 +00003447 for (ObjCMethodList *List = &Start; List; List = List->getNext()) {
Douglas Gregorc1489562013-02-12 23:36:21 +00003448 if (!Found) {
3449 if (List->Method == Method) {
3450 Found = true;
3451 } else {
3452 // Keep searching.
3453 continue;
3454 }
3455 }
3456
Argyrios Kyrtzidisd3da6e02013-04-17 00:08:58 +00003457 if (List->getNext())
3458 List->Method = List->getNext()->Method;
Douglas Gregorc1489562013-02-12 23:36:21 +00003459 else
3460 List->Method = Method;
3461 }
3462}
3463
Richard Smithe657bbd2014-07-18 22:13:40 +00003464void ASTReader::makeNamesVisible(const HiddenNames &Names, Module *Owner,
3465 bool FromFinalization) {
3466 // FIXME: Only do this if Owner->NameVisibility == AllVisible.
Richard Smith57721ac2014-07-21 04:10:40 +00003467 for (Decl *D : Names.HiddenDecls) {
Richard Smith49f906a2014-03-01 00:08:04 +00003468 bool wasHidden = D->Hidden;
3469 D->Hidden = false;
Guy Benyei11169dd2012-12-18 14:30:41 +00003470
Richard Smith49f906a2014-03-01 00:08:04 +00003471 if (wasHidden && SemaObj) {
3472 if (ObjCMethodDecl *Method = dyn_cast<ObjCMethodDecl>(D)) {
3473 moveMethodToBackOfGlobalList(*SemaObj, Method);
Douglas Gregorc1489562013-02-12 23:36:21 +00003474 }
Guy Benyei11169dd2012-12-18 14:30:41 +00003475 }
3476 }
Richard Smith49f906a2014-03-01 00:08:04 +00003477
Richard Smithe657bbd2014-07-18 22:13:40 +00003478 assert((FromFinalization || Owner->NameVisibility >= Module::MacrosVisible) &&
3479 "nothing to make visible?");
Richard Smithdaa69e02014-07-25 04:40:03 +00003480 for (const auto &Macro : Names.HiddenMacros) {
3481 if (FromFinalization)
3482 PP.appendMacroDirective(Macro.first,
3483 Macro.second->import(PP, SourceLocation()));
3484 else
3485 installImportedMacro(Macro.first, Macro.second, Owner);
3486 }
Guy Benyei11169dd2012-12-18 14:30:41 +00003487}
3488
Richard Smith49f906a2014-03-01 00:08:04 +00003489void ASTReader::makeModuleVisible(Module *Mod,
Argyrios Kyrtzidis125df052013-02-01 16:36:12 +00003490 Module::NameVisibilityKind NameVisibility,
Douglas Gregorfb912652013-03-20 21:10:35 +00003491 SourceLocation ImportLoc,
3492 bool Complain) {
Guy Benyei11169dd2012-12-18 14:30:41 +00003493 llvm::SmallPtrSet<Module *, 4> Visited;
Dmitri Gribenkof8579502013-01-12 19:30:44 +00003494 SmallVector<Module *, 4> Stack;
Robert Wilhelm25284cc2013-08-23 16:11:15 +00003495 Stack.push_back(Mod);
Guy Benyei11169dd2012-12-18 14:30:41 +00003496 while (!Stack.empty()) {
Robert Wilhelm25284cc2013-08-23 16:11:15 +00003497 Mod = Stack.pop_back_val();
Guy Benyei11169dd2012-12-18 14:30:41 +00003498
3499 if (NameVisibility <= Mod->NameVisibility) {
Robert Wilhelm25284cc2013-08-23 16:11:15 +00003500 // This module already has this level of visibility (or greater), so
Guy Benyei11169dd2012-12-18 14:30:41 +00003501 // there is nothing more to do.
3502 continue;
3503 }
Richard Smith49f906a2014-03-01 00:08:04 +00003504
Guy Benyei11169dd2012-12-18 14:30:41 +00003505 if (!Mod->isAvailable()) {
3506 // Modules that aren't available cannot be made visible.
3507 continue;
3508 }
3509
3510 // Update the module's name visibility.
Richard Smith49f906a2014-03-01 00:08:04 +00003511 if (NameVisibility >= Module::MacrosVisible &&
3512 Mod->NameVisibility < Module::MacrosVisible)
3513 Mod->MacroVisibilityLoc = ImportLoc;
Guy Benyei11169dd2012-12-18 14:30:41 +00003514 Mod->NameVisibility = NameVisibility;
Richard Smith49f906a2014-03-01 00:08:04 +00003515
Guy Benyei11169dd2012-12-18 14:30:41 +00003516 // If we've already deserialized any names from this module,
3517 // mark them as visible.
3518 HiddenNamesMapType::iterator Hidden = HiddenNamesMap.find(Mod);
3519 if (Hidden != HiddenNamesMap.end()) {
Richard Smith57721ac2014-07-21 04:10:40 +00003520 auto HiddenNames = std::move(*Hidden);
Guy Benyei11169dd2012-12-18 14:30:41 +00003521 HiddenNamesMap.erase(Hidden);
Richard Smith57721ac2014-07-21 04:10:40 +00003522 makeNamesVisible(HiddenNames.second, HiddenNames.first,
3523 /*FromFinalization*/false);
3524 assert(HiddenNamesMap.find(Mod) == HiddenNamesMap.end() &&
3525 "making names visible added hidden names");
Guy Benyei11169dd2012-12-18 14:30:41 +00003526 }
Dmitri Gribenkoe9bcf5b2013-11-04 21:51:33 +00003527
Guy Benyei11169dd2012-12-18 14:30:41 +00003528 // Push any exported modules onto the stack to be marked as visible.
Argyrios Kyrtzidis8739f7b2013-02-19 19:34:40 +00003529 SmallVector<Module *, 16> Exports;
3530 Mod->getExportedModules(Exports);
3531 for (SmallVectorImpl<Module *>::iterator
3532 I = Exports.begin(), E = Exports.end(); I != E; ++I) {
3533 Module *Exported = *I;
David Blaikie82e95a32014-11-19 07:49:47 +00003534 if (Visited.insert(Exported).second)
Argyrios Kyrtzidis8739f7b2013-02-19 19:34:40 +00003535 Stack.push_back(Exported);
Guy Benyei11169dd2012-12-18 14:30:41 +00003536 }
Douglas Gregorfb912652013-03-20 21:10:35 +00003537
3538 // Detect any conflicts.
3539 if (Complain) {
3540 assert(ImportLoc.isValid() && "Missing import location");
3541 for (unsigned I = 0, N = Mod->Conflicts.size(); I != N; ++I) {
3542 if (Mod->Conflicts[I].Other->NameVisibility >= NameVisibility) {
3543 Diag(ImportLoc, diag::warn_module_conflict)
3544 << Mod->getFullModuleName()
3545 << Mod->Conflicts[I].Other->getFullModuleName()
3546 << Mod->Conflicts[I].Message;
3547 // FIXME: Need note where the other module was imported.
3548 }
3549 }
3550 }
Guy Benyei11169dd2012-12-18 14:30:41 +00003551 }
3552}
3553
Douglas Gregore060e572013-01-25 01:03:03 +00003554bool ASTReader::loadGlobalIndex() {
3555 if (GlobalIndex)
3556 return false;
3557
3558 if (TriedLoadingGlobalIndex || !UseGlobalIndex ||
3559 !Context.getLangOpts().Modules)
3560 return true;
3561
3562 // Try to load the global index.
3563 TriedLoadingGlobalIndex = true;
3564 StringRef ModuleCachePath
3565 = getPreprocessor().getHeaderSearchInfo().getModuleCachePath();
3566 std::pair<GlobalModuleIndex *, GlobalModuleIndex::ErrorCode> Result
Douglas Gregor7029ce12013-03-19 00:28:20 +00003567 = GlobalModuleIndex::readIndex(ModuleCachePath);
Douglas Gregore060e572013-01-25 01:03:03 +00003568 if (!Result.first)
3569 return true;
3570
3571 GlobalIndex.reset(Result.first);
Douglas Gregor7211ac12013-01-25 23:32:03 +00003572 ModuleMgr.setGlobalIndex(GlobalIndex.get());
Douglas Gregore060e572013-01-25 01:03:03 +00003573 return false;
3574}
3575
3576bool ASTReader::isGlobalIndexUnavailable() const {
3577 return Context.getLangOpts().Modules && UseGlobalIndex &&
3578 !hasGlobalIndex() && TriedLoadingGlobalIndex;
3579}
3580
Dmitri Gribenkof430da42014-02-12 10:33:14 +00003581static void updateModuleTimestamp(ModuleFile &MF) {
3582 // Overwrite the timestamp file contents so that file's mtime changes.
3583 std::string TimestampFilename = MF.getTimestampFilename();
Rafael Espindoladae941a2014-08-25 18:17:04 +00003584 std::error_code EC;
3585 llvm::raw_fd_ostream OS(TimestampFilename, EC, llvm::sys::fs::F_Text);
3586 if (EC)
Dmitri Gribenkof430da42014-02-12 10:33:14 +00003587 return;
3588 OS << "Timestamp file\n";
3589}
3590
Guy Benyei11169dd2012-12-18 14:30:41 +00003591ASTReader::ASTReadResult ASTReader::ReadAST(const std::string &FileName,
3592 ModuleKind Type,
3593 SourceLocation ImportLoc,
3594 unsigned ClientLoadCapabilities) {
Argyrios Kyrtzidisdc9fdaf2013-05-24 05:44:08 +00003595 llvm::SaveAndRestore<SourceLocation>
3596 SetCurImportLocRAII(CurrentImportLoc, ImportLoc);
3597
Richard Smithd1c46742014-04-30 02:24:17 +00003598 // Defer any pending actions until we get to the end of reading the AST file.
3599 Deserializing AnASTFile(this);
3600
Guy Benyei11169dd2012-12-18 14:30:41 +00003601 // Bump the generation number.
Richard Smith053f6c62014-05-16 23:01:30 +00003602 unsigned PreviousGeneration = incrementGeneration(Context);
Guy Benyei11169dd2012-12-18 14:30:41 +00003603
3604 unsigned NumModules = ModuleMgr.size();
Dmitri Gribenkof8579502013-01-12 19:30:44 +00003605 SmallVector<ImportedModule, 4> Loaded;
Guy Benyei11169dd2012-12-18 14:30:41 +00003606 switch(ASTReadResult ReadResult = ReadASTCore(FileName, Type, ImportLoc,
Craig Toppera13603a2014-05-22 05:54:18 +00003607 /*ImportedBy=*/nullptr, Loaded,
Ben Langmuir487ea142014-10-23 18:05:36 +00003608 0, 0, 0,
Guy Benyei11169dd2012-12-18 14:30:41 +00003609 ClientLoadCapabilities)) {
3610 case Failure:
Douglas Gregor7029ce12013-03-19 00:28:20 +00003611 case Missing:
Guy Benyei11169dd2012-12-18 14:30:41 +00003612 case OutOfDate:
3613 case VersionMismatch:
3614 case ConfigurationMismatch:
Ben Langmuir9801b252014-06-20 00:24:56 +00003615 case HadErrors: {
3616 llvm::SmallPtrSet<ModuleFile *, 4> LoadedSet;
3617 for (const ImportedModule &IM : Loaded)
3618 LoadedSet.insert(IM.Mod);
3619
Douglas Gregor7029ce12013-03-19 00:28:20 +00003620 ModuleMgr.removeModules(ModuleMgr.begin() + NumModules, ModuleMgr.end(),
Ben Langmuir9801b252014-06-20 00:24:56 +00003621 LoadedSet,
Douglas Gregor7029ce12013-03-19 00:28:20 +00003622 Context.getLangOpts().Modules
3623 ? &PP.getHeaderSearchInfo().getModuleMap()
Craig Toppera13603a2014-05-22 05:54:18 +00003624 : nullptr);
Douglas Gregore060e572013-01-25 01:03:03 +00003625
3626 // If we find that any modules are unusable, the global index is going
3627 // to be out-of-date. Just remove it.
3628 GlobalIndex.reset();
Craig Toppera13603a2014-05-22 05:54:18 +00003629 ModuleMgr.setGlobalIndex(nullptr);
Guy Benyei11169dd2012-12-18 14:30:41 +00003630 return ReadResult;
Ben Langmuir9801b252014-06-20 00:24:56 +00003631 }
Guy Benyei11169dd2012-12-18 14:30:41 +00003632 case Success:
3633 break;
3634 }
3635
3636 // Here comes stuff that we only do once the entire chain is loaded.
3637
3638 // Load the AST blocks of all of the modules that we loaded.
Dmitri Gribenkof8579502013-01-12 19:30:44 +00003639 for (SmallVectorImpl<ImportedModule>::iterator M = Loaded.begin(),
3640 MEnd = Loaded.end();
Guy Benyei11169dd2012-12-18 14:30:41 +00003641 M != MEnd; ++M) {
3642 ModuleFile &F = *M->Mod;
3643
3644 // Read the AST block.
Ben Langmuir2c9af442014-04-10 17:57:43 +00003645 if (ASTReadResult Result = ReadASTBlock(F, ClientLoadCapabilities))
3646 return Result;
Guy Benyei11169dd2012-12-18 14:30:41 +00003647
3648 // Once read, set the ModuleFile bit base offset and update the size in
3649 // bits of all files we've seen.
3650 F.GlobalBitOffset = TotalModulesSizeInBits;
3651 TotalModulesSizeInBits += F.SizeInBits;
3652 GlobalBitOffsetsMap.insert(std::make_pair(F.GlobalBitOffset, &F));
3653
3654 // Preload SLocEntries.
3655 for (unsigned I = 0, N = F.PreloadSLocEntries.size(); I != N; ++I) {
3656 int Index = int(F.PreloadSLocEntries[I] - 1) + F.SLocEntryBaseID;
3657 // Load it through the SourceManager and don't call ReadSLocEntry()
3658 // directly because the entry may have already been loaded in which case
3659 // calling ReadSLocEntry() directly would trigger an assertion in
3660 // SourceManager.
3661 SourceMgr.getLoadedSLocEntryByID(Index);
3662 }
3663 }
3664
Douglas Gregor603cd862013-03-22 18:50:14 +00003665 // Setup the import locations and notify the module manager that we've
3666 // committed to these module files.
Dmitri Gribenkof8579502013-01-12 19:30:44 +00003667 for (SmallVectorImpl<ImportedModule>::iterator M = Loaded.begin(),
3668 MEnd = Loaded.end();
Guy Benyei11169dd2012-12-18 14:30:41 +00003669 M != MEnd; ++M) {
3670 ModuleFile &F = *M->Mod;
Douglas Gregor603cd862013-03-22 18:50:14 +00003671
3672 ModuleMgr.moduleFileAccepted(&F);
3673
3674 // Set the import location.
Argyrios Kyrtzidis71c1af82013-02-01 16:36:14 +00003675 F.DirectImportLoc = ImportLoc;
Guy Benyei11169dd2012-12-18 14:30:41 +00003676 if (!M->ImportedBy)
3677 F.ImportLoc = M->ImportLoc;
3678 else
3679 F.ImportLoc = ReadSourceLocation(*M->ImportedBy,
3680 M->ImportLoc.getRawEncoding());
3681 }
3682
3683 // Mark all of the identifiers in the identifier table as being out of date,
3684 // so that various accessors know to check the loaded modules when the
3685 // identifier is used.
3686 for (IdentifierTable::iterator Id = PP.getIdentifierTable().begin(),
3687 IdEnd = PP.getIdentifierTable().end();
3688 Id != IdEnd; ++Id)
3689 Id->second->setOutOfDate(true);
3690
3691 // Resolve any unresolved module exports.
Douglas Gregorfb912652013-03-20 21:10:35 +00003692 for (unsigned I = 0, N = UnresolvedModuleRefs.size(); I != N; ++I) {
3693 UnresolvedModuleRef &Unresolved = UnresolvedModuleRefs[I];
Guy Benyei11169dd2012-12-18 14:30:41 +00003694 SubmoduleID GlobalID = getGlobalSubmoduleID(*Unresolved.File,Unresolved.ID);
3695 Module *ResolvedMod = getSubmodule(GlobalID);
Douglas Gregorfb912652013-03-20 21:10:35 +00003696
3697 switch (Unresolved.Kind) {
3698 case UnresolvedModuleRef::Conflict:
3699 if (ResolvedMod) {
3700 Module::Conflict Conflict;
3701 Conflict.Other = ResolvedMod;
3702 Conflict.Message = Unresolved.String.str();
3703 Unresolved.Mod->Conflicts.push_back(Conflict);
3704 }
3705 continue;
3706
3707 case UnresolvedModuleRef::Import:
Guy Benyei11169dd2012-12-18 14:30:41 +00003708 if (ResolvedMod)
3709 Unresolved.Mod->Imports.push_back(ResolvedMod);
3710 continue;
Guy Benyei11169dd2012-12-18 14:30:41 +00003711
Douglas Gregorfb912652013-03-20 21:10:35 +00003712 case UnresolvedModuleRef::Export:
3713 if (ResolvedMod || Unresolved.IsWildcard)
3714 Unresolved.Mod->Exports.push_back(
3715 Module::ExportDecl(ResolvedMod, Unresolved.IsWildcard));
3716 continue;
3717 }
Guy Benyei11169dd2012-12-18 14:30:41 +00003718 }
Douglas Gregorfb912652013-03-20 21:10:35 +00003719 UnresolvedModuleRefs.clear();
Daniel Jasperba7f2f72013-09-24 09:14:14 +00003720
3721 // FIXME: How do we load the 'use'd modules? They may not be submodules.
3722 // Might be unnecessary as use declarations are only used to build the
3723 // module itself.
Guy Benyei11169dd2012-12-18 14:30:41 +00003724
3725 InitializeContext();
3726
Richard Smith3d8e97e2013-10-18 06:54:39 +00003727 if (SemaObj)
3728 UpdateSema();
3729
Guy Benyei11169dd2012-12-18 14:30:41 +00003730 if (DeserializationListener)
3731 DeserializationListener->ReaderInitialized(this);
3732
3733 ModuleFile &PrimaryModule = ModuleMgr.getPrimaryModule();
3734 if (!PrimaryModule.OriginalSourceFileID.isInvalid()) {
3735 PrimaryModule.OriginalSourceFileID
3736 = FileID::get(PrimaryModule.SLocEntryBaseID
3737 + PrimaryModule.OriginalSourceFileID.getOpaqueValue() - 1);
3738
3739 // If this AST file is a precompiled preamble, then set the
3740 // preamble file ID of the source manager to the file source file
3741 // from which the preamble was built.
3742 if (Type == MK_Preamble) {
3743 SourceMgr.setPreambleFileID(PrimaryModule.OriginalSourceFileID);
3744 } else if (Type == MK_MainFile) {
3745 SourceMgr.setMainFileID(PrimaryModule.OriginalSourceFileID);
3746 }
3747 }
3748
3749 // For any Objective-C class definitions we have already loaded, make sure
3750 // that we load any additional categories.
3751 for (unsigned I = 0, N = ObjCClassesLoaded.size(); I != N; ++I) {
3752 loadObjCCategories(ObjCClassesLoaded[I]->getGlobalID(),
3753 ObjCClassesLoaded[I],
3754 PreviousGeneration);
3755 }
Douglas Gregore060e572013-01-25 01:03:03 +00003756
Dmitri Gribenkof430da42014-02-12 10:33:14 +00003757 if (PP.getHeaderSearchInfo()
3758 .getHeaderSearchOpts()
3759 .ModulesValidateOncePerBuildSession) {
3760 // Now we are certain that the module and all modules it depends on are
3761 // up to date. Create or update timestamp files for modules that are
3762 // located in the module cache (not for PCH files that could be anywhere
3763 // in the filesystem).
3764 for (unsigned I = 0, N = Loaded.size(); I != N; ++I) {
3765 ImportedModule &M = Loaded[I];
Richard Smithe842a472014-10-22 02:05:46 +00003766 if (M.Mod->Kind == MK_ImplicitModule) {
Dmitri Gribenkof430da42014-02-12 10:33:14 +00003767 updateModuleTimestamp(*M.Mod);
3768 }
3769 }
3770 }
3771
Guy Benyei11169dd2012-12-18 14:30:41 +00003772 return Success;
3773}
3774
Ben Langmuir487ea142014-10-23 18:05:36 +00003775static ASTFileSignature readASTFileSignature(llvm::BitstreamReader &StreamFile);
3776
Guy Benyei11169dd2012-12-18 14:30:41 +00003777ASTReader::ASTReadResult
3778ASTReader::ReadASTCore(StringRef FileName,
3779 ModuleKind Type,
3780 SourceLocation ImportLoc,
3781 ModuleFile *ImportedBy,
Dmitri Gribenkof8579502013-01-12 19:30:44 +00003782 SmallVectorImpl<ImportedModule> &Loaded,
Douglas Gregor7029ce12013-03-19 00:28:20 +00003783 off_t ExpectedSize, time_t ExpectedModTime,
Ben Langmuir487ea142014-10-23 18:05:36 +00003784 ASTFileSignature ExpectedSignature,
Guy Benyei11169dd2012-12-18 14:30:41 +00003785 unsigned ClientLoadCapabilities) {
3786 ModuleFile *M;
Guy Benyei11169dd2012-12-18 14:30:41 +00003787 std::string ErrorStr;
Douglas Gregor7029ce12013-03-19 00:28:20 +00003788 ModuleManager::AddModuleResult AddResult
3789 = ModuleMgr.addModule(FileName, Type, ImportLoc, ImportedBy,
Richard Smith053f6c62014-05-16 23:01:30 +00003790 getGeneration(), ExpectedSize, ExpectedModTime,
Ben Langmuir487ea142014-10-23 18:05:36 +00003791 ExpectedSignature, readASTFileSignature,
Douglas Gregor7029ce12013-03-19 00:28:20 +00003792 M, ErrorStr);
Guy Benyei11169dd2012-12-18 14:30:41 +00003793
Douglas Gregor7029ce12013-03-19 00:28:20 +00003794 switch (AddResult) {
3795 case ModuleManager::AlreadyLoaded:
3796 return Success;
3797
3798 case ModuleManager::NewlyLoaded:
3799 // Load module file below.
3800 break;
3801
3802 case ModuleManager::Missing:
Richard Smithe842a472014-10-22 02:05:46 +00003803 // The module file was missing; if the client can handle that, return
Douglas Gregor7029ce12013-03-19 00:28:20 +00003804 // it.
3805 if (ClientLoadCapabilities & ARR_Missing)
3806 return Missing;
3807
3808 // Otherwise, return an error.
3809 {
3810 std::string Msg = "Unable to load module \"" + FileName.str() + "\": "
3811 + ErrorStr;
3812 Error(Msg);
3813 }
3814 return Failure;
3815
3816 case ModuleManager::OutOfDate:
3817 // We couldn't load the module file because it is out-of-date. If the
3818 // client can handle out-of-date, return it.
3819 if (ClientLoadCapabilities & ARR_OutOfDate)
3820 return OutOfDate;
3821
3822 // Otherwise, return an error.
3823 {
3824 std::string Msg = "Unable to load module \"" + FileName.str() + "\": "
3825 + ErrorStr;
3826 Error(Msg);
3827 }
Guy Benyei11169dd2012-12-18 14:30:41 +00003828 return Failure;
3829 }
3830
Douglas Gregor7029ce12013-03-19 00:28:20 +00003831 assert(M && "Missing module file");
Guy Benyei11169dd2012-12-18 14:30:41 +00003832
3833 // FIXME: This seems rather a hack. Should CurrentDir be part of the
3834 // module?
3835 if (FileName != "-") {
3836 CurrentDir = llvm::sys::path::parent_path(FileName);
3837 if (CurrentDir.empty()) CurrentDir = ".";
3838 }
3839
3840 ModuleFile &F = *M;
Chris Lattner7fb3bef2013-01-20 00:56:42 +00003841 BitstreamCursor &Stream = F.Stream;
Rafael Espindolafd832392014-11-12 14:48:44 +00003842 Stream.init(&F.StreamFile);
Guy Benyei11169dd2012-12-18 14:30:41 +00003843 F.SizeInBits = F.Buffer->getBufferSize() * 8;
3844
3845 // Sniff for the signature.
3846 if (Stream.Read(8) != 'C' ||
3847 Stream.Read(8) != 'P' ||
3848 Stream.Read(8) != 'C' ||
3849 Stream.Read(8) != 'H') {
3850 Diag(diag::err_not_a_pch_file) << FileName;
3851 return Failure;
3852 }
3853
3854 // This is used for compatibility with older PCH formats.
3855 bool HaveReadControlBlock = false;
3856
Chris Lattnerefa77172013-01-20 00:00:22 +00003857 while (1) {
3858 llvm::BitstreamEntry Entry = Stream.advance();
3859
3860 switch (Entry.Kind) {
3861 case llvm::BitstreamEntry::Error:
3862 case llvm::BitstreamEntry::EndBlock:
3863 case llvm::BitstreamEntry::Record:
Guy Benyei11169dd2012-12-18 14:30:41 +00003864 Error("invalid record at top-level of AST file");
3865 return Failure;
Chris Lattnerefa77172013-01-20 00:00:22 +00003866
3867 case llvm::BitstreamEntry::SubBlock:
3868 break;
Guy Benyei11169dd2012-12-18 14:30:41 +00003869 }
3870
Guy Benyei11169dd2012-12-18 14:30:41 +00003871 // We only know the control subblock ID.
Chris Lattnerefa77172013-01-20 00:00:22 +00003872 switch (Entry.ID) {
Guy Benyei11169dd2012-12-18 14:30:41 +00003873 case llvm::bitc::BLOCKINFO_BLOCK_ID:
3874 if (Stream.ReadBlockInfoBlock()) {
3875 Error("malformed BlockInfoBlock in AST file");
3876 return Failure;
3877 }
3878 break;
3879 case CONTROL_BLOCK_ID:
3880 HaveReadControlBlock = true;
Ben Langmuirbeee15e2014-04-14 18:00:01 +00003881 switch (ReadControlBlock(F, Loaded, ImportedBy, ClientLoadCapabilities)) {
Guy Benyei11169dd2012-12-18 14:30:41 +00003882 case Success:
3883 break;
3884
3885 case Failure: return Failure;
Douglas Gregor7029ce12013-03-19 00:28:20 +00003886 case Missing: return Missing;
Guy Benyei11169dd2012-12-18 14:30:41 +00003887 case OutOfDate: return OutOfDate;
3888 case VersionMismatch: return VersionMismatch;
3889 case ConfigurationMismatch: return ConfigurationMismatch;
3890 case HadErrors: return HadErrors;
3891 }
3892 break;
3893 case AST_BLOCK_ID:
3894 if (!HaveReadControlBlock) {
3895 if ((ClientLoadCapabilities & ARR_VersionMismatch) == 0)
Dmitri Gribenko2228cd32014-02-11 15:40:09 +00003896 Diag(diag::err_pch_version_too_old);
Guy Benyei11169dd2012-12-18 14:30:41 +00003897 return VersionMismatch;
3898 }
3899
3900 // Record that we've loaded this module.
3901 Loaded.push_back(ImportedModule(M, ImportedBy, ImportLoc));
3902 return Success;
3903
3904 default:
3905 if (Stream.SkipBlock()) {
3906 Error("malformed block record in AST file");
3907 return Failure;
3908 }
3909 break;
3910 }
3911 }
3912
3913 return Success;
3914}
3915
3916void ASTReader::InitializeContext() {
3917 // If there's a listener, notify them that we "read" the translation unit.
3918 if (DeserializationListener)
3919 DeserializationListener->DeclRead(PREDEF_DECL_TRANSLATION_UNIT_ID,
3920 Context.getTranslationUnitDecl());
3921
Guy Benyei11169dd2012-12-18 14:30:41 +00003922 // FIXME: Find a better way to deal with collisions between these
3923 // built-in types. Right now, we just ignore the problem.
3924
3925 // Load the special types.
3926 if (SpecialTypes.size() >= NumSpecialTypeIDs) {
3927 if (unsigned String = SpecialTypes[SPECIAL_TYPE_CF_CONSTANT_STRING]) {
3928 if (!Context.CFConstantStringTypeDecl)
3929 Context.setCFConstantStringType(GetType(String));
3930 }
3931
3932 if (unsigned File = SpecialTypes[SPECIAL_TYPE_FILE]) {
3933 QualType FileType = GetType(File);
3934 if (FileType.isNull()) {
3935 Error("FILE type is NULL");
3936 return;
3937 }
3938
3939 if (!Context.FILEDecl) {
3940 if (const TypedefType *Typedef = FileType->getAs<TypedefType>())
3941 Context.setFILEDecl(Typedef->getDecl());
3942 else {
3943 const TagType *Tag = FileType->getAs<TagType>();
3944 if (!Tag) {
3945 Error("Invalid FILE type in AST file");
3946 return;
3947 }
3948 Context.setFILEDecl(Tag->getDecl());
3949 }
3950 }
3951 }
3952
3953 if (unsigned Jmp_buf = SpecialTypes[SPECIAL_TYPE_JMP_BUF]) {
3954 QualType Jmp_bufType = GetType(Jmp_buf);
3955 if (Jmp_bufType.isNull()) {
3956 Error("jmp_buf type is NULL");
3957 return;
3958 }
3959
3960 if (!Context.jmp_bufDecl) {
3961 if (const TypedefType *Typedef = Jmp_bufType->getAs<TypedefType>())
3962 Context.setjmp_bufDecl(Typedef->getDecl());
3963 else {
3964 const TagType *Tag = Jmp_bufType->getAs<TagType>();
3965 if (!Tag) {
3966 Error("Invalid jmp_buf type in AST file");
3967 return;
3968 }
3969 Context.setjmp_bufDecl(Tag->getDecl());
3970 }
3971 }
3972 }
3973
3974 if (unsigned Sigjmp_buf = SpecialTypes[SPECIAL_TYPE_SIGJMP_BUF]) {
3975 QualType Sigjmp_bufType = GetType(Sigjmp_buf);
3976 if (Sigjmp_bufType.isNull()) {
3977 Error("sigjmp_buf type is NULL");
3978 return;
3979 }
3980
3981 if (!Context.sigjmp_bufDecl) {
3982 if (const TypedefType *Typedef = Sigjmp_bufType->getAs<TypedefType>())
3983 Context.setsigjmp_bufDecl(Typedef->getDecl());
3984 else {
3985 const TagType *Tag = Sigjmp_bufType->getAs<TagType>();
3986 assert(Tag && "Invalid sigjmp_buf type in AST file");
3987 Context.setsigjmp_bufDecl(Tag->getDecl());
3988 }
3989 }
3990 }
3991
3992 if (unsigned ObjCIdRedef
3993 = SpecialTypes[SPECIAL_TYPE_OBJC_ID_REDEFINITION]) {
3994 if (Context.ObjCIdRedefinitionType.isNull())
3995 Context.ObjCIdRedefinitionType = GetType(ObjCIdRedef);
3996 }
3997
3998 if (unsigned ObjCClassRedef
3999 = SpecialTypes[SPECIAL_TYPE_OBJC_CLASS_REDEFINITION]) {
4000 if (Context.ObjCClassRedefinitionType.isNull())
4001 Context.ObjCClassRedefinitionType = GetType(ObjCClassRedef);
4002 }
4003
4004 if (unsigned ObjCSelRedef
4005 = SpecialTypes[SPECIAL_TYPE_OBJC_SEL_REDEFINITION]) {
4006 if (Context.ObjCSelRedefinitionType.isNull())
4007 Context.ObjCSelRedefinitionType = GetType(ObjCSelRedef);
4008 }
4009
4010 if (unsigned Ucontext_t = SpecialTypes[SPECIAL_TYPE_UCONTEXT_T]) {
4011 QualType Ucontext_tType = GetType(Ucontext_t);
4012 if (Ucontext_tType.isNull()) {
4013 Error("ucontext_t type is NULL");
4014 return;
4015 }
4016
4017 if (!Context.ucontext_tDecl) {
4018 if (const TypedefType *Typedef = Ucontext_tType->getAs<TypedefType>())
4019 Context.setucontext_tDecl(Typedef->getDecl());
4020 else {
4021 const TagType *Tag = Ucontext_tType->getAs<TagType>();
4022 assert(Tag && "Invalid ucontext_t type in AST file");
4023 Context.setucontext_tDecl(Tag->getDecl());
4024 }
4025 }
4026 }
4027 }
4028
4029 ReadPragmaDiagnosticMappings(Context.getDiagnostics());
4030
4031 // If there were any CUDA special declarations, deserialize them.
4032 if (!CUDASpecialDeclRefs.empty()) {
4033 assert(CUDASpecialDeclRefs.size() == 1 && "More decl refs than expected!");
4034 Context.setcudaConfigureCallDecl(
4035 cast<FunctionDecl>(GetDecl(CUDASpecialDeclRefs[0])));
4036 }
Richard Smith56be7542014-03-21 00:33:59 +00004037
Guy Benyei11169dd2012-12-18 14:30:41 +00004038 // Re-export any modules that were imported by a non-module AST file.
Richard Smith56be7542014-03-21 00:33:59 +00004039 // FIXME: This does not make macro-only imports visible again. It also doesn't
4040 // make #includes mapped to module imports visible.
4041 for (auto &Import : ImportedModules) {
4042 if (Module *Imported = getSubmodule(Import.ID))
Argyrios Kyrtzidis125df052013-02-01 16:36:12 +00004043 makeModuleVisible(Imported, Module::AllVisible,
Richard Smith56be7542014-03-21 00:33:59 +00004044 /*ImportLoc=*/Import.ImportLoc,
Douglas Gregorfb912652013-03-20 21:10:35 +00004045 /*Complain=*/false);
Guy Benyei11169dd2012-12-18 14:30:41 +00004046 }
4047 ImportedModules.clear();
4048}
4049
4050void ASTReader::finalizeForWriting() {
Richard Smith57721ac2014-07-21 04:10:40 +00004051 while (!HiddenNamesMap.empty()) {
4052 auto HiddenNames = std::move(*HiddenNamesMap.begin());
4053 HiddenNamesMap.erase(HiddenNamesMap.begin());
4054 makeNamesVisible(HiddenNames.second, HiddenNames.first,
4055 /*FromFinalization*/true);
Guy Benyei11169dd2012-12-18 14:30:41 +00004056 }
Guy Benyei11169dd2012-12-18 14:30:41 +00004057}
4058
Argyrios Kyrtzidisc4cd2c42013-05-06 19:23:40 +00004059/// \brief Given a cursor at the start of an AST file, scan ahead and drop the
4060/// cursor into the start of the given block ID, returning false on success and
4061/// true on failure.
4062static bool SkipCursorToBlock(BitstreamCursor &Cursor, unsigned BlockID) {
Chris Lattner7fb3bef2013-01-20 00:56:42 +00004063 while (1) {
4064 llvm::BitstreamEntry Entry = Cursor.advance();
4065 switch (Entry.Kind) {
4066 case llvm::BitstreamEntry::Error:
4067 case llvm::BitstreamEntry::EndBlock:
4068 return true;
4069
4070 case llvm::BitstreamEntry::Record:
4071 // Ignore top-level records.
4072 Cursor.skipRecord(Entry.ID);
4073 break;
4074
4075 case llvm::BitstreamEntry::SubBlock:
Argyrios Kyrtzidisc4cd2c42013-05-06 19:23:40 +00004076 if (Entry.ID == BlockID) {
4077 if (Cursor.EnterSubBlock(BlockID))
Chris Lattner7fb3bef2013-01-20 00:56:42 +00004078 return true;
4079 // Found it!
4080 return false;
4081 }
4082
4083 if (Cursor.SkipBlock())
4084 return true;
4085 }
4086 }
4087}
4088
Ben Langmuir487ea142014-10-23 18:05:36 +00004089static ASTFileSignature readASTFileSignature(llvm::BitstreamReader &StreamFile){
4090 BitstreamCursor Stream(StreamFile);
4091 if (Stream.Read(8) != 'C' ||
4092 Stream.Read(8) != 'P' ||
4093 Stream.Read(8) != 'C' ||
4094 Stream.Read(8) != 'H') {
4095 return 0;
4096 }
4097
4098 // Scan for the CONTROL_BLOCK_ID block.
4099 if (SkipCursorToBlock(Stream, CONTROL_BLOCK_ID))
4100 return 0;
4101
4102 // Scan for SIGNATURE inside the control block.
4103 ASTReader::RecordData Record;
4104 while (1) {
4105 llvm::BitstreamEntry Entry = Stream.advanceSkippingSubblocks();
4106 if (Entry.Kind == llvm::BitstreamEntry::EndBlock ||
4107 Entry.Kind != llvm::BitstreamEntry::Record)
4108 return 0;
4109
4110 Record.clear();
4111 StringRef Blob;
4112 if (SIGNATURE == Stream.readRecord(Entry.ID, Record, &Blob))
4113 return Record[0];
4114 }
4115}
4116
Guy Benyei11169dd2012-12-18 14:30:41 +00004117/// \brief Retrieve the name of the original source file name
4118/// directly from the AST file, without actually loading the AST
4119/// file.
4120std::string ASTReader::getOriginalSourceFile(const std::string &ASTFileName,
4121 FileManager &FileMgr,
4122 DiagnosticsEngine &Diags) {
4123 // Open the AST file.
Benjamin Kramera8857962014-10-26 22:44:13 +00004124 auto Buffer = FileMgr.getBufferForFile(ASTFileName);
Guy Benyei11169dd2012-12-18 14:30:41 +00004125 if (!Buffer) {
Benjamin Kramera8857962014-10-26 22:44:13 +00004126 Diags.Report(diag::err_fe_unable_to_read_pch_file)
4127 << ASTFileName << Buffer.getError().message();
Guy Benyei11169dd2012-12-18 14:30:41 +00004128 return std::string();
4129 }
4130
4131 // Initialize the stream
4132 llvm::BitstreamReader StreamFile;
Benjamin Kramera8857962014-10-26 22:44:13 +00004133 StreamFile.init((const unsigned char *)(*Buffer)->getBufferStart(),
4134 (const unsigned char *)(*Buffer)->getBufferEnd());
Rafael Espindolaaf0e40a2014-11-12 14:42:25 +00004135 BitstreamCursor Stream(StreamFile);
Guy Benyei11169dd2012-12-18 14:30:41 +00004136
4137 // Sniff for the signature.
4138 if (Stream.Read(8) != 'C' ||
4139 Stream.Read(8) != 'P' ||
4140 Stream.Read(8) != 'C' ||
4141 Stream.Read(8) != 'H') {
4142 Diags.Report(diag::err_fe_not_a_pch_file) << ASTFileName;
4143 return std::string();
4144 }
Chris Lattner7fb3bef2013-01-20 00:56:42 +00004145
Chris Lattnere7b154b2013-01-19 21:39:22 +00004146 // Scan for the CONTROL_BLOCK_ID block.
Argyrios Kyrtzidisc4cd2c42013-05-06 19:23:40 +00004147 if (SkipCursorToBlock(Stream, CONTROL_BLOCK_ID)) {
Chris Lattner7fb3bef2013-01-20 00:56:42 +00004148 Diags.Report(diag::err_fe_pch_malformed_block) << ASTFileName;
4149 return std::string();
Chris Lattnere7b154b2013-01-19 21:39:22 +00004150 }
Guy Benyei11169dd2012-12-18 14:30:41 +00004151
Chris Lattner7fb3bef2013-01-20 00:56:42 +00004152 // Scan for ORIGINAL_FILE inside the control block.
4153 RecordData Record;
Chris Lattnere7b154b2013-01-19 21:39:22 +00004154 while (1) {
Chris Lattner7fb3bef2013-01-20 00:56:42 +00004155 llvm::BitstreamEntry Entry = Stream.advanceSkippingSubblocks();
Chris Lattnere7b154b2013-01-19 21:39:22 +00004156 if (Entry.Kind == llvm::BitstreamEntry::EndBlock)
4157 return std::string();
4158
4159 if (Entry.Kind != llvm::BitstreamEntry::Record) {
4160 Diags.Report(diag::err_fe_pch_malformed_block) << ASTFileName;
4161 return std::string();
Guy Benyei11169dd2012-12-18 14:30:41 +00004162 }
Chris Lattnere7b154b2013-01-19 21:39:22 +00004163
Guy Benyei11169dd2012-12-18 14:30:41 +00004164 Record.clear();
Chris Lattner0e6c9402013-01-20 02:38:54 +00004165 StringRef Blob;
4166 if (Stream.readRecord(Entry.ID, Record, &Blob) == ORIGINAL_FILE)
4167 return Blob.str();
Guy Benyei11169dd2012-12-18 14:30:41 +00004168 }
Guy Benyei11169dd2012-12-18 14:30:41 +00004169}
4170
4171namespace {
4172 class SimplePCHValidator : public ASTReaderListener {
4173 const LangOptions &ExistingLangOpts;
4174 const TargetOptions &ExistingTargetOpts;
4175 const PreprocessorOptions &ExistingPPOpts;
4176 FileManager &FileMgr;
4177
4178 public:
4179 SimplePCHValidator(const LangOptions &ExistingLangOpts,
4180 const TargetOptions &ExistingTargetOpts,
4181 const PreprocessorOptions &ExistingPPOpts,
4182 FileManager &FileMgr)
4183 : ExistingLangOpts(ExistingLangOpts),
4184 ExistingTargetOpts(ExistingTargetOpts),
4185 ExistingPPOpts(ExistingPPOpts),
4186 FileMgr(FileMgr)
4187 {
4188 }
4189
Richard Smith1e2cf0d2014-10-31 02:28:58 +00004190 bool ReadLanguageOptions(const LangOptions &LangOpts, bool Complain,
4191 bool AllowCompatibleDifferences) override {
4192 return checkLanguageOptions(ExistingLangOpts, LangOpts, nullptr,
4193 AllowCompatibleDifferences);
Guy Benyei11169dd2012-12-18 14:30:41 +00004194 }
Craig Topper3e89dfe2014-03-13 02:13:41 +00004195 bool ReadTargetOptions(const TargetOptions &TargetOpts,
4196 bool Complain) override {
Craig Toppera13603a2014-05-22 05:54:18 +00004197 return checkTargetOptions(ExistingTargetOpts, TargetOpts, nullptr);
Guy Benyei11169dd2012-12-18 14:30:41 +00004198 }
Craig Topper3e89dfe2014-03-13 02:13:41 +00004199 bool ReadPreprocessorOptions(const PreprocessorOptions &PPOpts,
4200 bool Complain,
4201 std::string &SuggestedPredefines) override {
Craig Toppera13603a2014-05-22 05:54:18 +00004202 return checkPreprocessorOptions(ExistingPPOpts, PPOpts, nullptr, FileMgr,
Argyrios Kyrtzidisd3afa0c2013-04-26 21:33:40 +00004203 SuggestedPredefines, ExistingLangOpts);
Guy Benyei11169dd2012-12-18 14:30:41 +00004204 }
4205 };
4206}
4207
4208bool ASTReader::readASTFileControlBlock(StringRef Filename,
4209 FileManager &FileMgr,
4210 ASTReaderListener &Listener) {
4211 // Open the AST file.
Benjamin Kramera8857962014-10-26 22:44:13 +00004212 auto Buffer = FileMgr.getBufferForFile(Filename);
Guy Benyei11169dd2012-12-18 14:30:41 +00004213 if (!Buffer) {
4214 return true;
4215 }
4216
4217 // Initialize the stream
4218 llvm::BitstreamReader StreamFile;
Benjamin Kramera8857962014-10-26 22:44:13 +00004219 StreamFile.init((const unsigned char *)(*Buffer)->getBufferStart(),
4220 (const unsigned char *)(*Buffer)->getBufferEnd());
Rafael Espindolaaf0e40a2014-11-12 14:42:25 +00004221 BitstreamCursor Stream(StreamFile);
Guy Benyei11169dd2012-12-18 14:30:41 +00004222
4223 // Sniff for the signature.
4224 if (Stream.Read(8) != 'C' ||
4225 Stream.Read(8) != 'P' ||
4226 Stream.Read(8) != 'C' ||
4227 Stream.Read(8) != 'H') {
4228 return true;
4229 }
4230
Chris Lattner7fb3bef2013-01-20 00:56:42 +00004231 // Scan for the CONTROL_BLOCK_ID block.
Argyrios Kyrtzidisc4cd2c42013-05-06 19:23:40 +00004232 if (SkipCursorToBlock(Stream, CONTROL_BLOCK_ID))
Chris Lattner7fb3bef2013-01-20 00:56:42 +00004233 return true;
Argyrios Kyrtzidisc4cd2c42013-05-06 19:23:40 +00004234
4235 bool NeedsInputFiles = Listener.needsInputFileVisitation();
Ben Langmuircb69b572014-03-07 06:40:32 +00004236 bool NeedsSystemInputFiles = Listener.needsSystemInputFileVisitation();
Richard Smithd4b230b2014-10-27 23:01:16 +00004237 bool NeedsImports = Listener.needsImportVisitation();
Argyrios Kyrtzidisc4cd2c42013-05-06 19:23:40 +00004238 BitstreamCursor InputFilesCursor;
4239 if (NeedsInputFiles) {
4240 InputFilesCursor = Stream;
4241 if (SkipCursorToBlock(InputFilesCursor, INPUT_FILES_BLOCK_ID))
4242 return true;
4243
4244 // Read the abbreviations
4245 while (true) {
4246 uint64_t Offset = InputFilesCursor.GetCurrentBitNo();
4247 unsigned Code = InputFilesCursor.ReadCode();
4248
4249 // We expect all abbrevs to be at the start of the block.
4250 if (Code != llvm::bitc::DEFINE_ABBREV) {
4251 InputFilesCursor.JumpToBit(Offset);
4252 break;
4253 }
4254 InputFilesCursor.ReadAbbrevRecord();
4255 }
4256 }
Chris Lattner7fb3bef2013-01-20 00:56:42 +00004257
4258 // Scan for ORIGINAL_FILE inside the control block.
Guy Benyei11169dd2012-12-18 14:30:41 +00004259 RecordData Record;
Chris Lattner7fb3bef2013-01-20 00:56:42 +00004260 while (1) {
4261 llvm::BitstreamEntry Entry = Stream.advanceSkippingSubblocks();
4262 if (Entry.Kind == llvm::BitstreamEntry::EndBlock)
4263 return false;
4264
4265 if (Entry.Kind != llvm::BitstreamEntry::Record)
4266 return true;
4267
Guy Benyei11169dd2012-12-18 14:30:41 +00004268 Record.clear();
Chris Lattner0e6c9402013-01-20 02:38:54 +00004269 StringRef Blob;
4270 unsigned RecCode = Stream.readRecord(Entry.ID, Record, &Blob);
Chris Lattner7fb3bef2013-01-20 00:56:42 +00004271 switch ((ControlRecordTypes)RecCode) {
4272 case METADATA: {
4273 if (Record[0] != VERSION_MAJOR)
4274 return true;
Guy Benyei11169dd2012-12-18 14:30:41 +00004275
Douglas Gregorbf7fc9c2013-03-27 16:47:18 +00004276 if (Listener.ReadFullVersionInformation(Blob))
Chris Lattner7fb3bef2013-01-20 00:56:42 +00004277 return true;
Douglas Gregorbf7fc9c2013-03-27 16:47:18 +00004278
Chris Lattner7fb3bef2013-01-20 00:56:42 +00004279 break;
4280 }
Ben Langmuir4f5212a2014-04-14 22:12:44 +00004281 case MODULE_NAME:
4282 Listener.ReadModuleName(Blob);
4283 break;
Ben Langmuir4b8a9e92014-08-12 16:42:33 +00004284 case MODULE_MAP_FILE: {
4285 unsigned Idx = 0;
4286 Listener.ReadModuleMapFile(ReadString(Record, Idx));
Ben Langmuir4f5212a2014-04-14 22:12:44 +00004287 break;
Ben Langmuir4b8a9e92014-08-12 16:42:33 +00004288 }
Chris Lattner7fb3bef2013-01-20 00:56:42 +00004289 case LANGUAGE_OPTIONS:
Richard Smith1e2cf0d2014-10-31 02:28:58 +00004290 if (ParseLanguageOptions(Record, false, Listener,
4291 /*AllowCompatibleConfigurationMismatch*/false))
Chris Lattner7fb3bef2013-01-20 00:56:42 +00004292 return true;
4293 break;
Guy Benyei11169dd2012-12-18 14:30:41 +00004294
Chris Lattner7fb3bef2013-01-20 00:56:42 +00004295 case TARGET_OPTIONS:
4296 if (ParseTargetOptions(Record, false, Listener))
4297 return true;
4298 break;
Guy Benyei11169dd2012-12-18 14:30:41 +00004299
Chris Lattner7fb3bef2013-01-20 00:56:42 +00004300 case DIAGNOSTIC_OPTIONS:
4301 if (ParseDiagnosticOptions(Record, false, Listener))
4302 return true;
4303 break;
Guy Benyei11169dd2012-12-18 14:30:41 +00004304
Chris Lattner7fb3bef2013-01-20 00:56:42 +00004305 case FILE_SYSTEM_OPTIONS:
4306 if (ParseFileSystemOptions(Record, false, Listener))
4307 return true;
4308 break;
Guy Benyei11169dd2012-12-18 14:30:41 +00004309
Chris Lattner7fb3bef2013-01-20 00:56:42 +00004310 case HEADER_SEARCH_OPTIONS:
4311 if (ParseHeaderSearchOptions(Record, false, Listener))
4312 return true;
4313 break;
Guy Benyei11169dd2012-12-18 14:30:41 +00004314
Chris Lattner7fb3bef2013-01-20 00:56:42 +00004315 case PREPROCESSOR_OPTIONS: {
4316 std::string IgnoredSuggestedPredefines;
4317 if (ParsePreprocessorOptions(Record, false, Listener,
4318 IgnoredSuggestedPredefines))
4319 return true;
4320 break;
4321 }
Guy Benyei11169dd2012-12-18 14:30:41 +00004322
Argyrios Kyrtzidisc4cd2c42013-05-06 19:23:40 +00004323 case INPUT_FILE_OFFSETS: {
4324 if (!NeedsInputFiles)
4325 break;
4326
4327 unsigned NumInputFiles = Record[0];
4328 unsigned NumUserFiles = Record[1];
4329 const uint32_t *InputFileOffs = (const uint32_t *)Blob.data();
4330 for (unsigned I = 0; I != NumInputFiles; ++I) {
4331 // Go find this input file.
4332 bool isSystemFile = I >= NumUserFiles;
Ben Langmuircb69b572014-03-07 06:40:32 +00004333
4334 if (isSystemFile && !NeedsSystemInputFiles)
4335 break; // the rest are system input files
4336
Argyrios Kyrtzidisc4cd2c42013-05-06 19:23:40 +00004337 BitstreamCursor &Cursor = InputFilesCursor;
4338 SavedStreamPosition SavedPosition(Cursor);
4339 Cursor.JumpToBit(InputFileOffs[I]);
4340
4341 unsigned Code = Cursor.ReadCode();
4342 RecordData Record;
4343 StringRef Blob;
4344 bool shouldContinue = false;
4345 switch ((InputFileRecordTypes)Cursor.readRecord(Code, Record, &Blob)) {
4346 case INPUT_FILE:
Argyrios Kyrtzidis68ccbe02014-03-14 02:26:31 +00004347 bool Overridden = static_cast<bool>(Record[3]);
4348 shouldContinue = Listener.visitInputFile(Blob, isSystemFile, Overridden);
Argyrios Kyrtzidisc4cd2c42013-05-06 19:23:40 +00004349 break;
4350 }
4351 if (!shouldContinue)
4352 break;
4353 }
4354 break;
4355 }
4356
Richard Smithd4b230b2014-10-27 23:01:16 +00004357 case IMPORTS: {
4358 if (!NeedsImports)
4359 break;
4360
4361 unsigned Idx = 0, N = Record.size();
4362 while (Idx < N) {
4363 // Read information about the AST file.
Richard Smith79c98cc2014-10-27 23:25:15 +00004364 Idx += 5; // ImportLoc, Size, ModTime, Signature
Richard Smithd4b230b2014-10-27 23:01:16 +00004365 unsigned Length = Record[Idx++];
4366 SmallString<128> ImportedFile(Record.begin() + Idx,
4367 Record.begin() + Idx + Length);
4368 Idx += Length;
4369 Listener.visitImport(ImportedFile);
4370 }
4371 break;
4372 }
4373
Chris Lattner7fb3bef2013-01-20 00:56:42 +00004374 default:
4375 // No other validation to perform.
4376 break;
Guy Benyei11169dd2012-12-18 14:30:41 +00004377 }
4378 }
Guy Benyei11169dd2012-12-18 14:30:41 +00004379}
4380
4381
4382bool ASTReader::isAcceptableASTFile(StringRef Filename,
4383 FileManager &FileMgr,
4384 const LangOptions &LangOpts,
4385 const TargetOptions &TargetOpts,
4386 const PreprocessorOptions &PPOpts) {
4387 SimplePCHValidator validator(LangOpts, TargetOpts, PPOpts, FileMgr);
4388 return !readASTFileControlBlock(Filename, FileMgr, validator);
4389}
4390
Ben Langmuir2c9af442014-04-10 17:57:43 +00004391ASTReader::ASTReadResult
4392ASTReader::ReadSubmoduleBlock(ModuleFile &F, unsigned ClientLoadCapabilities) {
Guy Benyei11169dd2012-12-18 14:30:41 +00004393 // Enter the submodule block.
4394 if (F.Stream.EnterSubBlock(SUBMODULE_BLOCK_ID)) {
4395 Error("malformed submodule block record in AST file");
Ben Langmuir2c9af442014-04-10 17:57:43 +00004396 return Failure;
Guy Benyei11169dd2012-12-18 14:30:41 +00004397 }
4398
4399 ModuleMap &ModMap = PP.getHeaderSearchInfo().getModuleMap();
4400 bool First = true;
Craig Toppera13603a2014-05-22 05:54:18 +00004401 Module *CurrentModule = nullptr;
Guy Benyei11169dd2012-12-18 14:30:41 +00004402 RecordData Record;
4403 while (true) {
Chris Lattner7fb3bef2013-01-20 00:56:42 +00004404 llvm::BitstreamEntry Entry = F.Stream.advanceSkippingSubblocks();
4405
4406 switch (Entry.Kind) {
4407 case llvm::BitstreamEntry::SubBlock: // Handled for us already.
4408 case llvm::BitstreamEntry::Error:
4409 Error("malformed block record in AST file");
Ben Langmuir2c9af442014-04-10 17:57:43 +00004410 return Failure;
Chris Lattner7fb3bef2013-01-20 00:56:42 +00004411 case llvm::BitstreamEntry::EndBlock:
Ben Langmuir2c9af442014-04-10 17:57:43 +00004412 return Success;
Chris Lattner7fb3bef2013-01-20 00:56:42 +00004413 case llvm::BitstreamEntry::Record:
4414 // The interesting case.
4415 break;
Guy Benyei11169dd2012-12-18 14:30:41 +00004416 }
Chris Lattner7fb3bef2013-01-20 00:56:42 +00004417
Guy Benyei11169dd2012-12-18 14:30:41 +00004418 // Read a record.
Chris Lattner0e6c9402013-01-20 02:38:54 +00004419 StringRef Blob;
Guy Benyei11169dd2012-12-18 14:30:41 +00004420 Record.clear();
Richard Smith03478d92014-10-23 22:12:14 +00004421 auto Kind = F.Stream.readRecord(Entry.ID, Record, &Blob);
4422
4423 if ((Kind == SUBMODULE_METADATA) != First) {
4424 Error("submodule metadata record should be at beginning of block");
4425 return Failure;
4426 }
4427 First = false;
4428
4429 // Submodule information is only valid if we have a current module.
4430 // FIXME: Should we error on these cases?
4431 if (!CurrentModule && Kind != SUBMODULE_METADATA &&
4432 Kind != SUBMODULE_DEFINITION)
4433 continue;
4434
4435 switch (Kind) {
Guy Benyei11169dd2012-12-18 14:30:41 +00004436 default: // Default behavior: ignore.
4437 break;
Guy Benyei11169dd2012-12-18 14:30:41 +00004438
Richard Smith03478d92014-10-23 22:12:14 +00004439 case SUBMODULE_DEFINITION: {
Douglas Gregor8d932422013-03-20 03:59:18 +00004440 if (Record.size() < 8) {
Guy Benyei11169dd2012-12-18 14:30:41 +00004441 Error("malformed module definition");
Ben Langmuir2c9af442014-04-10 17:57:43 +00004442 return Failure;
Guy Benyei11169dd2012-12-18 14:30:41 +00004443 }
Richard Smith03478d92014-10-23 22:12:14 +00004444
Chris Lattner0e6c9402013-01-20 02:38:54 +00004445 StringRef Name = Blob;
Richard Smith9bca2982014-03-08 00:03:56 +00004446 unsigned Idx = 0;
4447 SubmoduleID GlobalID = getGlobalSubmoduleID(F, Record[Idx++]);
4448 SubmoduleID Parent = getGlobalSubmoduleID(F, Record[Idx++]);
4449 bool IsFramework = Record[Idx++];
4450 bool IsExplicit = Record[Idx++];
4451 bool IsSystem = Record[Idx++];
4452 bool IsExternC = Record[Idx++];
4453 bool InferSubmodules = Record[Idx++];
4454 bool InferExplicitSubmodules = Record[Idx++];
4455 bool InferExportWildcard = Record[Idx++];
4456 bool ConfigMacrosExhaustive = Record[Idx++];
Douglas Gregor8d932422013-03-20 03:59:18 +00004457
Ben Langmuirbeee15e2014-04-14 18:00:01 +00004458 Module *ParentModule = nullptr;
Ben Langmuir9d6448b2014-08-09 00:57:23 +00004459 if (Parent)
Guy Benyei11169dd2012-12-18 14:30:41 +00004460 ParentModule = getSubmodule(Parent);
Ben Langmuirbeee15e2014-04-14 18:00:01 +00004461
Guy Benyei11169dd2012-12-18 14:30:41 +00004462 // Retrieve this (sub)module from the module map, creating it if
4463 // necessary.
Ben Langmuir9d6448b2014-08-09 00:57:23 +00004464 CurrentModule = ModMap.findOrCreateModule(Name, ParentModule, IsFramework,
Guy Benyei11169dd2012-12-18 14:30:41 +00004465 IsExplicit).first;
Ben Langmuir9d6448b2014-08-09 00:57:23 +00004466
4467 // FIXME: set the definition loc for CurrentModule, or call
4468 // ModMap.setInferredModuleAllowedBy()
4469
Guy Benyei11169dd2012-12-18 14:30:41 +00004470 SubmoduleID GlobalIndex = GlobalID - NUM_PREDEF_SUBMODULE_IDS;
4471 if (GlobalIndex >= SubmodulesLoaded.size() ||
4472 SubmodulesLoaded[GlobalIndex]) {
4473 Error("too many submodules");
Ben Langmuir2c9af442014-04-10 17:57:43 +00004474 return Failure;
Guy Benyei11169dd2012-12-18 14:30:41 +00004475 }
Douglas Gregor8a114ab2013-02-06 22:40:31 +00004476
Douglas Gregor7029ce12013-03-19 00:28:20 +00004477 if (!ParentModule) {
4478 if (const FileEntry *CurFile = CurrentModule->getASTFile()) {
4479 if (CurFile != F.File) {
4480 if (!Diags.isDiagnosticInFlight()) {
4481 Diag(diag::err_module_file_conflict)
4482 << CurrentModule->getTopLevelModuleName()
4483 << CurFile->getName()
4484 << F.File->getName();
4485 }
Ben Langmuir2c9af442014-04-10 17:57:43 +00004486 return Failure;
Douglas Gregor8a114ab2013-02-06 22:40:31 +00004487 }
Douglas Gregor8a114ab2013-02-06 22:40:31 +00004488 }
Douglas Gregor7029ce12013-03-19 00:28:20 +00004489
4490 CurrentModule->setASTFile(F.File);
Douglas Gregor8a114ab2013-02-06 22:40:31 +00004491 }
Ben Langmuirbeee15e2014-04-14 18:00:01 +00004492
Guy Benyei11169dd2012-12-18 14:30:41 +00004493 CurrentModule->IsFromModuleFile = true;
4494 CurrentModule->IsSystem = IsSystem || CurrentModule->IsSystem;
Richard Smith9bca2982014-03-08 00:03:56 +00004495 CurrentModule->IsExternC = IsExternC;
Guy Benyei11169dd2012-12-18 14:30:41 +00004496 CurrentModule->InferSubmodules = InferSubmodules;
4497 CurrentModule->InferExplicitSubmodules = InferExplicitSubmodules;
4498 CurrentModule->InferExportWildcard = InferExportWildcard;
Douglas Gregor8d932422013-03-20 03:59:18 +00004499 CurrentModule->ConfigMacrosExhaustive = ConfigMacrosExhaustive;
Guy Benyei11169dd2012-12-18 14:30:41 +00004500 if (DeserializationListener)
4501 DeserializationListener->ModuleRead(GlobalID, CurrentModule);
4502
4503 SubmodulesLoaded[GlobalIndex] = CurrentModule;
Douglas Gregor6ddfca92013-01-14 17:21:00 +00004504
Douglas Gregorfb912652013-03-20 21:10:35 +00004505 // Clear out data that will be replaced by what is the module file.
Douglas Gregor6ddfca92013-01-14 17:21:00 +00004506 CurrentModule->LinkLibraries.clear();
Douglas Gregor8d932422013-03-20 03:59:18 +00004507 CurrentModule->ConfigMacros.clear();
Douglas Gregorfb912652013-03-20 21:10:35 +00004508 CurrentModule->UnresolvedConflicts.clear();
4509 CurrentModule->Conflicts.clear();
Guy Benyei11169dd2012-12-18 14:30:41 +00004510 break;
4511 }
4512
4513 case SUBMODULE_UMBRELLA_HEADER: {
Chris Lattner0e6c9402013-01-20 02:38:54 +00004514 if (const FileEntry *Umbrella = PP.getFileManager().getFile(Blob)) {
Guy Benyei11169dd2012-12-18 14:30:41 +00004515 if (!CurrentModule->getUmbrellaHeader())
4516 ModMap.setUmbrellaHeader(CurrentModule, Umbrella);
4517 else if (CurrentModule->getUmbrellaHeader() != Umbrella) {
Ben Langmuir2c9af442014-04-10 17:57:43 +00004518 if ((ClientLoadCapabilities & ARR_OutOfDate) == 0)
4519 Error("mismatched umbrella headers in submodule");
4520 return OutOfDate;
Guy Benyei11169dd2012-12-18 14:30:41 +00004521 }
4522 }
4523 break;
4524 }
4525
Richard Smith202210b2014-10-24 20:23:01 +00004526 case SUBMODULE_HEADER:
4527 case SUBMODULE_EXCLUDED_HEADER:
4528 case SUBMODULE_PRIVATE_HEADER:
4529 // We lazily associate headers with their modules via the HeaderInfo table.
Argyrios Kyrtzidisb146baa2013-03-13 21:13:51 +00004530 // FIXME: Re-evaluate this section; maybe only store InputFile IDs instead
4531 // of complete filenames or remove it entirely.
Richard Smith202210b2014-10-24 20:23:01 +00004532 break;
Guy Benyei11169dd2012-12-18 14:30:41 +00004533
Richard Smith202210b2014-10-24 20:23:01 +00004534 case SUBMODULE_TEXTUAL_HEADER:
4535 case SUBMODULE_PRIVATE_TEXTUAL_HEADER:
4536 // FIXME: Textual headers are not marked in the HeaderInfo table. Load
4537 // them here.
4538 break;
Lawrence Crowlb53e5482013-06-20 21:14:14 +00004539
Guy Benyei11169dd2012-12-18 14:30:41 +00004540 case SUBMODULE_TOPHEADER: {
Argyrios Kyrtzidis3c5305c2013-03-13 21:13:43 +00004541 CurrentModule->addTopHeaderFilename(Blob);
Guy Benyei11169dd2012-12-18 14:30:41 +00004542 break;
4543 }
4544
4545 case SUBMODULE_UMBRELLA_DIR: {
Guy Benyei11169dd2012-12-18 14:30:41 +00004546 if (const DirectoryEntry *Umbrella
Chris Lattner0e6c9402013-01-20 02:38:54 +00004547 = PP.getFileManager().getDirectory(Blob)) {
Guy Benyei11169dd2012-12-18 14:30:41 +00004548 if (!CurrentModule->getUmbrellaDir())
4549 ModMap.setUmbrellaDir(CurrentModule, Umbrella);
4550 else if (CurrentModule->getUmbrellaDir() != Umbrella) {
Ben Langmuir2c9af442014-04-10 17:57:43 +00004551 if ((ClientLoadCapabilities & ARR_OutOfDate) == 0)
4552 Error("mismatched umbrella directories in submodule");
4553 return OutOfDate;
Guy Benyei11169dd2012-12-18 14:30:41 +00004554 }
4555 }
4556 break;
4557 }
4558
4559 case SUBMODULE_METADATA: {
Guy Benyei11169dd2012-12-18 14:30:41 +00004560 F.BaseSubmoduleID = getTotalNumSubmodules();
4561 F.LocalNumSubmodules = Record[0];
4562 unsigned LocalBaseSubmoduleID = Record[1];
4563 if (F.LocalNumSubmodules > 0) {
4564 // Introduce the global -> local mapping for submodules within this
4565 // module.
4566 GlobalSubmoduleMap.insert(std::make_pair(getTotalNumSubmodules()+1,&F));
4567
4568 // Introduce the local -> global mapping for submodules within this
4569 // module.
4570 F.SubmoduleRemap.insertOrReplace(
4571 std::make_pair(LocalBaseSubmoduleID,
4572 F.BaseSubmoduleID - LocalBaseSubmoduleID));
Ben Langmuirfe971d92014-08-16 04:54:18 +00004573
Ben Langmuir52ca6782014-10-20 16:27:32 +00004574 SubmodulesLoaded.resize(SubmodulesLoaded.size() + F.LocalNumSubmodules);
4575 }
Guy Benyei11169dd2012-12-18 14:30:41 +00004576 break;
4577 }
4578
4579 case SUBMODULE_IMPORTS: {
Guy Benyei11169dd2012-12-18 14:30:41 +00004580 for (unsigned Idx = 0; Idx != Record.size(); ++Idx) {
Douglas Gregorfb912652013-03-20 21:10:35 +00004581 UnresolvedModuleRef Unresolved;
Guy Benyei11169dd2012-12-18 14:30:41 +00004582 Unresolved.File = &F;
4583 Unresolved.Mod = CurrentModule;
4584 Unresolved.ID = Record[Idx];
Douglas Gregorfb912652013-03-20 21:10:35 +00004585 Unresolved.Kind = UnresolvedModuleRef::Import;
Guy Benyei11169dd2012-12-18 14:30:41 +00004586 Unresolved.IsWildcard = false;
Douglas Gregorfb912652013-03-20 21:10:35 +00004587 UnresolvedModuleRefs.push_back(Unresolved);
Guy Benyei11169dd2012-12-18 14:30:41 +00004588 }
4589 break;
4590 }
4591
4592 case SUBMODULE_EXPORTS: {
Guy Benyei11169dd2012-12-18 14:30:41 +00004593 for (unsigned Idx = 0; Idx + 1 < Record.size(); Idx += 2) {
Douglas Gregorfb912652013-03-20 21:10:35 +00004594 UnresolvedModuleRef Unresolved;
Guy Benyei11169dd2012-12-18 14:30:41 +00004595 Unresolved.File = &F;
4596 Unresolved.Mod = CurrentModule;
4597 Unresolved.ID = Record[Idx];
Douglas Gregorfb912652013-03-20 21:10:35 +00004598 Unresolved.Kind = UnresolvedModuleRef::Export;
Guy Benyei11169dd2012-12-18 14:30:41 +00004599 Unresolved.IsWildcard = Record[Idx + 1];
Douglas Gregorfb912652013-03-20 21:10:35 +00004600 UnresolvedModuleRefs.push_back(Unresolved);
Guy Benyei11169dd2012-12-18 14:30:41 +00004601 }
4602
4603 // Once we've loaded the set of exports, there's no reason to keep
4604 // the parsed, unresolved exports around.
4605 CurrentModule->UnresolvedExports.clear();
4606 break;
4607 }
4608 case SUBMODULE_REQUIRES: {
Richard Smitha3feee22013-10-28 22:18:19 +00004609 CurrentModule->addRequirement(Blob, Record[0], Context.getLangOpts(),
Guy Benyei11169dd2012-12-18 14:30:41 +00004610 Context.getTargetInfo());
4611 break;
4612 }
Douglas Gregor6ddfca92013-01-14 17:21:00 +00004613
4614 case SUBMODULE_LINK_LIBRARY:
Douglas Gregor6ddfca92013-01-14 17:21:00 +00004615 CurrentModule->LinkLibraries.push_back(
Chris Lattner0e6c9402013-01-20 02:38:54 +00004616 Module::LinkLibrary(Blob, Record[0]));
Douglas Gregor6ddfca92013-01-14 17:21:00 +00004617 break;
Douglas Gregor35b13ec2013-03-20 00:22:05 +00004618
4619 case SUBMODULE_CONFIG_MACRO:
Douglas Gregor35b13ec2013-03-20 00:22:05 +00004620 CurrentModule->ConfigMacros.push_back(Blob.str());
4621 break;
Douglas Gregorfb912652013-03-20 21:10:35 +00004622
4623 case SUBMODULE_CONFLICT: {
Douglas Gregorfb912652013-03-20 21:10:35 +00004624 UnresolvedModuleRef Unresolved;
4625 Unresolved.File = &F;
4626 Unresolved.Mod = CurrentModule;
4627 Unresolved.ID = Record[0];
4628 Unresolved.Kind = UnresolvedModuleRef::Conflict;
4629 Unresolved.IsWildcard = false;
4630 Unresolved.String = Blob;
4631 UnresolvedModuleRefs.push_back(Unresolved);
4632 break;
4633 }
Guy Benyei11169dd2012-12-18 14:30:41 +00004634 }
4635 }
4636}
4637
4638/// \brief Parse the record that corresponds to a LangOptions data
4639/// structure.
4640///
4641/// This routine parses the language options from the AST file and then gives
4642/// them to the AST listener if one is set.
4643///
4644/// \returns true if the listener deems the file unacceptable, false otherwise.
4645bool ASTReader::ParseLanguageOptions(const RecordData &Record,
4646 bool Complain,
Richard Smith1e2cf0d2014-10-31 02:28:58 +00004647 ASTReaderListener &Listener,
4648 bool AllowCompatibleDifferences) {
Guy Benyei11169dd2012-12-18 14:30:41 +00004649 LangOptions LangOpts;
4650 unsigned Idx = 0;
4651#define LANGOPT(Name, Bits, Default, Description) \
4652 LangOpts.Name = Record[Idx++];
4653#define ENUM_LANGOPT(Name, Type, Bits, Default, Description) \
4654 LangOpts.set##Name(static_cast<LangOptions::Type>(Record[Idx++]));
4655#include "clang/Basic/LangOptions.def"
Alexey Samsonovedf99a92014-11-07 22:29:38 +00004656#define SANITIZER(NAME, ID) \
4657 LangOpts.Sanitize.set(SanitizerKind::ID, Record[Idx++]);
Will Dietzf54319c2013-01-18 11:30:38 +00004658#include "clang/Basic/Sanitizers.def"
Guy Benyei11169dd2012-12-18 14:30:41 +00004659
4660 ObjCRuntime::Kind runtimeKind = (ObjCRuntime::Kind) Record[Idx++];
4661 VersionTuple runtimeVersion = ReadVersionTuple(Record, Idx);
4662 LangOpts.ObjCRuntime = ObjCRuntime(runtimeKind, runtimeVersion);
4663
4664 unsigned Length = Record[Idx++];
4665 LangOpts.CurrentModule.assign(Record.begin() + Idx,
4666 Record.begin() + Idx + Length);
Dmitri Gribenkoacf2e782013-02-22 14:21:27 +00004667
4668 Idx += Length;
4669
4670 // Comment options.
4671 for (unsigned N = Record[Idx++]; N; --N) {
4672 LangOpts.CommentOpts.BlockCommandNames.push_back(
4673 ReadString(Record, Idx));
4674 }
Dmitri Gribenkoa7d16ce2013-04-10 15:35:17 +00004675 LangOpts.CommentOpts.ParseAllComments = Record[Idx++];
Dmitri Gribenkoacf2e782013-02-22 14:21:27 +00004676
Richard Smith1e2cf0d2014-10-31 02:28:58 +00004677 return Listener.ReadLanguageOptions(LangOpts, Complain,
4678 AllowCompatibleDifferences);
Guy Benyei11169dd2012-12-18 14:30:41 +00004679}
4680
4681bool ASTReader::ParseTargetOptions(const RecordData &Record,
4682 bool Complain,
4683 ASTReaderListener &Listener) {
4684 unsigned Idx = 0;
4685 TargetOptions TargetOpts;
4686 TargetOpts.Triple = ReadString(Record, Idx);
4687 TargetOpts.CPU = ReadString(Record, Idx);
4688 TargetOpts.ABI = ReadString(Record, Idx);
Guy Benyei11169dd2012-12-18 14:30:41 +00004689 for (unsigned N = Record[Idx++]; N; --N) {
4690 TargetOpts.FeaturesAsWritten.push_back(ReadString(Record, Idx));
4691 }
4692 for (unsigned N = Record[Idx++]; N; --N) {
4693 TargetOpts.Features.push_back(ReadString(Record, Idx));
4694 }
4695
4696 return Listener.ReadTargetOptions(TargetOpts, Complain);
4697}
4698
4699bool ASTReader::ParseDiagnosticOptions(const RecordData &Record, bool Complain,
4700 ASTReaderListener &Listener) {
Ben Langmuirb92de022014-04-29 16:25:26 +00004701 IntrusiveRefCntPtr<DiagnosticOptions> DiagOpts(new DiagnosticOptions);
Guy Benyei11169dd2012-12-18 14:30:41 +00004702 unsigned Idx = 0;
Ben Langmuirb92de022014-04-29 16:25:26 +00004703#define DIAGOPT(Name, Bits, Default) DiagOpts->Name = Record[Idx++];
Guy Benyei11169dd2012-12-18 14:30:41 +00004704#define ENUM_DIAGOPT(Name, Type, Bits, Default) \
Ben Langmuirb92de022014-04-29 16:25:26 +00004705 DiagOpts->set##Name(static_cast<Type>(Record[Idx++]));
Guy Benyei11169dd2012-12-18 14:30:41 +00004706#include "clang/Basic/DiagnosticOptions.def"
4707
Richard Smith3be1cb22014-08-07 00:24:21 +00004708 for (unsigned N = Record[Idx++]; N; --N)
Ben Langmuirb92de022014-04-29 16:25:26 +00004709 DiagOpts->Warnings.push_back(ReadString(Record, Idx));
Richard Smith3be1cb22014-08-07 00:24:21 +00004710 for (unsigned N = Record[Idx++]; N; --N)
4711 DiagOpts->Remarks.push_back(ReadString(Record, Idx));
Guy Benyei11169dd2012-12-18 14:30:41 +00004712
4713 return Listener.ReadDiagnosticOptions(DiagOpts, Complain);
4714}
4715
4716bool ASTReader::ParseFileSystemOptions(const RecordData &Record, bool Complain,
4717 ASTReaderListener &Listener) {
4718 FileSystemOptions FSOpts;
4719 unsigned Idx = 0;
4720 FSOpts.WorkingDir = ReadString(Record, Idx);
4721 return Listener.ReadFileSystemOptions(FSOpts, Complain);
4722}
4723
4724bool ASTReader::ParseHeaderSearchOptions(const RecordData &Record,
4725 bool Complain,
4726 ASTReaderListener &Listener) {
4727 HeaderSearchOptions HSOpts;
4728 unsigned Idx = 0;
4729 HSOpts.Sysroot = ReadString(Record, Idx);
4730
4731 // Include entries.
4732 for (unsigned N = Record[Idx++]; N; --N) {
4733 std::string Path = ReadString(Record, Idx);
4734 frontend::IncludeDirGroup Group
4735 = static_cast<frontend::IncludeDirGroup>(Record[Idx++]);
Guy Benyei11169dd2012-12-18 14:30:41 +00004736 bool IsFramework = Record[Idx++];
4737 bool IgnoreSysRoot = Record[Idx++];
Guy Benyei11169dd2012-12-18 14:30:41 +00004738 HSOpts.UserEntries.push_back(
Daniel Dunbar53681732013-01-30 00:34:26 +00004739 HeaderSearchOptions::Entry(Path, Group, IsFramework, IgnoreSysRoot));
Guy Benyei11169dd2012-12-18 14:30:41 +00004740 }
4741
4742 // System header prefixes.
4743 for (unsigned N = Record[Idx++]; N; --N) {
4744 std::string Prefix = ReadString(Record, Idx);
4745 bool IsSystemHeader = Record[Idx++];
4746 HSOpts.SystemHeaderPrefixes.push_back(
4747 HeaderSearchOptions::SystemHeaderPrefix(Prefix, IsSystemHeader));
4748 }
4749
4750 HSOpts.ResourceDir = ReadString(Record, Idx);
4751 HSOpts.ModuleCachePath = ReadString(Record, Idx);
Argyrios Kyrtzidis1594c152014-03-03 08:12:05 +00004752 HSOpts.ModuleUserBuildPath = ReadString(Record, Idx);
Guy Benyei11169dd2012-12-18 14:30:41 +00004753 HSOpts.DisableModuleHash = Record[Idx++];
4754 HSOpts.UseBuiltinIncludes = Record[Idx++];
4755 HSOpts.UseStandardSystemIncludes = Record[Idx++];
4756 HSOpts.UseStandardCXXIncludes = Record[Idx++];
4757 HSOpts.UseLibcxx = Record[Idx++];
4758
4759 return Listener.ReadHeaderSearchOptions(HSOpts, Complain);
4760}
4761
4762bool ASTReader::ParsePreprocessorOptions(const RecordData &Record,
4763 bool Complain,
4764 ASTReaderListener &Listener,
4765 std::string &SuggestedPredefines) {
4766 PreprocessorOptions PPOpts;
4767 unsigned Idx = 0;
4768
4769 // Macro definitions/undefs
4770 for (unsigned N = Record[Idx++]; N; --N) {
4771 std::string Macro = ReadString(Record, Idx);
4772 bool IsUndef = Record[Idx++];
4773 PPOpts.Macros.push_back(std::make_pair(Macro, IsUndef));
4774 }
4775
4776 // Includes
4777 for (unsigned N = Record[Idx++]; N; --N) {
4778 PPOpts.Includes.push_back(ReadString(Record, Idx));
4779 }
4780
4781 // Macro Includes
4782 for (unsigned N = Record[Idx++]; N; --N) {
4783 PPOpts.MacroIncludes.push_back(ReadString(Record, Idx));
4784 }
4785
4786 PPOpts.UsePredefines = Record[Idx++];
Argyrios Kyrtzidisd3afa0c2013-04-26 21:33:40 +00004787 PPOpts.DetailedRecord = Record[Idx++];
Guy Benyei11169dd2012-12-18 14:30:41 +00004788 PPOpts.ImplicitPCHInclude = ReadString(Record, Idx);
4789 PPOpts.ImplicitPTHInclude = ReadString(Record, Idx);
4790 PPOpts.ObjCXXARCStandardLibrary =
4791 static_cast<ObjCXXARCStandardLibraryKind>(Record[Idx++]);
4792 SuggestedPredefines.clear();
4793 return Listener.ReadPreprocessorOptions(PPOpts, Complain,
4794 SuggestedPredefines);
4795}
4796
4797std::pair<ModuleFile *, unsigned>
4798ASTReader::getModulePreprocessedEntity(unsigned GlobalIndex) {
4799 GlobalPreprocessedEntityMapType::iterator
4800 I = GlobalPreprocessedEntityMap.find(GlobalIndex);
4801 assert(I != GlobalPreprocessedEntityMap.end() &&
4802 "Corrupted global preprocessed entity map");
4803 ModuleFile *M = I->second;
4804 unsigned LocalIndex = GlobalIndex - M->BasePreprocessedEntityID;
4805 return std::make_pair(M, LocalIndex);
4806}
4807
4808std::pair<PreprocessingRecord::iterator, PreprocessingRecord::iterator>
4809ASTReader::getModulePreprocessedEntities(ModuleFile &Mod) const {
4810 if (PreprocessingRecord *PPRec = PP.getPreprocessingRecord())
4811 return PPRec->getIteratorsForLoadedRange(Mod.BasePreprocessedEntityID,
4812 Mod.NumPreprocessedEntities);
4813
4814 return std::make_pair(PreprocessingRecord::iterator(),
4815 PreprocessingRecord::iterator());
4816}
4817
4818std::pair<ASTReader::ModuleDeclIterator, ASTReader::ModuleDeclIterator>
4819ASTReader::getModuleFileLevelDecls(ModuleFile &Mod) {
4820 return std::make_pair(ModuleDeclIterator(this, &Mod, Mod.FileSortedDecls),
4821 ModuleDeclIterator(this, &Mod,
4822 Mod.FileSortedDecls + Mod.NumFileSortedDecls));
4823}
4824
4825PreprocessedEntity *ASTReader::ReadPreprocessedEntity(unsigned Index) {
4826 PreprocessedEntityID PPID = Index+1;
4827 std::pair<ModuleFile *, unsigned> PPInfo = getModulePreprocessedEntity(Index);
4828 ModuleFile &M = *PPInfo.first;
4829 unsigned LocalIndex = PPInfo.second;
4830 const PPEntityOffset &PPOffs = M.PreprocessedEntityOffsets[LocalIndex];
4831
Guy Benyei11169dd2012-12-18 14:30:41 +00004832 if (!PP.getPreprocessingRecord()) {
4833 Error("no preprocessing record");
Craig Toppera13603a2014-05-22 05:54:18 +00004834 return nullptr;
Guy Benyei11169dd2012-12-18 14:30:41 +00004835 }
4836
Chris Lattner7fb3bef2013-01-20 00:56:42 +00004837 SavedStreamPosition SavedPosition(M.PreprocessorDetailCursor);
4838 M.PreprocessorDetailCursor.JumpToBit(PPOffs.BitOffset);
4839
4840 llvm::BitstreamEntry Entry =
4841 M.PreprocessorDetailCursor.advance(BitstreamCursor::AF_DontPopBlockAtEnd);
4842 if (Entry.Kind != llvm::BitstreamEntry::Record)
Craig Toppera13603a2014-05-22 05:54:18 +00004843 return nullptr;
Chris Lattner7fb3bef2013-01-20 00:56:42 +00004844
Guy Benyei11169dd2012-12-18 14:30:41 +00004845 // Read the record.
4846 SourceRange Range(ReadSourceLocation(M, PPOffs.Begin),
4847 ReadSourceLocation(M, PPOffs.End));
4848 PreprocessingRecord &PPRec = *PP.getPreprocessingRecord();
Chris Lattner0e6c9402013-01-20 02:38:54 +00004849 StringRef Blob;
Guy Benyei11169dd2012-12-18 14:30:41 +00004850 RecordData Record;
4851 PreprocessorDetailRecordTypes RecType =
Chris Lattner0e6c9402013-01-20 02:38:54 +00004852 (PreprocessorDetailRecordTypes)M.PreprocessorDetailCursor.readRecord(
4853 Entry.ID, Record, &Blob);
Guy Benyei11169dd2012-12-18 14:30:41 +00004854 switch (RecType) {
4855 case PPD_MACRO_EXPANSION: {
4856 bool isBuiltin = Record[0];
Craig Toppera13603a2014-05-22 05:54:18 +00004857 IdentifierInfo *Name = nullptr;
4858 MacroDefinition *Def = nullptr;
Guy Benyei11169dd2012-12-18 14:30:41 +00004859 if (isBuiltin)
4860 Name = getLocalIdentifier(M, Record[1]);
4861 else {
4862 PreprocessedEntityID
4863 GlobalID = getGlobalPreprocessedEntityID(M, Record[1]);
4864 Def =cast<MacroDefinition>(PPRec.getLoadedPreprocessedEntity(GlobalID-1));
4865 }
4866
4867 MacroExpansion *ME;
4868 if (isBuiltin)
4869 ME = new (PPRec) MacroExpansion(Name, Range);
4870 else
4871 ME = new (PPRec) MacroExpansion(Def, Range);
4872
4873 return ME;
4874 }
4875
4876 case PPD_MACRO_DEFINITION: {
4877 // Decode the identifier info and then check again; if the macro is
4878 // still defined and associated with the identifier,
4879 IdentifierInfo *II = getLocalIdentifier(M, Record[0]);
4880 MacroDefinition *MD
4881 = new (PPRec) MacroDefinition(II, Range);
4882
4883 if (DeserializationListener)
4884 DeserializationListener->MacroDefinitionRead(PPID, MD);
4885
4886 return MD;
4887 }
4888
4889 case PPD_INCLUSION_DIRECTIVE: {
Chris Lattner0e6c9402013-01-20 02:38:54 +00004890 const char *FullFileNameStart = Blob.data() + Record[0];
4891 StringRef FullFileName(FullFileNameStart, Blob.size() - Record[0]);
Craig Toppera13603a2014-05-22 05:54:18 +00004892 const FileEntry *File = nullptr;
Guy Benyei11169dd2012-12-18 14:30:41 +00004893 if (!FullFileName.empty())
4894 File = PP.getFileManager().getFile(FullFileName);
4895
4896 // FIXME: Stable encoding
4897 InclusionDirective::InclusionKind Kind
4898 = static_cast<InclusionDirective::InclusionKind>(Record[2]);
4899 InclusionDirective *ID
4900 = new (PPRec) InclusionDirective(PPRec, Kind,
Chris Lattner0e6c9402013-01-20 02:38:54 +00004901 StringRef(Blob.data(), Record[0]),
Guy Benyei11169dd2012-12-18 14:30:41 +00004902 Record[1], Record[3],
4903 File,
4904 Range);
4905 return ID;
4906 }
4907 }
4908
4909 llvm_unreachable("Invalid PreprocessorDetailRecordTypes");
4910}
4911
4912/// \brief \arg SLocMapI points at a chunk of a module that contains no
4913/// preprocessed entities or the entities it contains are not the ones we are
4914/// looking for. Find the next module that contains entities and return the ID
4915/// of the first entry.
4916PreprocessedEntityID ASTReader::findNextPreprocessedEntity(
4917 GlobalSLocOffsetMapType::const_iterator SLocMapI) const {
4918 ++SLocMapI;
4919 for (GlobalSLocOffsetMapType::const_iterator
4920 EndI = GlobalSLocOffsetMap.end(); SLocMapI != EndI; ++SLocMapI) {
4921 ModuleFile &M = *SLocMapI->second;
4922 if (M.NumPreprocessedEntities)
4923 return M.BasePreprocessedEntityID;
4924 }
4925
4926 return getTotalNumPreprocessedEntities();
4927}
4928
4929namespace {
4930
4931template <unsigned PPEntityOffset::*PPLoc>
4932struct PPEntityComp {
4933 const ASTReader &Reader;
4934 ModuleFile &M;
4935
4936 PPEntityComp(const ASTReader &Reader, ModuleFile &M) : Reader(Reader), M(M) { }
4937
4938 bool operator()(const PPEntityOffset &L, const PPEntityOffset &R) const {
4939 SourceLocation LHS = getLoc(L);
4940 SourceLocation RHS = getLoc(R);
4941 return Reader.getSourceManager().isBeforeInTranslationUnit(LHS, RHS);
4942 }
4943
4944 bool operator()(const PPEntityOffset &L, SourceLocation RHS) const {
4945 SourceLocation LHS = getLoc(L);
4946 return Reader.getSourceManager().isBeforeInTranslationUnit(LHS, RHS);
4947 }
4948
4949 bool operator()(SourceLocation LHS, const PPEntityOffset &R) const {
4950 SourceLocation RHS = getLoc(R);
4951 return Reader.getSourceManager().isBeforeInTranslationUnit(LHS, RHS);
4952 }
4953
4954 SourceLocation getLoc(const PPEntityOffset &PPE) const {
4955 return Reader.ReadSourceLocation(M, PPE.*PPLoc);
4956 }
4957};
4958
4959}
4960
Alp Toker2e9ce4c2014-05-16 18:59:21 +00004961PreprocessedEntityID ASTReader::findPreprocessedEntity(SourceLocation Loc,
4962 bool EndsAfter) const {
4963 if (SourceMgr.isLocalSourceLocation(Loc))
Guy Benyei11169dd2012-12-18 14:30:41 +00004964 return getTotalNumPreprocessedEntities();
4965
Alp Toker2e9ce4c2014-05-16 18:59:21 +00004966 GlobalSLocOffsetMapType::const_iterator SLocMapI = GlobalSLocOffsetMap.find(
4967 SourceManager::MaxLoadedOffset - Loc.getOffset() - 1);
Guy Benyei11169dd2012-12-18 14:30:41 +00004968 assert(SLocMapI != GlobalSLocOffsetMap.end() &&
4969 "Corrupted global sloc offset map");
4970
4971 if (SLocMapI->second->NumPreprocessedEntities == 0)
4972 return findNextPreprocessedEntity(SLocMapI);
4973
4974 ModuleFile &M = *SLocMapI->second;
4975 typedef const PPEntityOffset *pp_iterator;
4976 pp_iterator pp_begin = M.PreprocessedEntityOffsets;
4977 pp_iterator pp_end = pp_begin + M.NumPreprocessedEntities;
4978
4979 size_t Count = M.NumPreprocessedEntities;
4980 size_t Half;
4981 pp_iterator First = pp_begin;
4982 pp_iterator PPI;
4983
Alp Toker2e9ce4c2014-05-16 18:59:21 +00004984 if (EndsAfter) {
4985 PPI = std::upper_bound(pp_begin, pp_end, Loc,
4986 PPEntityComp<&PPEntityOffset::Begin>(*this, M));
4987 } else {
4988 // Do a binary search manually instead of using std::lower_bound because
4989 // The end locations of entities may be unordered (when a macro expansion
4990 // is inside another macro argument), but for this case it is not important
4991 // whether we get the first macro expansion or its containing macro.
4992 while (Count > 0) {
4993 Half = Count / 2;
4994 PPI = First;
4995 std::advance(PPI, Half);
4996 if (SourceMgr.isBeforeInTranslationUnit(ReadSourceLocation(M, PPI->End),
4997 Loc)) {
4998 First = PPI;
4999 ++First;
5000 Count = Count - Half - 1;
5001 } else
5002 Count = Half;
5003 }
Guy Benyei11169dd2012-12-18 14:30:41 +00005004 }
5005
5006 if (PPI == pp_end)
5007 return findNextPreprocessedEntity(SLocMapI);
5008
5009 return M.BasePreprocessedEntityID + (PPI - pp_begin);
5010}
5011
Guy Benyei11169dd2012-12-18 14:30:41 +00005012/// \brief Returns a pair of [Begin, End) indices of preallocated
5013/// preprocessed entities that \arg Range encompasses.
5014std::pair<unsigned, unsigned>
5015 ASTReader::findPreprocessedEntitiesInRange(SourceRange Range) {
5016 if (Range.isInvalid())
5017 return std::make_pair(0,0);
5018 assert(!SourceMgr.isBeforeInTranslationUnit(Range.getEnd(),Range.getBegin()));
5019
Alp Toker2e9ce4c2014-05-16 18:59:21 +00005020 PreprocessedEntityID BeginID =
5021 findPreprocessedEntity(Range.getBegin(), false);
5022 PreprocessedEntityID EndID = findPreprocessedEntity(Range.getEnd(), true);
Guy Benyei11169dd2012-12-18 14:30:41 +00005023 return std::make_pair(BeginID, EndID);
5024}
5025
5026/// \brief Optionally returns true or false if the preallocated preprocessed
5027/// entity with index \arg Index came from file \arg FID.
David Blaikie05785d12013-02-20 22:23:23 +00005028Optional<bool> ASTReader::isPreprocessedEntityInFileID(unsigned Index,
Guy Benyei11169dd2012-12-18 14:30:41 +00005029 FileID FID) {
5030 if (FID.isInvalid())
5031 return false;
5032
5033 std::pair<ModuleFile *, unsigned> PPInfo = getModulePreprocessedEntity(Index);
5034 ModuleFile &M = *PPInfo.first;
5035 unsigned LocalIndex = PPInfo.second;
5036 const PPEntityOffset &PPOffs = M.PreprocessedEntityOffsets[LocalIndex];
5037
5038 SourceLocation Loc = ReadSourceLocation(M, PPOffs.Begin);
5039 if (Loc.isInvalid())
5040 return false;
5041
5042 if (SourceMgr.isInFileID(SourceMgr.getFileLoc(Loc), FID))
5043 return true;
5044 else
5045 return false;
5046}
5047
5048namespace {
5049 /// \brief Visitor used to search for information about a header file.
5050 class HeaderFileInfoVisitor {
Guy Benyei11169dd2012-12-18 14:30:41 +00005051 const FileEntry *FE;
5052
David Blaikie05785d12013-02-20 22:23:23 +00005053 Optional<HeaderFileInfo> HFI;
Guy Benyei11169dd2012-12-18 14:30:41 +00005054
5055 public:
Argyrios Kyrtzidis61a38962013-03-06 18:12:44 +00005056 explicit HeaderFileInfoVisitor(const FileEntry *FE)
5057 : FE(FE) { }
Guy Benyei11169dd2012-12-18 14:30:41 +00005058
5059 static bool visit(ModuleFile &M, void *UserData) {
5060 HeaderFileInfoVisitor *This
5061 = static_cast<HeaderFileInfoVisitor *>(UserData);
5062
Guy Benyei11169dd2012-12-18 14:30:41 +00005063 HeaderFileInfoLookupTable *Table
5064 = static_cast<HeaderFileInfoLookupTable *>(M.HeaderFileInfoTable);
5065 if (!Table)
5066 return false;
5067
5068 // Look in the on-disk hash table for an entry for this file name.
Argyrios Kyrtzidis5c2a3452013-03-06 18:12:47 +00005069 HeaderFileInfoLookupTable::iterator Pos = Table->find(This->FE);
Guy Benyei11169dd2012-12-18 14:30:41 +00005070 if (Pos == Table->end())
5071 return false;
5072
5073 This->HFI = *Pos;
5074 return true;
5075 }
5076
David Blaikie05785d12013-02-20 22:23:23 +00005077 Optional<HeaderFileInfo> getHeaderFileInfo() const { return HFI; }
Guy Benyei11169dd2012-12-18 14:30:41 +00005078 };
5079}
5080
5081HeaderFileInfo ASTReader::GetHeaderFileInfo(const FileEntry *FE) {
Argyrios Kyrtzidis61a38962013-03-06 18:12:44 +00005082 HeaderFileInfoVisitor Visitor(FE);
Guy Benyei11169dd2012-12-18 14:30:41 +00005083 ModuleMgr.visit(&HeaderFileInfoVisitor::visit, &Visitor);
Argyrios Kyrtzidis1054bbf2013-05-08 23:46:55 +00005084 if (Optional<HeaderFileInfo> HFI = Visitor.getHeaderFileInfo())
Guy Benyei11169dd2012-12-18 14:30:41 +00005085 return *HFI;
Guy Benyei11169dd2012-12-18 14:30:41 +00005086
5087 return HeaderFileInfo();
5088}
5089
5090void ASTReader::ReadPragmaDiagnosticMappings(DiagnosticsEngine &Diag) {
5091 // FIXME: Make it work properly with modules.
Dmitri Gribenkof8579502013-01-12 19:30:44 +00005092 SmallVector<DiagnosticsEngine::DiagState *, 32> DiagStates;
Guy Benyei11169dd2012-12-18 14:30:41 +00005093 for (ModuleIterator I = ModuleMgr.begin(), E = ModuleMgr.end(); I != E; ++I) {
5094 ModuleFile &F = *(*I);
5095 unsigned Idx = 0;
5096 DiagStates.clear();
5097 assert(!Diag.DiagStates.empty());
5098 DiagStates.push_back(&Diag.DiagStates.front()); // the command-line one.
5099 while (Idx < F.PragmaDiagMappings.size()) {
5100 SourceLocation Loc = ReadSourceLocation(F, F.PragmaDiagMappings[Idx++]);
5101 unsigned DiagStateID = F.PragmaDiagMappings[Idx++];
5102 if (DiagStateID != 0) {
5103 Diag.DiagStatePoints.push_back(
5104 DiagnosticsEngine::DiagStatePoint(DiagStates[DiagStateID-1],
5105 FullSourceLoc(Loc, SourceMgr)));
5106 continue;
5107 }
5108
5109 assert(DiagStateID == 0);
5110 // A new DiagState was created here.
5111 Diag.DiagStates.push_back(*Diag.GetCurDiagState());
5112 DiagnosticsEngine::DiagState *NewState = &Diag.DiagStates.back();
5113 DiagStates.push_back(NewState);
5114 Diag.DiagStatePoints.push_back(
5115 DiagnosticsEngine::DiagStatePoint(NewState,
5116 FullSourceLoc(Loc, SourceMgr)));
5117 while (1) {
5118 assert(Idx < F.PragmaDiagMappings.size() &&
5119 "Invalid data, didn't find '-1' marking end of diag/map pairs");
5120 if (Idx >= F.PragmaDiagMappings.size()) {
5121 break; // Something is messed up but at least avoid infinite loop in
5122 // release build.
5123 }
5124 unsigned DiagID = F.PragmaDiagMappings[Idx++];
5125 if (DiagID == (unsigned)-1) {
5126 break; // no more diag/map pairs for this location.
5127 }
Alp Tokerc726c362014-06-10 09:31:37 +00005128 diag::Severity Map = (diag::Severity)F.PragmaDiagMappings[Idx++];
5129 DiagnosticMapping Mapping = Diag.makeUserMapping(Map, Loc);
5130 Diag.GetCurDiagState()->setMapping(DiagID, Mapping);
Guy Benyei11169dd2012-12-18 14:30:41 +00005131 }
5132 }
5133 }
5134}
5135
5136/// \brief Get the correct cursor and offset for loading a type.
5137ASTReader::RecordLocation ASTReader::TypeCursorForIndex(unsigned Index) {
5138 GlobalTypeMapType::iterator I = GlobalTypeMap.find(Index);
5139 assert(I != GlobalTypeMap.end() && "Corrupted global type map");
5140 ModuleFile *M = I->second;
5141 return RecordLocation(M, M->TypeOffsets[Index - M->BaseTypeIndex]);
5142}
5143
5144/// \brief Read and return the type with the given index..
5145///
5146/// The index is the type ID, shifted and minus the number of predefs. This
5147/// routine actually reads the record corresponding to the type at the given
5148/// location. It is a helper routine for GetType, which deals with reading type
5149/// IDs.
5150QualType ASTReader::readTypeRecord(unsigned Index) {
5151 RecordLocation Loc = TypeCursorForIndex(Index);
Chris Lattner7fb3bef2013-01-20 00:56:42 +00005152 BitstreamCursor &DeclsCursor = Loc.F->DeclsCursor;
Guy Benyei11169dd2012-12-18 14:30:41 +00005153
5154 // Keep track of where we are in the stream, then jump back there
5155 // after reading this type.
5156 SavedStreamPosition SavedPosition(DeclsCursor);
5157
5158 ReadingKindTracker ReadingKind(Read_Type, *this);
5159
5160 // Note that we are loading a type record.
5161 Deserializing AType(this);
5162
5163 unsigned Idx = 0;
5164 DeclsCursor.JumpToBit(Loc.Offset);
5165 RecordData Record;
5166 unsigned Code = DeclsCursor.ReadCode();
Chris Lattner0e6c9402013-01-20 02:38:54 +00005167 switch ((TypeCode)DeclsCursor.readRecord(Code, Record)) {
Guy Benyei11169dd2012-12-18 14:30:41 +00005168 case TYPE_EXT_QUAL: {
5169 if (Record.size() != 2) {
5170 Error("Incorrect encoding of extended qualifier type");
5171 return QualType();
5172 }
5173 QualType Base = readType(*Loc.F, Record, Idx);
5174 Qualifiers Quals = Qualifiers::fromOpaqueValue(Record[Idx++]);
5175 return Context.getQualifiedType(Base, Quals);
5176 }
5177
5178 case TYPE_COMPLEX: {
5179 if (Record.size() != 1) {
5180 Error("Incorrect encoding of complex type");
5181 return QualType();
5182 }
5183 QualType ElemType = readType(*Loc.F, Record, Idx);
5184 return Context.getComplexType(ElemType);
5185 }
5186
5187 case TYPE_POINTER: {
5188 if (Record.size() != 1) {
5189 Error("Incorrect encoding of pointer type");
5190 return QualType();
5191 }
5192 QualType PointeeType = readType(*Loc.F, Record, Idx);
5193 return Context.getPointerType(PointeeType);
5194 }
5195
Reid Kleckner8a365022013-06-24 17:51:48 +00005196 case TYPE_DECAYED: {
5197 if (Record.size() != 1) {
5198 Error("Incorrect encoding of decayed type");
5199 return QualType();
5200 }
5201 QualType OriginalType = readType(*Loc.F, Record, Idx);
5202 QualType DT = Context.getAdjustedParameterType(OriginalType);
5203 if (!isa<DecayedType>(DT))
5204 Error("Decayed type does not decay");
5205 return DT;
5206 }
5207
Reid Kleckner0503a872013-12-05 01:23:43 +00005208 case TYPE_ADJUSTED: {
5209 if (Record.size() != 2) {
5210 Error("Incorrect encoding of adjusted type");
5211 return QualType();
5212 }
5213 QualType OriginalTy = readType(*Loc.F, Record, Idx);
5214 QualType AdjustedTy = readType(*Loc.F, Record, Idx);
5215 return Context.getAdjustedType(OriginalTy, AdjustedTy);
5216 }
5217
Guy Benyei11169dd2012-12-18 14:30:41 +00005218 case TYPE_BLOCK_POINTER: {
5219 if (Record.size() != 1) {
5220 Error("Incorrect encoding of block pointer type");
5221 return QualType();
5222 }
5223 QualType PointeeType = readType(*Loc.F, Record, Idx);
5224 return Context.getBlockPointerType(PointeeType);
5225 }
5226
5227 case TYPE_LVALUE_REFERENCE: {
5228 if (Record.size() != 2) {
5229 Error("Incorrect encoding of lvalue reference type");
5230 return QualType();
5231 }
5232 QualType PointeeType = readType(*Loc.F, Record, Idx);
5233 return Context.getLValueReferenceType(PointeeType, Record[1]);
5234 }
5235
5236 case TYPE_RVALUE_REFERENCE: {
5237 if (Record.size() != 1) {
5238 Error("Incorrect encoding of rvalue reference type");
5239 return QualType();
5240 }
5241 QualType PointeeType = readType(*Loc.F, Record, Idx);
5242 return Context.getRValueReferenceType(PointeeType);
5243 }
5244
5245 case TYPE_MEMBER_POINTER: {
5246 if (Record.size() != 2) {
5247 Error("Incorrect encoding of member pointer type");
5248 return QualType();
5249 }
5250 QualType PointeeType = readType(*Loc.F, Record, Idx);
5251 QualType ClassType = readType(*Loc.F, Record, Idx);
5252 if (PointeeType.isNull() || ClassType.isNull())
5253 return QualType();
5254
5255 return Context.getMemberPointerType(PointeeType, ClassType.getTypePtr());
5256 }
5257
5258 case TYPE_CONSTANT_ARRAY: {
5259 QualType ElementType = readType(*Loc.F, Record, Idx);
5260 ArrayType::ArraySizeModifier ASM = (ArrayType::ArraySizeModifier)Record[1];
5261 unsigned IndexTypeQuals = Record[2];
5262 unsigned Idx = 3;
5263 llvm::APInt Size = ReadAPInt(Record, Idx);
5264 return Context.getConstantArrayType(ElementType, Size,
5265 ASM, IndexTypeQuals);
5266 }
5267
5268 case TYPE_INCOMPLETE_ARRAY: {
5269 QualType ElementType = readType(*Loc.F, Record, Idx);
5270 ArrayType::ArraySizeModifier ASM = (ArrayType::ArraySizeModifier)Record[1];
5271 unsigned IndexTypeQuals = Record[2];
5272 return Context.getIncompleteArrayType(ElementType, ASM, IndexTypeQuals);
5273 }
5274
5275 case TYPE_VARIABLE_ARRAY: {
5276 QualType ElementType = readType(*Loc.F, Record, Idx);
5277 ArrayType::ArraySizeModifier ASM = (ArrayType::ArraySizeModifier)Record[1];
5278 unsigned IndexTypeQuals = Record[2];
5279 SourceLocation LBLoc = ReadSourceLocation(*Loc.F, Record[3]);
5280 SourceLocation RBLoc = ReadSourceLocation(*Loc.F, Record[4]);
5281 return Context.getVariableArrayType(ElementType, ReadExpr(*Loc.F),
5282 ASM, IndexTypeQuals,
5283 SourceRange(LBLoc, RBLoc));
5284 }
5285
5286 case TYPE_VECTOR: {
5287 if (Record.size() != 3) {
5288 Error("incorrect encoding of vector type in AST file");
5289 return QualType();
5290 }
5291
5292 QualType ElementType = readType(*Loc.F, Record, Idx);
5293 unsigned NumElements = Record[1];
5294 unsigned VecKind = Record[2];
5295 return Context.getVectorType(ElementType, NumElements,
5296 (VectorType::VectorKind)VecKind);
5297 }
5298
5299 case TYPE_EXT_VECTOR: {
5300 if (Record.size() != 3) {
5301 Error("incorrect encoding of extended vector type in AST file");
5302 return QualType();
5303 }
5304
5305 QualType ElementType = readType(*Loc.F, Record, Idx);
5306 unsigned NumElements = Record[1];
5307 return Context.getExtVectorType(ElementType, NumElements);
5308 }
5309
5310 case TYPE_FUNCTION_NO_PROTO: {
5311 if (Record.size() != 6) {
5312 Error("incorrect encoding of no-proto function type");
5313 return QualType();
5314 }
5315 QualType ResultType = readType(*Loc.F, Record, Idx);
5316 FunctionType::ExtInfo Info(Record[1], Record[2], Record[3],
5317 (CallingConv)Record[4], Record[5]);
5318 return Context.getFunctionNoProtoType(ResultType, Info);
5319 }
5320
5321 case TYPE_FUNCTION_PROTO: {
5322 QualType ResultType = readType(*Loc.F, Record, Idx);
5323
5324 FunctionProtoType::ExtProtoInfo EPI;
5325 EPI.ExtInfo = FunctionType::ExtInfo(/*noreturn*/ Record[1],
5326 /*hasregparm*/ Record[2],
5327 /*regparm*/ Record[3],
5328 static_cast<CallingConv>(Record[4]),
5329 /*produces*/ Record[5]);
5330
5331 unsigned Idx = 6;
Guy Benyei11169dd2012-12-18 14:30:41 +00005332
5333 EPI.Variadic = Record[Idx++];
5334 EPI.HasTrailingReturn = Record[Idx++];
5335 EPI.TypeQuals = Record[Idx++];
5336 EPI.RefQualifier = static_cast<RefQualifierKind>(Record[Idx++]);
Richard Smith564417a2014-03-20 21:47:22 +00005337 SmallVector<QualType, 8> ExceptionStorage;
Richard Smith8acb4282014-07-31 21:57:55 +00005338 readExceptionSpec(*Loc.F, ExceptionStorage, EPI.ExceptionSpec, Record, Idx);
Richard Smith01b2cb42014-07-26 06:37:51 +00005339
5340 unsigned NumParams = Record[Idx++];
5341 SmallVector<QualType, 16> ParamTypes;
5342 for (unsigned I = 0; I != NumParams; ++I)
5343 ParamTypes.push_back(readType(*Loc.F, Record, Idx));
5344
Jordan Rose5c382722013-03-08 21:51:21 +00005345 return Context.getFunctionType(ResultType, ParamTypes, EPI);
Guy Benyei11169dd2012-12-18 14:30:41 +00005346 }
5347
5348 case TYPE_UNRESOLVED_USING: {
5349 unsigned Idx = 0;
5350 return Context.getTypeDeclType(
5351 ReadDeclAs<UnresolvedUsingTypenameDecl>(*Loc.F, Record, Idx));
5352 }
5353
5354 case TYPE_TYPEDEF: {
5355 if (Record.size() != 2) {
5356 Error("incorrect encoding of typedef type");
5357 return QualType();
5358 }
5359 unsigned Idx = 0;
5360 TypedefNameDecl *Decl = ReadDeclAs<TypedefNameDecl>(*Loc.F, Record, Idx);
5361 QualType Canonical = readType(*Loc.F, Record, Idx);
5362 if (!Canonical.isNull())
5363 Canonical = Context.getCanonicalType(Canonical);
5364 return Context.getTypedefType(Decl, Canonical);
5365 }
5366
5367 case TYPE_TYPEOF_EXPR:
5368 return Context.getTypeOfExprType(ReadExpr(*Loc.F));
5369
5370 case TYPE_TYPEOF: {
5371 if (Record.size() != 1) {
5372 Error("incorrect encoding of typeof(type) in AST file");
5373 return QualType();
5374 }
5375 QualType UnderlyingType = readType(*Loc.F, Record, Idx);
5376 return Context.getTypeOfType(UnderlyingType);
5377 }
5378
5379 case TYPE_DECLTYPE: {
5380 QualType UnderlyingType = readType(*Loc.F, Record, Idx);
5381 return Context.getDecltypeType(ReadExpr(*Loc.F), UnderlyingType);
5382 }
5383
5384 case TYPE_UNARY_TRANSFORM: {
5385 QualType BaseType = readType(*Loc.F, Record, Idx);
5386 QualType UnderlyingType = readType(*Loc.F, Record, Idx);
5387 UnaryTransformType::UTTKind UKind = (UnaryTransformType::UTTKind)Record[2];
5388 return Context.getUnaryTransformType(BaseType, UnderlyingType, UKind);
5389 }
5390
Richard Smith74aeef52013-04-26 16:15:35 +00005391 case TYPE_AUTO: {
5392 QualType Deduced = readType(*Loc.F, Record, Idx);
5393 bool IsDecltypeAuto = Record[Idx++];
Richard Smith27d807c2013-04-30 13:56:41 +00005394 bool IsDependent = Deduced.isNull() ? Record[Idx++] : false;
Manuel Klimek2fdbea22013-08-22 12:12:24 +00005395 return Context.getAutoType(Deduced, IsDecltypeAuto, IsDependent);
Richard Smith74aeef52013-04-26 16:15:35 +00005396 }
Guy Benyei11169dd2012-12-18 14:30:41 +00005397
5398 case TYPE_RECORD: {
5399 if (Record.size() != 2) {
5400 Error("incorrect encoding of record type");
5401 return QualType();
5402 }
5403 unsigned Idx = 0;
5404 bool IsDependent = Record[Idx++];
5405 RecordDecl *RD = ReadDeclAs<RecordDecl>(*Loc.F, Record, Idx);
5406 RD = cast_or_null<RecordDecl>(RD->getCanonicalDecl());
5407 QualType T = Context.getRecordType(RD);
5408 const_cast<Type*>(T.getTypePtr())->setDependent(IsDependent);
5409 return T;
5410 }
5411
5412 case TYPE_ENUM: {
5413 if (Record.size() != 2) {
5414 Error("incorrect encoding of enum type");
5415 return QualType();
5416 }
5417 unsigned Idx = 0;
5418 bool IsDependent = Record[Idx++];
5419 QualType T
5420 = Context.getEnumType(ReadDeclAs<EnumDecl>(*Loc.F, Record, Idx));
5421 const_cast<Type*>(T.getTypePtr())->setDependent(IsDependent);
5422 return T;
5423 }
5424
5425 case TYPE_ATTRIBUTED: {
5426 if (Record.size() != 3) {
5427 Error("incorrect encoding of attributed type");
5428 return QualType();
5429 }
5430 QualType modifiedType = readType(*Loc.F, Record, Idx);
5431 QualType equivalentType = readType(*Loc.F, Record, Idx);
5432 AttributedType::Kind kind = static_cast<AttributedType::Kind>(Record[2]);
5433 return Context.getAttributedType(kind, modifiedType, equivalentType);
5434 }
5435
5436 case TYPE_PAREN: {
5437 if (Record.size() != 1) {
5438 Error("incorrect encoding of paren type");
5439 return QualType();
5440 }
5441 QualType InnerType = readType(*Loc.F, Record, Idx);
5442 return Context.getParenType(InnerType);
5443 }
5444
5445 case TYPE_PACK_EXPANSION: {
5446 if (Record.size() != 2) {
5447 Error("incorrect encoding of pack expansion type");
5448 return QualType();
5449 }
5450 QualType Pattern = readType(*Loc.F, Record, Idx);
5451 if (Pattern.isNull())
5452 return QualType();
David Blaikie05785d12013-02-20 22:23:23 +00005453 Optional<unsigned> NumExpansions;
Guy Benyei11169dd2012-12-18 14:30:41 +00005454 if (Record[1])
5455 NumExpansions = Record[1] - 1;
5456 return Context.getPackExpansionType(Pattern, NumExpansions);
5457 }
5458
5459 case TYPE_ELABORATED: {
5460 unsigned Idx = 0;
5461 ElaboratedTypeKeyword Keyword = (ElaboratedTypeKeyword)Record[Idx++];
5462 NestedNameSpecifier *NNS = ReadNestedNameSpecifier(*Loc.F, Record, Idx);
5463 QualType NamedType = readType(*Loc.F, Record, Idx);
5464 return Context.getElaboratedType(Keyword, NNS, NamedType);
5465 }
5466
5467 case TYPE_OBJC_INTERFACE: {
5468 unsigned Idx = 0;
5469 ObjCInterfaceDecl *ItfD
5470 = ReadDeclAs<ObjCInterfaceDecl>(*Loc.F, Record, Idx);
5471 return Context.getObjCInterfaceType(ItfD->getCanonicalDecl());
5472 }
5473
5474 case TYPE_OBJC_OBJECT: {
5475 unsigned Idx = 0;
5476 QualType Base = readType(*Loc.F, Record, Idx);
5477 unsigned NumProtos = Record[Idx++];
5478 SmallVector<ObjCProtocolDecl*, 4> Protos;
5479 for (unsigned I = 0; I != NumProtos; ++I)
5480 Protos.push_back(ReadDeclAs<ObjCProtocolDecl>(*Loc.F, Record, Idx));
5481 return Context.getObjCObjectType(Base, Protos.data(), NumProtos);
5482 }
5483
5484 case TYPE_OBJC_OBJECT_POINTER: {
5485 unsigned Idx = 0;
5486 QualType Pointee = readType(*Loc.F, Record, Idx);
5487 return Context.getObjCObjectPointerType(Pointee);
5488 }
5489
5490 case TYPE_SUBST_TEMPLATE_TYPE_PARM: {
5491 unsigned Idx = 0;
5492 QualType Parm = readType(*Loc.F, Record, Idx);
5493 QualType Replacement = readType(*Loc.F, Record, Idx);
Stephan Tolksdorfe96f8b32014-03-15 10:23:27 +00005494 return Context.getSubstTemplateTypeParmType(
5495 cast<TemplateTypeParmType>(Parm),
5496 Context.getCanonicalType(Replacement));
Guy Benyei11169dd2012-12-18 14:30:41 +00005497 }
5498
5499 case TYPE_SUBST_TEMPLATE_TYPE_PARM_PACK: {
5500 unsigned Idx = 0;
5501 QualType Parm = readType(*Loc.F, Record, Idx);
5502 TemplateArgument ArgPack = ReadTemplateArgument(*Loc.F, Record, Idx);
5503 return Context.getSubstTemplateTypeParmPackType(
5504 cast<TemplateTypeParmType>(Parm),
5505 ArgPack);
5506 }
5507
5508 case TYPE_INJECTED_CLASS_NAME: {
5509 CXXRecordDecl *D = ReadDeclAs<CXXRecordDecl>(*Loc.F, Record, Idx);
5510 QualType TST = readType(*Loc.F, Record, Idx); // probably derivable
5511 // FIXME: ASTContext::getInjectedClassNameType is not currently suitable
5512 // for AST reading, too much interdependencies.
Richard Smith6377f8f2014-10-21 21:15:18 +00005513 const Type *T = nullptr;
5514 for (auto *DI = D; DI; DI = DI->getPreviousDecl()) {
5515 if (const Type *Existing = DI->getTypeForDecl()) {
5516 T = Existing;
5517 break;
5518 }
5519 }
5520 if (!T) {
Richard Smithf17fdbd2014-04-24 02:25:27 +00005521 T = new (Context, TypeAlignment) InjectedClassNameType(D, TST);
Richard Smith6377f8f2014-10-21 21:15:18 +00005522 for (auto *DI = D; DI; DI = DI->getPreviousDecl())
5523 DI->setTypeForDecl(T);
5524 }
Richard Smithf17fdbd2014-04-24 02:25:27 +00005525 return QualType(T, 0);
Guy Benyei11169dd2012-12-18 14:30:41 +00005526 }
5527
5528 case TYPE_TEMPLATE_TYPE_PARM: {
5529 unsigned Idx = 0;
5530 unsigned Depth = Record[Idx++];
5531 unsigned Index = Record[Idx++];
5532 bool Pack = Record[Idx++];
5533 TemplateTypeParmDecl *D
5534 = ReadDeclAs<TemplateTypeParmDecl>(*Loc.F, Record, Idx);
5535 return Context.getTemplateTypeParmType(Depth, Index, Pack, D);
5536 }
5537
5538 case TYPE_DEPENDENT_NAME: {
5539 unsigned Idx = 0;
5540 ElaboratedTypeKeyword Keyword = (ElaboratedTypeKeyword)Record[Idx++];
5541 NestedNameSpecifier *NNS = ReadNestedNameSpecifier(*Loc.F, Record, Idx);
5542 const IdentifierInfo *Name = this->GetIdentifierInfo(*Loc.F, Record, Idx);
5543 QualType Canon = readType(*Loc.F, Record, Idx);
5544 if (!Canon.isNull())
5545 Canon = Context.getCanonicalType(Canon);
5546 return Context.getDependentNameType(Keyword, NNS, Name, Canon);
5547 }
5548
5549 case TYPE_DEPENDENT_TEMPLATE_SPECIALIZATION: {
5550 unsigned Idx = 0;
5551 ElaboratedTypeKeyword Keyword = (ElaboratedTypeKeyword)Record[Idx++];
5552 NestedNameSpecifier *NNS = ReadNestedNameSpecifier(*Loc.F, Record, Idx);
5553 const IdentifierInfo *Name = this->GetIdentifierInfo(*Loc.F, Record, Idx);
5554 unsigned NumArgs = Record[Idx++];
5555 SmallVector<TemplateArgument, 8> Args;
5556 Args.reserve(NumArgs);
5557 while (NumArgs--)
5558 Args.push_back(ReadTemplateArgument(*Loc.F, Record, Idx));
5559 return Context.getDependentTemplateSpecializationType(Keyword, NNS, Name,
5560 Args.size(), Args.data());
5561 }
5562
5563 case TYPE_DEPENDENT_SIZED_ARRAY: {
5564 unsigned Idx = 0;
5565
5566 // ArrayType
5567 QualType ElementType = readType(*Loc.F, Record, Idx);
5568 ArrayType::ArraySizeModifier ASM
5569 = (ArrayType::ArraySizeModifier)Record[Idx++];
5570 unsigned IndexTypeQuals = Record[Idx++];
5571
5572 // DependentSizedArrayType
5573 Expr *NumElts = ReadExpr(*Loc.F);
5574 SourceRange Brackets = ReadSourceRange(*Loc.F, Record, Idx);
5575
5576 return Context.getDependentSizedArrayType(ElementType, NumElts, ASM,
5577 IndexTypeQuals, Brackets);
5578 }
5579
5580 case TYPE_TEMPLATE_SPECIALIZATION: {
5581 unsigned Idx = 0;
5582 bool IsDependent = Record[Idx++];
5583 TemplateName Name = ReadTemplateName(*Loc.F, Record, Idx);
5584 SmallVector<TemplateArgument, 8> Args;
5585 ReadTemplateArgumentList(Args, *Loc.F, Record, Idx);
5586 QualType Underlying = readType(*Loc.F, Record, Idx);
5587 QualType T;
5588 if (Underlying.isNull())
5589 T = Context.getCanonicalTemplateSpecializationType(Name, Args.data(),
5590 Args.size());
5591 else
5592 T = Context.getTemplateSpecializationType(Name, Args.data(),
5593 Args.size(), Underlying);
5594 const_cast<Type*>(T.getTypePtr())->setDependent(IsDependent);
5595 return T;
5596 }
5597
5598 case TYPE_ATOMIC: {
5599 if (Record.size() != 1) {
5600 Error("Incorrect encoding of atomic type");
5601 return QualType();
5602 }
5603 QualType ValueType = readType(*Loc.F, Record, Idx);
5604 return Context.getAtomicType(ValueType);
5605 }
5606 }
5607 llvm_unreachable("Invalid TypeCode!");
5608}
5609
Richard Smith564417a2014-03-20 21:47:22 +00005610void ASTReader::readExceptionSpec(ModuleFile &ModuleFile,
5611 SmallVectorImpl<QualType> &Exceptions,
Richard Smith8acb4282014-07-31 21:57:55 +00005612 FunctionProtoType::ExceptionSpecInfo &ESI,
Richard Smith564417a2014-03-20 21:47:22 +00005613 const RecordData &Record, unsigned &Idx) {
5614 ExceptionSpecificationType EST =
5615 static_cast<ExceptionSpecificationType>(Record[Idx++]);
Richard Smith8acb4282014-07-31 21:57:55 +00005616 ESI.Type = EST;
Richard Smith564417a2014-03-20 21:47:22 +00005617 if (EST == EST_Dynamic) {
Richard Smith8acb4282014-07-31 21:57:55 +00005618 for (unsigned I = 0, N = Record[Idx++]; I != N; ++I)
Richard Smith564417a2014-03-20 21:47:22 +00005619 Exceptions.push_back(readType(ModuleFile, Record, Idx));
Richard Smith8acb4282014-07-31 21:57:55 +00005620 ESI.Exceptions = Exceptions;
Richard Smith564417a2014-03-20 21:47:22 +00005621 } else if (EST == EST_ComputedNoexcept) {
Richard Smith8acb4282014-07-31 21:57:55 +00005622 ESI.NoexceptExpr = ReadExpr(ModuleFile);
Richard Smith564417a2014-03-20 21:47:22 +00005623 } else if (EST == EST_Uninstantiated) {
Richard Smith8acb4282014-07-31 21:57:55 +00005624 ESI.SourceDecl = ReadDeclAs<FunctionDecl>(ModuleFile, Record, Idx);
5625 ESI.SourceTemplate = ReadDeclAs<FunctionDecl>(ModuleFile, Record, Idx);
Richard Smith564417a2014-03-20 21:47:22 +00005626 } else if (EST == EST_Unevaluated) {
Richard Smith8acb4282014-07-31 21:57:55 +00005627 ESI.SourceDecl = ReadDeclAs<FunctionDecl>(ModuleFile, Record, Idx);
Richard Smith564417a2014-03-20 21:47:22 +00005628 }
5629}
5630
Guy Benyei11169dd2012-12-18 14:30:41 +00005631class clang::TypeLocReader : public TypeLocVisitor<TypeLocReader> {
5632 ASTReader &Reader;
5633 ModuleFile &F;
5634 const ASTReader::RecordData &Record;
5635 unsigned &Idx;
5636
5637 SourceLocation ReadSourceLocation(const ASTReader::RecordData &R,
5638 unsigned &I) {
5639 return Reader.ReadSourceLocation(F, R, I);
5640 }
5641
5642 template<typename T>
5643 T *ReadDeclAs(const ASTReader::RecordData &Record, unsigned &Idx) {
5644 return Reader.ReadDeclAs<T>(F, Record, Idx);
5645 }
5646
5647public:
5648 TypeLocReader(ASTReader &Reader, ModuleFile &F,
5649 const ASTReader::RecordData &Record, unsigned &Idx)
5650 : Reader(Reader), F(F), Record(Record), Idx(Idx)
5651 { }
5652
5653 // We want compile-time assurance that we've enumerated all of
5654 // these, so unfortunately we have to declare them first, then
5655 // define them out-of-line.
5656#define ABSTRACT_TYPELOC(CLASS, PARENT)
5657#define TYPELOC(CLASS, PARENT) \
5658 void Visit##CLASS##TypeLoc(CLASS##TypeLoc TyLoc);
5659#include "clang/AST/TypeLocNodes.def"
5660
5661 void VisitFunctionTypeLoc(FunctionTypeLoc);
5662 void VisitArrayTypeLoc(ArrayTypeLoc);
5663};
5664
5665void TypeLocReader::VisitQualifiedTypeLoc(QualifiedTypeLoc TL) {
5666 // nothing to do
5667}
5668void TypeLocReader::VisitBuiltinTypeLoc(BuiltinTypeLoc TL) {
5669 TL.setBuiltinLoc(ReadSourceLocation(Record, Idx));
5670 if (TL.needsExtraLocalData()) {
5671 TL.setWrittenTypeSpec(static_cast<DeclSpec::TST>(Record[Idx++]));
5672 TL.setWrittenSignSpec(static_cast<DeclSpec::TSS>(Record[Idx++]));
5673 TL.setWrittenWidthSpec(static_cast<DeclSpec::TSW>(Record[Idx++]));
5674 TL.setModeAttr(Record[Idx++]);
5675 }
5676}
5677void TypeLocReader::VisitComplexTypeLoc(ComplexTypeLoc TL) {
5678 TL.setNameLoc(ReadSourceLocation(Record, Idx));
5679}
5680void TypeLocReader::VisitPointerTypeLoc(PointerTypeLoc TL) {
5681 TL.setStarLoc(ReadSourceLocation(Record, Idx));
5682}
Reid Kleckner8a365022013-06-24 17:51:48 +00005683void TypeLocReader::VisitDecayedTypeLoc(DecayedTypeLoc TL) {
5684 // nothing to do
5685}
Reid Kleckner0503a872013-12-05 01:23:43 +00005686void TypeLocReader::VisitAdjustedTypeLoc(AdjustedTypeLoc TL) {
5687 // nothing to do
5688}
Guy Benyei11169dd2012-12-18 14:30:41 +00005689void TypeLocReader::VisitBlockPointerTypeLoc(BlockPointerTypeLoc TL) {
5690 TL.setCaretLoc(ReadSourceLocation(Record, Idx));
5691}
5692void TypeLocReader::VisitLValueReferenceTypeLoc(LValueReferenceTypeLoc TL) {
5693 TL.setAmpLoc(ReadSourceLocation(Record, Idx));
5694}
5695void TypeLocReader::VisitRValueReferenceTypeLoc(RValueReferenceTypeLoc TL) {
5696 TL.setAmpAmpLoc(ReadSourceLocation(Record, Idx));
5697}
5698void TypeLocReader::VisitMemberPointerTypeLoc(MemberPointerTypeLoc TL) {
5699 TL.setStarLoc(ReadSourceLocation(Record, Idx));
5700 TL.setClassTInfo(Reader.GetTypeSourceInfo(F, Record, Idx));
5701}
5702void TypeLocReader::VisitArrayTypeLoc(ArrayTypeLoc TL) {
5703 TL.setLBracketLoc(ReadSourceLocation(Record, Idx));
5704 TL.setRBracketLoc(ReadSourceLocation(Record, Idx));
5705 if (Record[Idx++])
5706 TL.setSizeExpr(Reader.ReadExpr(F));
5707 else
Craig Toppera13603a2014-05-22 05:54:18 +00005708 TL.setSizeExpr(nullptr);
Guy Benyei11169dd2012-12-18 14:30:41 +00005709}
5710void TypeLocReader::VisitConstantArrayTypeLoc(ConstantArrayTypeLoc TL) {
5711 VisitArrayTypeLoc(TL);
5712}
5713void TypeLocReader::VisitIncompleteArrayTypeLoc(IncompleteArrayTypeLoc TL) {
5714 VisitArrayTypeLoc(TL);
5715}
5716void TypeLocReader::VisitVariableArrayTypeLoc(VariableArrayTypeLoc TL) {
5717 VisitArrayTypeLoc(TL);
5718}
5719void TypeLocReader::VisitDependentSizedArrayTypeLoc(
5720 DependentSizedArrayTypeLoc TL) {
5721 VisitArrayTypeLoc(TL);
5722}
5723void TypeLocReader::VisitDependentSizedExtVectorTypeLoc(
5724 DependentSizedExtVectorTypeLoc TL) {
5725 TL.setNameLoc(ReadSourceLocation(Record, Idx));
5726}
5727void TypeLocReader::VisitVectorTypeLoc(VectorTypeLoc TL) {
5728 TL.setNameLoc(ReadSourceLocation(Record, Idx));
5729}
5730void TypeLocReader::VisitExtVectorTypeLoc(ExtVectorTypeLoc TL) {
5731 TL.setNameLoc(ReadSourceLocation(Record, Idx));
5732}
5733void TypeLocReader::VisitFunctionTypeLoc(FunctionTypeLoc TL) {
5734 TL.setLocalRangeBegin(ReadSourceLocation(Record, Idx));
5735 TL.setLParenLoc(ReadSourceLocation(Record, Idx));
5736 TL.setRParenLoc(ReadSourceLocation(Record, Idx));
5737 TL.setLocalRangeEnd(ReadSourceLocation(Record, Idx));
Alp Tokerb3fd5cf2014-01-21 00:32:38 +00005738 for (unsigned i = 0, e = TL.getNumParams(); i != e; ++i) {
5739 TL.setParam(i, ReadDeclAs<ParmVarDecl>(Record, Idx));
Guy Benyei11169dd2012-12-18 14:30:41 +00005740 }
5741}
5742void TypeLocReader::VisitFunctionProtoTypeLoc(FunctionProtoTypeLoc TL) {
5743 VisitFunctionTypeLoc(TL);
5744}
5745void TypeLocReader::VisitFunctionNoProtoTypeLoc(FunctionNoProtoTypeLoc TL) {
5746 VisitFunctionTypeLoc(TL);
5747}
5748void TypeLocReader::VisitUnresolvedUsingTypeLoc(UnresolvedUsingTypeLoc TL) {
5749 TL.setNameLoc(ReadSourceLocation(Record, Idx));
5750}
5751void TypeLocReader::VisitTypedefTypeLoc(TypedefTypeLoc TL) {
5752 TL.setNameLoc(ReadSourceLocation(Record, Idx));
5753}
5754void TypeLocReader::VisitTypeOfExprTypeLoc(TypeOfExprTypeLoc TL) {
5755 TL.setTypeofLoc(ReadSourceLocation(Record, Idx));
5756 TL.setLParenLoc(ReadSourceLocation(Record, Idx));
5757 TL.setRParenLoc(ReadSourceLocation(Record, Idx));
5758}
5759void TypeLocReader::VisitTypeOfTypeLoc(TypeOfTypeLoc TL) {
5760 TL.setTypeofLoc(ReadSourceLocation(Record, Idx));
5761 TL.setLParenLoc(ReadSourceLocation(Record, Idx));
5762 TL.setRParenLoc(ReadSourceLocation(Record, Idx));
5763 TL.setUnderlyingTInfo(Reader.GetTypeSourceInfo(F, Record, Idx));
5764}
5765void TypeLocReader::VisitDecltypeTypeLoc(DecltypeTypeLoc TL) {
5766 TL.setNameLoc(ReadSourceLocation(Record, Idx));
5767}
5768void TypeLocReader::VisitUnaryTransformTypeLoc(UnaryTransformTypeLoc TL) {
5769 TL.setKWLoc(ReadSourceLocation(Record, Idx));
5770 TL.setLParenLoc(ReadSourceLocation(Record, Idx));
5771 TL.setRParenLoc(ReadSourceLocation(Record, Idx));
5772 TL.setUnderlyingTInfo(Reader.GetTypeSourceInfo(F, Record, Idx));
5773}
5774void TypeLocReader::VisitAutoTypeLoc(AutoTypeLoc TL) {
5775 TL.setNameLoc(ReadSourceLocation(Record, Idx));
5776}
5777void TypeLocReader::VisitRecordTypeLoc(RecordTypeLoc TL) {
5778 TL.setNameLoc(ReadSourceLocation(Record, Idx));
5779}
5780void TypeLocReader::VisitEnumTypeLoc(EnumTypeLoc TL) {
5781 TL.setNameLoc(ReadSourceLocation(Record, Idx));
5782}
5783void TypeLocReader::VisitAttributedTypeLoc(AttributedTypeLoc TL) {
5784 TL.setAttrNameLoc(ReadSourceLocation(Record, Idx));
5785 if (TL.hasAttrOperand()) {
5786 SourceRange range;
5787 range.setBegin(ReadSourceLocation(Record, Idx));
5788 range.setEnd(ReadSourceLocation(Record, Idx));
5789 TL.setAttrOperandParensRange(range);
5790 }
5791 if (TL.hasAttrExprOperand()) {
5792 if (Record[Idx++])
5793 TL.setAttrExprOperand(Reader.ReadExpr(F));
5794 else
Craig Toppera13603a2014-05-22 05:54:18 +00005795 TL.setAttrExprOperand(nullptr);
Guy Benyei11169dd2012-12-18 14:30:41 +00005796 } else if (TL.hasAttrEnumOperand())
5797 TL.setAttrEnumOperandLoc(ReadSourceLocation(Record, Idx));
5798}
5799void TypeLocReader::VisitTemplateTypeParmTypeLoc(TemplateTypeParmTypeLoc TL) {
5800 TL.setNameLoc(ReadSourceLocation(Record, Idx));
5801}
5802void TypeLocReader::VisitSubstTemplateTypeParmTypeLoc(
5803 SubstTemplateTypeParmTypeLoc TL) {
5804 TL.setNameLoc(ReadSourceLocation(Record, Idx));
5805}
5806void TypeLocReader::VisitSubstTemplateTypeParmPackTypeLoc(
5807 SubstTemplateTypeParmPackTypeLoc TL) {
5808 TL.setNameLoc(ReadSourceLocation(Record, Idx));
5809}
5810void TypeLocReader::VisitTemplateSpecializationTypeLoc(
5811 TemplateSpecializationTypeLoc TL) {
5812 TL.setTemplateKeywordLoc(ReadSourceLocation(Record, Idx));
5813 TL.setTemplateNameLoc(ReadSourceLocation(Record, Idx));
5814 TL.setLAngleLoc(ReadSourceLocation(Record, Idx));
5815 TL.setRAngleLoc(ReadSourceLocation(Record, Idx));
5816 for (unsigned i = 0, e = TL.getNumArgs(); i != e; ++i)
5817 TL.setArgLocInfo(i,
5818 Reader.GetTemplateArgumentLocInfo(F,
5819 TL.getTypePtr()->getArg(i).getKind(),
5820 Record, Idx));
5821}
5822void TypeLocReader::VisitParenTypeLoc(ParenTypeLoc TL) {
5823 TL.setLParenLoc(ReadSourceLocation(Record, Idx));
5824 TL.setRParenLoc(ReadSourceLocation(Record, Idx));
5825}
5826void TypeLocReader::VisitElaboratedTypeLoc(ElaboratedTypeLoc TL) {
5827 TL.setElaboratedKeywordLoc(ReadSourceLocation(Record, Idx));
5828 TL.setQualifierLoc(Reader.ReadNestedNameSpecifierLoc(F, Record, Idx));
5829}
5830void TypeLocReader::VisitInjectedClassNameTypeLoc(InjectedClassNameTypeLoc TL) {
5831 TL.setNameLoc(ReadSourceLocation(Record, Idx));
5832}
5833void TypeLocReader::VisitDependentNameTypeLoc(DependentNameTypeLoc TL) {
5834 TL.setElaboratedKeywordLoc(ReadSourceLocation(Record, Idx));
5835 TL.setQualifierLoc(Reader.ReadNestedNameSpecifierLoc(F, Record, Idx));
5836 TL.setNameLoc(ReadSourceLocation(Record, Idx));
5837}
5838void TypeLocReader::VisitDependentTemplateSpecializationTypeLoc(
5839 DependentTemplateSpecializationTypeLoc TL) {
5840 TL.setElaboratedKeywordLoc(ReadSourceLocation(Record, Idx));
5841 TL.setQualifierLoc(Reader.ReadNestedNameSpecifierLoc(F, Record, Idx));
5842 TL.setTemplateKeywordLoc(ReadSourceLocation(Record, Idx));
5843 TL.setTemplateNameLoc(ReadSourceLocation(Record, Idx));
5844 TL.setLAngleLoc(ReadSourceLocation(Record, Idx));
5845 TL.setRAngleLoc(ReadSourceLocation(Record, Idx));
5846 for (unsigned I = 0, E = TL.getNumArgs(); I != E; ++I)
5847 TL.setArgLocInfo(I,
5848 Reader.GetTemplateArgumentLocInfo(F,
5849 TL.getTypePtr()->getArg(I).getKind(),
5850 Record, Idx));
5851}
5852void TypeLocReader::VisitPackExpansionTypeLoc(PackExpansionTypeLoc TL) {
5853 TL.setEllipsisLoc(ReadSourceLocation(Record, Idx));
5854}
5855void TypeLocReader::VisitObjCInterfaceTypeLoc(ObjCInterfaceTypeLoc TL) {
5856 TL.setNameLoc(ReadSourceLocation(Record, Idx));
5857}
5858void TypeLocReader::VisitObjCObjectTypeLoc(ObjCObjectTypeLoc TL) {
5859 TL.setHasBaseTypeAsWritten(Record[Idx++]);
5860 TL.setLAngleLoc(ReadSourceLocation(Record, Idx));
5861 TL.setRAngleLoc(ReadSourceLocation(Record, Idx));
5862 for (unsigned i = 0, e = TL.getNumProtocols(); i != e; ++i)
5863 TL.setProtocolLoc(i, ReadSourceLocation(Record, Idx));
5864}
5865void TypeLocReader::VisitObjCObjectPointerTypeLoc(ObjCObjectPointerTypeLoc TL) {
5866 TL.setStarLoc(ReadSourceLocation(Record, Idx));
5867}
5868void TypeLocReader::VisitAtomicTypeLoc(AtomicTypeLoc TL) {
5869 TL.setKWLoc(ReadSourceLocation(Record, Idx));
5870 TL.setLParenLoc(ReadSourceLocation(Record, Idx));
5871 TL.setRParenLoc(ReadSourceLocation(Record, Idx));
5872}
5873
5874TypeSourceInfo *ASTReader::GetTypeSourceInfo(ModuleFile &F,
5875 const RecordData &Record,
5876 unsigned &Idx) {
5877 QualType InfoTy = readType(F, Record, Idx);
5878 if (InfoTy.isNull())
Craig Toppera13603a2014-05-22 05:54:18 +00005879 return nullptr;
Guy Benyei11169dd2012-12-18 14:30:41 +00005880
5881 TypeSourceInfo *TInfo = getContext().CreateTypeSourceInfo(InfoTy);
5882 TypeLocReader TLR(*this, F, Record, Idx);
5883 for (TypeLoc TL = TInfo->getTypeLoc(); !TL.isNull(); TL = TL.getNextTypeLoc())
5884 TLR.Visit(TL);
5885 return TInfo;
5886}
5887
5888QualType ASTReader::GetType(TypeID ID) {
5889 unsigned FastQuals = ID & Qualifiers::FastMask;
5890 unsigned Index = ID >> Qualifiers::FastWidth;
5891
5892 if (Index < NUM_PREDEF_TYPE_IDS) {
5893 QualType T;
5894 switch ((PredefinedTypeIDs)Index) {
5895 case PREDEF_TYPE_NULL_ID: return QualType();
5896 case PREDEF_TYPE_VOID_ID: T = Context.VoidTy; break;
5897 case PREDEF_TYPE_BOOL_ID: T = Context.BoolTy; break;
5898
5899 case PREDEF_TYPE_CHAR_U_ID:
5900 case PREDEF_TYPE_CHAR_S_ID:
5901 // FIXME: Check that the signedness of CharTy is correct!
5902 T = Context.CharTy;
5903 break;
5904
5905 case PREDEF_TYPE_UCHAR_ID: T = Context.UnsignedCharTy; break;
5906 case PREDEF_TYPE_USHORT_ID: T = Context.UnsignedShortTy; break;
5907 case PREDEF_TYPE_UINT_ID: T = Context.UnsignedIntTy; break;
5908 case PREDEF_TYPE_ULONG_ID: T = Context.UnsignedLongTy; break;
5909 case PREDEF_TYPE_ULONGLONG_ID: T = Context.UnsignedLongLongTy; break;
5910 case PREDEF_TYPE_UINT128_ID: T = Context.UnsignedInt128Ty; break;
5911 case PREDEF_TYPE_SCHAR_ID: T = Context.SignedCharTy; break;
5912 case PREDEF_TYPE_WCHAR_ID: T = Context.WCharTy; break;
5913 case PREDEF_TYPE_SHORT_ID: T = Context.ShortTy; break;
5914 case PREDEF_TYPE_INT_ID: T = Context.IntTy; break;
5915 case PREDEF_TYPE_LONG_ID: T = Context.LongTy; break;
5916 case PREDEF_TYPE_LONGLONG_ID: T = Context.LongLongTy; break;
5917 case PREDEF_TYPE_INT128_ID: T = Context.Int128Ty; break;
5918 case PREDEF_TYPE_HALF_ID: T = Context.HalfTy; break;
5919 case PREDEF_TYPE_FLOAT_ID: T = Context.FloatTy; break;
5920 case PREDEF_TYPE_DOUBLE_ID: T = Context.DoubleTy; break;
5921 case PREDEF_TYPE_LONGDOUBLE_ID: T = Context.LongDoubleTy; break;
5922 case PREDEF_TYPE_OVERLOAD_ID: T = Context.OverloadTy; break;
5923 case PREDEF_TYPE_BOUND_MEMBER: T = Context.BoundMemberTy; break;
5924 case PREDEF_TYPE_PSEUDO_OBJECT: T = Context.PseudoObjectTy; break;
5925 case PREDEF_TYPE_DEPENDENT_ID: T = Context.DependentTy; break;
5926 case PREDEF_TYPE_UNKNOWN_ANY: T = Context.UnknownAnyTy; break;
5927 case PREDEF_TYPE_NULLPTR_ID: T = Context.NullPtrTy; break;
5928 case PREDEF_TYPE_CHAR16_ID: T = Context.Char16Ty; break;
5929 case PREDEF_TYPE_CHAR32_ID: T = Context.Char32Ty; break;
5930 case PREDEF_TYPE_OBJC_ID: T = Context.ObjCBuiltinIdTy; break;
5931 case PREDEF_TYPE_OBJC_CLASS: T = Context.ObjCBuiltinClassTy; break;
5932 case PREDEF_TYPE_OBJC_SEL: T = Context.ObjCBuiltinSelTy; break;
Guy Benyeid8a08ea2012-12-18 14:38:23 +00005933 case PREDEF_TYPE_IMAGE1D_ID: T = Context.OCLImage1dTy; break;
5934 case PREDEF_TYPE_IMAGE1D_ARR_ID: T = Context.OCLImage1dArrayTy; break;
5935 case PREDEF_TYPE_IMAGE1D_BUFF_ID: T = Context.OCLImage1dBufferTy; break;
5936 case PREDEF_TYPE_IMAGE2D_ID: T = Context.OCLImage2dTy; break;
5937 case PREDEF_TYPE_IMAGE2D_ARR_ID: T = Context.OCLImage2dArrayTy; break;
5938 case PREDEF_TYPE_IMAGE3D_ID: T = Context.OCLImage3dTy; break;
Guy Benyei61054192013-02-07 10:55:47 +00005939 case PREDEF_TYPE_SAMPLER_ID: T = Context.OCLSamplerTy; break;
Guy Benyei1b4fb3e2013-01-20 12:31:11 +00005940 case PREDEF_TYPE_EVENT_ID: T = Context.OCLEventTy; break;
Guy Benyei11169dd2012-12-18 14:30:41 +00005941 case PREDEF_TYPE_AUTO_DEDUCT: T = Context.getAutoDeductType(); break;
5942
5943 case PREDEF_TYPE_AUTO_RREF_DEDUCT:
5944 T = Context.getAutoRRefDeductType();
5945 break;
5946
5947 case PREDEF_TYPE_ARC_UNBRIDGED_CAST:
5948 T = Context.ARCUnbridgedCastTy;
5949 break;
5950
5951 case PREDEF_TYPE_VA_LIST_TAG:
5952 T = Context.getVaListTagType();
5953 break;
5954
5955 case PREDEF_TYPE_BUILTIN_FN:
5956 T = Context.BuiltinFnTy;
5957 break;
5958 }
5959
5960 assert(!T.isNull() && "Unknown predefined type");
5961 return T.withFastQualifiers(FastQuals);
5962 }
5963
5964 Index -= NUM_PREDEF_TYPE_IDS;
5965 assert(Index < TypesLoaded.size() && "Type index out-of-range");
5966 if (TypesLoaded[Index].isNull()) {
5967 TypesLoaded[Index] = readTypeRecord(Index);
5968 if (TypesLoaded[Index].isNull())
5969 return QualType();
5970
5971 TypesLoaded[Index]->setFromAST();
5972 if (DeserializationListener)
5973 DeserializationListener->TypeRead(TypeIdx::fromTypeID(ID),
5974 TypesLoaded[Index]);
5975 }
5976
5977 return TypesLoaded[Index].withFastQualifiers(FastQuals);
5978}
5979
5980QualType ASTReader::getLocalType(ModuleFile &F, unsigned LocalID) {
5981 return GetType(getGlobalTypeID(F, LocalID));
5982}
5983
5984serialization::TypeID
5985ASTReader::getGlobalTypeID(ModuleFile &F, unsigned LocalID) const {
5986 unsigned FastQuals = LocalID & Qualifiers::FastMask;
5987 unsigned LocalIndex = LocalID >> Qualifiers::FastWidth;
5988
5989 if (LocalIndex < NUM_PREDEF_TYPE_IDS)
5990 return LocalID;
5991
5992 ContinuousRangeMap<uint32_t, int, 2>::iterator I
5993 = F.TypeRemap.find(LocalIndex - NUM_PREDEF_TYPE_IDS);
5994 assert(I != F.TypeRemap.end() && "Invalid index into type index remap");
5995
5996 unsigned GlobalIndex = LocalIndex + I->second;
5997 return (GlobalIndex << Qualifiers::FastWidth) | FastQuals;
5998}
5999
6000TemplateArgumentLocInfo
6001ASTReader::GetTemplateArgumentLocInfo(ModuleFile &F,
6002 TemplateArgument::ArgKind Kind,
6003 const RecordData &Record,
6004 unsigned &Index) {
6005 switch (Kind) {
6006 case TemplateArgument::Expression:
6007 return ReadExpr(F);
6008 case TemplateArgument::Type:
6009 return GetTypeSourceInfo(F, Record, Index);
6010 case TemplateArgument::Template: {
6011 NestedNameSpecifierLoc QualifierLoc = ReadNestedNameSpecifierLoc(F, Record,
6012 Index);
6013 SourceLocation TemplateNameLoc = ReadSourceLocation(F, Record, Index);
6014 return TemplateArgumentLocInfo(QualifierLoc, TemplateNameLoc,
6015 SourceLocation());
6016 }
6017 case TemplateArgument::TemplateExpansion: {
6018 NestedNameSpecifierLoc QualifierLoc = ReadNestedNameSpecifierLoc(F, Record,
6019 Index);
6020 SourceLocation TemplateNameLoc = ReadSourceLocation(F, Record, Index);
6021 SourceLocation EllipsisLoc = ReadSourceLocation(F, Record, Index);
6022 return TemplateArgumentLocInfo(QualifierLoc, TemplateNameLoc,
6023 EllipsisLoc);
6024 }
6025 case TemplateArgument::Null:
6026 case TemplateArgument::Integral:
6027 case TemplateArgument::Declaration:
6028 case TemplateArgument::NullPtr:
6029 case TemplateArgument::Pack:
6030 // FIXME: Is this right?
6031 return TemplateArgumentLocInfo();
6032 }
6033 llvm_unreachable("unexpected template argument loc");
6034}
6035
6036TemplateArgumentLoc
6037ASTReader::ReadTemplateArgumentLoc(ModuleFile &F,
6038 const RecordData &Record, unsigned &Index) {
6039 TemplateArgument Arg = ReadTemplateArgument(F, Record, Index);
6040
6041 if (Arg.getKind() == TemplateArgument::Expression) {
6042 if (Record[Index++]) // bool InfoHasSameExpr.
6043 return TemplateArgumentLoc(Arg, TemplateArgumentLocInfo(Arg.getAsExpr()));
6044 }
6045 return TemplateArgumentLoc(Arg, GetTemplateArgumentLocInfo(F, Arg.getKind(),
6046 Record, Index));
6047}
6048
Enea Zaffanella6dbe1872013-08-10 07:24:53 +00006049const ASTTemplateArgumentListInfo*
6050ASTReader::ReadASTTemplateArgumentListInfo(ModuleFile &F,
6051 const RecordData &Record,
6052 unsigned &Index) {
6053 SourceLocation LAngleLoc = ReadSourceLocation(F, Record, Index);
6054 SourceLocation RAngleLoc = ReadSourceLocation(F, Record, Index);
6055 unsigned NumArgsAsWritten = Record[Index++];
6056 TemplateArgumentListInfo TemplArgsInfo(LAngleLoc, RAngleLoc);
6057 for (unsigned i = 0; i != NumArgsAsWritten; ++i)
6058 TemplArgsInfo.addArgument(ReadTemplateArgumentLoc(F, Record, Index));
6059 return ASTTemplateArgumentListInfo::Create(getContext(), TemplArgsInfo);
6060}
6061
Guy Benyei11169dd2012-12-18 14:30:41 +00006062Decl *ASTReader::GetExternalDecl(uint32_t ID) {
6063 return GetDecl(ID);
6064}
6065
Richard Smith053f6c62014-05-16 23:01:30 +00006066void ASTReader::CompleteRedeclChain(const Decl *D) {
Richard Smith851072e2014-05-19 20:59:20 +00006067 if (NumCurrentElementsDeserializing) {
6068 // We arrange to not care about the complete redeclaration chain while we're
6069 // deserializing. Just remember that the AST has marked this one as complete
6070 // but that it's not actually complete yet, so we know we still need to
6071 // complete it later.
6072 PendingIncompleteDeclChains.push_back(const_cast<Decl*>(D));
6073 return;
6074 }
6075
Richard Smith053f6c62014-05-16 23:01:30 +00006076 const DeclContext *DC = D->getDeclContext()->getRedeclContext();
6077
Richard Smith053f6c62014-05-16 23:01:30 +00006078 // If this is a named declaration, complete it by looking it up
6079 // within its context.
6080 //
Richard Smith01bdb7a2014-08-28 05:44:07 +00006081 // FIXME: Merging a function definition should merge
Richard Smith053f6c62014-05-16 23:01:30 +00006082 // all mergeable entities within it.
6083 if (isa<TranslationUnitDecl>(DC) || isa<NamespaceDecl>(DC) ||
6084 isa<CXXRecordDecl>(DC) || isa<EnumDecl>(DC)) {
6085 if (DeclarationName Name = cast<NamedDecl>(D)->getDeclName()) {
6086 auto *II = Name.getAsIdentifierInfo();
6087 if (isa<TranslationUnitDecl>(DC) && II) {
6088 // Outside of C++, we don't have a lookup table for the TU, so update
6089 // the identifier instead. In C++, either way should work fine.
6090 if (II->isOutOfDate())
6091 updateOutOfDateIdentifier(*II);
6092 } else
6093 DC->lookup(Name);
Richard Smith01bdb7a2014-08-28 05:44:07 +00006094 } else if (needsAnonymousDeclarationNumber(cast<NamedDecl>(D))) {
6095 // FIXME: It'd be nice to do something a bit more targeted here.
6096 D->getDeclContext()->decls_begin();
Richard Smith053f6c62014-05-16 23:01:30 +00006097 }
6098 }
6099}
6100
Richard Smithcd45dbc2014-04-19 03:48:30 +00006101uint64_t ASTReader::readCXXBaseSpecifiers(ModuleFile &M,
6102 const RecordData &Record,
6103 unsigned &Idx) {
6104 if (Idx >= Record.size() || Record[Idx] > M.LocalNumCXXBaseSpecifiers) {
6105 Error("malformed AST file: missing C++ base specifier");
Guy Benyei11169dd2012-12-18 14:30:41 +00006106 return 0;
Richard Smithcd45dbc2014-04-19 03:48:30 +00006107 }
6108
Guy Benyei11169dd2012-12-18 14:30:41 +00006109 unsigned LocalID = Record[Idx++];
6110 return getGlobalBitOffset(M, M.CXXBaseSpecifiersOffsets[LocalID - 1]);
6111}
6112
6113CXXBaseSpecifier *ASTReader::GetExternalCXXBaseSpecifiers(uint64_t Offset) {
6114 RecordLocation Loc = getLocalBitOffset(Offset);
Chris Lattner7fb3bef2013-01-20 00:56:42 +00006115 BitstreamCursor &Cursor = Loc.F->DeclsCursor;
Guy Benyei11169dd2012-12-18 14:30:41 +00006116 SavedStreamPosition SavedPosition(Cursor);
6117 Cursor.JumpToBit(Loc.Offset);
6118 ReadingKindTracker ReadingKind(Read_Decl, *this);
6119 RecordData Record;
6120 unsigned Code = Cursor.ReadCode();
Chris Lattner0e6c9402013-01-20 02:38:54 +00006121 unsigned RecCode = Cursor.readRecord(Code, Record);
Guy Benyei11169dd2012-12-18 14:30:41 +00006122 if (RecCode != DECL_CXX_BASE_SPECIFIERS) {
Richard Smithcd45dbc2014-04-19 03:48:30 +00006123 Error("malformed AST file: missing C++ base specifiers");
Craig Toppera13603a2014-05-22 05:54:18 +00006124 return nullptr;
Guy Benyei11169dd2012-12-18 14:30:41 +00006125 }
6126
6127 unsigned Idx = 0;
6128 unsigned NumBases = Record[Idx++];
6129 void *Mem = Context.Allocate(sizeof(CXXBaseSpecifier) * NumBases);
6130 CXXBaseSpecifier *Bases = new (Mem) CXXBaseSpecifier [NumBases];
6131 for (unsigned I = 0; I != NumBases; ++I)
6132 Bases[I] = ReadCXXBaseSpecifier(*Loc.F, Record, Idx);
6133 return Bases;
6134}
6135
6136serialization::DeclID
6137ASTReader::getGlobalDeclID(ModuleFile &F, LocalDeclID LocalID) const {
6138 if (LocalID < NUM_PREDEF_DECL_IDS)
6139 return LocalID;
6140
6141 ContinuousRangeMap<uint32_t, int, 2>::iterator I
6142 = F.DeclRemap.find(LocalID - NUM_PREDEF_DECL_IDS);
6143 assert(I != F.DeclRemap.end() && "Invalid index into decl index remap");
6144
6145 return LocalID + I->second;
6146}
6147
6148bool ASTReader::isDeclIDFromModule(serialization::GlobalDeclID ID,
6149 ModuleFile &M) const {
6150 GlobalDeclMapType::const_iterator I = GlobalDeclMap.find(ID);
6151 assert(I != GlobalDeclMap.end() && "Corrupted global declaration map");
6152 return &M == I->second;
6153}
6154
Douglas Gregor9f782892013-01-21 15:25:38 +00006155ModuleFile *ASTReader::getOwningModuleFile(const Decl *D) {
Guy Benyei11169dd2012-12-18 14:30:41 +00006156 if (!D->isFromASTFile())
Craig Toppera13603a2014-05-22 05:54:18 +00006157 return nullptr;
Guy Benyei11169dd2012-12-18 14:30:41 +00006158 GlobalDeclMapType::const_iterator I = GlobalDeclMap.find(D->getGlobalID());
6159 assert(I != GlobalDeclMap.end() && "Corrupted global declaration map");
6160 return I->second;
6161}
6162
6163SourceLocation ASTReader::getSourceLocationForDeclID(GlobalDeclID ID) {
6164 if (ID < NUM_PREDEF_DECL_IDS)
6165 return SourceLocation();
Richard Smithcd45dbc2014-04-19 03:48:30 +00006166
Guy Benyei11169dd2012-12-18 14:30:41 +00006167 unsigned Index = ID - NUM_PREDEF_DECL_IDS;
6168
6169 if (Index > DeclsLoaded.size()) {
6170 Error("declaration ID out-of-range for AST file");
6171 return SourceLocation();
6172 }
Richard Smithcd45dbc2014-04-19 03:48:30 +00006173
Guy Benyei11169dd2012-12-18 14:30:41 +00006174 if (Decl *D = DeclsLoaded[Index])
6175 return D->getLocation();
6176
6177 unsigned RawLocation = 0;
6178 RecordLocation Rec = DeclCursorForID(ID, RawLocation);
6179 return ReadSourceLocation(*Rec.F, RawLocation);
6180}
6181
Richard Smithcd45dbc2014-04-19 03:48:30 +00006182Decl *ASTReader::GetExistingDecl(DeclID ID) {
6183 if (ID < NUM_PREDEF_DECL_IDS) {
Guy Benyei11169dd2012-12-18 14:30:41 +00006184 switch ((PredefinedDeclIDs)ID) {
6185 case PREDEF_DECL_NULL_ID:
Craig Toppera13603a2014-05-22 05:54:18 +00006186 return nullptr;
Richard Smithcd45dbc2014-04-19 03:48:30 +00006187
Guy Benyei11169dd2012-12-18 14:30:41 +00006188 case PREDEF_DECL_TRANSLATION_UNIT_ID:
6189 return Context.getTranslationUnitDecl();
Richard Smithcd45dbc2014-04-19 03:48:30 +00006190
Guy Benyei11169dd2012-12-18 14:30:41 +00006191 case PREDEF_DECL_OBJC_ID_ID:
6192 return Context.getObjCIdDecl();
6193
6194 case PREDEF_DECL_OBJC_SEL_ID:
6195 return Context.getObjCSelDecl();
6196
6197 case PREDEF_DECL_OBJC_CLASS_ID:
6198 return Context.getObjCClassDecl();
Richard Smithcd45dbc2014-04-19 03:48:30 +00006199
Guy Benyei11169dd2012-12-18 14:30:41 +00006200 case PREDEF_DECL_OBJC_PROTOCOL_ID:
6201 return Context.getObjCProtocolDecl();
Richard Smithcd45dbc2014-04-19 03:48:30 +00006202
Guy Benyei11169dd2012-12-18 14:30:41 +00006203 case PREDEF_DECL_INT_128_ID:
6204 return Context.getInt128Decl();
6205
6206 case PREDEF_DECL_UNSIGNED_INT_128_ID:
6207 return Context.getUInt128Decl();
Richard Smithcd45dbc2014-04-19 03:48:30 +00006208
Guy Benyei11169dd2012-12-18 14:30:41 +00006209 case PREDEF_DECL_OBJC_INSTANCETYPE_ID:
6210 return Context.getObjCInstanceTypeDecl();
6211
6212 case PREDEF_DECL_BUILTIN_VA_LIST_ID:
6213 return Context.getBuiltinVaListDecl();
6214 }
6215 }
Richard Smithcd45dbc2014-04-19 03:48:30 +00006216
Guy Benyei11169dd2012-12-18 14:30:41 +00006217 unsigned Index = ID - NUM_PREDEF_DECL_IDS;
6218
6219 if (Index >= DeclsLoaded.size()) {
6220 assert(0 && "declaration ID out-of-range for AST file");
6221 Error("declaration ID out-of-range for AST file");
Craig Toppera13603a2014-05-22 05:54:18 +00006222 return nullptr;
Guy Benyei11169dd2012-12-18 14:30:41 +00006223 }
Richard Smithcd45dbc2014-04-19 03:48:30 +00006224
6225 return DeclsLoaded[Index];
6226}
6227
6228Decl *ASTReader::GetDecl(DeclID ID) {
6229 if (ID < NUM_PREDEF_DECL_IDS)
6230 return GetExistingDecl(ID);
6231
6232 unsigned Index = ID - NUM_PREDEF_DECL_IDS;
6233
6234 if (Index >= DeclsLoaded.size()) {
6235 assert(0 && "declaration ID out-of-range for AST file");
6236 Error("declaration ID out-of-range for AST file");
Craig Toppera13603a2014-05-22 05:54:18 +00006237 return nullptr;
Richard Smithcd45dbc2014-04-19 03:48:30 +00006238 }
6239
Guy Benyei11169dd2012-12-18 14:30:41 +00006240 if (!DeclsLoaded[Index]) {
6241 ReadDeclRecord(ID);
6242 if (DeserializationListener)
6243 DeserializationListener->DeclRead(ID, DeclsLoaded[Index]);
6244 }
6245
6246 return DeclsLoaded[Index];
6247}
6248
6249DeclID ASTReader::mapGlobalIDToModuleFileGlobalID(ModuleFile &M,
6250 DeclID GlobalID) {
6251 if (GlobalID < NUM_PREDEF_DECL_IDS)
6252 return GlobalID;
6253
6254 GlobalDeclMapType::const_iterator I = GlobalDeclMap.find(GlobalID);
6255 assert(I != GlobalDeclMap.end() && "Corrupted global declaration map");
6256 ModuleFile *Owner = I->second;
6257
6258 llvm::DenseMap<ModuleFile *, serialization::DeclID>::iterator Pos
6259 = M.GlobalToLocalDeclIDs.find(Owner);
6260 if (Pos == M.GlobalToLocalDeclIDs.end())
6261 return 0;
6262
6263 return GlobalID - Owner->BaseDeclID + Pos->second;
6264}
6265
6266serialization::DeclID ASTReader::ReadDeclID(ModuleFile &F,
6267 const RecordData &Record,
6268 unsigned &Idx) {
6269 if (Idx >= Record.size()) {
6270 Error("Corrupted AST file");
6271 return 0;
6272 }
6273
6274 return getGlobalDeclID(F, Record[Idx++]);
6275}
6276
6277/// \brief Resolve the offset of a statement into a statement.
6278///
6279/// This operation will read a new statement from the external
6280/// source each time it is called, and is meant to be used via a
6281/// LazyOffsetPtr (which is used by Decls for the body of functions, etc).
6282Stmt *ASTReader::GetExternalDeclStmt(uint64_t Offset) {
6283 // Switch case IDs are per Decl.
6284 ClearSwitchCaseIDs();
6285
6286 // Offset here is a global offset across the entire chain.
6287 RecordLocation Loc = getLocalBitOffset(Offset);
6288 Loc.F->DeclsCursor.JumpToBit(Loc.Offset);
6289 return ReadStmtFromStream(*Loc.F);
6290}
6291
6292namespace {
6293 class FindExternalLexicalDeclsVisitor {
6294 ASTReader &Reader;
6295 const DeclContext *DC;
6296 bool (*isKindWeWant)(Decl::Kind);
6297
6298 SmallVectorImpl<Decl*> &Decls;
6299 bool PredefsVisited[NUM_PREDEF_DECL_IDS];
6300
6301 public:
6302 FindExternalLexicalDeclsVisitor(ASTReader &Reader, const DeclContext *DC,
6303 bool (*isKindWeWant)(Decl::Kind),
6304 SmallVectorImpl<Decl*> &Decls)
6305 : Reader(Reader), DC(DC), isKindWeWant(isKindWeWant), Decls(Decls)
6306 {
6307 for (unsigned I = 0; I != NUM_PREDEF_DECL_IDS; ++I)
6308 PredefsVisited[I] = false;
6309 }
6310
6311 static bool visit(ModuleFile &M, bool Preorder, void *UserData) {
6312 if (Preorder)
6313 return false;
6314
6315 FindExternalLexicalDeclsVisitor *This
6316 = static_cast<FindExternalLexicalDeclsVisitor *>(UserData);
6317
6318 ModuleFile::DeclContextInfosMap::iterator Info
6319 = M.DeclContextInfos.find(This->DC);
6320 if (Info == M.DeclContextInfos.end() || !Info->second.LexicalDecls)
6321 return false;
6322
6323 // Load all of the declaration IDs
6324 for (const KindDeclIDPair *ID = Info->second.LexicalDecls,
6325 *IDE = ID + Info->second.NumLexicalDecls;
6326 ID != IDE; ++ID) {
6327 if (This->isKindWeWant && !This->isKindWeWant((Decl::Kind)ID->first))
6328 continue;
6329
6330 // Don't add predefined declarations to the lexical context more
6331 // than once.
6332 if (ID->second < NUM_PREDEF_DECL_IDS) {
6333 if (This->PredefsVisited[ID->second])
6334 continue;
6335
6336 This->PredefsVisited[ID->second] = true;
6337 }
6338
6339 if (Decl *D = This->Reader.GetLocalDecl(M, ID->second)) {
6340 if (!This->DC->isDeclInLexicalTraversal(D))
6341 This->Decls.push_back(D);
6342 }
6343 }
6344
6345 return false;
6346 }
6347 };
6348}
6349
6350ExternalLoadResult ASTReader::FindExternalLexicalDecls(const DeclContext *DC,
6351 bool (*isKindWeWant)(Decl::Kind),
6352 SmallVectorImpl<Decl*> &Decls) {
6353 // There might be lexical decls in multiple modules, for the TU at
6354 // least. Walk all of the modules in the order they were loaded.
6355 FindExternalLexicalDeclsVisitor Visitor(*this, DC, isKindWeWant, Decls);
6356 ModuleMgr.visitDepthFirst(&FindExternalLexicalDeclsVisitor::visit, &Visitor);
6357 ++NumLexicalDeclContextsRead;
6358 return ELR_Success;
6359}
6360
6361namespace {
6362
6363class DeclIDComp {
6364 ASTReader &Reader;
6365 ModuleFile &Mod;
6366
6367public:
6368 DeclIDComp(ASTReader &Reader, ModuleFile &M) : Reader(Reader), Mod(M) {}
6369
6370 bool operator()(LocalDeclID L, LocalDeclID R) const {
6371 SourceLocation LHS = getLocation(L);
6372 SourceLocation RHS = getLocation(R);
6373 return Reader.getSourceManager().isBeforeInTranslationUnit(LHS, RHS);
6374 }
6375
6376 bool operator()(SourceLocation LHS, LocalDeclID R) const {
6377 SourceLocation RHS = getLocation(R);
6378 return Reader.getSourceManager().isBeforeInTranslationUnit(LHS, RHS);
6379 }
6380
6381 bool operator()(LocalDeclID L, SourceLocation RHS) const {
6382 SourceLocation LHS = getLocation(L);
6383 return Reader.getSourceManager().isBeforeInTranslationUnit(LHS, RHS);
6384 }
6385
6386 SourceLocation getLocation(LocalDeclID ID) const {
6387 return Reader.getSourceManager().getFileLoc(
6388 Reader.getSourceLocationForDeclID(Reader.getGlobalDeclID(Mod, ID)));
6389 }
6390};
6391
6392}
6393
6394void ASTReader::FindFileRegionDecls(FileID File,
6395 unsigned Offset, unsigned Length,
6396 SmallVectorImpl<Decl *> &Decls) {
6397 SourceManager &SM = getSourceManager();
6398
6399 llvm::DenseMap<FileID, FileDeclsInfo>::iterator I = FileDeclIDs.find(File);
6400 if (I == FileDeclIDs.end())
6401 return;
6402
6403 FileDeclsInfo &DInfo = I->second;
6404 if (DInfo.Decls.empty())
6405 return;
6406
6407 SourceLocation
6408 BeginLoc = SM.getLocForStartOfFile(File).getLocWithOffset(Offset);
6409 SourceLocation EndLoc = BeginLoc.getLocWithOffset(Length);
6410
6411 DeclIDComp DIDComp(*this, *DInfo.Mod);
6412 ArrayRef<serialization::LocalDeclID>::iterator
6413 BeginIt = std::lower_bound(DInfo.Decls.begin(), DInfo.Decls.end(),
6414 BeginLoc, DIDComp);
6415 if (BeginIt != DInfo.Decls.begin())
6416 --BeginIt;
6417
6418 // If we are pointing at a top-level decl inside an objc container, we need
6419 // to backtrack until we find it otherwise we will fail to report that the
6420 // region overlaps with an objc container.
6421 while (BeginIt != DInfo.Decls.begin() &&
6422 GetDecl(getGlobalDeclID(*DInfo.Mod, *BeginIt))
6423 ->isTopLevelDeclInObjCContainer())
6424 --BeginIt;
6425
6426 ArrayRef<serialization::LocalDeclID>::iterator
6427 EndIt = std::upper_bound(DInfo.Decls.begin(), DInfo.Decls.end(),
6428 EndLoc, DIDComp);
6429 if (EndIt != DInfo.Decls.end())
6430 ++EndIt;
6431
6432 for (ArrayRef<serialization::LocalDeclID>::iterator
6433 DIt = BeginIt; DIt != EndIt; ++DIt)
6434 Decls.push_back(GetDecl(getGlobalDeclID(*DInfo.Mod, *DIt)));
6435}
6436
6437namespace {
6438 /// \brief ModuleFile visitor used to perform name lookup into a
6439 /// declaration context.
6440 class DeclContextNameLookupVisitor {
6441 ASTReader &Reader;
Richard Smith8c913ec2014-08-14 02:21:01 +00006442 ArrayRef<const DeclContext *> Contexts;
Guy Benyei11169dd2012-12-18 14:30:41 +00006443 DeclarationName Name;
6444 SmallVectorImpl<NamedDecl *> &Decls;
6445
6446 public:
Richard Smith8c913ec2014-08-14 02:21:01 +00006447 DeclContextNameLookupVisitor(ASTReader &Reader,
6448 ArrayRef<const DeclContext *> Contexts,
Guy Benyei11169dd2012-12-18 14:30:41 +00006449 DeclarationName Name,
6450 SmallVectorImpl<NamedDecl *> &Decls)
6451 : Reader(Reader), Contexts(Contexts), Name(Name), Decls(Decls) { }
6452
6453 static bool visit(ModuleFile &M, void *UserData) {
6454 DeclContextNameLookupVisitor *This
6455 = static_cast<DeclContextNameLookupVisitor *>(UserData);
6456
6457 // Check whether we have any visible declaration information for
6458 // this context in this module.
6459 ModuleFile::DeclContextInfosMap::iterator Info;
6460 bool FoundInfo = false;
Richard Smith8c913ec2014-08-14 02:21:01 +00006461 for (auto *DC : This->Contexts) {
6462 Info = M.DeclContextInfos.find(DC);
6463 if (Info != M.DeclContextInfos.end() &&
Guy Benyei11169dd2012-12-18 14:30:41 +00006464 Info->second.NameLookupTableData) {
6465 FoundInfo = true;
6466 break;
6467 }
6468 }
6469
6470 if (!FoundInfo)
6471 return false;
Richard Smith8c913ec2014-08-14 02:21:01 +00006472
Guy Benyei11169dd2012-12-18 14:30:41 +00006473 // Look for this name within this module.
Richard Smith52e3fba2014-03-11 07:17:35 +00006474 ASTDeclContextNameLookupTable *LookupTable =
Guy Benyei11169dd2012-12-18 14:30:41 +00006475 Info->second.NameLookupTableData;
6476 ASTDeclContextNameLookupTable::iterator Pos
6477 = LookupTable->find(This->Name);
6478 if (Pos == LookupTable->end())
6479 return false;
6480
6481 bool FoundAnything = false;
6482 ASTDeclContextNameLookupTrait::data_type Data = *Pos;
6483 for (; Data.first != Data.second; ++Data.first) {
6484 NamedDecl *ND = This->Reader.GetLocalDeclAs<NamedDecl>(M, *Data.first);
6485 if (!ND)
6486 continue;
6487
6488 if (ND->getDeclName() != This->Name) {
6489 // A name might be null because the decl's redeclarable part is
6490 // currently read before reading its name. The lookup is triggered by
6491 // building that decl (likely indirectly), and so it is later in the
6492 // sense of "already existing" and can be ignored here.
Richard Smith8c913ec2014-08-14 02:21:01 +00006493 // FIXME: This should not happen; deserializing declarations should
6494 // not perform lookups since that can lead to deserialization cycles.
Guy Benyei11169dd2012-12-18 14:30:41 +00006495 continue;
6496 }
Richard Smith8c913ec2014-08-14 02:21:01 +00006497
Guy Benyei11169dd2012-12-18 14:30:41 +00006498 // Record this declaration.
6499 FoundAnything = true;
6500 This->Decls.push_back(ND);
6501 }
6502
6503 return FoundAnything;
6504 }
6505 };
6506}
6507
Douglas Gregor9f782892013-01-21 15:25:38 +00006508/// \brief Retrieve the "definitive" module file for the definition of the
6509/// given declaration context, if there is one.
6510///
6511/// The "definitive" module file is the only place where we need to look to
6512/// find information about the declarations within the given declaration
6513/// context. For example, C++ and Objective-C classes, C structs/unions, and
6514/// Objective-C protocols, categories, and extensions are all defined in a
6515/// single place in the source code, so they have definitive module files
6516/// associated with them. C++ namespaces, on the other hand, can have
6517/// definitions in multiple different module files.
6518///
6519/// Note: this needs to be kept in sync with ASTWriter::AddedVisibleDecl's
6520/// NDEBUG checking.
6521static ModuleFile *getDefinitiveModuleFileFor(const DeclContext *DC,
6522 ASTReader &Reader) {
Douglas Gregor7a6e2002013-01-22 17:08:30 +00006523 if (const DeclContext *DefDC = getDefinitiveDeclContext(DC))
6524 return Reader.getOwningModuleFile(cast<Decl>(DefDC));
Douglas Gregor9f782892013-01-21 15:25:38 +00006525
Craig Toppera13603a2014-05-22 05:54:18 +00006526 return nullptr;
Douglas Gregor9f782892013-01-21 15:25:38 +00006527}
6528
Richard Smith9ce12e32013-02-07 03:30:24 +00006529bool
Guy Benyei11169dd2012-12-18 14:30:41 +00006530ASTReader::FindExternalVisibleDeclsByName(const DeclContext *DC,
6531 DeclarationName Name) {
6532 assert(DC->hasExternalVisibleStorage() &&
6533 "DeclContext has no visible decls in storage");
6534 if (!Name)
Richard Smith9ce12e32013-02-07 03:30:24 +00006535 return false;
Guy Benyei11169dd2012-12-18 14:30:41 +00006536
Richard Smith8c913ec2014-08-14 02:21:01 +00006537 Deserializing LookupResults(this);
6538
Guy Benyei11169dd2012-12-18 14:30:41 +00006539 SmallVector<NamedDecl *, 64> Decls;
Richard Smith8c913ec2014-08-14 02:21:01 +00006540
Guy Benyei11169dd2012-12-18 14:30:41 +00006541 // Compute the declaration contexts we need to look into. Multiple such
6542 // declaration contexts occur when two declaration contexts from disjoint
6543 // modules get merged, e.g., when two namespaces with the same name are
6544 // independently defined in separate modules.
6545 SmallVector<const DeclContext *, 2> Contexts;
6546 Contexts.push_back(DC);
Richard Smith8c913ec2014-08-14 02:21:01 +00006547
Guy Benyei11169dd2012-12-18 14:30:41 +00006548 if (DC->isNamespace()) {
Richard Smithcd45dbc2014-04-19 03:48:30 +00006549 auto Merged = MergedDecls.find(const_cast<Decl *>(cast<Decl>(DC)));
Guy Benyei11169dd2012-12-18 14:30:41 +00006550 if (Merged != MergedDecls.end()) {
6551 for (unsigned I = 0, N = Merged->second.size(); I != N; ++I)
6552 Contexts.push_back(cast<DeclContext>(GetDecl(Merged->second[I])));
6553 }
6554 }
Richard Smith8c913ec2014-08-14 02:21:01 +00006555
6556 auto LookUpInContexts = [&](ArrayRef<const DeclContext*> Contexts) {
6557 DeclContextNameLookupVisitor Visitor(*this, Contexts, Name, Decls);
6558
6559 // If we can definitively determine which module file to look into,
6560 // only look there. Otherwise, look in all module files.
6561 ModuleFile *Definitive;
6562 if (Contexts.size() == 1 &&
6563 (Definitive = getDefinitiveModuleFileFor(Contexts[0], *this))) {
6564 DeclContextNameLookupVisitor::visit(*Definitive, &Visitor);
6565 } else {
6566 ModuleMgr.visit(&DeclContextNameLookupVisitor::visit, &Visitor);
6567 }
6568 };
6569
6570 LookUpInContexts(Contexts);
6571
6572 // If this might be an implicit special member function, then also search
6573 // all merged definitions of the surrounding class. We need to search them
6574 // individually, because finding an entity in one of them doesn't imply that
6575 // we can't find a different entity in another one.
Richard Smithcd45dbc2014-04-19 03:48:30 +00006576 if (isa<CXXRecordDecl>(DC)) {
Richard Smith8c913ec2014-08-14 02:21:01 +00006577 auto Kind = Name.getNameKind();
6578 if (Kind == DeclarationName::CXXConstructorName ||
6579 Kind == DeclarationName::CXXDestructorName ||
6580 (Kind == DeclarationName::CXXOperatorName &&
6581 Name.getCXXOverloadedOperator() == OO_Equal)) {
6582 auto Merged = MergedLookups.find(DC);
Richard Smithe0612472014-11-21 05:16:13 +00006583 if (Merged != MergedLookups.end()) {
6584 for (unsigned I = 0; I != Merged->second.size(); ++I) {
6585 LookUpInContexts(Merged->second[I]);
6586 // We might have just added some more merged lookups. If so, our
6587 // iterator is now invalid, so grab a fresh one before continuing.
6588 Merged = MergedLookups.find(DC);
6589 }
6590 }
Richard Smith8c913ec2014-08-14 02:21:01 +00006591 }
Richard Smithcd45dbc2014-04-19 03:48:30 +00006592 }
6593
Guy Benyei11169dd2012-12-18 14:30:41 +00006594 ++NumVisibleDeclContextsRead;
6595 SetExternalVisibleDeclsForName(DC, Name, Decls);
Richard Smith9ce12e32013-02-07 03:30:24 +00006596 return !Decls.empty();
Guy Benyei11169dd2012-12-18 14:30:41 +00006597}
6598
6599namespace {
6600 /// \brief ModuleFile visitor used to retrieve all visible names in a
6601 /// declaration context.
6602 class DeclContextAllNamesVisitor {
6603 ASTReader &Reader;
Dmitri Gribenkof8579502013-01-12 19:30:44 +00006604 SmallVectorImpl<const DeclContext *> &Contexts;
Craig Topper3598eb72013-07-05 04:43:31 +00006605 DeclsMap &Decls;
Argyrios Kyrtzidis2810e9d2012-12-19 22:21:18 +00006606 bool VisitAll;
Guy Benyei11169dd2012-12-18 14:30:41 +00006607
6608 public:
6609 DeclContextAllNamesVisitor(ASTReader &Reader,
6610 SmallVectorImpl<const DeclContext *> &Contexts,
Craig Topper3598eb72013-07-05 04:43:31 +00006611 DeclsMap &Decls, bool VisitAll)
Argyrios Kyrtzidis2810e9d2012-12-19 22:21:18 +00006612 : Reader(Reader), Contexts(Contexts), Decls(Decls), VisitAll(VisitAll) { }
Guy Benyei11169dd2012-12-18 14:30:41 +00006613
6614 static bool visit(ModuleFile &M, void *UserData) {
6615 DeclContextAllNamesVisitor *This
6616 = static_cast<DeclContextAllNamesVisitor *>(UserData);
6617
6618 // Check whether we have any visible declaration information for
6619 // this context in this module.
6620 ModuleFile::DeclContextInfosMap::iterator Info;
6621 bool FoundInfo = false;
6622 for (unsigned I = 0, N = This->Contexts.size(); I != N; ++I) {
6623 Info = M.DeclContextInfos.find(This->Contexts[I]);
6624 if (Info != M.DeclContextInfos.end() &&
6625 Info->second.NameLookupTableData) {
6626 FoundInfo = true;
6627 break;
6628 }
6629 }
6630
6631 if (!FoundInfo)
6632 return false;
6633
Richard Smith52e3fba2014-03-11 07:17:35 +00006634 ASTDeclContextNameLookupTable *LookupTable =
Guy Benyei11169dd2012-12-18 14:30:41 +00006635 Info->second.NameLookupTableData;
6636 bool FoundAnything = false;
6637 for (ASTDeclContextNameLookupTable::data_iterator
Douglas Gregor5e306b12013-01-23 22:38:11 +00006638 I = LookupTable->data_begin(), E = LookupTable->data_end();
6639 I != E;
6640 ++I) {
Guy Benyei11169dd2012-12-18 14:30:41 +00006641 ASTDeclContextNameLookupTrait::data_type Data = *I;
6642 for (; Data.first != Data.second; ++Data.first) {
6643 NamedDecl *ND = This->Reader.GetLocalDeclAs<NamedDecl>(M,
6644 *Data.first);
6645 if (!ND)
6646 continue;
6647
6648 // Record this declaration.
6649 FoundAnything = true;
6650 This->Decls[ND->getDeclName()].push_back(ND);
6651 }
6652 }
6653
Argyrios Kyrtzidis2810e9d2012-12-19 22:21:18 +00006654 return FoundAnything && !This->VisitAll;
Guy Benyei11169dd2012-12-18 14:30:41 +00006655 }
6656 };
6657}
6658
6659void ASTReader::completeVisibleDeclsMap(const DeclContext *DC) {
6660 if (!DC->hasExternalVisibleStorage())
6661 return;
Craig Topper79be4cd2013-07-05 04:33:53 +00006662 DeclsMap Decls;
Guy Benyei11169dd2012-12-18 14:30:41 +00006663
6664 // Compute the declaration contexts we need to look into. Multiple such
6665 // declaration contexts occur when two declaration contexts from disjoint
6666 // modules get merged, e.g., when two namespaces with the same name are
6667 // independently defined in separate modules.
6668 SmallVector<const DeclContext *, 2> Contexts;
6669 Contexts.push_back(DC);
6670
6671 if (DC->isNamespace()) {
6672 MergedDeclsMap::iterator Merged
6673 = MergedDecls.find(const_cast<Decl *>(cast<Decl>(DC)));
6674 if (Merged != MergedDecls.end()) {
6675 for (unsigned I = 0, N = Merged->second.size(); I != N; ++I)
6676 Contexts.push_back(cast<DeclContext>(GetDecl(Merged->second[I])));
6677 }
6678 }
6679
Argyrios Kyrtzidis2810e9d2012-12-19 22:21:18 +00006680 DeclContextAllNamesVisitor Visitor(*this, Contexts, Decls,
6681 /*VisitAll=*/DC->isFileContext());
Guy Benyei11169dd2012-12-18 14:30:41 +00006682 ModuleMgr.visit(&DeclContextAllNamesVisitor::visit, &Visitor);
6683 ++NumVisibleDeclContextsRead;
6684
Craig Topper79be4cd2013-07-05 04:33:53 +00006685 for (DeclsMap::iterator I = Decls.begin(), E = Decls.end(); I != E; ++I) {
Guy Benyei11169dd2012-12-18 14:30:41 +00006686 SetExternalVisibleDeclsForName(DC, I->first, I->second);
6687 }
6688 const_cast<DeclContext *>(DC)->setHasExternalVisibleStorage(false);
6689}
6690
6691/// \brief Under non-PCH compilation the consumer receives the objc methods
6692/// before receiving the implementation, and codegen depends on this.
6693/// We simulate this by deserializing and passing to consumer the methods of the
6694/// implementation before passing the deserialized implementation decl.
6695static void PassObjCImplDeclToConsumer(ObjCImplDecl *ImplD,
6696 ASTConsumer *Consumer) {
6697 assert(ImplD && Consumer);
6698
Aaron Ballmanaff18c02014-03-13 19:03:34 +00006699 for (auto *I : ImplD->methods())
6700 Consumer->HandleInterestingDecl(DeclGroupRef(I));
Guy Benyei11169dd2012-12-18 14:30:41 +00006701
6702 Consumer->HandleInterestingDecl(DeclGroupRef(ImplD));
6703}
6704
6705void ASTReader::PassInterestingDeclsToConsumer() {
6706 assert(Consumer);
Richard Smith04d05b52014-03-23 00:27:18 +00006707
6708 if (PassingDeclsToConsumer)
6709 return;
6710
6711 // Guard variable to avoid recursively redoing the process of passing
6712 // decls to consumer.
6713 SaveAndRestore<bool> GuardPassingDeclsToConsumer(PassingDeclsToConsumer,
6714 true);
6715
Guy Benyei11169dd2012-12-18 14:30:41 +00006716 while (!InterestingDecls.empty()) {
6717 Decl *D = InterestingDecls.front();
6718 InterestingDecls.pop_front();
6719
6720 PassInterestingDeclToConsumer(D);
6721 }
6722}
6723
6724void ASTReader::PassInterestingDeclToConsumer(Decl *D) {
6725 if (ObjCImplDecl *ImplD = dyn_cast<ObjCImplDecl>(D))
6726 PassObjCImplDeclToConsumer(ImplD, Consumer);
6727 else
6728 Consumer->HandleInterestingDecl(DeclGroupRef(D));
6729}
6730
6731void ASTReader::StartTranslationUnit(ASTConsumer *Consumer) {
6732 this->Consumer = Consumer;
6733
6734 if (!Consumer)
6735 return;
6736
Ben Langmuir332aafe2014-01-31 01:06:56 +00006737 for (unsigned I = 0, N = EagerlyDeserializedDecls.size(); I != N; ++I) {
Guy Benyei11169dd2012-12-18 14:30:41 +00006738 // Force deserialization of this decl, which will cause it to be queued for
6739 // passing to the consumer.
Ben Langmuir332aafe2014-01-31 01:06:56 +00006740 GetDecl(EagerlyDeserializedDecls[I]);
Guy Benyei11169dd2012-12-18 14:30:41 +00006741 }
Ben Langmuir332aafe2014-01-31 01:06:56 +00006742 EagerlyDeserializedDecls.clear();
Guy Benyei11169dd2012-12-18 14:30:41 +00006743
6744 PassInterestingDeclsToConsumer();
6745}
6746
6747void ASTReader::PrintStats() {
6748 std::fprintf(stderr, "*** AST File Statistics:\n");
6749
6750 unsigned NumTypesLoaded
6751 = TypesLoaded.size() - std::count(TypesLoaded.begin(), TypesLoaded.end(),
6752 QualType());
6753 unsigned NumDeclsLoaded
6754 = DeclsLoaded.size() - std::count(DeclsLoaded.begin(), DeclsLoaded.end(),
Craig Toppera13603a2014-05-22 05:54:18 +00006755 (Decl *)nullptr);
Guy Benyei11169dd2012-12-18 14:30:41 +00006756 unsigned NumIdentifiersLoaded
6757 = IdentifiersLoaded.size() - std::count(IdentifiersLoaded.begin(),
6758 IdentifiersLoaded.end(),
Craig Toppera13603a2014-05-22 05:54:18 +00006759 (IdentifierInfo *)nullptr);
Guy Benyei11169dd2012-12-18 14:30:41 +00006760 unsigned NumMacrosLoaded
6761 = MacrosLoaded.size() - std::count(MacrosLoaded.begin(),
6762 MacrosLoaded.end(),
Craig Toppera13603a2014-05-22 05:54:18 +00006763 (MacroInfo *)nullptr);
Guy Benyei11169dd2012-12-18 14:30:41 +00006764 unsigned NumSelectorsLoaded
6765 = SelectorsLoaded.size() - std::count(SelectorsLoaded.begin(),
6766 SelectorsLoaded.end(),
6767 Selector());
6768
6769 if (unsigned TotalNumSLocEntries = getTotalNumSLocs())
6770 std::fprintf(stderr, " %u/%u source location entries read (%f%%)\n",
6771 NumSLocEntriesRead, TotalNumSLocEntries,
6772 ((float)NumSLocEntriesRead/TotalNumSLocEntries * 100));
6773 if (!TypesLoaded.empty())
6774 std::fprintf(stderr, " %u/%u types read (%f%%)\n",
6775 NumTypesLoaded, (unsigned)TypesLoaded.size(),
6776 ((float)NumTypesLoaded/TypesLoaded.size() * 100));
6777 if (!DeclsLoaded.empty())
6778 std::fprintf(stderr, " %u/%u declarations read (%f%%)\n",
6779 NumDeclsLoaded, (unsigned)DeclsLoaded.size(),
6780 ((float)NumDeclsLoaded/DeclsLoaded.size() * 100));
6781 if (!IdentifiersLoaded.empty())
6782 std::fprintf(stderr, " %u/%u identifiers read (%f%%)\n",
6783 NumIdentifiersLoaded, (unsigned)IdentifiersLoaded.size(),
6784 ((float)NumIdentifiersLoaded/IdentifiersLoaded.size() * 100));
6785 if (!MacrosLoaded.empty())
6786 std::fprintf(stderr, " %u/%u macros read (%f%%)\n",
6787 NumMacrosLoaded, (unsigned)MacrosLoaded.size(),
6788 ((float)NumMacrosLoaded/MacrosLoaded.size() * 100));
6789 if (!SelectorsLoaded.empty())
6790 std::fprintf(stderr, " %u/%u selectors read (%f%%)\n",
6791 NumSelectorsLoaded, (unsigned)SelectorsLoaded.size(),
6792 ((float)NumSelectorsLoaded/SelectorsLoaded.size() * 100));
6793 if (TotalNumStatements)
6794 std::fprintf(stderr, " %u/%u statements read (%f%%)\n",
6795 NumStatementsRead, TotalNumStatements,
6796 ((float)NumStatementsRead/TotalNumStatements * 100));
6797 if (TotalNumMacros)
6798 std::fprintf(stderr, " %u/%u macros read (%f%%)\n",
6799 NumMacrosRead, TotalNumMacros,
6800 ((float)NumMacrosRead/TotalNumMacros * 100));
6801 if (TotalLexicalDeclContexts)
6802 std::fprintf(stderr, " %u/%u lexical declcontexts read (%f%%)\n",
6803 NumLexicalDeclContextsRead, TotalLexicalDeclContexts,
6804 ((float)NumLexicalDeclContextsRead/TotalLexicalDeclContexts
6805 * 100));
6806 if (TotalVisibleDeclContexts)
6807 std::fprintf(stderr, " %u/%u visible declcontexts read (%f%%)\n",
6808 NumVisibleDeclContextsRead, TotalVisibleDeclContexts,
6809 ((float)NumVisibleDeclContextsRead/TotalVisibleDeclContexts
6810 * 100));
6811 if (TotalNumMethodPoolEntries) {
6812 std::fprintf(stderr, " %u/%u method pool entries read (%f%%)\n",
6813 NumMethodPoolEntriesRead, TotalNumMethodPoolEntries,
6814 ((float)NumMethodPoolEntriesRead/TotalNumMethodPoolEntries
6815 * 100));
Guy Benyei11169dd2012-12-18 14:30:41 +00006816 }
Douglas Gregorad2f7a52013-01-28 17:54:36 +00006817 if (NumMethodPoolLookups) {
6818 std::fprintf(stderr, " %u/%u method pool lookups succeeded (%f%%)\n",
6819 NumMethodPoolHits, NumMethodPoolLookups,
6820 ((float)NumMethodPoolHits/NumMethodPoolLookups * 100.0));
6821 }
6822 if (NumMethodPoolTableLookups) {
6823 std::fprintf(stderr, " %u/%u method pool table lookups succeeded (%f%%)\n",
6824 NumMethodPoolTableHits, NumMethodPoolTableLookups,
6825 ((float)NumMethodPoolTableHits/NumMethodPoolTableLookups
6826 * 100.0));
6827 }
6828
Douglas Gregor00a50f72013-01-25 00:38:33 +00006829 if (NumIdentifierLookupHits) {
6830 std::fprintf(stderr,
6831 " %u / %u identifier table lookups succeeded (%f%%)\n",
6832 NumIdentifierLookupHits, NumIdentifierLookups,
6833 (double)NumIdentifierLookupHits*100.0/NumIdentifierLookups);
6834 }
6835
Douglas Gregore060e572013-01-25 01:03:03 +00006836 if (GlobalIndex) {
6837 std::fprintf(stderr, "\n");
6838 GlobalIndex->printStats();
6839 }
6840
Guy Benyei11169dd2012-12-18 14:30:41 +00006841 std::fprintf(stderr, "\n");
6842 dump();
6843 std::fprintf(stderr, "\n");
6844}
6845
6846template<typename Key, typename ModuleFile, unsigned InitialCapacity>
6847static void
6848dumpModuleIDMap(StringRef Name,
6849 const ContinuousRangeMap<Key, ModuleFile *,
6850 InitialCapacity> &Map) {
6851 if (Map.begin() == Map.end())
6852 return;
6853
6854 typedef ContinuousRangeMap<Key, ModuleFile *, InitialCapacity> MapType;
6855 llvm::errs() << Name << ":\n";
6856 for (typename MapType::const_iterator I = Map.begin(), IEnd = Map.end();
6857 I != IEnd; ++I) {
6858 llvm::errs() << " " << I->first << " -> " << I->second->FileName
6859 << "\n";
6860 }
6861}
6862
6863void ASTReader::dump() {
6864 llvm::errs() << "*** PCH/ModuleFile Remappings:\n";
6865 dumpModuleIDMap("Global bit offset map", GlobalBitOffsetsMap);
6866 dumpModuleIDMap("Global source location entry map", GlobalSLocEntryMap);
6867 dumpModuleIDMap("Global type map", GlobalTypeMap);
6868 dumpModuleIDMap("Global declaration map", GlobalDeclMap);
6869 dumpModuleIDMap("Global identifier map", GlobalIdentifierMap);
6870 dumpModuleIDMap("Global macro map", GlobalMacroMap);
6871 dumpModuleIDMap("Global submodule map", GlobalSubmoduleMap);
6872 dumpModuleIDMap("Global selector map", GlobalSelectorMap);
6873 dumpModuleIDMap("Global preprocessed entity map",
6874 GlobalPreprocessedEntityMap);
6875
6876 llvm::errs() << "\n*** PCH/Modules Loaded:";
6877 for (ModuleManager::ModuleConstIterator M = ModuleMgr.begin(),
6878 MEnd = ModuleMgr.end();
6879 M != MEnd; ++M)
6880 (*M)->dump();
6881}
6882
6883/// Return the amount of memory used by memory buffers, breaking down
6884/// by heap-backed versus mmap'ed memory.
6885void ASTReader::getMemoryBufferSizes(MemoryBufferSizes &sizes) const {
6886 for (ModuleConstIterator I = ModuleMgr.begin(),
6887 E = ModuleMgr.end(); I != E; ++I) {
6888 if (llvm::MemoryBuffer *buf = (*I)->Buffer.get()) {
6889 size_t bytes = buf->getBufferSize();
6890 switch (buf->getBufferKind()) {
6891 case llvm::MemoryBuffer::MemoryBuffer_Malloc:
6892 sizes.malloc_bytes += bytes;
6893 break;
6894 case llvm::MemoryBuffer::MemoryBuffer_MMap:
6895 sizes.mmap_bytes += bytes;
6896 break;
6897 }
6898 }
6899 }
6900}
6901
6902void ASTReader::InitializeSema(Sema &S) {
6903 SemaObj = &S;
6904 S.addExternalSource(this);
6905
6906 // Makes sure any declarations that were deserialized "too early"
6907 // still get added to the identifier's declaration chains.
Ben Langmuir5418f402014-09-10 21:29:41 +00006908 for (uint64_t ID : PreloadedDeclIDs) {
6909 NamedDecl *D = cast<NamedDecl>(GetDecl(ID));
6910 pushExternalDeclIntoScope(D, D->getDeclName());
Guy Benyei11169dd2012-12-18 14:30:41 +00006911 }
Ben Langmuir5418f402014-09-10 21:29:41 +00006912 PreloadedDeclIDs.clear();
Guy Benyei11169dd2012-12-18 14:30:41 +00006913
Richard Smith3d8e97e2013-10-18 06:54:39 +00006914 // FIXME: What happens if these are changed by a module import?
Guy Benyei11169dd2012-12-18 14:30:41 +00006915 if (!FPPragmaOptions.empty()) {
6916 assert(FPPragmaOptions.size() == 1 && "Wrong number of FP_PRAGMA_OPTIONS");
6917 SemaObj->FPFeatures.fp_contract = FPPragmaOptions[0];
6918 }
6919
Richard Smith3d8e97e2013-10-18 06:54:39 +00006920 // FIXME: What happens if these are changed by a module import?
Guy Benyei11169dd2012-12-18 14:30:41 +00006921 if (!OpenCLExtensions.empty()) {
6922 unsigned I = 0;
6923#define OPENCLEXT(nm) SemaObj->OpenCLFeatures.nm = OpenCLExtensions[I++];
6924#include "clang/Basic/OpenCLExtensions.def"
6925
6926 assert(OpenCLExtensions.size() == I && "Wrong number of OPENCL_EXTENSIONS");
6927 }
Richard Smith3d8e97e2013-10-18 06:54:39 +00006928
6929 UpdateSema();
6930}
6931
6932void ASTReader::UpdateSema() {
6933 assert(SemaObj && "no Sema to update");
6934
6935 // Load the offsets of the declarations that Sema references.
6936 // They will be lazily deserialized when needed.
6937 if (!SemaDeclRefs.empty()) {
6938 assert(SemaDeclRefs.size() % 2 == 0);
6939 for (unsigned I = 0; I != SemaDeclRefs.size(); I += 2) {
6940 if (!SemaObj->StdNamespace)
6941 SemaObj->StdNamespace = SemaDeclRefs[I];
6942 if (!SemaObj->StdBadAlloc)
6943 SemaObj->StdBadAlloc = SemaDeclRefs[I+1];
6944 }
6945 SemaDeclRefs.clear();
6946 }
Dario Domizioli13a0a382014-05-23 12:13:25 +00006947
6948 // Update the state of 'pragma clang optimize'. Use the same API as if we had
6949 // encountered the pragma in the source.
6950 if(OptimizeOffPragmaLocation.isValid())
6951 SemaObj->ActOnPragmaOptimize(/* IsOn = */ false, OptimizeOffPragmaLocation);
Guy Benyei11169dd2012-12-18 14:30:41 +00006952}
6953
6954IdentifierInfo* ASTReader::get(const char *NameStart, const char *NameEnd) {
6955 // Note that we are loading an identifier.
6956 Deserializing AnIdentifier(this);
Douglas Gregore060e572013-01-25 01:03:03 +00006957 StringRef Name(NameStart, NameEnd - NameStart);
6958
6959 // If there is a global index, look there first to determine which modules
6960 // provably do not have any results for this identifier.
Douglas Gregor7211ac12013-01-25 23:32:03 +00006961 GlobalModuleIndex::HitSet Hits;
Craig Toppera13603a2014-05-22 05:54:18 +00006962 GlobalModuleIndex::HitSet *HitsPtr = nullptr;
Douglas Gregore060e572013-01-25 01:03:03 +00006963 if (!loadGlobalIndex()) {
Douglas Gregor7211ac12013-01-25 23:32:03 +00006964 if (GlobalIndex->lookupIdentifier(Name, Hits)) {
6965 HitsPtr = &Hits;
Douglas Gregore060e572013-01-25 01:03:03 +00006966 }
6967 }
Douglas Gregor7211ac12013-01-25 23:32:03 +00006968 IdentifierLookupVisitor Visitor(Name, /*PriorGeneration=*/0,
Douglas Gregor00a50f72013-01-25 00:38:33 +00006969 NumIdentifierLookups,
6970 NumIdentifierLookupHits);
Douglas Gregor7211ac12013-01-25 23:32:03 +00006971 ModuleMgr.visit(IdentifierLookupVisitor::visit, &Visitor, HitsPtr);
Guy Benyei11169dd2012-12-18 14:30:41 +00006972 IdentifierInfo *II = Visitor.getIdentifierInfo();
6973 markIdentifierUpToDate(II);
6974 return II;
6975}
6976
6977namespace clang {
6978 /// \brief An identifier-lookup iterator that enumerates all of the
6979 /// identifiers stored within a set of AST files.
6980 class ASTIdentifierIterator : public IdentifierIterator {
6981 /// \brief The AST reader whose identifiers are being enumerated.
6982 const ASTReader &Reader;
6983
6984 /// \brief The current index into the chain of AST files stored in
6985 /// the AST reader.
6986 unsigned Index;
6987
6988 /// \brief The current position within the identifier lookup table
6989 /// of the current AST file.
6990 ASTIdentifierLookupTable::key_iterator Current;
6991
6992 /// \brief The end position within the identifier lookup table of
6993 /// the current AST file.
6994 ASTIdentifierLookupTable::key_iterator End;
6995
6996 public:
6997 explicit ASTIdentifierIterator(const ASTReader &Reader);
6998
Craig Topper3e89dfe2014-03-13 02:13:41 +00006999 StringRef Next() override;
Guy Benyei11169dd2012-12-18 14:30:41 +00007000 };
7001}
7002
7003ASTIdentifierIterator::ASTIdentifierIterator(const ASTReader &Reader)
7004 : Reader(Reader), Index(Reader.ModuleMgr.size() - 1) {
7005 ASTIdentifierLookupTable *IdTable
7006 = (ASTIdentifierLookupTable *)Reader.ModuleMgr[Index].IdentifierLookupTable;
7007 Current = IdTable->key_begin();
7008 End = IdTable->key_end();
7009}
7010
7011StringRef ASTIdentifierIterator::Next() {
7012 while (Current == End) {
7013 // If we have exhausted all of our AST files, we're done.
7014 if (Index == 0)
7015 return StringRef();
7016
7017 --Index;
7018 ASTIdentifierLookupTable *IdTable
7019 = (ASTIdentifierLookupTable *)Reader.ModuleMgr[Index].
7020 IdentifierLookupTable;
7021 Current = IdTable->key_begin();
7022 End = IdTable->key_end();
7023 }
7024
7025 // We have any identifiers remaining in the current AST file; return
7026 // the next one.
Douglas Gregorbfd73d72013-01-23 18:53:14 +00007027 StringRef Result = *Current;
Guy Benyei11169dd2012-12-18 14:30:41 +00007028 ++Current;
Douglas Gregorbfd73d72013-01-23 18:53:14 +00007029 return Result;
Guy Benyei11169dd2012-12-18 14:30:41 +00007030}
7031
Argyrios Kyrtzidis9aca3c62013-04-17 22:10:55 +00007032IdentifierIterator *ASTReader::getIdentifiers() {
7033 if (!loadGlobalIndex())
7034 return GlobalIndex->createIdentifierIterator();
7035
Guy Benyei11169dd2012-12-18 14:30:41 +00007036 return new ASTIdentifierIterator(*this);
7037}
7038
7039namespace clang { namespace serialization {
7040 class ReadMethodPoolVisitor {
7041 ASTReader &Reader;
7042 Selector Sel;
7043 unsigned PriorGeneration;
Argyrios Kyrtzidisd3da6e02013-04-17 00:08:58 +00007044 unsigned InstanceBits;
7045 unsigned FactoryBits;
Dmitri Gribenkof8579502013-01-12 19:30:44 +00007046 SmallVector<ObjCMethodDecl *, 4> InstanceMethods;
7047 SmallVector<ObjCMethodDecl *, 4> FactoryMethods;
Guy Benyei11169dd2012-12-18 14:30:41 +00007048
7049 public:
7050 ReadMethodPoolVisitor(ASTReader &Reader, Selector Sel,
7051 unsigned PriorGeneration)
Argyrios Kyrtzidisd3da6e02013-04-17 00:08:58 +00007052 : Reader(Reader), Sel(Sel), PriorGeneration(PriorGeneration),
7053 InstanceBits(0), FactoryBits(0) { }
Guy Benyei11169dd2012-12-18 14:30:41 +00007054
7055 static bool visit(ModuleFile &M, void *UserData) {
7056 ReadMethodPoolVisitor *This
7057 = static_cast<ReadMethodPoolVisitor *>(UserData);
7058
7059 if (!M.SelectorLookupTable)
7060 return false;
7061
7062 // If we've already searched this module file, skip it now.
7063 if (M.Generation <= This->PriorGeneration)
7064 return true;
7065
Douglas Gregorad2f7a52013-01-28 17:54:36 +00007066 ++This->Reader.NumMethodPoolTableLookups;
Guy Benyei11169dd2012-12-18 14:30:41 +00007067 ASTSelectorLookupTable *PoolTable
7068 = (ASTSelectorLookupTable*)M.SelectorLookupTable;
7069 ASTSelectorLookupTable::iterator Pos = PoolTable->find(This->Sel);
7070 if (Pos == PoolTable->end())
7071 return false;
Douglas Gregorad2f7a52013-01-28 17:54:36 +00007072
7073 ++This->Reader.NumMethodPoolTableHits;
Guy Benyei11169dd2012-12-18 14:30:41 +00007074 ++This->Reader.NumSelectorsRead;
7075 // FIXME: Not quite happy with the statistics here. We probably should
7076 // disable this tracking when called via LoadSelector.
7077 // Also, should entries without methods count as misses?
7078 ++This->Reader.NumMethodPoolEntriesRead;
7079 ASTSelectorLookupTrait::data_type Data = *Pos;
7080 if (This->Reader.DeserializationListener)
7081 This->Reader.DeserializationListener->SelectorRead(Data.ID,
7082 This->Sel);
7083
7084 This->InstanceMethods.append(Data.Instance.begin(), Data.Instance.end());
7085 This->FactoryMethods.append(Data.Factory.begin(), Data.Factory.end());
Argyrios Kyrtzidisd3da6e02013-04-17 00:08:58 +00007086 This->InstanceBits = Data.InstanceBits;
7087 This->FactoryBits = Data.FactoryBits;
Guy Benyei11169dd2012-12-18 14:30:41 +00007088 return true;
7089 }
7090
7091 /// \brief Retrieve the instance methods found by this visitor.
7092 ArrayRef<ObjCMethodDecl *> getInstanceMethods() const {
7093 return InstanceMethods;
7094 }
7095
7096 /// \brief Retrieve the instance methods found by this visitor.
7097 ArrayRef<ObjCMethodDecl *> getFactoryMethods() const {
7098 return FactoryMethods;
7099 }
Argyrios Kyrtzidisd3da6e02013-04-17 00:08:58 +00007100
7101 unsigned getInstanceBits() const { return InstanceBits; }
7102 unsigned getFactoryBits() const { return FactoryBits; }
Guy Benyei11169dd2012-12-18 14:30:41 +00007103 };
7104} } // end namespace clang::serialization
7105
7106/// \brief Add the given set of methods to the method list.
7107static void addMethodsToPool(Sema &S, ArrayRef<ObjCMethodDecl *> Methods,
7108 ObjCMethodList &List) {
7109 for (unsigned I = 0, N = Methods.size(); I != N; ++I) {
7110 S.addMethodToGlobalList(&List, Methods[I]);
7111 }
7112}
7113
7114void ASTReader::ReadMethodPool(Selector Sel) {
7115 // Get the selector generation and update it to the current generation.
7116 unsigned &Generation = SelectorGeneration[Sel];
7117 unsigned PriorGeneration = Generation;
Richard Smith053f6c62014-05-16 23:01:30 +00007118 Generation = getGeneration();
Guy Benyei11169dd2012-12-18 14:30:41 +00007119
7120 // Search for methods defined with this selector.
Douglas Gregorad2f7a52013-01-28 17:54:36 +00007121 ++NumMethodPoolLookups;
Guy Benyei11169dd2012-12-18 14:30:41 +00007122 ReadMethodPoolVisitor Visitor(*this, Sel, PriorGeneration);
7123 ModuleMgr.visit(&ReadMethodPoolVisitor::visit, &Visitor);
7124
7125 if (Visitor.getInstanceMethods().empty() &&
Douglas Gregorad2f7a52013-01-28 17:54:36 +00007126 Visitor.getFactoryMethods().empty())
Guy Benyei11169dd2012-12-18 14:30:41 +00007127 return;
Douglas Gregorad2f7a52013-01-28 17:54:36 +00007128
7129 ++NumMethodPoolHits;
7130
Guy Benyei11169dd2012-12-18 14:30:41 +00007131 if (!getSema())
7132 return;
7133
7134 Sema &S = *getSema();
7135 Sema::GlobalMethodPool::iterator Pos
7136 = S.MethodPool.insert(std::make_pair(Sel, Sema::GlobalMethods())).first;
7137
7138 addMethodsToPool(S, Visitor.getInstanceMethods(), Pos->second.first);
7139 addMethodsToPool(S, Visitor.getFactoryMethods(), Pos->second.second);
Argyrios Kyrtzidisd3da6e02013-04-17 00:08:58 +00007140 Pos->second.first.setBits(Visitor.getInstanceBits());
7141 Pos->second.second.setBits(Visitor.getFactoryBits());
Guy Benyei11169dd2012-12-18 14:30:41 +00007142}
7143
7144void ASTReader::ReadKnownNamespaces(
7145 SmallVectorImpl<NamespaceDecl *> &Namespaces) {
7146 Namespaces.clear();
7147
7148 for (unsigned I = 0, N = KnownNamespaces.size(); I != N; ++I) {
7149 if (NamespaceDecl *Namespace
7150 = dyn_cast_or_null<NamespaceDecl>(GetDecl(KnownNamespaces[I])))
7151 Namespaces.push_back(Namespace);
7152 }
7153}
7154
Nick Lewycky9c7eb1d2013-02-01 08:13:20 +00007155void ASTReader::ReadUndefinedButUsed(
Nick Lewyckyf0f56162013-01-31 03:23:57 +00007156 llvm::DenseMap<NamedDecl*, SourceLocation> &Undefined) {
Nick Lewycky9c7eb1d2013-02-01 08:13:20 +00007157 for (unsigned Idx = 0, N = UndefinedButUsed.size(); Idx != N;) {
7158 NamedDecl *D = cast<NamedDecl>(GetDecl(UndefinedButUsed[Idx++]));
Nick Lewycky8334af82013-01-26 00:35:08 +00007159 SourceLocation Loc =
Nick Lewycky9c7eb1d2013-02-01 08:13:20 +00007160 SourceLocation::getFromRawEncoding(UndefinedButUsed[Idx++]);
Nick Lewycky8334af82013-01-26 00:35:08 +00007161 Undefined.insert(std::make_pair(D, Loc));
7162 }
7163}
Nick Lewycky8334af82013-01-26 00:35:08 +00007164
Guy Benyei11169dd2012-12-18 14:30:41 +00007165void ASTReader::ReadTentativeDefinitions(
7166 SmallVectorImpl<VarDecl *> &TentativeDefs) {
7167 for (unsigned I = 0, N = TentativeDefinitions.size(); I != N; ++I) {
7168 VarDecl *Var = dyn_cast_or_null<VarDecl>(GetDecl(TentativeDefinitions[I]));
7169 if (Var)
7170 TentativeDefs.push_back(Var);
7171 }
7172 TentativeDefinitions.clear();
7173}
7174
7175void ASTReader::ReadUnusedFileScopedDecls(
7176 SmallVectorImpl<const DeclaratorDecl *> &Decls) {
7177 for (unsigned I = 0, N = UnusedFileScopedDecls.size(); I != N; ++I) {
7178 DeclaratorDecl *D
7179 = dyn_cast_or_null<DeclaratorDecl>(GetDecl(UnusedFileScopedDecls[I]));
7180 if (D)
7181 Decls.push_back(D);
7182 }
7183 UnusedFileScopedDecls.clear();
7184}
7185
7186void ASTReader::ReadDelegatingConstructors(
7187 SmallVectorImpl<CXXConstructorDecl *> &Decls) {
7188 for (unsigned I = 0, N = DelegatingCtorDecls.size(); I != N; ++I) {
7189 CXXConstructorDecl *D
7190 = dyn_cast_or_null<CXXConstructorDecl>(GetDecl(DelegatingCtorDecls[I]));
7191 if (D)
7192 Decls.push_back(D);
7193 }
7194 DelegatingCtorDecls.clear();
7195}
7196
7197void ASTReader::ReadExtVectorDecls(SmallVectorImpl<TypedefNameDecl *> &Decls) {
7198 for (unsigned I = 0, N = ExtVectorDecls.size(); I != N; ++I) {
7199 TypedefNameDecl *D
7200 = dyn_cast_or_null<TypedefNameDecl>(GetDecl(ExtVectorDecls[I]));
7201 if (D)
7202 Decls.push_back(D);
7203 }
7204 ExtVectorDecls.clear();
7205}
7206
7207void ASTReader::ReadDynamicClasses(SmallVectorImpl<CXXRecordDecl *> &Decls) {
7208 for (unsigned I = 0, N = DynamicClasses.size(); I != N; ++I) {
7209 CXXRecordDecl *D
7210 = dyn_cast_or_null<CXXRecordDecl>(GetDecl(DynamicClasses[I]));
7211 if (D)
7212 Decls.push_back(D);
7213 }
7214 DynamicClasses.clear();
7215}
7216
Nico Weber72889432014-09-06 01:25:55 +00007217void ASTReader::ReadUnusedLocalTypedefNameCandidates(
7218 llvm::SmallSetVector<const TypedefNameDecl *, 4> &Decls) {
7219 for (unsigned I = 0, N = UnusedLocalTypedefNameCandidates.size(); I != N;
7220 ++I) {
7221 TypedefNameDecl *D = dyn_cast_or_null<TypedefNameDecl>(
7222 GetDecl(UnusedLocalTypedefNameCandidates[I]));
7223 if (D)
7224 Decls.insert(D);
7225 }
7226 UnusedLocalTypedefNameCandidates.clear();
7227}
7228
Guy Benyei11169dd2012-12-18 14:30:41 +00007229void
Richard Smith78165b52013-01-10 23:43:47 +00007230ASTReader::ReadLocallyScopedExternCDecls(SmallVectorImpl<NamedDecl *> &Decls) {
7231 for (unsigned I = 0, N = LocallyScopedExternCDecls.size(); I != N; ++I) {
7232 NamedDecl *D
7233 = dyn_cast_or_null<NamedDecl>(GetDecl(LocallyScopedExternCDecls[I]));
Guy Benyei11169dd2012-12-18 14:30:41 +00007234 if (D)
7235 Decls.push_back(D);
7236 }
Richard Smith78165b52013-01-10 23:43:47 +00007237 LocallyScopedExternCDecls.clear();
Guy Benyei11169dd2012-12-18 14:30:41 +00007238}
7239
7240void ASTReader::ReadReferencedSelectors(
7241 SmallVectorImpl<std::pair<Selector, SourceLocation> > &Sels) {
7242 if (ReferencedSelectorsData.empty())
7243 return;
7244
7245 // If there are @selector references added them to its pool. This is for
7246 // implementation of -Wselector.
7247 unsigned int DataSize = ReferencedSelectorsData.size()-1;
7248 unsigned I = 0;
7249 while (I < DataSize) {
7250 Selector Sel = DecodeSelector(ReferencedSelectorsData[I++]);
7251 SourceLocation SelLoc
7252 = SourceLocation::getFromRawEncoding(ReferencedSelectorsData[I++]);
7253 Sels.push_back(std::make_pair(Sel, SelLoc));
7254 }
7255 ReferencedSelectorsData.clear();
7256}
7257
7258void ASTReader::ReadWeakUndeclaredIdentifiers(
7259 SmallVectorImpl<std::pair<IdentifierInfo *, WeakInfo> > &WeakIDs) {
7260 if (WeakUndeclaredIdentifiers.empty())
7261 return;
7262
7263 for (unsigned I = 0, N = WeakUndeclaredIdentifiers.size(); I < N; /*none*/) {
7264 IdentifierInfo *WeakId
7265 = DecodeIdentifierInfo(WeakUndeclaredIdentifiers[I++]);
7266 IdentifierInfo *AliasId
7267 = DecodeIdentifierInfo(WeakUndeclaredIdentifiers[I++]);
7268 SourceLocation Loc
7269 = SourceLocation::getFromRawEncoding(WeakUndeclaredIdentifiers[I++]);
7270 bool Used = WeakUndeclaredIdentifiers[I++];
7271 WeakInfo WI(AliasId, Loc);
7272 WI.setUsed(Used);
7273 WeakIDs.push_back(std::make_pair(WeakId, WI));
7274 }
7275 WeakUndeclaredIdentifiers.clear();
7276}
7277
7278void ASTReader::ReadUsedVTables(SmallVectorImpl<ExternalVTableUse> &VTables) {
7279 for (unsigned Idx = 0, N = VTableUses.size(); Idx < N; /* In loop */) {
7280 ExternalVTableUse VT;
7281 VT.Record = dyn_cast_or_null<CXXRecordDecl>(GetDecl(VTableUses[Idx++]));
7282 VT.Location = SourceLocation::getFromRawEncoding(VTableUses[Idx++]);
7283 VT.DefinitionRequired = VTableUses[Idx++];
7284 VTables.push_back(VT);
7285 }
7286
7287 VTableUses.clear();
7288}
7289
7290void ASTReader::ReadPendingInstantiations(
7291 SmallVectorImpl<std::pair<ValueDecl *, SourceLocation> > &Pending) {
7292 for (unsigned Idx = 0, N = PendingInstantiations.size(); Idx < N;) {
7293 ValueDecl *D = cast<ValueDecl>(GetDecl(PendingInstantiations[Idx++]));
7294 SourceLocation Loc
7295 = SourceLocation::getFromRawEncoding(PendingInstantiations[Idx++]);
7296
7297 Pending.push_back(std::make_pair(D, Loc));
7298 }
7299 PendingInstantiations.clear();
7300}
7301
Richard Smithe40f2ba2013-08-07 21:41:30 +00007302void ASTReader::ReadLateParsedTemplates(
7303 llvm::DenseMap<const FunctionDecl *, LateParsedTemplate *> &LPTMap) {
7304 for (unsigned Idx = 0, N = LateParsedTemplates.size(); Idx < N;
7305 /* In loop */) {
7306 FunctionDecl *FD = cast<FunctionDecl>(GetDecl(LateParsedTemplates[Idx++]));
7307
7308 LateParsedTemplate *LT = new LateParsedTemplate;
7309 LT->D = GetDecl(LateParsedTemplates[Idx++]);
7310
7311 ModuleFile *F = getOwningModuleFile(LT->D);
7312 assert(F && "No module");
7313
7314 unsigned TokN = LateParsedTemplates[Idx++];
7315 LT->Toks.reserve(TokN);
7316 for (unsigned T = 0; T < TokN; ++T)
7317 LT->Toks.push_back(ReadToken(*F, LateParsedTemplates, Idx));
7318
7319 LPTMap[FD] = LT;
7320 }
7321
7322 LateParsedTemplates.clear();
7323}
7324
Guy Benyei11169dd2012-12-18 14:30:41 +00007325void ASTReader::LoadSelector(Selector Sel) {
7326 // It would be complicated to avoid reading the methods anyway. So don't.
7327 ReadMethodPool(Sel);
7328}
7329
7330void ASTReader::SetIdentifierInfo(IdentifierID ID, IdentifierInfo *II) {
7331 assert(ID && "Non-zero identifier ID required");
7332 assert(ID <= IdentifiersLoaded.size() && "identifier ID out of range");
7333 IdentifiersLoaded[ID - 1] = II;
7334 if (DeserializationListener)
7335 DeserializationListener->IdentifierRead(ID, II);
7336}
7337
7338/// \brief Set the globally-visible declarations associated with the given
7339/// identifier.
7340///
7341/// If the AST reader is currently in a state where the given declaration IDs
7342/// cannot safely be resolved, they are queued until it is safe to resolve
7343/// them.
7344///
7345/// \param II an IdentifierInfo that refers to one or more globally-visible
7346/// declarations.
7347///
7348/// \param DeclIDs the set of declaration IDs with the name @p II that are
7349/// visible at global scope.
7350///
Douglas Gregor6168bd22013-02-18 15:53:43 +00007351/// \param Decls if non-null, this vector will be populated with the set of
7352/// deserialized declarations. These declarations will not be pushed into
7353/// scope.
Guy Benyei11169dd2012-12-18 14:30:41 +00007354void
7355ASTReader::SetGloballyVisibleDecls(IdentifierInfo *II,
7356 const SmallVectorImpl<uint32_t> &DeclIDs,
Douglas Gregor6168bd22013-02-18 15:53:43 +00007357 SmallVectorImpl<Decl *> *Decls) {
7358 if (NumCurrentElementsDeserializing && !Decls) {
7359 PendingIdentifierInfos[II].append(DeclIDs.begin(), DeclIDs.end());
Guy Benyei11169dd2012-12-18 14:30:41 +00007360 return;
7361 }
7362
7363 for (unsigned I = 0, N = DeclIDs.size(); I != N; ++I) {
Ben Langmuir5418f402014-09-10 21:29:41 +00007364 if (!SemaObj) {
Guy Benyei11169dd2012-12-18 14:30:41 +00007365 // Queue this declaration so that it will be added to the
7366 // translation unit scope and identifier's declaration chain
7367 // once a Sema object is known.
Ben Langmuir5418f402014-09-10 21:29:41 +00007368 PreloadedDeclIDs.push_back(DeclIDs[I]);
7369 continue;
Guy Benyei11169dd2012-12-18 14:30:41 +00007370 }
Ben Langmuir5418f402014-09-10 21:29:41 +00007371
7372 NamedDecl *D = cast<NamedDecl>(GetDecl(DeclIDs[I]));
7373
7374 // If we're simply supposed to record the declarations, do so now.
7375 if (Decls) {
7376 Decls->push_back(D);
7377 continue;
7378 }
7379
7380 // Introduce this declaration into the translation-unit scope
7381 // and add it to the declaration chain for this identifier, so
7382 // that (unqualified) name lookup will find it.
7383 pushExternalDeclIntoScope(D, II);
Guy Benyei11169dd2012-12-18 14:30:41 +00007384 }
7385}
7386
Douglas Gregorc8a992f2013-01-21 16:52:34 +00007387IdentifierInfo *ASTReader::DecodeIdentifierInfo(IdentifierID ID) {
Guy Benyei11169dd2012-12-18 14:30:41 +00007388 if (ID == 0)
Craig Toppera13603a2014-05-22 05:54:18 +00007389 return nullptr;
Guy Benyei11169dd2012-12-18 14:30:41 +00007390
7391 if (IdentifiersLoaded.empty()) {
7392 Error("no identifier table in AST file");
Craig Toppera13603a2014-05-22 05:54:18 +00007393 return nullptr;
Guy Benyei11169dd2012-12-18 14:30:41 +00007394 }
7395
7396 ID -= 1;
7397 if (!IdentifiersLoaded[ID]) {
7398 GlobalIdentifierMapType::iterator I = GlobalIdentifierMap.find(ID + 1);
7399 assert(I != GlobalIdentifierMap.end() && "Corrupted global identifier map");
7400 ModuleFile *M = I->second;
7401 unsigned Index = ID - M->BaseIdentifierID;
7402 const char *Str = M->IdentifierTableData + M->IdentifierOffsets[Index];
7403
7404 // All of the strings in the AST file are preceded by a 16-bit length.
7405 // Extract that 16-bit length to avoid having to execute strlen().
7406 // NOTE: 'StrLenPtr' is an 'unsigned char*' so that we load bytes as
7407 // unsigned integers. This is important to avoid integer overflow when
7408 // we cast them to 'unsigned'.
7409 const unsigned char *StrLenPtr = (const unsigned char*) Str - 2;
7410 unsigned StrLen = (((unsigned) StrLenPtr[0])
7411 | (((unsigned) StrLenPtr[1]) << 8)) - 1;
Douglas Gregorc8a992f2013-01-21 16:52:34 +00007412 IdentifiersLoaded[ID]
7413 = &PP.getIdentifierTable().get(StringRef(Str, StrLen));
Guy Benyei11169dd2012-12-18 14:30:41 +00007414 if (DeserializationListener)
7415 DeserializationListener->IdentifierRead(ID + 1, IdentifiersLoaded[ID]);
7416 }
7417
7418 return IdentifiersLoaded[ID];
7419}
7420
Douglas Gregorc8a992f2013-01-21 16:52:34 +00007421IdentifierInfo *ASTReader::getLocalIdentifier(ModuleFile &M, unsigned LocalID) {
7422 return DecodeIdentifierInfo(getGlobalIdentifierID(M, LocalID));
Guy Benyei11169dd2012-12-18 14:30:41 +00007423}
7424
7425IdentifierID ASTReader::getGlobalIdentifierID(ModuleFile &M, unsigned LocalID) {
7426 if (LocalID < NUM_PREDEF_IDENT_IDS)
7427 return LocalID;
7428
7429 ContinuousRangeMap<uint32_t, int, 2>::iterator I
7430 = M.IdentifierRemap.find(LocalID - NUM_PREDEF_IDENT_IDS);
7431 assert(I != M.IdentifierRemap.end()
7432 && "Invalid index into identifier index remap");
7433
7434 return LocalID + I->second;
7435}
7436
Argyrios Kyrtzidiseb663da2013-03-22 21:12:57 +00007437MacroInfo *ASTReader::getMacro(MacroID ID) {
Guy Benyei11169dd2012-12-18 14:30:41 +00007438 if (ID == 0)
Craig Toppera13603a2014-05-22 05:54:18 +00007439 return nullptr;
Guy Benyei11169dd2012-12-18 14:30:41 +00007440
7441 if (MacrosLoaded.empty()) {
7442 Error("no macro table in AST file");
Craig Toppera13603a2014-05-22 05:54:18 +00007443 return nullptr;
Guy Benyei11169dd2012-12-18 14:30:41 +00007444 }
7445
7446 ID -= NUM_PREDEF_MACRO_IDS;
7447 if (!MacrosLoaded[ID]) {
7448 GlobalMacroMapType::iterator I
7449 = GlobalMacroMap.find(ID + NUM_PREDEF_MACRO_IDS);
7450 assert(I != GlobalMacroMap.end() && "Corrupted global macro map");
7451 ModuleFile *M = I->second;
7452 unsigned Index = ID - M->BaseMacroID;
Argyrios Kyrtzidiseb663da2013-03-22 21:12:57 +00007453 MacrosLoaded[ID] = ReadMacroRecord(*M, M->MacroOffsets[Index]);
7454
7455 if (DeserializationListener)
7456 DeserializationListener->MacroRead(ID + NUM_PREDEF_MACRO_IDS,
7457 MacrosLoaded[ID]);
Guy Benyei11169dd2012-12-18 14:30:41 +00007458 }
7459
7460 return MacrosLoaded[ID];
7461}
7462
7463MacroID ASTReader::getGlobalMacroID(ModuleFile &M, unsigned LocalID) {
7464 if (LocalID < NUM_PREDEF_MACRO_IDS)
7465 return LocalID;
7466
7467 ContinuousRangeMap<uint32_t, int, 2>::iterator I
7468 = M.MacroRemap.find(LocalID - NUM_PREDEF_MACRO_IDS);
7469 assert(I != M.MacroRemap.end() && "Invalid index into macro index remap");
7470
7471 return LocalID + I->second;
7472}
7473
7474serialization::SubmoduleID
7475ASTReader::getGlobalSubmoduleID(ModuleFile &M, unsigned LocalID) {
7476 if (LocalID < NUM_PREDEF_SUBMODULE_IDS)
7477 return LocalID;
7478
7479 ContinuousRangeMap<uint32_t, int, 2>::iterator I
7480 = M.SubmoduleRemap.find(LocalID - NUM_PREDEF_SUBMODULE_IDS);
7481 assert(I != M.SubmoduleRemap.end()
7482 && "Invalid index into submodule index remap");
7483
7484 return LocalID + I->second;
7485}
7486
7487Module *ASTReader::getSubmodule(SubmoduleID GlobalID) {
7488 if (GlobalID < NUM_PREDEF_SUBMODULE_IDS) {
7489 assert(GlobalID == 0 && "Unhandled global submodule ID");
Craig Toppera13603a2014-05-22 05:54:18 +00007490 return nullptr;
Guy Benyei11169dd2012-12-18 14:30:41 +00007491 }
7492
7493 if (GlobalID > SubmodulesLoaded.size()) {
7494 Error("submodule ID out of range in AST file");
Craig Toppera13603a2014-05-22 05:54:18 +00007495 return nullptr;
Guy Benyei11169dd2012-12-18 14:30:41 +00007496 }
7497
7498 return SubmodulesLoaded[GlobalID - NUM_PREDEF_SUBMODULE_IDS];
7499}
Douglas Gregorc147b0b2013-01-12 01:29:50 +00007500
7501Module *ASTReader::getModule(unsigned ID) {
7502 return getSubmodule(ID);
7503}
7504
Guy Benyei11169dd2012-12-18 14:30:41 +00007505Selector ASTReader::getLocalSelector(ModuleFile &M, unsigned LocalID) {
7506 return DecodeSelector(getGlobalSelectorID(M, LocalID));
7507}
7508
7509Selector ASTReader::DecodeSelector(serialization::SelectorID ID) {
7510 if (ID == 0)
7511 return Selector();
7512
7513 if (ID > SelectorsLoaded.size()) {
7514 Error("selector ID out of range in AST file");
7515 return Selector();
7516 }
7517
Craig Toppera13603a2014-05-22 05:54:18 +00007518 if (SelectorsLoaded[ID - 1].getAsOpaquePtr() == nullptr) {
Guy Benyei11169dd2012-12-18 14:30:41 +00007519 // Load this selector from the selector table.
7520 GlobalSelectorMapType::iterator I = GlobalSelectorMap.find(ID);
7521 assert(I != GlobalSelectorMap.end() && "Corrupted global selector map");
7522 ModuleFile &M = *I->second;
7523 ASTSelectorLookupTrait Trait(*this, M);
7524 unsigned Idx = ID - M.BaseSelectorID - NUM_PREDEF_SELECTOR_IDS;
7525 SelectorsLoaded[ID - 1] =
7526 Trait.ReadKey(M.SelectorLookupTableData + M.SelectorOffsets[Idx], 0);
7527 if (DeserializationListener)
7528 DeserializationListener->SelectorRead(ID, SelectorsLoaded[ID - 1]);
7529 }
7530
7531 return SelectorsLoaded[ID - 1];
7532}
7533
7534Selector ASTReader::GetExternalSelector(serialization::SelectorID ID) {
7535 return DecodeSelector(ID);
7536}
7537
7538uint32_t ASTReader::GetNumExternalSelectors() {
7539 // ID 0 (the null selector) is considered an external selector.
7540 return getTotalNumSelectors() + 1;
7541}
7542
7543serialization::SelectorID
7544ASTReader::getGlobalSelectorID(ModuleFile &M, unsigned LocalID) const {
7545 if (LocalID < NUM_PREDEF_SELECTOR_IDS)
7546 return LocalID;
7547
7548 ContinuousRangeMap<uint32_t, int, 2>::iterator I
7549 = M.SelectorRemap.find(LocalID - NUM_PREDEF_SELECTOR_IDS);
7550 assert(I != M.SelectorRemap.end()
7551 && "Invalid index into selector index remap");
7552
7553 return LocalID + I->second;
7554}
7555
7556DeclarationName
7557ASTReader::ReadDeclarationName(ModuleFile &F,
7558 const RecordData &Record, unsigned &Idx) {
7559 DeclarationName::NameKind Kind = (DeclarationName::NameKind)Record[Idx++];
7560 switch (Kind) {
7561 case DeclarationName::Identifier:
Douglas Gregorc8a992f2013-01-21 16:52:34 +00007562 return DeclarationName(GetIdentifierInfo(F, Record, Idx));
Guy Benyei11169dd2012-12-18 14:30:41 +00007563
7564 case DeclarationName::ObjCZeroArgSelector:
7565 case DeclarationName::ObjCOneArgSelector:
7566 case DeclarationName::ObjCMultiArgSelector:
7567 return DeclarationName(ReadSelector(F, Record, Idx));
7568
7569 case DeclarationName::CXXConstructorName:
7570 return Context.DeclarationNames.getCXXConstructorName(
7571 Context.getCanonicalType(readType(F, Record, Idx)));
7572
7573 case DeclarationName::CXXDestructorName:
7574 return Context.DeclarationNames.getCXXDestructorName(
7575 Context.getCanonicalType(readType(F, Record, Idx)));
7576
7577 case DeclarationName::CXXConversionFunctionName:
7578 return Context.DeclarationNames.getCXXConversionFunctionName(
7579 Context.getCanonicalType(readType(F, Record, Idx)));
7580
7581 case DeclarationName::CXXOperatorName:
7582 return Context.DeclarationNames.getCXXOperatorName(
7583 (OverloadedOperatorKind)Record[Idx++]);
7584
7585 case DeclarationName::CXXLiteralOperatorName:
7586 return Context.DeclarationNames.getCXXLiteralOperatorName(
7587 GetIdentifierInfo(F, Record, Idx));
7588
7589 case DeclarationName::CXXUsingDirective:
7590 return DeclarationName::getUsingDirectiveName();
7591 }
7592
7593 llvm_unreachable("Invalid NameKind!");
7594}
7595
7596void ASTReader::ReadDeclarationNameLoc(ModuleFile &F,
7597 DeclarationNameLoc &DNLoc,
7598 DeclarationName Name,
7599 const RecordData &Record, unsigned &Idx) {
7600 switch (Name.getNameKind()) {
7601 case DeclarationName::CXXConstructorName:
7602 case DeclarationName::CXXDestructorName:
7603 case DeclarationName::CXXConversionFunctionName:
7604 DNLoc.NamedType.TInfo = GetTypeSourceInfo(F, Record, Idx);
7605 break;
7606
7607 case DeclarationName::CXXOperatorName:
7608 DNLoc.CXXOperatorName.BeginOpNameLoc
7609 = ReadSourceLocation(F, Record, Idx).getRawEncoding();
7610 DNLoc.CXXOperatorName.EndOpNameLoc
7611 = ReadSourceLocation(F, Record, Idx).getRawEncoding();
7612 break;
7613
7614 case DeclarationName::CXXLiteralOperatorName:
7615 DNLoc.CXXLiteralOperatorName.OpNameLoc
7616 = ReadSourceLocation(F, Record, Idx).getRawEncoding();
7617 break;
7618
7619 case DeclarationName::Identifier:
7620 case DeclarationName::ObjCZeroArgSelector:
7621 case DeclarationName::ObjCOneArgSelector:
7622 case DeclarationName::ObjCMultiArgSelector:
7623 case DeclarationName::CXXUsingDirective:
7624 break;
7625 }
7626}
7627
7628void ASTReader::ReadDeclarationNameInfo(ModuleFile &F,
7629 DeclarationNameInfo &NameInfo,
7630 const RecordData &Record, unsigned &Idx) {
7631 NameInfo.setName(ReadDeclarationName(F, Record, Idx));
7632 NameInfo.setLoc(ReadSourceLocation(F, Record, Idx));
7633 DeclarationNameLoc DNLoc;
7634 ReadDeclarationNameLoc(F, DNLoc, NameInfo.getName(), Record, Idx);
7635 NameInfo.setInfo(DNLoc);
7636}
7637
7638void ASTReader::ReadQualifierInfo(ModuleFile &F, QualifierInfo &Info,
7639 const RecordData &Record, unsigned &Idx) {
7640 Info.QualifierLoc = ReadNestedNameSpecifierLoc(F, Record, Idx);
7641 unsigned NumTPLists = Record[Idx++];
7642 Info.NumTemplParamLists = NumTPLists;
7643 if (NumTPLists) {
7644 Info.TemplParamLists = new (Context) TemplateParameterList*[NumTPLists];
7645 for (unsigned i=0; i != NumTPLists; ++i)
7646 Info.TemplParamLists[i] = ReadTemplateParameterList(F, Record, Idx);
7647 }
7648}
7649
7650TemplateName
7651ASTReader::ReadTemplateName(ModuleFile &F, const RecordData &Record,
7652 unsigned &Idx) {
7653 TemplateName::NameKind Kind = (TemplateName::NameKind)Record[Idx++];
7654 switch (Kind) {
7655 case TemplateName::Template:
7656 return TemplateName(ReadDeclAs<TemplateDecl>(F, Record, Idx));
7657
7658 case TemplateName::OverloadedTemplate: {
7659 unsigned size = Record[Idx++];
7660 UnresolvedSet<8> Decls;
7661 while (size--)
7662 Decls.addDecl(ReadDeclAs<NamedDecl>(F, Record, Idx));
7663
7664 return Context.getOverloadedTemplateName(Decls.begin(), Decls.end());
7665 }
7666
7667 case TemplateName::QualifiedTemplate: {
7668 NestedNameSpecifier *NNS = ReadNestedNameSpecifier(F, Record, Idx);
7669 bool hasTemplKeyword = Record[Idx++];
7670 TemplateDecl *Template = ReadDeclAs<TemplateDecl>(F, Record, Idx);
7671 return Context.getQualifiedTemplateName(NNS, hasTemplKeyword, Template);
7672 }
7673
7674 case TemplateName::DependentTemplate: {
7675 NestedNameSpecifier *NNS = ReadNestedNameSpecifier(F, Record, Idx);
7676 if (Record[Idx++]) // isIdentifier
7677 return Context.getDependentTemplateName(NNS,
7678 GetIdentifierInfo(F, Record,
7679 Idx));
7680 return Context.getDependentTemplateName(NNS,
7681 (OverloadedOperatorKind)Record[Idx++]);
7682 }
7683
7684 case TemplateName::SubstTemplateTemplateParm: {
7685 TemplateTemplateParmDecl *param
7686 = ReadDeclAs<TemplateTemplateParmDecl>(F, Record, Idx);
7687 if (!param) return TemplateName();
7688 TemplateName replacement = ReadTemplateName(F, Record, Idx);
7689 return Context.getSubstTemplateTemplateParm(param, replacement);
7690 }
7691
7692 case TemplateName::SubstTemplateTemplateParmPack: {
7693 TemplateTemplateParmDecl *Param
7694 = ReadDeclAs<TemplateTemplateParmDecl>(F, Record, Idx);
7695 if (!Param)
7696 return TemplateName();
7697
7698 TemplateArgument ArgPack = ReadTemplateArgument(F, Record, Idx);
7699 if (ArgPack.getKind() != TemplateArgument::Pack)
7700 return TemplateName();
7701
7702 return Context.getSubstTemplateTemplateParmPack(Param, ArgPack);
7703 }
7704 }
7705
7706 llvm_unreachable("Unhandled template name kind!");
7707}
7708
7709TemplateArgument
7710ASTReader::ReadTemplateArgument(ModuleFile &F,
7711 const RecordData &Record, unsigned &Idx) {
7712 TemplateArgument::ArgKind Kind = (TemplateArgument::ArgKind)Record[Idx++];
7713 switch (Kind) {
7714 case TemplateArgument::Null:
7715 return TemplateArgument();
7716 case TemplateArgument::Type:
7717 return TemplateArgument(readType(F, Record, Idx));
7718 case TemplateArgument::Declaration: {
7719 ValueDecl *D = ReadDeclAs<ValueDecl>(F, Record, Idx);
David Blaikie0f62c8d2014-10-16 04:21:25 +00007720 return TemplateArgument(D, readType(F, Record, Idx));
Guy Benyei11169dd2012-12-18 14:30:41 +00007721 }
7722 case TemplateArgument::NullPtr:
7723 return TemplateArgument(readType(F, Record, Idx), /*isNullPtr*/true);
7724 case TemplateArgument::Integral: {
7725 llvm::APSInt Value = ReadAPSInt(Record, Idx);
7726 QualType T = readType(F, Record, Idx);
7727 return TemplateArgument(Context, Value, T);
7728 }
7729 case TemplateArgument::Template:
7730 return TemplateArgument(ReadTemplateName(F, Record, Idx));
7731 case TemplateArgument::TemplateExpansion: {
7732 TemplateName Name = ReadTemplateName(F, Record, Idx);
David Blaikie05785d12013-02-20 22:23:23 +00007733 Optional<unsigned> NumTemplateExpansions;
Guy Benyei11169dd2012-12-18 14:30:41 +00007734 if (unsigned NumExpansions = Record[Idx++])
7735 NumTemplateExpansions = NumExpansions - 1;
7736 return TemplateArgument(Name, NumTemplateExpansions);
7737 }
7738 case TemplateArgument::Expression:
7739 return TemplateArgument(ReadExpr(F));
7740 case TemplateArgument::Pack: {
7741 unsigned NumArgs = Record[Idx++];
7742 TemplateArgument *Args = new (Context) TemplateArgument[NumArgs];
7743 for (unsigned I = 0; I != NumArgs; ++I)
7744 Args[I] = ReadTemplateArgument(F, Record, Idx);
7745 return TemplateArgument(Args, NumArgs);
7746 }
7747 }
7748
7749 llvm_unreachable("Unhandled template argument kind!");
7750}
7751
7752TemplateParameterList *
7753ASTReader::ReadTemplateParameterList(ModuleFile &F,
7754 const RecordData &Record, unsigned &Idx) {
7755 SourceLocation TemplateLoc = ReadSourceLocation(F, Record, Idx);
7756 SourceLocation LAngleLoc = ReadSourceLocation(F, Record, Idx);
7757 SourceLocation RAngleLoc = ReadSourceLocation(F, Record, Idx);
7758
7759 unsigned NumParams = Record[Idx++];
7760 SmallVector<NamedDecl *, 16> Params;
7761 Params.reserve(NumParams);
7762 while (NumParams--)
7763 Params.push_back(ReadDeclAs<NamedDecl>(F, Record, Idx));
7764
7765 TemplateParameterList* TemplateParams =
7766 TemplateParameterList::Create(Context, TemplateLoc, LAngleLoc,
7767 Params.data(), Params.size(), RAngleLoc);
7768 return TemplateParams;
7769}
7770
7771void
7772ASTReader::
Craig Topper5603df42013-07-05 19:34:19 +00007773ReadTemplateArgumentList(SmallVectorImpl<TemplateArgument> &TemplArgs,
Guy Benyei11169dd2012-12-18 14:30:41 +00007774 ModuleFile &F, const RecordData &Record,
7775 unsigned &Idx) {
7776 unsigned NumTemplateArgs = Record[Idx++];
7777 TemplArgs.reserve(NumTemplateArgs);
7778 while (NumTemplateArgs--)
7779 TemplArgs.push_back(ReadTemplateArgument(F, Record, Idx));
7780}
7781
7782/// \brief Read a UnresolvedSet structure.
Richard Smitha4ba74c2013-08-30 04:46:40 +00007783void ASTReader::ReadUnresolvedSet(ModuleFile &F, LazyASTUnresolvedSet &Set,
Guy Benyei11169dd2012-12-18 14:30:41 +00007784 const RecordData &Record, unsigned &Idx) {
7785 unsigned NumDecls = Record[Idx++];
7786 Set.reserve(Context, NumDecls);
7787 while (NumDecls--) {
Richard Smitha4ba74c2013-08-30 04:46:40 +00007788 DeclID ID = ReadDeclID(F, Record, Idx);
Guy Benyei11169dd2012-12-18 14:30:41 +00007789 AccessSpecifier AS = (AccessSpecifier)Record[Idx++];
Richard Smitha4ba74c2013-08-30 04:46:40 +00007790 Set.addLazyDecl(Context, ID, AS);
Guy Benyei11169dd2012-12-18 14:30:41 +00007791 }
7792}
7793
7794CXXBaseSpecifier
7795ASTReader::ReadCXXBaseSpecifier(ModuleFile &F,
7796 const RecordData &Record, unsigned &Idx) {
7797 bool isVirtual = static_cast<bool>(Record[Idx++]);
7798 bool isBaseOfClass = static_cast<bool>(Record[Idx++]);
7799 AccessSpecifier AS = static_cast<AccessSpecifier>(Record[Idx++]);
7800 bool inheritConstructors = static_cast<bool>(Record[Idx++]);
7801 TypeSourceInfo *TInfo = GetTypeSourceInfo(F, Record, Idx);
7802 SourceRange Range = ReadSourceRange(F, Record, Idx);
7803 SourceLocation EllipsisLoc = ReadSourceLocation(F, Record, Idx);
7804 CXXBaseSpecifier Result(Range, isVirtual, isBaseOfClass, AS, TInfo,
7805 EllipsisLoc);
7806 Result.setInheritConstructors(inheritConstructors);
7807 return Result;
7808}
7809
7810std::pair<CXXCtorInitializer **, unsigned>
7811ASTReader::ReadCXXCtorInitializers(ModuleFile &F, const RecordData &Record,
7812 unsigned &Idx) {
Craig Toppera13603a2014-05-22 05:54:18 +00007813 CXXCtorInitializer **CtorInitializers = nullptr;
Guy Benyei11169dd2012-12-18 14:30:41 +00007814 unsigned NumInitializers = Record[Idx++];
7815 if (NumInitializers) {
7816 CtorInitializers
7817 = new (Context) CXXCtorInitializer*[NumInitializers];
7818 for (unsigned i=0; i != NumInitializers; ++i) {
Craig Toppera13603a2014-05-22 05:54:18 +00007819 TypeSourceInfo *TInfo = nullptr;
Guy Benyei11169dd2012-12-18 14:30:41 +00007820 bool IsBaseVirtual = false;
Craig Toppera13603a2014-05-22 05:54:18 +00007821 FieldDecl *Member = nullptr;
7822 IndirectFieldDecl *IndirectMember = nullptr;
Guy Benyei11169dd2012-12-18 14:30:41 +00007823
7824 CtorInitializerType Type = (CtorInitializerType)Record[Idx++];
7825 switch (Type) {
7826 case CTOR_INITIALIZER_BASE:
7827 TInfo = GetTypeSourceInfo(F, Record, Idx);
7828 IsBaseVirtual = Record[Idx++];
7829 break;
7830
7831 case CTOR_INITIALIZER_DELEGATING:
7832 TInfo = GetTypeSourceInfo(F, Record, Idx);
7833 break;
7834
7835 case CTOR_INITIALIZER_MEMBER:
7836 Member = ReadDeclAs<FieldDecl>(F, Record, Idx);
7837 break;
7838
7839 case CTOR_INITIALIZER_INDIRECT_MEMBER:
7840 IndirectMember = ReadDeclAs<IndirectFieldDecl>(F, Record, Idx);
7841 break;
7842 }
7843
7844 SourceLocation MemberOrEllipsisLoc = ReadSourceLocation(F, Record, Idx);
7845 Expr *Init = ReadExpr(F);
7846 SourceLocation LParenLoc = ReadSourceLocation(F, Record, Idx);
7847 SourceLocation RParenLoc = ReadSourceLocation(F, Record, Idx);
7848 bool IsWritten = Record[Idx++];
7849 unsigned SourceOrderOrNumArrayIndices;
7850 SmallVector<VarDecl *, 8> Indices;
7851 if (IsWritten) {
7852 SourceOrderOrNumArrayIndices = Record[Idx++];
7853 } else {
7854 SourceOrderOrNumArrayIndices = Record[Idx++];
7855 Indices.reserve(SourceOrderOrNumArrayIndices);
7856 for (unsigned i=0; i != SourceOrderOrNumArrayIndices; ++i)
7857 Indices.push_back(ReadDeclAs<VarDecl>(F, Record, Idx));
7858 }
7859
7860 CXXCtorInitializer *BOMInit;
7861 if (Type == CTOR_INITIALIZER_BASE) {
7862 BOMInit = new (Context) CXXCtorInitializer(Context, TInfo, IsBaseVirtual,
7863 LParenLoc, Init, RParenLoc,
7864 MemberOrEllipsisLoc);
7865 } else if (Type == CTOR_INITIALIZER_DELEGATING) {
7866 BOMInit = new (Context) CXXCtorInitializer(Context, TInfo, LParenLoc,
7867 Init, RParenLoc);
7868 } else if (IsWritten) {
7869 if (Member)
7870 BOMInit = new (Context) CXXCtorInitializer(Context, Member, MemberOrEllipsisLoc,
7871 LParenLoc, Init, RParenLoc);
7872 else
7873 BOMInit = new (Context) CXXCtorInitializer(Context, IndirectMember,
7874 MemberOrEllipsisLoc, LParenLoc,
7875 Init, RParenLoc);
7876 } else {
Argyrios Kyrtzidis794671d2013-05-30 23:59:46 +00007877 if (IndirectMember) {
7878 assert(Indices.empty() && "Indirect field improperly initialized");
7879 BOMInit = new (Context) CXXCtorInitializer(Context, IndirectMember,
7880 MemberOrEllipsisLoc, LParenLoc,
7881 Init, RParenLoc);
7882 } else {
7883 BOMInit = CXXCtorInitializer::Create(Context, Member, MemberOrEllipsisLoc,
7884 LParenLoc, Init, RParenLoc,
7885 Indices.data(), Indices.size());
7886 }
Guy Benyei11169dd2012-12-18 14:30:41 +00007887 }
7888
7889 if (IsWritten)
7890 BOMInit->setSourceOrder(SourceOrderOrNumArrayIndices);
7891 CtorInitializers[i] = BOMInit;
7892 }
7893 }
7894
7895 return std::make_pair(CtorInitializers, NumInitializers);
7896}
7897
7898NestedNameSpecifier *
7899ASTReader::ReadNestedNameSpecifier(ModuleFile &F,
7900 const RecordData &Record, unsigned &Idx) {
7901 unsigned N = Record[Idx++];
Craig Toppera13603a2014-05-22 05:54:18 +00007902 NestedNameSpecifier *NNS = nullptr, *Prev = nullptr;
Guy Benyei11169dd2012-12-18 14:30:41 +00007903 for (unsigned I = 0; I != N; ++I) {
7904 NestedNameSpecifier::SpecifierKind Kind
7905 = (NestedNameSpecifier::SpecifierKind)Record[Idx++];
7906 switch (Kind) {
7907 case NestedNameSpecifier::Identifier: {
7908 IdentifierInfo *II = GetIdentifierInfo(F, Record, Idx);
7909 NNS = NestedNameSpecifier::Create(Context, Prev, II);
7910 break;
7911 }
7912
7913 case NestedNameSpecifier::Namespace: {
7914 NamespaceDecl *NS = ReadDeclAs<NamespaceDecl>(F, Record, Idx);
7915 NNS = NestedNameSpecifier::Create(Context, Prev, NS);
7916 break;
7917 }
7918
7919 case NestedNameSpecifier::NamespaceAlias: {
7920 NamespaceAliasDecl *Alias =ReadDeclAs<NamespaceAliasDecl>(F, Record, Idx);
7921 NNS = NestedNameSpecifier::Create(Context, Prev, Alias);
7922 break;
7923 }
7924
7925 case NestedNameSpecifier::TypeSpec:
7926 case NestedNameSpecifier::TypeSpecWithTemplate: {
7927 const Type *T = readType(F, Record, Idx).getTypePtrOrNull();
7928 if (!T)
Craig Toppera13603a2014-05-22 05:54:18 +00007929 return nullptr;
7930
Guy Benyei11169dd2012-12-18 14:30:41 +00007931 bool Template = Record[Idx++];
7932 NNS = NestedNameSpecifier::Create(Context, Prev, Template, T);
7933 break;
7934 }
7935
7936 case NestedNameSpecifier::Global: {
7937 NNS = NestedNameSpecifier::GlobalSpecifier(Context);
7938 // No associated value, and there can't be a prefix.
7939 break;
7940 }
Nikola Smiljanic67860242014-09-26 00:28:20 +00007941
7942 case NestedNameSpecifier::Super: {
7943 CXXRecordDecl *RD = ReadDeclAs<CXXRecordDecl>(F, Record, Idx);
7944 NNS = NestedNameSpecifier::SuperSpecifier(Context, RD);
7945 break;
7946 }
Guy Benyei11169dd2012-12-18 14:30:41 +00007947 }
7948 Prev = NNS;
7949 }
7950 return NNS;
7951}
7952
7953NestedNameSpecifierLoc
7954ASTReader::ReadNestedNameSpecifierLoc(ModuleFile &F, const RecordData &Record,
7955 unsigned &Idx) {
7956 unsigned N = Record[Idx++];
7957 NestedNameSpecifierLocBuilder Builder;
7958 for (unsigned I = 0; I != N; ++I) {
7959 NestedNameSpecifier::SpecifierKind Kind
7960 = (NestedNameSpecifier::SpecifierKind)Record[Idx++];
7961 switch (Kind) {
7962 case NestedNameSpecifier::Identifier: {
7963 IdentifierInfo *II = GetIdentifierInfo(F, Record, Idx);
7964 SourceRange Range = ReadSourceRange(F, Record, Idx);
7965 Builder.Extend(Context, II, Range.getBegin(), Range.getEnd());
7966 break;
7967 }
7968
7969 case NestedNameSpecifier::Namespace: {
7970 NamespaceDecl *NS = ReadDeclAs<NamespaceDecl>(F, Record, Idx);
7971 SourceRange Range = ReadSourceRange(F, Record, Idx);
7972 Builder.Extend(Context, NS, Range.getBegin(), Range.getEnd());
7973 break;
7974 }
7975
7976 case NestedNameSpecifier::NamespaceAlias: {
7977 NamespaceAliasDecl *Alias =ReadDeclAs<NamespaceAliasDecl>(F, Record, Idx);
7978 SourceRange Range = ReadSourceRange(F, Record, Idx);
7979 Builder.Extend(Context, Alias, Range.getBegin(), Range.getEnd());
7980 break;
7981 }
7982
7983 case NestedNameSpecifier::TypeSpec:
7984 case NestedNameSpecifier::TypeSpecWithTemplate: {
7985 bool Template = Record[Idx++];
7986 TypeSourceInfo *T = GetTypeSourceInfo(F, Record, Idx);
7987 if (!T)
7988 return NestedNameSpecifierLoc();
7989 SourceLocation ColonColonLoc = ReadSourceLocation(F, Record, Idx);
7990
7991 // FIXME: 'template' keyword location not saved anywhere, so we fake it.
7992 Builder.Extend(Context,
7993 Template? T->getTypeLoc().getBeginLoc() : SourceLocation(),
7994 T->getTypeLoc(), ColonColonLoc);
7995 break;
7996 }
7997
7998 case NestedNameSpecifier::Global: {
7999 SourceLocation ColonColonLoc = ReadSourceLocation(F, Record, Idx);
8000 Builder.MakeGlobal(Context, ColonColonLoc);
8001 break;
8002 }
Nikola Smiljanic67860242014-09-26 00:28:20 +00008003
8004 case NestedNameSpecifier::Super: {
8005 CXXRecordDecl *RD = ReadDeclAs<CXXRecordDecl>(F, Record, Idx);
8006 SourceRange Range = ReadSourceRange(F, Record, Idx);
8007 Builder.MakeSuper(Context, RD, Range.getBegin(), Range.getEnd());
8008 break;
8009 }
Guy Benyei11169dd2012-12-18 14:30:41 +00008010 }
8011 }
Nikola Smiljanic67860242014-09-26 00:28:20 +00008012
Guy Benyei11169dd2012-12-18 14:30:41 +00008013 return Builder.getWithLocInContext(Context);
8014}
8015
8016SourceRange
8017ASTReader::ReadSourceRange(ModuleFile &F, const RecordData &Record,
8018 unsigned &Idx) {
8019 SourceLocation beg = ReadSourceLocation(F, Record, Idx);
8020 SourceLocation end = ReadSourceLocation(F, Record, Idx);
8021 return SourceRange(beg, end);
8022}
8023
8024/// \brief Read an integral value
8025llvm::APInt ASTReader::ReadAPInt(const RecordData &Record, unsigned &Idx) {
8026 unsigned BitWidth = Record[Idx++];
8027 unsigned NumWords = llvm::APInt::getNumWords(BitWidth);
8028 llvm::APInt Result(BitWidth, NumWords, &Record[Idx]);
8029 Idx += NumWords;
8030 return Result;
8031}
8032
8033/// \brief Read a signed integral value
8034llvm::APSInt ASTReader::ReadAPSInt(const RecordData &Record, unsigned &Idx) {
8035 bool isUnsigned = Record[Idx++];
8036 return llvm::APSInt(ReadAPInt(Record, Idx), isUnsigned);
8037}
8038
8039/// \brief Read a floating-point value
Tim Northover178723a2013-01-22 09:46:51 +00008040llvm::APFloat ASTReader::ReadAPFloat(const RecordData &Record,
8041 const llvm::fltSemantics &Sem,
8042 unsigned &Idx) {
8043 return llvm::APFloat(Sem, ReadAPInt(Record, Idx));
Guy Benyei11169dd2012-12-18 14:30:41 +00008044}
8045
8046// \brief Read a string
8047std::string ASTReader::ReadString(const RecordData &Record, unsigned &Idx) {
8048 unsigned Len = Record[Idx++];
8049 std::string Result(Record.data() + Idx, Record.data() + Idx + Len);
8050 Idx += Len;
8051 return Result;
8052}
8053
8054VersionTuple ASTReader::ReadVersionTuple(const RecordData &Record,
8055 unsigned &Idx) {
8056 unsigned Major = Record[Idx++];
8057 unsigned Minor = Record[Idx++];
8058 unsigned Subminor = Record[Idx++];
8059 if (Minor == 0)
8060 return VersionTuple(Major);
8061 if (Subminor == 0)
8062 return VersionTuple(Major, Minor - 1);
8063 return VersionTuple(Major, Minor - 1, Subminor - 1);
8064}
8065
8066CXXTemporary *ASTReader::ReadCXXTemporary(ModuleFile &F,
8067 const RecordData &Record,
8068 unsigned &Idx) {
8069 CXXDestructorDecl *Decl = ReadDeclAs<CXXDestructorDecl>(F, Record, Idx);
8070 return CXXTemporary::Create(Context, Decl);
8071}
8072
8073DiagnosticBuilder ASTReader::Diag(unsigned DiagID) {
Argyrios Kyrtzidisdc9fdaf2013-05-24 05:44:08 +00008074 return Diag(CurrentImportLoc, DiagID);
Guy Benyei11169dd2012-12-18 14:30:41 +00008075}
8076
8077DiagnosticBuilder ASTReader::Diag(SourceLocation Loc, unsigned DiagID) {
8078 return Diags.Report(Loc, DiagID);
8079}
8080
8081/// \brief Retrieve the identifier table associated with the
8082/// preprocessor.
8083IdentifierTable &ASTReader::getIdentifierTable() {
8084 return PP.getIdentifierTable();
8085}
8086
8087/// \brief Record that the given ID maps to the given switch-case
8088/// statement.
8089void ASTReader::RecordSwitchCaseID(SwitchCase *SC, unsigned ID) {
Craig Toppera13603a2014-05-22 05:54:18 +00008090 assert((*CurrSwitchCaseStmts)[ID] == nullptr &&
Guy Benyei11169dd2012-12-18 14:30:41 +00008091 "Already have a SwitchCase with this ID");
8092 (*CurrSwitchCaseStmts)[ID] = SC;
8093}
8094
8095/// \brief Retrieve the switch-case statement with the given ID.
8096SwitchCase *ASTReader::getSwitchCaseWithID(unsigned ID) {
Craig Toppera13603a2014-05-22 05:54:18 +00008097 assert((*CurrSwitchCaseStmts)[ID] != nullptr && "No SwitchCase with this ID");
Guy Benyei11169dd2012-12-18 14:30:41 +00008098 return (*CurrSwitchCaseStmts)[ID];
8099}
8100
8101void ASTReader::ClearSwitchCaseIDs() {
8102 CurrSwitchCaseStmts->clear();
8103}
8104
8105void ASTReader::ReadComments() {
8106 std::vector<RawComment *> Comments;
Chris Lattner7fb3bef2013-01-20 00:56:42 +00008107 for (SmallVectorImpl<std::pair<BitstreamCursor,
Guy Benyei11169dd2012-12-18 14:30:41 +00008108 serialization::ModuleFile *> >::iterator
8109 I = CommentsCursors.begin(),
8110 E = CommentsCursors.end();
8111 I != E; ++I) {
Dmitri Gribenko9ee0e302014-03-27 15:40:39 +00008112 Comments.clear();
Chris Lattner7fb3bef2013-01-20 00:56:42 +00008113 BitstreamCursor &Cursor = I->first;
Guy Benyei11169dd2012-12-18 14:30:41 +00008114 serialization::ModuleFile &F = *I->second;
8115 SavedStreamPosition SavedPosition(Cursor);
8116
8117 RecordData Record;
8118 while (true) {
Chris Lattner7fb3bef2013-01-20 00:56:42 +00008119 llvm::BitstreamEntry Entry =
8120 Cursor.advanceSkippingSubblocks(BitstreamCursor::AF_DontPopBlockAtEnd);
Dmitri Gribenko9ee0e302014-03-27 15:40:39 +00008121
Chris Lattner7fb3bef2013-01-20 00:56:42 +00008122 switch (Entry.Kind) {
8123 case llvm::BitstreamEntry::SubBlock: // Handled for us already.
8124 case llvm::BitstreamEntry::Error:
8125 Error("malformed block record in AST file");
8126 return;
8127 case llvm::BitstreamEntry::EndBlock:
8128 goto NextCursor;
8129 case llvm::BitstreamEntry::Record:
8130 // The interesting case.
Guy Benyei11169dd2012-12-18 14:30:41 +00008131 break;
Guy Benyei11169dd2012-12-18 14:30:41 +00008132 }
8133
8134 // Read a record.
8135 Record.clear();
Chris Lattner0e6c9402013-01-20 02:38:54 +00008136 switch ((CommentRecordTypes)Cursor.readRecord(Entry.ID, Record)) {
Guy Benyei11169dd2012-12-18 14:30:41 +00008137 case COMMENTS_RAW_COMMENT: {
8138 unsigned Idx = 0;
8139 SourceRange SR = ReadSourceRange(F, Record, Idx);
8140 RawComment::CommentKind Kind =
8141 (RawComment::CommentKind) Record[Idx++];
8142 bool IsTrailingComment = Record[Idx++];
8143 bool IsAlmostTrailingComment = Record[Idx++];
Dmitri Gribenkoa7d16ce2013-04-10 15:35:17 +00008144 Comments.push_back(new (Context) RawComment(
8145 SR, Kind, IsTrailingComment, IsAlmostTrailingComment,
8146 Context.getLangOpts().CommentOpts.ParseAllComments));
Guy Benyei11169dd2012-12-18 14:30:41 +00008147 break;
8148 }
8149 }
8150 }
Dmitri Gribenko9ee0e302014-03-27 15:40:39 +00008151 NextCursor:
8152 Context.Comments.addDeserializedComments(Comments);
Guy Benyei11169dd2012-12-18 14:30:41 +00008153 }
Guy Benyei11169dd2012-12-18 14:30:41 +00008154}
8155
Argyrios Kyrtzidis1bde1172014-11-18 05:24:18 +00008156void ASTReader::getInputFiles(ModuleFile &F,
8157 SmallVectorImpl<serialization::InputFile> &Files) {
8158 for (unsigned I = 0, E = F.InputFilesLoaded.size(); I != E; ++I) {
8159 unsigned ID = I+1;
8160 Files.push_back(getInputFile(F, ID));
8161 }
8162}
8163
Richard Smithcd45dbc2014-04-19 03:48:30 +00008164std::string ASTReader::getOwningModuleNameForDiagnostic(const Decl *D) {
8165 // If we know the owning module, use it.
8166 if (Module *M = D->getOwningModule())
8167 return M->getFullModuleName();
8168
8169 // Otherwise, use the name of the top-level module the decl is within.
8170 if (ModuleFile *M = getOwningModuleFile(D))
8171 return M->ModuleName;
8172
8173 // Not from a module.
8174 return "";
8175}
8176
Guy Benyei11169dd2012-12-18 14:30:41 +00008177void ASTReader::finishPendingActions() {
Richard Smith851072e2014-05-19 20:59:20 +00008178 while (!PendingIdentifierInfos.empty() ||
8179 !PendingIncompleteDeclChains.empty() || !PendingDeclChains.empty() ||
Richard Smith2b9e3e32013-10-18 06:05:18 +00008180 !PendingMacroIDs.empty() || !PendingDeclContextInfos.empty() ||
Richard Smitha0ce9c42014-07-29 23:23:27 +00008181 !PendingUpdateRecords.empty()) {
Guy Benyei11169dd2012-12-18 14:30:41 +00008182 // If any identifiers with corresponding top-level declarations have
8183 // been loaded, load those declarations now.
Craig Topper79be4cd2013-07-05 04:33:53 +00008184 typedef llvm::DenseMap<IdentifierInfo *, SmallVector<Decl *, 2> >
8185 TopLevelDeclsMap;
8186 TopLevelDeclsMap TopLevelDecls;
8187
Guy Benyei11169dd2012-12-18 14:30:41 +00008188 while (!PendingIdentifierInfos.empty()) {
Douglas Gregor6168bd22013-02-18 15:53:43 +00008189 IdentifierInfo *II = PendingIdentifierInfos.back().first;
Richard Smithf0ae3c2d2014-03-28 17:31:23 +00008190 SmallVector<uint32_t, 4> DeclIDs =
8191 std::move(PendingIdentifierInfos.back().second);
Douglas Gregorcb15f082013-02-19 18:26:28 +00008192 PendingIdentifierInfos.pop_back();
Douglas Gregor6168bd22013-02-18 15:53:43 +00008193
8194 SetGloballyVisibleDecls(II, DeclIDs, &TopLevelDecls[II]);
Guy Benyei11169dd2012-12-18 14:30:41 +00008195 }
Richard Smithf0ae3c2d2014-03-28 17:31:23 +00008196
Richard Smith851072e2014-05-19 20:59:20 +00008197 // For each decl chain that we wanted to complete while deserializing, mark
8198 // it as "still needs to be completed".
8199 for (unsigned I = 0; I != PendingIncompleteDeclChains.size(); ++I) {
8200 markIncompleteDeclChain(PendingIncompleteDeclChains[I]);
8201 }
8202 PendingIncompleteDeclChains.clear();
8203
Guy Benyei11169dd2012-12-18 14:30:41 +00008204 // Load pending declaration chains.
8205 for (unsigned I = 0; I != PendingDeclChains.size(); ++I) {
8206 loadPendingDeclChain(PendingDeclChains[I]);
8207 PendingDeclChainsKnown.erase(PendingDeclChains[I]);
8208 }
8209 PendingDeclChains.clear();
8210
Douglas Gregor6168bd22013-02-18 15:53:43 +00008211 // Make the most recent of the top-level declarations visible.
Craig Topper79be4cd2013-07-05 04:33:53 +00008212 for (TopLevelDeclsMap::iterator TLD = TopLevelDecls.begin(),
8213 TLDEnd = TopLevelDecls.end(); TLD != TLDEnd; ++TLD) {
Douglas Gregor6168bd22013-02-18 15:53:43 +00008214 IdentifierInfo *II = TLD->first;
8215 for (unsigned I = 0, N = TLD->second.size(); I != N; ++I) {
Argyrios Kyrtzidise5edbf92013-04-26 21:33:35 +00008216 pushExternalDeclIntoScope(cast<NamedDecl>(TLD->second[I]), II);
Douglas Gregor6168bd22013-02-18 15:53:43 +00008217 }
8218 }
8219
Guy Benyei11169dd2012-12-18 14:30:41 +00008220 // Load any pending macro definitions.
8221 for (unsigned I = 0; I != PendingMacroIDs.size(); ++I) {
Argyrios Kyrtzidiseb663da2013-03-22 21:12:57 +00008222 IdentifierInfo *II = PendingMacroIDs.begin()[I].first;
8223 SmallVector<PendingMacroInfo, 2> GlobalIDs;
8224 GlobalIDs.swap(PendingMacroIDs.begin()[I].second);
8225 // Initialize the macro history from chained-PCHs ahead of module imports.
Richard Smith49f906a2014-03-01 00:08:04 +00008226 for (unsigned IDIdx = 0, NumIDs = GlobalIDs.size(); IDIdx != NumIDs;
Argyrios Kyrtzidis719736c2013-01-19 03:14:56 +00008227 ++IDIdx) {
Argyrios Kyrtzidiseb663da2013-03-22 21:12:57 +00008228 const PendingMacroInfo &Info = GlobalIDs[IDIdx];
Richard Smithe842a472014-10-22 02:05:46 +00008229 if (Info.M->Kind != MK_ImplicitModule &&
8230 Info.M->Kind != MK_ExplicitModule)
Argyrios Kyrtzidiseb663da2013-03-22 21:12:57 +00008231 resolvePendingMacro(II, Info);
8232 }
8233 // Handle module imports.
Richard Smith49f906a2014-03-01 00:08:04 +00008234 for (unsigned IDIdx = 0, NumIDs = GlobalIDs.size(); IDIdx != NumIDs;
Argyrios Kyrtzidiseb663da2013-03-22 21:12:57 +00008235 ++IDIdx) {
8236 const PendingMacroInfo &Info = GlobalIDs[IDIdx];
Richard Smithe842a472014-10-22 02:05:46 +00008237 if (Info.M->Kind == MK_ImplicitModule ||
8238 Info.M->Kind == MK_ExplicitModule)
Argyrios Kyrtzidiseb663da2013-03-22 21:12:57 +00008239 resolvePendingMacro(II, Info);
Guy Benyei11169dd2012-12-18 14:30:41 +00008240 }
8241 }
8242 PendingMacroIDs.clear();
Argyrios Kyrtzidis83a6e3b2013-02-16 00:48:59 +00008243
8244 // Wire up the DeclContexts for Decls that we delayed setting until
8245 // recursive loading is completed.
8246 while (!PendingDeclContextInfos.empty()) {
8247 PendingDeclContextInfo Info = PendingDeclContextInfos.front();
8248 PendingDeclContextInfos.pop_front();
8249 DeclContext *SemaDC = cast<DeclContext>(GetDecl(Info.SemaDC));
8250 DeclContext *LexicalDC = cast<DeclContext>(GetDecl(Info.LexicalDC));
8251 Info.D->setDeclContextsImpl(SemaDC, LexicalDC, getContext());
8252 }
Richard Smith2b9e3e32013-10-18 06:05:18 +00008253
Richard Smithd1c46742014-04-30 02:24:17 +00008254 // Perform any pending declaration updates.
Richard Smithd6db68c2014-08-07 20:58:41 +00008255 while (!PendingUpdateRecords.empty()) {
Richard Smithd1c46742014-04-30 02:24:17 +00008256 auto Update = PendingUpdateRecords.pop_back_val();
8257 ReadingKindTracker ReadingKind(Read_Decl, *this);
8258 loadDeclUpdateRecords(Update.first, Update.second);
8259 }
Guy Benyei11169dd2012-12-18 14:30:41 +00008260 }
8261
8262 // If we deserialized any C++ or Objective-C class definitions, any
8263 // Objective-C protocol definitions, or any redeclarable templates, make sure
8264 // that all redeclarations point to the definitions. Note that this can only
8265 // happen now, after the redeclaration chains have been fully wired.
Craig Topperc6914d02014-08-25 04:15:02 +00008266 for (Decl *D : PendingDefinitions) {
8267 if (TagDecl *TD = dyn_cast<TagDecl>(D)) {
Richard Smith5b21db82014-04-23 18:20:42 +00008268 if (const TagType *TagT = dyn_cast<TagType>(TD->getTypeForDecl())) {
Guy Benyei11169dd2012-12-18 14:30:41 +00008269 // Make sure that the TagType points at the definition.
8270 const_cast<TagType*>(TagT)->decl = TD;
8271 }
8272
Craig Topperc6914d02014-08-25 04:15:02 +00008273 if (auto RD = dyn_cast<CXXRecordDecl>(D)) {
Richard Smith2c381642014-08-27 23:11:59 +00008274 for (auto R : RD->redecls()) {
8275 assert((R == D) == R->isThisDeclarationADefinition() &&
8276 "declaration thinks it's the definition but it isn't");
Aaron Ballman86c93902014-03-06 23:45:36 +00008277 cast<CXXRecordDecl>(R)->DefinitionData = RD->DefinitionData;
Richard Smith2c381642014-08-27 23:11:59 +00008278 }
Guy Benyei11169dd2012-12-18 14:30:41 +00008279 }
8280
8281 continue;
8282 }
8283
Craig Topperc6914d02014-08-25 04:15:02 +00008284 if (auto ID = dyn_cast<ObjCInterfaceDecl>(D)) {
Guy Benyei11169dd2012-12-18 14:30:41 +00008285 // Make sure that the ObjCInterfaceType points at the definition.
8286 const_cast<ObjCInterfaceType *>(cast<ObjCInterfaceType>(ID->TypeForDecl))
8287 ->Decl = ID;
8288
Aaron Ballman86c93902014-03-06 23:45:36 +00008289 for (auto R : ID->redecls())
Guy Benyei11169dd2012-12-18 14:30:41 +00008290 R->Data = ID->Data;
8291
8292 continue;
8293 }
8294
Craig Topperc6914d02014-08-25 04:15:02 +00008295 if (auto PD = dyn_cast<ObjCProtocolDecl>(D)) {
Aaron Ballman86c93902014-03-06 23:45:36 +00008296 for (auto R : PD->redecls())
Guy Benyei11169dd2012-12-18 14:30:41 +00008297 R->Data = PD->Data;
8298
8299 continue;
8300 }
8301
Craig Topperc6914d02014-08-25 04:15:02 +00008302 auto RTD = cast<RedeclarableTemplateDecl>(D)->getCanonicalDecl();
Aaron Ballman86c93902014-03-06 23:45:36 +00008303 for (auto R : RTD->redecls())
Guy Benyei11169dd2012-12-18 14:30:41 +00008304 R->Common = RTD->Common;
8305 }
8306 PendingDefinitions.clear();
8307
8308 // Load the bodies of any functions or methods we've encountered. We do
8309 // this now (delayed) so that we can be sure that the declaration chains
8310 // have been fully wired up.
8311 for (PendingBodiesMap::iterator PB = PendingBodies.begin(),
8312 PBEnd = PendingBodies.end();
8313 PB != PBEnd; ++PB) {
8314 if (FunctionDecl *FD = dyn_cast<FunctionDecl>(PB->first)) {
8315 // FIXME: Check for =delete/=default?
8316 // FIXME: Complain about ODR violations here?
8317 if (!getContext().getLangOpts().Modules || !FD->hasBody())
8318 FD->setLazyBody(PB->second);
8319 continue;
8320 }
8321
8322 ObjCMethodDecl *MD = cast<ObjCMethodDecl>(PB->first);
8323 if (!getContext().getLangOpts().Modules || !MD->hasBody())
8324 MD->setLazyBody(PB->second);
8325 }
8326 PendingBodies.clear();
Richard Smitha0ce9c42014-07-29 23:23:27 +00008327}
8328
8329void ASTReader::diagnoseOdrViolations() {
Richard Smithbb853c72014-08-13 01:23:33 +00008330 if (PendingOdrMergeFailures.empty() && PendingOdrMergeChecks.empty())
8331 return;
8332
Richard Smitha0ce9c42014-07-29 23:23:27 +00008333 // Trigger the import of the full definition of each class that had any
8334 // odr-merging problems, so we can produce better diagnostics for them.
Richard Smithbb853c72014-08-13 01:23:33 +00008335 // These updates may in turn find and diagnose some ODR failures, so take
8336 // ownership of the set first.
8337 auto OdrMergeFailures = std::move(PendingOdrMergeFailures);
8338 PendingOdrMergeFailures.clear();
8339 for (auto &Merge : OdrMergeFailures) {
Richard Smitha0ce9c42014-07-29 23:23:27 +00008340 Merge.first->buildLookup();
8341 Merge.first->decls_begin();
8342 Merge.first->bases_begin();
8343 Merge.first->vbases_begin();
8344 for (auto *RD : Merge.second) {
8345 RD->decls_begin();
8346 RD->bases_begin();
8347 RD->vbases_begin();
8348 }
8349 }
8350
8351 // For each declaration from a merged context, check that the canonical
8352 // definition of that context also contains a declaration of the same
8353 // entity.
8354 //
8355 // Caution: this loop does things that might invalidate iterators into
8356 // PendingOdrMergeChecks. Don't turn this into a range-based for loop!
8357 while (!PendingOdrMergeChecks.empty()) {
8358 NamedDecl *D = PendingOdrMergeChecks.pop_back_val();
8359
8360 // FIXME: Skip over implicit declarations for now. This matters for things
8361 // like implicitly-declared special member functions. This isn't entirely
8362 // correct; we can end up with multiple unmerged declarations of the same
8363 // implicit entity.
8364 if (D->isImplicit())
8365 continue;
8366
8367 DeclContext *CanonDef = D->getDeclContext();
Richard Smitha0ce9c42014-07-29 23:23:27 +00008368
8369 bool Found = false;
8370 const Decl *DCanon = D->getCanonicalDecl();
8371
Richard Smith01bdb7a2014-08-28 05:44:07 +00008372 for (auto RI : D->redecls()) {
8373 if (RI->getLexicalDeclContext() == CanonDef) {
8374 Found = true;
8375 break;
8376 }
8377 }
8378 if (Found)
8379 continue;
8380
Richard Smitha0ce9c42014-07-29 23:23:27 +00008381 llvm::SmallVector<const NamedDecl*, 4> Candidates;
Richard Smith01bdb7a2014-08-28 05:44:07 +00008382 DeclContext::lookup_result R = CanonDef->lookup(D->getDeclName());
Richard Smitha0ce9c42014-07-29 23:23:27 +00008383 for (DeclContext::lookup_iterator I = R.begin(), E = R.end();
8384 !Found && I != E; ++I) {
8385 for (auto RI : (*I)->redecls()) {
8386 if (RI->getLexicalDeclContext() == CanonDef) {
8387 // This declaration is present in the canonical definition. If it's
8388 // in the same redecl chain, it's the one we're looking for.
8389 if (RI->getCanonicalDecl() == DCanon)
8390 Found = true;
8391 else
8392 Candidates.push_back(cast<NamedDecl>(RI));
8393 break;
8394 }
8395 }
8396 }
8397
8398 if (!Found) {
Richard Smithd08aeb62014-08-28 01:33:39 +00008399 // The AST doesn't like TagDecls becoming invalid after they've been
8400 // completed. We only really need to mark FieldDecls as invalid here.
8401 if (!isa<TagDecl>(D))
8402 D->setInvalidDecl();
Richard Smitha0ce9c42014-07-29 23:23:27 +00008403
8404 std::string CanonDefModule =
8405 getOwningModuleNameForDiagnostic(cast<Decl>(CanonDef));
8406 Diag(D->getLocation(), diag::err_module_odr_violation_missing_decl)
8407 << D << getOwningModuleNameForDiagnostic(D)
8408 << CanonDef << CanonDefModule.empty() << CanonDefModule;
8409
8410 if (Candidates.empty())
8411 Diag(cast<Decl>(CanonDef)->getLocation(),
8412 diag::note_module_odr_violation_no_possible_decls) << D;
8413 else {
8414 for (unsigned I = 0, N = Candidates.size(); I != N; ++I)
8415 Diag(Candidates[I]->getLocation(),
8416 diag::note_module_odr_violation_possible_decl)
8417 << Candidates[I];
8418 }
8419
8420 DiagnosedOdrMergeFailures.insert(CanonDef);
8421 }
8422 }
Richard Smithcd45dbc2014-04-19 03:48:30 +00008423
8424 // Issue any pending ODR-failure diagnostics.
Richard Smithbb853c72014-08-13 01:23:33 +00008425 for (auto &Merge : OdrMergeFailures) {
Richard Smitha0ce9c42014-07-29 23:23:27 +00008426 // If we've already pointed out a specific problem with this class, don't
8427 // bother issuing a general "something's different" diagnostic.
David Blaikie82e95a32014-11-19 07:49:47 +00008428 if (!DiagnosedOdrMergeFailures.insert(Merge.first).second)
Richard Smithcd45dbc2014-04-19 03:48:30 +00008429 continue;
8430
8431 bool Diagnosed = false;
8432 for (auto *RD : Merge.second) {
8433 // Multiple different declarations got merged together; tell the user
8434 // where they came from.
8435 if (Merge.first != RD) {
8436 // FIXME: Walk the definition, figure out what's different,
8437 // and diagnose that.
8438 if (!Diagnosed) {
8439 std::string Module = getOwningModuleNameForDiagnostic(Merge.first);
8440 Diag(Merge.first->getLocation(),
8441 diag::err_module_odr_violation_different_definitions)
8442 << Merge.first << Module.empty() << Module;
8443 Diagnosed = true;
8444 }
8445
8446 Diag(RD->getLocation(),
8447 diag::note_module_odr_violation_different_definitions)
8448 << getOwningModuleNameForDiagnostic(RD);
8449 }
8450 }
8451
8452 if (!Diagnosed) {
8453 // All definitions are updates to the same declaration. This happens if a
8454 // module instantiates the declaration of a class template specialization
8455 // and two or more other modules instantiate its definition.
8456 //
8457 // FIXME: Indicate which modules had instantiations of this definition.
8458 // FIXME: How can this even happen?
8459 Diag(Merge.first->getLocation(),
8460 diag::err_module_odr_violation_different_instantiations)
8461 << Merge.first;
8462 }
8463 }
Guy Benyei11169dd2012-12-18 14:30:41 +00008464}
8465
8466void ASTReader::FinishedDeserializing() {
8467 assert(NumCurrentElementsDeserializing &&
8468 "FinishedDeserializing not paired with StartedDeserializing");
8469 if (NumCurrentElementsDeserializing == 1) {
8470 // We decrease NumCurrentElementsDeserializing only after pending actions
8471 // are finished, to avoid recursively re-calling finishPendingActions().
8472 finishPendingActions();
8473 }
8474 --NumCurrentElementsDeserializing;
8475
Richard Smitha0ce9c42014-07-29 23:23:27 +00008476 if (NumCurrentElementsDeserializing == 0) {
8477 diagnoseOdrViolations();
8478
Richard Smith04d05b52014-03-23 00:27:18 +00008479 // We are not in recursive loading, so it's safe to pass the "interesting"
8480 // decls to the consumer.
Richard Smitha0ce9c42014-07-29 23:23:27 +00008481 if (Consumer)
8482 PassInterestingDeclsToConsumer();
Guy Benyei11169dd2012-12-18 14:30:41 +00008483 }
8484}
8485
Argyrios Kyrtzidise5edbf92013-04-26 21:33:35 +00008486void ASTReader::pushExternalDeclIntoScope(NamedDecl *D, DeclarationName Name) {
Rafael Espindola7b56f6c2013-10-19 16:55:03 +00008487 D = D->getMostRecentDecl();
Argyrios Kyrtzidise5edbf92013-04-26 21:33:35 +00008488
8489 if (SemaObj->IdResolver.tryAddTopLevelDecl(D, Name) && SemaObj->TUScope) {
8490 SemaObj->TUScope->AddDecl(D);
8491 } else if (SemaObj->TUScope) {
8492 // Adding the decl to IdResolver may have failed because it was already in
8493 // (even though it was not added in scope). If it is already in, make sure
8494 // it gets in the scope as well.
8495 if (std::find(SemaObj->IdResolver.begin(Name),
8496 SemaObj->IdResolver.end(), D) != SemaObj->IdResolver.end())
8497 SemaObj->TUScope->AddDecl(D);
8498 }
8499}
8500
Nico Weber824285e2014-05-08 04:26:47 +00008501ASTReader::ASTReader(Preprocessor &PP, ASTContext &Context, StringRef isysroot,
8502 bool DisableValidation, bool AllowASTWithCompilerErrors,
8503 bool AllowConfigurationMismatch, bool ValidateSystemInputs,
Ben Langmuir2cb4a782014-02-05 22:21:15 +00008504 bool UseGlobalIndex)
Craig Toppera13603a2014-05-22 05:54:18 +00008505 : Listener(new PCHValidator(PP, *this)), DeserializationListener(nullptr),
Nico Weber824285e2014-05-08 04:26:47 +00008506 OwnsDeserializationListener(false), SourceMgr(PP.getSourceManager()),
Craig Toppera13603a2014-05-22 05:54:18 +00008507 FileMgr(PP.getFileManager()), Diags(PP.getDiagnostics()),
8508 SemaObj(nullptr), PP(PP), Context(Context), Consumer(nullptr),
8509 ModuleMgr(PP.getFileManager()), isysroot(isysroot),
8510 DisableValidation(DisableValidation),
Nico Weber824285e2014-05-08 04:26:47 +00008511 AllowASTWithCompilerErrors(AllowASTWithCompilerErrors),
8512 AllowConfigurationMismatch(AllowConfigurationMismatch),
8513 ValidateSystemInputs(ValidateSystemInputs),
8514 UseGlobalIndex(UseGlobalIndex), TriedLoadingGlobalIndex(false),
Richard Smith053f6c62014-05-16 23:01:30 +00008515 CurrSwitchCaseStmts(&SwitchCaseStmts),
Nico Weber824285e2014-05-08 04:26:47 +00008516 NumSLocEntriesRead(0), TotalNumSLocEntries(0), NumStatementsRead(0),
8517 TotalNumStatements(0), NumMacrosRead(0), TotalNumMacros(0),
8518 NumIdentifierLookups(0), NumIdentifierLookupHits(0), NumSelectorsRead(0),
8519 NumMethodPoolEntriesRead(0), NumMethodPoolLookups(0),
8520 NumMethodPoolHits(0), NumMethodPoolTableLookups(0),
8521 NumMethodPoolTableHits(0), TotalNumMethodPoolEntries(0),
8522 NumLexicalDeclContextsRead(0), TotalLexicalDeclContexts(0),
8523 NumVisibleDeclContextsRead(0), TotalVisibleDeclContexts(0),
8524 TotalModulesSizeInBits(0), NumCurrentElementsDeserializing(0),
8525 PassingDeclsToConsumer(false), NumCXXBaseSpecifiersLoaded(0),
8526 ReadingKind(Read_None) {
Guy Benyei11169dd2012-12-18 14:30:41 +00008527 SourceMgr.setExternalSLocEntrySource(this);
8528}
8529
8530ASTReader::~ASTReader() {
Nico Weber824285e2014-05-08 04:26:47 +00008531 if (OwnsDeserializationListener)
8532 delete DeserializationListener;
8533
Guy Benyei11169dd2012-12-18 14:30:41 +00008534 for (DeclContextVisibleUpdatesPending::iterator
8535 I = PendingVisibleUpdates.begin(),
8536 E = PendingVisibleUpdates.end();
8537 I != E; ++I) {
8538 for (DeclContextVisibleUpdates::iterator J = I->second.begin(),
8539 F = I->second.end();
8540 J != F; ++J)
8541 delete J->first;
8542 }
8543}