blob: dd73bbae3784a2f9a91bfe88f6f745f93a943b2d [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"
Adrian Prantl8bf7af32015-02-25 01:31:45 +000049#include "llvm/Object/COFF.h"
50#include "llvm/Object/ObjectFile.h"
Guy Benyei11169dd2012-12-18 14:30:41 +000051#include "llvm/Support/ErrorHandling.h"
52#include "llvm/Support/FileSystem.h"
53#include "llvm/Support/MemoryBuffer.h"
54#include "llvm/Support/Path.h"
55#include "llvm/Support/SaveAndRestore.h"
Dmitri Gribenkof430da42014-02-12 10:33:14 +000056#include "llvm/Support/raw_ostream.h"
Guy Benyei11169dd2012-12-18 14:30:41 +000057#include <algorithm>
Chris Lattner91f373e2013-01-20 00:57:52 +000058#include <cstdio>
Guy Benyei11169dd2012-12-18 14:30:41 +000059#include <iterator>
Rafael Espindola8a8e5542014-06-12 17:19:42 +000060#include <system_error>
Guy Benyei11169dd2012-12-18 14:30:41 +000061
62using namespace clang;
63using namespace clang::serialization;
64using namespace clang::serialization::reader;
Chris Lattner7fb3bef2013-01-20 00:56:42 +000065using llvm::BitstreamCursor;
Guy Benyei11169dd2012-12-18 14:30:41 +000066
Ben Langmuircb69b572014-03-07 06:40:32 +000067
68//===----------------------------------------------------------------------===//
69// ChainedASTReaderListener implementation
70//===----------------------------------------------------------------------===//
71
72bool
73ChainedASTReaderListener::ReadFullVersionInformation(StringRef FullVersion) {
74 return First->ReadFullVersionInformation(FullVersion) ||
75 Second->ReadFullVersionInformation(FullVersion);
76}
Ben Langmuir4f5212a2014-04-14 22:12:44 +000077void ChainedASTReaderListener::ReadModuleName(StringRef ModuleName) {
78 First->ReadModuleName(ModuleName);
79 Second->ReadModuleName(ModuleName);
80}
81void ChainedASTReaderListener::ReadModuleMapFile(StringRef ModuleMapPath) {
82 First->ReadModuleMapFile(ModuleMapPath);
83 Second->ReadModuleMapFile(ModuleMapPath);
84}
Richard Smith1e2cf0d2014-10-31 02:28:58 +000085bool
86ChainedASTReaderListener::ReadLanguageOptions(const LangOptions &LangOpts,
87 bool Complain,
88 bool AllowCompatibleDifferences) {
89 return First->ReadLanguageOptions(LangOpts, Complain,
90 AllowCompatibleDifferences) ||
91 Second->ReadLanguageOptions(LangOpts, Complain,
92 AllowCompatibleDifferences);
Ben Langmuircb69b572014-03-07 06:40:32 +000093}
94bool
95ChainedASTReaderListener::ReadTargetOptions(const TargetOptions &TargetOpts,
96 bool Complain) {
97 return First->ReadTargetOptions(TargetOpts, Complain) ||
98 Second->ReadTargetOptions(TargetOpts, Complain);
99}
100bool ChainedASTReaderListener::ReadDiagnosticOptions(
Ben Langmuirb92de022014-04-29 16:25:26 +0000101 IntrusiveRefCntPtr<DiagnosticOptions> DiagOpts, bool Complain) {
Ben Langmuircb69b572014-03-07 06:40:32 +0000102 return First->ReadDiagnosticOptions(DiagOpts, Complain) ||
103 Second->ReadDiagnosticOptions(DiagOpts, Complain);
104}
105bool
106ChainedASTReaderListener::ReadFileSystemOptions(const FileSystemOptions &FSOpts,
107 bool Complain) {
108 return First->ReadFileSystemOptions(FSOpts, Complain) ||
109 Second->ReadFileSystemOptions(FSOpts, Complain);
110}
111
112bool ChainedASTReaderListener::ReadHeaderSearchOptions(
Argyrios Kyrtzidisbd0b6512015-02-19 20:12:20 +0000113 const HeaderSearchOptions &HSOpts, StringRef SpecificModuleCachePath,
114 bool Complain) {
115 return First->ReadHeaderSearchOptions(HSOpts, SpecificModuleCachePath,
116 Complain) ||
117 Second->ReadHeaderSearchOptions(HSOpts, SpecificModuleCachePath,
118 Complain);
Ben Langmuircb69b572014-03-07 06:40:32 +0000119}
120bool ChainedASTReaderListener::ReadPreprocessorOptions(
121 const PreprocessorOptions &PPOpts, bool Complain,
122 std::string &SuggestedPredefines) {
123 return First->ReadPreprocessorOptions(PPOpts, Complain,
124 SuggestedPredefines) ||
125 Second->ReadPreprocessorOptions(PPOpts, Complain, SuggestedPredefines);
126}
127void ChainedASTReaderListener::ReadCounter(const serialization::ModuleFile &M,
128 unsigned Value) {
129 First->ReadCounter(M, Value);
130 Second->ReadCounter(M, Value);
131}
132bool ChainedASTReaderListener::needsInputFileVisitation() {
133 return First->needsInputFileVisitation() ||
134 Second->needsInputFileVisitation();
135}
136bool ChainedASTReaderListener::needsSystemInputFileVisitation() {
137 return First->needsSystemInputFileVisitation() ||
138 Second->needsSystemInputFileVisitation();
139}
Argyrios Kyrtzidis6d0753d2014-03-14 03:07:38 +0000140void ChainedASTReaderListener::visitModuleFile(StringRef Filename) {
141 First->visitModuleFile(Filename);
142 Second->visitModuleFile(Filename);
143}
Ben Langmuircb69b572014-03-07 06:40:32 +0000144bool ChainedASTReaderListener::visitInputFile(StringRef Filename,
Argyrios Kyrtzidis68ccbe02014-03-14 02:26:31 +0000145 bool isSystem,
146 bool isOverridden) {
Justin Bognerc65a66d2014-05-22 06:04:59 +0000147 bool Continue = false;
148 if (First->needsInputFileVisitation() &&
149 (!isSystem || First->needsSystemInputFileVisitation()))
150 Continue |= First->visitInputFile(Filename, isSystem, isOverridden);
151 if (Second->needsInputFileVisitation() &&
152 (!isSystem || Second->needsSystemInputFileVisitation()))
153 Continue |= Second->visitInputFile(Filename, isSystem, isOverridden);
154 return Continue;
Ben Langmuircb69b572014-03-07 06:40:32 +0000155}
156
Guy Benyei11169dd2012-12-18 14:30:41 +0000157//===----------------------------------------------------------------------===//
158// PCH validator implementation
159//===----------------------------------------------------------------------===//
160
161ASTReaderListener::~ASTReaderListener() {}
162
163/// \brief Compare the given set of language options against an existing set of
164/// language options.
165///
166/// \param Diags If non-NULL, diagnostics will be emitted via this engine.
Richard Smith1e2cf0d2014-10-31 02:28:58 +0000167/// \param AllowCompatibleDifferences If true, differences between compatible
168/// language options will be permitted.
Guy Benyei11169dd2012-12-18 14:30:41 +0000169///
170/// \returns true if the languagae options mis-match, false otherwise.
171static bool checkLanguageOptions(const LangOptions &LangOpts,
172 const LangOptions &ExistingLangOpts,
Richard Smith1e2cf0d2014-10-31 02:28:58 +0000173 DiagnosticsEngine *Diags,
174 bool AllowCompatibleDifferences = true) {
Guy Benyei11169dd2012-12-18 14:30:41 +0000175#define LANGOPT(Name, Bits, Default, Description) \
176 if (ExistingLangOpts.Name != LangOpts.Name) { \
177 if (Diags) \
178 Diags->Report(diag::err_pch_langopt_mismatch) \
179 << Description << LangOpts.Name << ExistingLangOpts.Name; \
180 return true; \
181 }
182
183#define VALUE_LANGOPT(Name, Bits, Default, Description) \
184 if (ExistingLangOpts.Name != LangOpts.Name) { \
185 if (Diags) \
186 Diags->Report(diag::err_pch_langopt_value_mismatch) \
187 << Description; \
188 return true; \
189 }
190
191#define ENUM_LANGOPT(Name, Type, Bits, Default, Description) \
192 if (ExistingLangOpts.get##Name() != LangOpts.get##Name()) { \
193 if (Diags) \
194 Diags->Report(diag::err_pch_langopt_value_mismatch) \
195 << Description; \
196 return true; \
197 }
198
Richard Smith1e2cf0d2014-10-31 02:28:58 +0000199#define COMPATIBLE_LANGOPT(Name, Bits, Default, Description) \
200 if (!AllowCompatibleDifferences) \
201 LANGOPT(Name, Bits, Default, Description)
202
203#define COMPATIBLE_ENUM_LANGOPT(Name, Bits, Default, Description) \
204 if (!AllowCompatibleDifferences) \
205 ENUM_LANGOPT(Name, Bits, Default, Description)
206
Guy Benyei11169dd2012-12-18 14:30:41 +0000207#define BENIGN_LANGOPT(Name, Bits, Default, Description)
208#define BENIGN_ENUM_LANGOPT(Name, Type, Bits, Default, Description)
209#include "clang/Basic/LangOptions.def"
210
211 if (ExistingLangOpts.ObjCRuntime != LangOpts.ObjCRuntime) {
212 if (Diags)
213 Diags->Report(diag::err_pch_langopt_value_mismatch)
214 << "target Objective-C runtime";
215 return true;
216 }
217
Dmitri Gribenkoacf2e782013-02-22 14:21:27 +0000218 if (ExistingLangOpts.CommentOpts.BlockCommandNames !=
219 LangOpts.CommentOpts.BlockCommandNames) {
220 if (Diags)
221 Diags->Report(diag::err_pch_langopt_value_mismatch)
222 << "block command names";
223 return true;
224 }
225
Guy Benyei11169dd2012-12-18 14:30:41 +0000226 return false;
227}
228
229/// \brief Compare the given set of target options against an existing set of
230/// target options.
231///
232/// \param Diags If non-NULL, diagnostics will be emitted via this engine.
233///
234/// \returns true if the target options mis-match, false otherwise.
235static bool checkTargetOptions(const TargetOptions &TargetOpts,
236 const TargetOptions &ExistingTargetOpts,
237 DiagnosticsEngine *Diags) {
238#define CHECK_TARGET_OPT(Field, Name) \
239 if (TargetOpts.Field != ExistingTargetOpts.Field) { \
240 if (Diags) \
241 Diags->Report(diag::err_pch_targetopt_mismatch) \
242 << Name << TargetOpts.Field << ExistingTargetOpts.Field; \
243 return true; \
244 }
245
246 CHECK_TARGET_OPT(Triple, "target");
247 CHECK_TARGET_OPT(CPU, "target CPU");
248 CHECK_TARGET_OPT(ABI, "target ABI");
Guy Benyei11169dd2012-12-18 14:30:41 +0000249#undef CHECK_TARGET_OPT
250
251 // Compare feature sets.
252 SmallVector<StringRef, 4> ExistingFeatures(
253 ExistingTargetOpts.FeaturesAsWritten.begin(),
254 ExistingTargetOpts.FeaturesAsWritten.end());
255 SmallVector<StringRef, 4> ReadFeatures(TargetOpts.FeaturesAsWritten.begin(),
256 TargetOpts.FeaturesAsWritten.end());
257 std::sort(ExistingFeatures.begin(), ExistingFeatures.end());
258 std::sort(ReadFeatures.begin(), ReadFeatures.end());
259
260 unsigned ExistingIdx = 0, ExistingN = ExistingFeatures.size();
261 unsigned ReadIdx = 0, ReadN = ReadFeatures.size();
262 while (ExistingIdx < ExistingN && ReadIdx < ReadN) {
263 if (ExistingFeatures[ExistingIdx] == ReadFeatures[ReadIdx]) {
264 ++ExistingIdx;
265 ++ReadIdx;
266 continue;
267 }
268
269 if (ReadFeatures[ReadIdx] < ExistingFeatures[ExistingIdx]) {
270 if (Diags)
271 Diags->Report(diag::err_pch_targetopt_feature_mismatch)
272 << false << ReadFeatures[ReadIdx];
273 return true;
274 }
275
276 if (Diags)
277 Diags->Report(diag::err_pch_targetopt_feature_mismatch)
278 << true << ExistingFeatures[ExistingIdx];
279 return true;
280 }
281
282 if (ExistingIdx < ExistingN) {
283 if (Diags)
284 Diags->Report(diag::err_pch_targetopt_feature_mismatch)
285 << true << ExistingFeatures[ExistingIdx];
286 return true;
287 }
288
289 if (ReadIdx < ReadN) {
290 if (Diags)
291 Diags->Report(diag::err_pch_targetopt_feature_mismatch)
292 << false << ReadFeatures[ReadIdx];
293 return true;
294 }
295
296 return false;
297}
298
299bool
300PCHValidator::ReadLanguageOptions(const LangOptions &LangOpts,
Richard Smith1e2cf0d2014-10-31 02:28:58 +0000301 bool Complain,
302 bool AllowCompatibleDifferences) {
Guy Benyei11169dd2012-12-18 14:30:41 +0000303 const LangOptions &ExistingLangOpts = PP.getLangOpts();
304 return checkLanguageOptions(LangOpts, ExistingLangOpts,
Richard Smith1e2cf0d2014-10-31 02:28:58 +0000305 Complain ? &Reader.Diags : nullptr,
306 AllowCompatibleDifferences);
Guy Benyei11169dd2012-12-18 14:30:41 +0000307}
308
309bool PCHValidator::ReadTargetOptions(const TargetOptions &TargetOpts,
310 bool Complain) {
311 const TargetOptions &ExistingTargetOpts = PP.getTargetInfo().getTargetOpts();
312 return checkTargetOptions(TargetOpts, ExistingTargetOpts,
Craig Toppera13603a2014-05-22 05:54:18 +0000313 Complain? &Reader.Diags : nullptr);
Guy Benyei11169dd2012-12-18 14:30:41 +0000314}
315
316namespace {
317 typedef llvm::StringMap<std::pair<StringRef, bool /*IsUndef*/> >
318 MacroDefinitionsMap;
Craig Topper3598eb72013-07-05 04:43:31 +0000319 typedef llvm::DenseMap<DeclarationName, SmallVector<NamedDecl *, 8> >
320 DeclsMap;
Guy Benyei11169dd2012-12-18 14:30:41 +0000321}
322
Ben Langmuirb92de022014-04-29 16:25:26 +0000323static bool checkDiagnosticGroupMappings(DiagnosticsEngine &StoredDiags,
324 DiagnosticsEngine &Diags,
325 bool Complain) {
326 typedef DiagnosticsEngine::Level Level;
327
328 // Check current mappings for new -Werror mappings, and the stored mappings
329 // for cases that were explicitly mapped to *not* be errors that are now
330 // errors because of options like -Werror.
331 DiagnosticsEngine *MappingSources[] = { &Diags, &StoredDiags };
332
333 for (DiagnosticsEngine *MappingSource : MappingSources) {
334 for (auto DiagIDMappingPair : MappingSource->getDiagnosticMappings()) {
335 diag::kind DiagID = DiagIDMappingPair.first;
336 Level CurLevel = Diags.getDiagnosticLevel(DiagID, SourceLocation());
337 if (CurLevel < DiagnosticsEngine::Error)
338 continue; // not significant
339 Level StoredLevel =
340 StoredDiags.getDiagnosticLevel(DiagID, SourceLocation());
341 if (StoredLevel < DiagnosticsEngine::Error) {
342 if (Complain)
343 Diags.Report(diag::err_pch_diagopt_mismatch) << "-Werror=" +
344 Diags.getDiagnosticIDs()->getWarningOptionForDiag(DiagID).str();
345 return true;
346 }
347 }
348 }
349
350 return false;
351}
352
Alp Tokerac4e8e52014-06-22 21:58:33 +0000353static bool isExtHandlingFromDiagsError(DiagnosticsEngine &Diags) {
354 diag::Severity Ext = Diags.getExtensionHandlingBehavior();
355 if (Ext == diag::Severity::Warning && Diags.getWarningsAsErrors())
356 return true;
357 return Ext >= diag::Severity::Error;
Ben Langmuirb92de022014-04-29 16:25:26 +0000358}
359
360static bool checkDiagnosticMappings(DiagnosticsEngine &StoredDiags,
361 DiagnosticsEngine &Diags,
362 bool IsSystem, bool Complain) {
363 // Top-level options
364 if (IsSystem) {
365 if (Diags.getSuppressSystemWarnings())
366 return false;
367 // If -Wsystem-headers was not enabled before, be conservative
368 if (StoredDiags.getSuppressSystemWarnings()) {
369 if (Complain)
370 Diags.Report(diag::err_pch_diagopt_mismatch) << "-Wsystem-headers";
371 return true;
372 }
373 }
374
375 if (Diags.getWarningsAsErrors() && !StoredDiags.getWarningsAsErrors()) {
376 if (Complain)
377 Diags.Report(diag::err_pch_diagopt_mismatch) << "-Werror";
378 return true;
379 }
380
381 if (Diags.getWarningsAsErrors() && Diags.getEnableAllWarnings() &&
382 !StoredDiags.getEnableAllWarnings()) {
383 if (Complain)
384 Diags.Report(diag::err_pch_diagopt_mismatch) << "-Weverything -Werror";
385 return true;
386 }
387
388 if (isExtHandlingFromDiagsError(Diags) &&
389 !isExtHandlingFromDiagsError(StoredDiags)) {
390 if (Complain)
391 Diags.Report(diag::err_pch_diagopt_mismatch) << "-pedantic-errors";
392 return true;
393 }
394
395 return checkDiagnosticGroupMappings(StoredDiags, Diags, Complain);
396}
397
398bool PCHValidator::ReadDiagnosticOptions(
399 IntrusiveRefCntPtr<DiagnosticOptions> DiagOpts, bool Complain) {
400 DiagnosticsEngine &ExistingDiags = PP.getDiagnostics();
401 IntrusiveRefCntPtr<DiagnosticIDs> DiagIDs(ExistingDiags.getDiagnosticIDs());
402 IntrusiveRefCntPtr<DiagnosticsEngine> Diags(
Alp Tokerf994cef2014-07-05 03:08:06 +0000403 new DiagnosticsEngine(DiagIDs, DiagOpts.get()));
Ben Langmuirb92de022014-04-29 16:25:26 +0000404 // This should never fail, because we would have processed these options
405 // before writing them to an ASTFile.
406 ProcessWarningOptions(*Diags, *DiagOpts, /*Report*/false);
407
408 ModuleManager &ModuleMgr = Reader.getModuleManager();
409 assert(ModuleMgr.size() >= 1 && "what ASTFile is this then");
410
411 // If the original import came from a file explicitly generated by the user,
412 // don't check the diagnostic mappings.
413 // FIXME: currently this is approximated by checking whether this is not a
Richard Smithe842a472014-10-22 02:05:46 +0000414 // module import of an implicitly-loaded module file.
Ben Langmuirb92de022014-04-29 16:25:26 +0000415 // Note: ModuleMgr.rbegin() may not be the current module, but it must be in
416 // the transitive closure of its imports, since unrelated modules cannot be
417 // imported until after this module finishes validation.
418 ModuleFile *TopImport = *ModuleMgr.rbegin();
419 while (!TopImport->ImportedBy.empty())
420 TopImport = TopImport->ImportedBy[0];
Richard Smithe842a472014-10-22 02:05:46 +0000421 if (TopImport->Kind != MK_ImplicitModule)
Ben Langmuirb92de022014-04-29 16:25:26 +0000422 return false;
423
424 StringRef ModuleName = TopImport->ModuleName;
425 assert(!ModuleName.empty() && "diagnostic options read before module name");
426
427 Module *M = PP.getHeaderSearchInfo().lookupModule(ModuleName);
428 assert(M && "missing module");
429
430 // FIXME: if the diagnostics are incompatible, save a DiagnosticOptions that
431 // contains the union of their flags.
432 return checkDiagnosticMappings(*Diags, ExistingDiags, M->IsSystem, Complain);
433}
434
Guy Benyei11169dd2012-12-18 14:30:41 +0000435/// \brief Collect the macro definitions provided by the given preprocessor
436/// options.
Craig Toppera13603a2014-05-22 05:54:18 +0000437static void
438collectMacroDefinitions(const PreprocessorOptions &PPOpts,
439 MacroDefinitionsMap &Macros,
440 SmallVectorImpl<StringRef> *MacroNames = nullptr) {
Guy Benyei11169dd2012-12-18 14:30:41 +0000441 for (unsigned I = 0, N = PPOpts.Macros.size(); I != N; ++I) {
442 StringRef Macro = PPOpts.Macros[I].first;
443 bool IsUndef = PPOpts.Macros[I].second;
444
445 std::pair<StringRef, StringRef> MacroPair = Macro.split('=');
446 StringRef MacroName = MacroPair.first;
447 StringRef MacroBody = MacroPair.second;
448
449 // For an #undef'd macro, we only care about the name.
450 if (IsUndef) {
451 if (MacroNames && !Macros.count(MacroName))
452 MacroNames->push_back(MacroName);
453
454 Macros[MacroName] = std::make_pair("", true);
455 continue;
456 }
457
458 // For a #define'd macro, figure out the actual definition.
459 if (MacroName.size() == Macro.size())
460 MacroBody = "1";
461 else {
462 // Note: GCC drops anything following an end-of-line character.
463 StringRef::size_type End = MacroBody.find_first_of("\n\r");
464 MacroBody = MacroBody.substr(0, End);
465 }
466
467 if (MacroNames && !Macros.count(MacroName))
468 MacroNames->push_back(MacroName);
469 Macros[MacroName] = std::make_pair(MacroBody, false);
470 }
471}
Argyrios Kyrtzidisbd0b6512015-02-19 20:12:20 +0000472
Guy Benyei11169dd2012-12-18 14:30:41 +0000473/// \brief Check the preprocessor options deserialized from the control block
474/// against the preprocessor options in an existing preprocessor.
475///
476/// \param Diags If non-null, produce diagnostics for any mismatches incurred.
477static bool checkPreprocessorOptions(const PreprocessorOptions &PPOpts,
478 const PreprocessorOptions &ExistingPPOpts,
479 DiagnosticsEngine *Diags,
480 FileManager &FileMgr,
Argyrios Kyrtzidisd3afa0c2013-04-26 21:33:40 +0000481 std::string &SuggestedPredefines,
482 const LangOptions &LangOpts) {
Guy Benyei11169dd2012-12-18 14:30:41 +0000483 // Check macro definitions.
484 MacroDefinitionsMap ASTFileMacros;
485 collectMacroDefinitions(PPOpts, ASTFileMacros);
486 MacroDefinitionsMap ExistingMacros;
487 SmallVector<StringRef, 4> ExistingMacroNames;
488 collectMacroDefinitions(ExistingPPOpts, ExistingMacros, &ExistingMacroNames);
489
490 for (unsigned I = 0, N = ExistingMacroNames.size(); I != N; ++I) {
491 // Dig out the macro definition in the existing preprocessor options.
492 StringRef MacroName = ExistingMacroNames[I];
493 std::pair<StringRef, bool> Existing = ExistingMacros[MacroName];
494
495 // Check whether we know anything about this macro name or not.
496 llvm::StringMap<std::pair<StringRef, bool /*IsUndef*/> >::iterator Known
497 = ASTFileMacros.find(MacroName);
498 if (Known == ASTFileMacros.end()) {
499 // FIXME: Check whether this identifier was referenced anywhere in the
500 // AST file. If so, we should reject the AST file. Unfortunately, this
501 // information isn't in the control block. What shall we do about it?
502
503 if (Existing.second) {
504 SuggestedPredefines += "#undef ";
505 SuggestedPredefines += MacroName.str();
506 SuggestedPredefines += '\n';
507 } else {
508 SuggestedPredefines += "#define ";
509 SuggestedPredefines += MacroName.str();
510 SuggestedPredefines += ' ';
511 SuggestedPredefines += Existing.first.str();
512 SuggestedPredefines += '\n';
513 }
514 continue;
515 }
516
517 // If the macro was defined in one but undef'd in the other, we have a
518 // conflict.
519 if (Existing.second != Known->second.second) {
520 if (Diags) {
521 Diags->Report(diag::err_pch_macro_def_undef)
522 << MacroName << Known->second.second;
523 }
524 return true;
525 }
526
527 // If the macro was #undef'd in both, or if the macro bodies are identical,
528 // it's fine.
529 if (Existing.second || Existing.first == Known->second.first)
530 continue;
531
532 // The macro bodies differ; complain.
533 if (Diags) {
534 Diags->Report(diag::err_pch_macro_def_conflict)
535 << MacroName << Known->second.first << Existing.first;
536 }
537 return true;
538 }
539
540 // Check whether we're using predefines.
541 if (PPOpts.UsePredefines != ExistingPPOpts.UsePredefines) {
542 if (Diags) {
543 Diags->Report(diag::err_pch_undef) << ExistingPPOpts.UsePredefines;
544 }
545 return true;
546 }
547
Argyrios Kyrtzidisd3afa0c2013-04-26 21:33:40 +0000548 // Detailed record is important since it is used for the module cache hash.
549 if (LangOpts.Modules &&
550 PPOpts.DetailedRecord != ExistingPPOpts.DetailedRecord) {
551 if (Diags) {
552 Diags->Report(diag::err_pch_pp_detailed_record) << PPOpts.DetailedRecord;
553 }
554 return true;
555 }
556
Guy Benyei11169dd2012-12-18 14:30:41 +0000557 // Compute the #include and #include_macros lines we need.
558 for (unsigned I = 0, N = ExistingPPOpts.Includes.size(); I != N; ++I) {
559 StringRef File = ExistingPPOpts.Includes[I];
560 if (File == ExistingPPOpts.ImplicitPCHInclude)
561 continue;
562
563 if (std::find(PPOpts.Includes.begin(), PPOpts.Includes.end(), File)
564 != PPOpts.Includes.end())
565 continue;
566
567 SuggestedPredefines += "#include \"";
Manuel Klimek9af34ae2014-08-12 08:25:57 +0000568 SuggestedPredefines += File;
Guy Benyei11169dd2012-12-18 14:30:41 +0000569 SuggestedPredefines += "\"\n";
570 }
571
572 for (unsigned I = 0, N = ExistingPPOpts.MacroIncludes.size(); I != N; ++I) {
573 StringRef File = ExistingPPOpts.MacroIncludes[I];
574 if (std::find(PPOpts.MacroIncludes.begin(), PPOpts.MacroIncludes.end(),
575 File)
576 != PPOpts.MacroIncludes.end())
577 continue;
578
579 SuggestedPredefines += "#__include_macros \"";
Manuel Klimek9af34ae2014-08-12 08:25:57 +0000580 SuggestedPredefines += File;
Guy Benyei11169dd2012-12-18 14:30:41 +0000581 SuggestedPredefines += "\"\n##\n";
582 }
583
584 return false;
585}
586
587bool PCHValidator::ReadPreprocessorOptions(const PreprocessorOptions &PPOpts,
588 bool Complain,
589 std::string &SuggestedPredefines) {
590 const PreprocessorOptions &ExistingPPOpts = PP.getPreprocessorOpts();
591
592 return checkPreprocessorOptions(PPOpts, ExistingPPOpts,
Craig Toppera13603a2014-05-22 05:54:18 +0000593 Complain? &Reader.Diags : nullptr,
Guy Benyei11169dd2012-12-18 14:30:41 +0000594 PP.getFileManager(),
Argyrios Kyrtzidisd3afa0c2013-04-26 21:33:40 +0000595 SuggestedPredefines,
596 PP.getLangOpts());
Guy Benyei11169dd2012-12-18 14:30:41 +0000597}
598
Argyrios Kyrtzidisbd0b6512015-02-19 20:12:20 +0000599/// Check the header search options deserialized from the control block
600/// against the header search options in an existing preprocessor.
601///
602/// \param Diags If non-null, produce diagnostics for any mismatches incurred.
603static bool checkHeaderSearchOptions(const HeaderSearchOptions &HSOpts,
604 StringRef SpecificModuleCachePath,
605 StringRef ExistingModuleCachePath,
606 DiagnosticsEngine *Diags,
607 const LangOptions &LangOpts) {
608 if (LangOpts.Modules) {
609 if (SpecificModuleCachePath != ExistingModuleCachePath) {
610 if (Diags)
611 Diags->Report(diag::err_pch_modulecache_mismatch)
612 << SpecificModuleCachePath << ExistingModuleCachePath;
613 return true;
614 }
615 }
616
617 return false;
618}
619
620bool PCHValidator::ReadHeaderSearchOptions(const HeaderSearchOptions &HSOpts,
621 StringRef SpecificModuleCachePath,
622 bool Complain) {
623 return checkHeaderSearchOptions(HSOpts, SpecificModuleCachePath,
624 PP.getHeaderSearchInfo().getModuleCachePath(),
625 Complain ? &Reader.Diags : nullptr,
626 PP.getLangOpts());
627}
628
Guy Benyei11169dd2012-12-18 14:30:41 +0000629void PCHValidator::ReadCounter(const ModuleFile &M, unsigned Value) {
630 PP.setCounterValue(Value);
631}
632
633//===----------------------------------------------------------------------===//
634// AST reader implementation
635//===----------------------------------------------------------------------===//
636
Adrian Prantl8bf7af32015-02-25 01:31:45 +0000637void ASTReader::InitStreamFileWithModule(llvm::MemoryBufferRef Buffer,
638 llvm::BitstreamReader &StreamFile) {
639 if (auto OF = llvm::object::ObjectFile::createObjectFile(Buffer)) {
640 bool IsCOFF = isa<llvm::object::COFFObjectFile>(OF.get().get());
641 // Find the clang AST section in the container.
642 for (auto &Section : OF->get()->sections()) {
643 StringRef Name;
644 Section.getName(Name);
645 if ((!IsCOFF && Name == "__clangast") ||
646 ( IsCOFF && Name == "clangast")) {
647 StringRef Buf;
648 Section.getContents(Buf);
649 return StreamFile.init((const unsigned char*)Buf.begin(),
650 (const unsigned char*)Buf.end());
651 }
652 }
653 }
654 StreamFile.init((const unsigned char *)Buffer.getBufferStart(),
655 (const unsigned char *)Buffer.getBufferEnd());
656}
657
Nico Weber824285e2014-05-08 04:26:47 +0000658void ASTReader::setDeserializationListener(ASTDeserializationListener *Listener,
659 bool TakeOwnership) {
Guy Benyei11169dd2012-12-18 14:30:41 +0000660 DeserializationListener = Listener;
Nico Weber824285e2014-05-08 04:26:47 +0000661 OwnsDeserializationListener = TakeOwnership;
Guy Benyei11169dd2012-12-18 14:30:41 +0000662}
663
664
665
666unsigned ASTSelectorLookupTrait::ComputeHash(Selector Sel) {
667 return serialization::ComputeHash(Sel);
668}
669
670
671std::pair<unsigned, unsigned>
672ASTSelectorLookupTrait::ReadKeyDataLength(const unsigned char*& d) {
Justin Bogner57ba0b22014-03-28 22:03:24 +0000673 using namespace llvm::support;
674 unsigned KeyLen = endian::readNext<uint16_t, little, unaligned>(d);
675 unsigned DataLen = endian::readNext<uint16_t, little, unaligned>(d);
Guy Benyei11169dd2012-12-18 14:30:41 +0000676 return std::make_pair(KeyLen, DataLen);
677}
678
679ASTSelectorLookupTrait::internal_key_type
680ASTSelectorLookupTrait::ReadKey(const unsigned char* d, unsigned) {
Justin Bogner57ba0b22014-03-28 22:03:24 +0000681 using namespace llvm::support;
Guy Benyei11169dd2012-12-18 14:30:41 +0000682 SelectorTable &SelTable = Reader.getContext().Selectors;
Justin Bogner57ba0b22014-03-28 22:03:24 +0000683 unsigned N = endian::readNext<uint16_t, little, unaligned>(d);
684 IdentifierInfo *FirstII = Reader.getLocalIdentifier(
685 F, endian::readNext<uint32_t, little, unaligned>(d));
Guy Benyei11169dd2012-12-18 14:30:41 +0000686 if (N == 0)
687 return SelTable.getNullarySelector(FirstII);
688 else if (N == 1)
689 return SelTable.getUnarySelector(FirstII);
690
691 SmallVector<IdentifierInfo *, 16> Args;
692 Args.push_back(FirstII);
693 for (unsigned I = 1; I != N; ++I)
Justin Bogner57ba0b22014-03-28 22:03:24 +0000694 Args.push_back(Reader.getLocalIdentifier(
695 F, endian::readNext<uint32_t, little, unaligned>(d)));
Guy Benyei11169dd2012-12-18 14:30:41 +0000696
697 return SelTable.getSelector(N, Args.data());
698}
699
700ASTSelectorLookupTrait::data_type
701ASTSelectorLookupTrait::ReadData(Selector, const unsigned char* d,
702 unsigned DataLen) {
Justin Bogner57ba0b22014-03-28 22:03:24 +0000703 using namespace llvm::support;
Guy Benyei11169dd2012-12-18 14:30:41 +0000704
705 data_type Result;
706
Justin Bogner57ba0b22014-03-28 22:03:24 +0000707 Result.ID = Reader.getGlobalSelectorID(
708 F, endian::readNext<uint32_t, little, unaligned>(d));
Nico Weberff4b35e2014-12-27 22:14:15 +0000709 unsigned FullInstanceBits = endian::readNext<uint16_t, little, unaligned>(d);
710 unsigned FullFactoryBits = endian::readNext<uint16_t, little, unaligned>(d);
711 Result.InstanceBits = FullInstanceBits & 0x3;
712 Result.InstanceHasMoreThanOneDecl = (FullInstanceBits >> 2) & 0x1;
713 Result.FactoryBits = FullFactoryBits & 0x3;
714 Result.FactoryHasMoreThanOneDecl = (FullFactoryBits >> 2) & 0x1;
715 unsigned NumInstanceMethods = FullInstanceBits >> 3;
716 unsigned NumFactoryMethods = FullFactoryBits >> 3;
Guy Benyei11169dd2012-12-18 14:30:41 +0000717
718 // Load instance methods
719 for (unsigned I = 0; I != NumInstanceMethods; ++I) {
Justin Bogner57ba0b22014-03-28 22:03:24 +0000720 if (ObjCMethodDecl *Method = Reader.GetLocalDeclAs<ObjCMethodDecl>(
721 F, endian::readNext<uint32_t, little, unaligned>(d)))
Guy Benyei11169dd2012-12-18 14:30:41 +0000722 Result.Instance.push_back(Method);
723 }
724
725 // Load factory methods
726 for (unsigned I = 0; I != NumFactoryMethods; ++I) {
Justin Bogner57ba0b22014-03-28 22:03:24 +0000727 if (ObjCMethodDecl *Method = Reader.GetLocalDeclAs<ObjCMethodDecl>(
728 F, endian::readNext<uint32_t, little, unaligned>(d)))
Guy Benyei11169dd2012-12-18 14:30:41 +0000729 Result.Factory.push_back(Method);
730 }
731
732 return Result;
733}
734
Douglas Gregorbfd73d72013-01-23 18:53:14 +0000735unsigned ASTIdentifierLookupTraitBase::ComputeHash(const internal_key_type& a) {
736 return llvm::HashString(a);
Guy Benyei11169dd2012-12-18 14:30:41 +0000737}
738
739std::pair<unsigned, unsigned>
Douglas Gregorbfd73d72013-01-23 18:53:14 +0000740ASTIdentifierLookupTraitBase::ReadKeyDataLength(const unsigned char*& d) {
Justin Bogner57ba0b22014-03-28 22:03:24 +0000741 using namespace llvm::support;
742 unsigned DataLen = endian::readNext<uint16_t, little, unaligned>(d);
743 unsigned KeyLen = endian::readNext<uint16_t, little, unaligned>(d);
Guy Benyei11169dd2012-12-18 14:30:41 +0000744 return std::make_pair(KeyLen, DataLen);
745}
746
Douglas Gregorbfd73d72013-01-23 18:53:14 +0000747ASTIdentifierLookupTraitBase::internal_key_type
748ASTIdentifierLookupTraitBase::ReadKey(const unsigned char* d, unsigned n) {
Guy Benyei11169dd2012-12-18 14:30:41 +0000749 assert(n >= 2 && d[n-1] == '\0');
Douglas Gregorbfd73d72013-01-23 18:53:14 +0000750 return StringRef((const char*) d, n-1);
Guy Benyei11169dd2012-12-18 14:30:41 +0000751}
752
Douglas Gregordcf25082013-02-11 18:16:18 +0000753/// \brief Whether the given identifier is "interesting".
754static bool isInterestingIdentifier(IdentifierInfo &II) {
755 return II.isPoisoned() ||
756 II.isExtensionToken() ||
757 II.getObjCOrBuiltinID() ||
758 II.hasRevertedTokenIDToIdentifier() ||
759 II.hadMacroDefinition() ||
760 II.getFETokenInfo<void>();
761}
762
Guy Benyei11169dd2012-12-18 14:30:41 +0000763IdentifierInfo *ASTIdentifierLookupTrait::ReadData(const internal_key_type& k,
764 const unsigned char* d,
765 unsigned DataLen) {
Justin Bogner57ba0b22014-03-28 22:03:24 +0000766 using namespace llvm::support;
767 unsigned RawID = endian::readNext<uint32_t, little, unaligned>(d);
Guy Benyei11169dd2012-12-18 14:30:41 +0000768 bool IsInteresting = RawID & 0x01;
769
770 // Wipe out the "is interesting" bit.
771 RawID = RawID >> 1;
772
773 IdentID ID = Reader.getGlobalIdentifierID(F, RawID);
774 if (!IsInteresting) {
775 // For uninteresting identifiers, just build the IdentifierInfo
776 // and associate it with the persistent ID.
777 IdentifierInfo *II = KnownII;
778 if (!II) {
Douglas Gregorbfd73d72013-01-23 18:53:14 +0000779 II = &Reader.getIdentifierTable().getOwn(k);
Guy Benyei11169dd2012-12-18 14:30:41 +0000780 KnownII = II;
781 }
782 Reader.SetIdentifierInfo(ID, II);
Douglas Gregordcf25082013-02-11 18:16:18 +0000783 if (!II->isFromAST()) {
784 bool WasInteresting = isInterestingIdentifier(*II);
785 II->setIsFromAST();
786 if (WasInteresting)
787 II->setChangedSinceDeserialization();
788 }
789 Reader.markIdentifierUpToDate(II);
Guy Benyei11169dd2012-12-18 14:30:41 +0000790 return II;
791 }
792
Justin Bogner57ba0b22014-03-28 22:03:24 +0000793 unsigned ObjCOrBuiltinID = endian::readNext<uint16_t, little, unaligned>(d);
794 unsigned Bits = endian::readNext<uint16_t, little, unaligned>(d);
Guy Benyei11169dd2012-12-18 14:30:41 +0000795 bool CPlusPlusOperatorKeyword = Bits & 0x01;
796 Bits >>= 1;
797 bool HasRevertedTokenIDToIdentifier = Bits & 0x01;
798 Bits >>= 1;
799 bool Poisoned = Bits & 0x01;
800 Bits >>= 1;
801 bool ExtensionToken = Bits & 0x01;
802 Bits >>= 1;
Argyrios Kyrtzidiseb663da2013-03-22 21:12:57 +0000803 bool hasSubmoduleMacros = Bits & 0x01;
804 Bits >>= 1;
Guy Benyei11169dd2012-12-18 14:30:41 +0000805 bool hadMacroDefinition = Bits & 0x01;
806 Bits >>= 1;
807
808 assert(Bits == 0 && "Extra bits in the identifier?");
809 DataLen -= 8;
810
811 // Build the IdentifierInfo itself and link the identifier ID with
812 // the new IdentifierInfo.
813 IdentifierInfo *II = KnownII;
814 if (!II) {
Douglas Gregorbfd73d72013-01-23 18:53:14 +0000815 II = &Reader.getIdentifierTable().getOwn(StringRef(k));
Guy Benyei11169dd2012-12-18 14:30:41 +0000816 KnownII = II;
817 }
818 Reader.markIdentifierUpToDate(II);
Douglas Gregordcf25082013-02-11 18:16:18 +0000819 if (!II->isFromAST()) {
820 bool WasInteresting = isInterestingIdentifier(*II);
821 II->setIsFromAST();
822 if (WasInteresting)
823 II->setChangedSinceDeserialization();
824 }
Guy Benyei11169dd2012-12-18 14:30:41 +0000825
826 // Set or check the various bits in the IdentifierInfo structure.
827 // Token IDs are read-only.
Argyrios Kyrtzidisddee8c92013-02-27 01:13:51 +0000828 if (HasRevertedTokenIDToIdentifier && II->getTokenID() != tok::identifier)
Guy Benyei11169dd2012-12-18 14:30:41 +0000829 II->RevertTokenIDToIdentifier();
830 II->setObjCOrBuiltinID(ObjCOrBuiltinID);
831 assert(II->isExtensionToken() == ExtensionToken &&
832 "Incorrect extension token flag");
833 (void)ExtensionToken;
834 if (Poisoned)
835 II->setIsPoisoned(true);
836 assert(II->isCPlusPlusOperatorKeyword() == CPlusPlusOperatorKeyword &&
837 "Incorrect C++ operator keyword flag");
838 (void)CPlusPlusOperatorKeyword;
839
840 // If this identifier is a macro, deserialize the macro
841 // definition.
842 if (hadMacroDefinition) {
Justin Bogner57ba0b22014-03-28 22:03:24 +0000843 uint32_t MacroDirectivesOffset =
844 endian::readNext<uint32_t, little, unaligned>(d);
Argyrios Kyrtzidiseb663da2013-03-22 21:12:57 +0000845 DataLen -= 4;
846 SmallVector<uint32_t, 8> LocalMacroIDs;
847 if (hasSubmoduleMacros) {
Richard Smithdaa69e02014-07-25 04:40:03 +0000848 while (true) {
849 uint32_t LocalMacroID =
850 endian::readNext<uint32_t, little, unaligned>(d);
Argyrios Kyrtzidiseb663da2013-03-22 21:12:57 +0000851 DataLen -= 4;
Richard Smithdaa69e02014-07-25 04:40:03 +0000852 if (LocalMacroID == 0xdeadbeef) break;
Argyrios Kyrtzidiseb663da2013-03-22 21:12:57 +0000853 LocalMacroIDs.push_back(LocalMacroID);
854 }
Argyrios Kyrtzidis719736c2013-01-19 03:14:56 +0000855 }
Argyrios Kyrtzidiseb663da2013-03-22 21:12:57 +0000856
Richard Smithe842a472014-10-22 02:05:46 +0000857 if (F.Kind == MK_ImplicitModule || F.Kind == MK_ExplicitModule) {
Richard Smith49f906a2014-03-01 00:08:04 +0000858 // Macro definitions are stored from newest to oldest, so reverse them
859 // before registering them.
860 llvm::SmallVector<unsigned, 8> MacroSizes;
Argyrios Kyrtzidiseb663da2013-03-22 21:12:57 +0000861 for (SmallVectorImpl<uint32_t>::iterator
Richard Smith49f906a2014-03-01 00:08:04 +0000862 I = LocalMacroIDs.begin(), E = LocalMacroIDs.end(); I != E; /**/) {
863 unsigned Size = 1;
864
865 static const uint32_t HasOverridesFlag = 0x80000000U;
866 if (I + 1 != E && (I[1] & HasOverridesFlag))
867 Size += 1 + (I[1] & ~HasOverridesFlag);
868
869 MacroSizes.push_back(Size);
870 I += Size;
Argyrios Kyrtzidiseb663da2013-03-22 21:12:57 +0000871 }
Richard Smith49f906a2014-03-01 00:08:04 +0000872
873 SmallVectorImpl<uint32_t>::iterator I = LocalMacroIDs.end();
874 for (SmallVectorImpl<unsigned>::reverse_iterator SI = MacroSizes.rbegin(),
875 SE = MacroSizes.rend();
876 SI != SE; ++SI) {
877 I -= *SI;
878
879 uint32_t LocalMacroID = *I;
Craig Topper00bbdcf2014-06-28 23:22:23 +0000880 ArrayRef<uint32_t> Overrides;
Richard Smith49f906a2014-03-01 00:08:04 +0000881 if (*SI != 1)
882 Overrides = llvm::makeArrayRef(&I[2], *SI - 2);
883 Reader.addPendingMacroFromModule(II, &F, LocalMacroID, Overrides);
884 }
885 assert(I == LocalMacroIDs.begin());
Argyrios Kyrtzidiseb663da2013-03-22 21:12:57 +0000886 } else {
887 Reader.addPendingMacroFromPCH(II, &F, MacroDirectivesOffset);
888 }
Guy Benyei11169dd2012-12-18 14:30:41 +0000889 }
890
891 Reader.SetIdentifierInfo(ID, II);
892
893 // Read all of the declarations visible at global scope with this
894 // name.
895 if (DataLen > 0) {
896 SmallVector<uint32_t, 4> DeclIDs;
897 for (; DataLen > 0; DataLen -= 4)
Justin Bogner57ba0b22014-03-28 22:03:24 +0000898 DeclIDs.push_back(Reader.getGlobalDeclID(
899 F, endian::readNext<uint32_t, little, unaligned>(d)));
Guy Benyei11169dd2012-12-18 14:30:41 +0000900 Reader.SetGloballyVisibleDecls(II, DeclIDs);
901 }
902
903 return II;
904}
905
906unsigned
907ASTDeclContextNameLookupTrait::ComputeHash(const DeclNameKey &Key) const {
908 llvm::FoldingSetNodeID ID;
909 ID.AddInteger(Key.Kind);
910
911 switch (Key.Kind) {
912 case DeclarationName::Identifier:
913 case DeclarationName::CXXLiteralOperatorName:
914 ID.AddString(((IdentifierInfo*)Key.Data)->getName());
915 break;
916 case DeclarationName::ObjCZeroArgSelector:
917 case DeclarationName::ObjCOneArgSelector:
918 case DeclarationName::ObjCMultiArgSelector:
919 ID.AddInteger(serialization::ComputeHash(Selector(Key.Data)));
920 break;
921 case DeclarationName::CXXOperatorName:
922 ID.AddInteger((OverloadedOperatorKind)Key.Data);
923 break;
924 case DeclarationName::CXXConstructorName:
925 case DeclarationName::CXXDestructorName:
926 case DeclarationName::CXXConversionFunctionName:
927 case DeclarationName::CXXUsingDirective:
928 break;
929 }
930
931 return ID.ComputeHash();
932}
933
934ASTDeclContextNameLookupTrait::internal_key_type
935ASTDeclContextNameLookupTrait::GetInternalKey(
936 const external_key_type& Name) const {
937 DeclNameKey Key;
938 Key.Kind = Name.getNameKind();
939 switch (Name.getNameKind()) {
940 case DeclarationName::Identifier:
941 Key.Data = (uint64_t)Name.getAsIdentifierInfo();
942 break;
943 case DeclarationName::ObjCZeroArgSelector:
944 case DeclarationName::ObjCOneArgSelector:
945 case DeclarationName::ObjCMultiArgSelector:
946 Key.Data = (uint64_t)Name.getObjCSelector().getAsOpaquePtr();
947 break;
948 case DeclarationName::CXXOperatorName:
949 Key.Data = Name.getCXXOverloadedOperator();
950 break;
951 case DeclarationName::CXXLiteralOperatorName:
952 Key.Data = (uint64_t)Name.getCXXLiteralIdentifier();
953 break;
954 case DeclarationName::CXXConstructorName:
955 case DeclarationName::CXXDestructorName:
956 case DeclarationName::CXXConversionFunctionName:
957 case DeclarationName::CXXUsingDirective:
958 Key.Data = 0;
959 break;
960 }
961
962 return Key;
963}
964
965std::pair<unsigned, unsigned>
966ASTDeclContextNameLookupTrait::ReadKeyDataLength(const unsigned char*& d) {
Justin Bogner57ba0b22014-03-28 22:03:24 +0000967 using namespace llvm::support;
968 unsigned KeyLen = endian::readNext<uint16_t, little, unaligned>(d);
969 unsigned DataLen = endian::readNext<uint16_t, little, unaligned>(d);
Guy Benyei11169dd2012-12-18 14:30:41 +0000970 return std::make_pair(KeyLen, DataLen);
971}
972
973ASTDeclContextNameLookupTrait::internal_key_type
974ASTDeclContextNameLookupTrait::ReadKey(const unsigned char* d, unsigned) {
Justin Bogner57ba0b22014-03-28 22:03:24 +0000975 using namespace llvm::support;
Guy Benyei11169dd2012-12-18 14:30:41 +0000976
977 DeclNameKey Key;
978 Key.Kind = (DeclarationName::NameKind)*d++;
979 switch (Key.Kind) {
980 case DeclarationName::Identifier:
Justin Bogner57ba0b22014-03-28 22:03:24 +0000981 Key.Data = (uint64_t)Reader.getLocalIdentifier(
982 F, endian::readNext<uint32_t, little, unaligned>(d));
Guy Benyei11169dd2012-12-18 14:30:41 +0000983 break;
984 case DeclarationName::ObjCZeroArgSelector:
985 case DeclarationName::ObjCOneArgSelector:
986 case DeclarationName::ObjCMultiArgSelector:
987 Key.Data =
Justin Bogner57ba0b22014-03-28 22:03:24 +0000988 (uint64_t)Reader.getLocalSelector(
989 F, endian::readNext<uint32_t, little, unaligned>(
990 d)).getAsOpaquePtr();
Guy Benyei11169dd2012-12-18 14:30:41 +0000991 break;
992 case DeclarationName::CXXOperatorName:
993 Key.Data = *d++; // OverloadedOperatorKind
994 break;
995 case DeclarationName::CXXLiteralOperatorName:
Justin Bogner57ba0b22014-03-28 22:03:24 +0000996 Key.Data = (uint64_t)Reader.getLocalIdentifier(
997 F, endian::readNext<uint32_t, little, unaligned>(d));
Guy Benyei11169dd2012-12-18 14:30:41 +0000998 break;
999 case DeclarationName::CXXConstructorName:
1000 case DeclarationName::CXXDestructorName:
1001 case DeclarationName::CXXConversionFunctionName:
1002 case DeclarationName::CXXUsingDirective:
1003 Key.Data = 0;
1004 break;
1005 }
1006
1007 return Key;
1008}
1009
1010ASTDeclContextNameLookupTrait::data_type
1011ASTDeclContextNameLookupTrait::ReadData(internal_key_type,
1012 const unsigned char* d,
1013 unsigned DataLen) {
Justin Bogner57ba0b22014-03-28 22:03:24 +00001014 using namespace llvm::support;
1015 unsigned NumDecls = endian::readNext<uint16_t, little, unaligned>(d);
Argyrios Kyrtzidisc57e5032013-01-11 22:29:49 +00001016 LE32DeclID *Start = reinterpret_cast<LE32DeclID *>(
1017 const_cast<unsigned char *>(d));
Guy Benyei11169dd2012-12-18 14:30:41 +00001018 return std::make_pair(Start, Start + NumDecls);
1019}
1020
1021bool ASTReader::ReadDeclContextStorage(ModuleFile &M,
Chris Lattner7fb3bef2013-01-20 00:56:42 +00001022 BitstreamCursor &Cursor,
Guy Benyei11169dd2012-12-18 14:30:41 +00001023 const std::pair<uint64_t, uint64_t> &Offsets,
1024 DeclContextInfo &Info) {
1025 SavedStreamPosition SavedPosition(Cursor);
1026 // First the lexical decls.
1027 if (Offsets.first != 0) {
1028 Cursor.JumpToBit(Offsets.first);
1029
1030 RecordData Record;
Chris Lattner0e6c9402013-01-20 02:38:54 +00001031 StringRef Blob;
Guy Benyei11169dd2012-12-18 14:30:41 +00001032 unsigned Code = Cursor.ReadCode();
Chris Lattner0e6c9402013-01-20 02:38:54 +00001033 unsigned RecCode = Cursor.readRecord(Code, Record, &Blob);
Guy Benyei11169dd2012-12-18 14:30:41 +00001034 if (RecCode != DECL_CONTEXT_LEXICAL) {
1035 Error("Expected lexical block");
1036 return true;
1037 }
1038
Chris Lattner0e6c9402013-01-20 02:38:54 +00001039 Info.LexicalDecls = reinterpret_cast<const KindDeclIDPair*>(Blob.data());
1040 Info.NumLexicalDecls = Blob.size() / sizeof(KindDeclIDPair);
Guy Benyei11169dd2012-12-18 14:30:41 +00001041 }
1042
1043 // Now the lookup table.
1044 if (Offsets.second != 0) {
1045 Cursor.JumpToBit(Offsets.second);
1046
1047 RecordData Record;
Chris Lattner0e6c9402013-01-20 02:38:54 +00001048 StringRef Blob;
Guy Benyei11169dd2012-12-18 14:30:41 +00001049 unsigned Code = Cursor.ReadCode();
Chris Lattner0e6c9402013-01-20 02:38:54 +00001050 unsigned RecCode = Cursor.readRecord(Code, Record, &Blob);
Guy Benyei11169dd2012-12-18 14:30:41 +00001051 if (RecCode != DECL_CONTEXT_VISIBLE) {
1052 Error("Expected visible lookup table block");
1053 return true;
1054 }
Justin Bognerda4e6502014-04-14 16:34:29 +00001055 Info.NameLookupTableData = ASTDeclContextNameLookupTable::Create(
1056 (const unsigned char *)Blob.data() + Record[0],
1057 (const unsigned char *)Blob.data() + sizeof(uint32_t),
1058 (const unsigned char *)Blob.data(),
1059 ASTDeclContextNameLookupTrait(*this, M));
Guy Benyei11169dd2012-12-18 14:30:41 +00001060 }
1061
1062 return false;
1063}
1064
1065void ASTReader::Error(StringRef Msg) {
1066 Error(diag::err_fe_pch_malformed, Msg);
Douglas Gregor940e8052013-05-10 22:15:13 +00001067 if (Context.getLangOpts().Modules && !Diags.isDiagnosticInFlight()) {
1068 Diag(diag::note_module_cache_path)
1069 << PP.getHeaderSearchInfo().getModuleCachePath();
1070 }
Guy Benyei11169dd2012-12-18 14:30:41 +00001071}
1072
1073void ASTReader::Error(unsigned DiagID,
1074 StringRef Arg1, StringRef Arg2) {
1075 if (Diags.isDiagnosticInFlight())
1076 Diags.SetDelayedDiagnostic(DiagID, Arg1, Arg2);
1077 else
1078 Diag(DiagID) << Arg1 << Arg2;
1079}
1080
1081//===----------------------------------------------------------------------===//
1082// Source Manager Deserialization
1083//===----------------------------------------------------------------------===//
1084
1085/// \brief Read the line table in the source manager block.
1086/// \returns true if there was an error.
1087bool ASTReader::ParseLineTable(ModuleFile &F,
Richard Smith7ed1bc92014-12-05 22:42:13 +00001088 const RecordData &Record) {
Guy Benyei11169dd2012-12-18 14:30:41 +00001089 unsigned Idx = 0;
1090 LineTableInfo &LineTable = SourceMgr.getLineTable();
1091
1092 // Parse the file names
1093 std::map<int, int> FileIDs;
1094 for (int I = 0, N = Record[Idx++]; I != N; ++I) {
1095 // Extract the file name
Richard Smith7ed1bc92014-12-05 22:42:13 +00001096 auto Filename = ReadPath(F, Record, Idx);
Guy Benyei11169dd2012-12-18 14:30:41 +00001097 FileIDs[I] = LineTable.getLineTableFilenameID(Filename);
1098 }
1099
1100 // Parse the line entries
1101 std::vector<LineEntry> Entries;
1102 while (Idx < Record.size()) {
1103 int FID = Record[Idx++];
1104 assert(FID >= 0 && "Serialized line entries for non-local file.");
1105 // Remap FileID from 1-based old view.
1106 FID += F.SLocEntryBaseID - 1;
1107
1108 // Extract the line entries
1109 unsigned NumEntries = Record[Idx++];
1110 assert(NumEntries && "Numentries is 00000");
1111 Entries.clear();
1112 Entries.reserve(NumEntries);
1113 for (unsigned I = 0; I != NumEntries; ++I) {
1114 unsigned FileOffset = Record[Idx++];
1115 unsigned LineNo = Record[Idx++];
1116 int FilenameID = FileIDs[Record[Idx++]];
1117 SrcMgr::CharacteristicKind FileKind
1118 = (SrcMgr::CharacteristicKind)Record[Idx++];
1119 unsigned IncludeOffset = Record[Idx++];
1120 Entries.push_back(LineEntry::get(FileOffset, LineNo, FilenameID,
1121 FileKind, IncludeOffset));
1122 }
1123 LineTable.AddEntry(FileID::get(FID), Entries);
1124 }
1125
1126 return false;
1127}
1128
1129/// \brief Read a source manager block
1130bool ASTReader::ReadSourceManagerBlock(ModuleFile &F) {
1131 using namespace SrcMgr;
1132
Chris Lattner7fb3bef2013-01-20 00:56:42 +00001133 BitstreamCursor &SLocEntryCursor = F.SLocEntryCursor;
Guy Benyei11169dd2012-12-18 14:30:41 +00001134
1135 // Set the source-location entry cursor to the current position in
1136 // the stream. This cursor will be used to read the contents of the
1137 // source manager block initially, and then lazily read
1138 // source-location entries as needed.
1139 SLocEntryCursor = F.Stream;
1140
1141 // The stream itself is going to skip over the source manager block.
1142 if (F.Stream.SkipBlock()) {
1143 Error("malformed block record in AST file");
1144 return true;
1145 }
1146
1147 // Enter the source manager block.
1148 if (SLocEntryCursor.EnterSubBlock(SOURCE_MANAGER_BLOCK_ID)) {
1149 Error("malformed source manager block record in AST file");
1150 return true;
1151 }
1152
1153 RecordData Record;
1154 while (true) {
Chris Lattnere7b154b2013-01-19 21:39:22 +00001155 llvm::BitstreamEntry E = SLocEntryCursor.advanceSkippingSubblocks();
1156
1157 switch (E.Kind) {
1158 case llvm::BitstreamEntry::SubBlock: // Handled for us already.
1159 case llvm::BitstreamEntry::Error:
1160 Error("malformed block record in AST file");
1161 return true;
1162 case llvm::BitstreamEntry::EndBlock:
Guy Benyei11169dd2012-12-18 14:30:41 +00001163 return false;
Chris Lattnere7b154b2013-01-19 21:39:22 +00001164 case llvm::BitstreamEntry::Record:
1165 // The interesting case.
1166 break;
Guy Benyei11169dd2012-12-18 14:30:41 +00001167 }
Chris Lattnere7b154b2013-01-19 21:39:22 +00001168
Guy Benyei11169dd2012-12-18 14:30:41 +00001169 // Read a record.
Guy Benyei11169dd2012-12-18 14:30:41 +00001170 Record.clear();
Chris Lattner15c3e7d2013-01-21 18:28:26 +00001171 StringRef Blob;
1172 switch (SLocEntryCursor.readRecord(E.ID, Record, &Blob)) {
Guy Benyei11169dd2012-12-18 14:30:41 +00001173 default: // Default behavior: ignore.
1174 break;
1175
1176 case SM_SLOC_FILE_ENTRY:
1177 case SM_SLOC_BUFFER_ENTRY:
1178 case SM_SLOC_EXPANSION_ENTRY:
1179 // Once we hit one of the source location entries, we're done.
1180 return false;
1181 }
1182 }
1183}
1184
1185/// \brief If a header file is not found at the path that we expect it to be
1186/// and the PCH file was moved from its original location, try to resolve the
1187/// file by assuming that header+PCH were moved together and the header is in
1188/// the same place relative to the PCH.
1189static std::string
1190resolveFileRelativeToOriginalDir(const std::string &Filename,
1191 const std::string &OriginalDir,
1192 const std::string &CurrDir) {
1193 assert(OriginalDir != CurrDir &&
1194 "No point trying to resolve the file if the PCH dir didn't change");
1195 using namespace llvm::sys;
1196 SmallString<128> filePath(Filename);
1197 fs::make_absolute(filePath);
1198 assert(path::is_absolute(OriginalDir));
1199 SmallString<128> currPCHPath(CurrDir);
1200
1201 path::const_iterator fileDirI = path::begin(path::parent_path(filePath)),
1202 fileDirE = path::end(path::parent_path(filePath));
1203 path::const_iterator origDirI = path::begin(OriginalDir),
1204 origDirE = path::end(OriginalDir);
1205 // Skip the common path components from filePath and OriginalDir.
1206 while (fileDirI != fileDirE && origDirI != origDirE &&
1207 *fileDirI == *origDirI) {
1208 ++fileDirI;
1209 ++origDirI;
1210 }
1211 for (; origDirI != origDirE; ++origDirI)
1212 path::append(currPCHPath, "..");
1213 path::append(currPCHPath, fileDirI, fileDirE);
1214 path::append(currPCHPath, path::filename(Filename));
1215 return currPCHPath.str();
1216}
1217
1218bool ASTReader::ReadSLocEntry(int ID) {
1219 if (ID == 0)
1220 return false;
1221
1222 if (unsigned(-ID) - 2 >= getTotalNumSLocs() || ID > 0) {
1223 Error("source location entry ID out-of-range for AST file");
1224 return true;
1225 }
1226
1227 ModuleFile *F = GlobalSLocEntryMap.find(-ID)->second;
1228 F->SLocEntryCursor.JumpToBit(F->SLocEntryOffsets[ID - F->SLocEntryBaseID]);
Chris Lattner7fb3bef2013-01-20 00:56:42 +00001229 BitstreamCursor &SLocEntryCursor = F->SLocEntryCursor;
Guy Benyei11169dd2012-12-18 14:30:41 +00001230 unsigned BaseOffset = F->SLocEntryBaseOffset;
1231
1232 ++NumSLocEntriesRead;
Chris Lattnere7b154b2013-01-19 21:39:22 +00001233 llvm::BitstreamEntry Entry = SLocEntryCursor.advance();
1234 if (Entry.Kind != llvm::BitstreamEntry::Record) {
Guy Benyei11169dd2012-12-18 14:30:41 +00001235 Error("incorrectly-formatted source location entry in AST file");
1236 return true;
1237 }
Chris Lattnere7b154b2013-01-19 21:39:22 +00001238
Guy Benyei11169dd2012-12-18 14:30:41 +00001239 RecordData Record;
Chris Lattner0e6c9402013-01-20 02:38:54 +00001240 StringRef Blob;
1241 switch (SLocEntryCursor.readRecord(Entry.ID, Record, &Blob)) {
Guy Benyei11169dd2012-12-18 14:30:41 +00001242 default:
1243 Error("incorrectly-formatted source location entry in AST file");
1244 return true;
1245
1246 case SM_SLOC_FILE_ENTRY: {
1247 // We will detect whether a file changed and return 'Failure' for it, but
1248 // we will also try to fail gracefully by setting up the SLocEntry.
1249 unsigned InputID = Record[4];
1250 InputFile IF = getInputFile(*F, InputID);
Argyrios Kyrtzidis61c3d872013-03-01 03:26:04 +00001251 const FileEntry *File = IF.getFile();
1252 bool OverriddenBuffer = IF.isOverridden();
Guy Benyei11169dd2012-12-18 14:30:41 +00001253
Argyrios Kyrtzidis61c3d872013-03-01 03:26:04 +00001254 // Note that we only check if a File was returned. If it was out-of-date
1255 // we have complained but we will continue creating a FileID to recover
1256 // gracefully.
1257 if (!File)
Guy Benyei11169dd2012-12-18 14:30:41 +00001258 return true;
1259
1260 SourceLocation IncludeLoc = ReadSourceLocation(*F, Record[1]);
1261 if (IncludeLoc.isInvalid() && F->Kind != MK_MainFile) {
1262 // This is the module's main file.
1263 IncludeLoc = getImportLocation(F);
1264 }
1265 SrcMgr::CharacteristicKind
1266 FileCharacter = (SrcMgr::CharacteristicKind)Record[2];
1267 FileID FID = SourceMgr.createFileID(File, IncludeLoc, FileCharacter,
1268 ID, BaseOffset + Record[0]);
1269 SrcMgr::FileInfo &FileInfo =
1270 const_cast<SrcMgr::FileInfo&>(SourceMgr.getSLocEntry(FID).getFile());
1271 FileInfo.NumCreatedFIDs = Record[5];
1272 if (Record[3])
1273 FileInfo.setHasLineDirectives();
1274
1275 const DeclID *FirstDecl = F->FileSortedDecls + Record[6];
1276 unsigned NumFileDecls = Record[7];
1277 if (NumFileDecls) {
1278 assert(F->FileSortedDecls && "FILE_SORTED_DECLS not encountered yet ?");
1279 FileDeclIDs[FID] = FileDeclsInfo(F, llvm::makeArrayRef(FirstDecl,
1280 NumFileDecls));
1281 }
1282
1283 const SrcMgr::ContentCache *ContentCache
1284 = SourceMgr.getOrCreateContentCache(File,
1285 /*isSystemFile=*/FileCharacter != SrcMgr::C_User);
1286 if (OverriddenBuffer && !ContentCache->BufferOverridden &&
1287 ContentCache->ContentsEntry == ContentCache->OrigEntry) {
1288 unsigned Code = SLocEntryCursor.ReadCode();
1289 Record.clear();
Chris Lattner0e6c9402013-01-20 02:38:54 +00001290 unsigned RecCode = SLocEntryCursor.readRecord(Code, Record, &Blob);
Guy Benyei11169dd2012-12-18 14:30:41 +00001291
1292 if (RecCode != SM_SLOC_BUFFER_BLOB) {
1293 Error("AST record has invalid code");
1294 return true;
1295 }
1296
Rafael Espindolad87f8d72014-08-27 20:03:29 +00001297 std::unique_ptr<llvm::MemoryBuffer> Buffer
Chris Lattner0e6c9402013-01-20 02:38:54 +00001298 = llvm::MemoryBuffer::getMemBuffer(Blob.drop_back(1), File->getName());
David Blaikie49cc3182014-08-27 20:54:45 +00001299 SourceMgr.overrideFileContents(File, std::move(Buffer));
Guy Benyei11169dd2012-12-18 14:30:41 +00001300 }
1301
1302 break;
1303 }
1304
1305 case SM_SLOC_BUFFER_ENTRY: {
Chris Lattner0e6c9402013-01-20 02:38:54 +00001306 const char *Name = Blob.data();
Guy Benyei11169dd2012-12-18 14:30:41 +00001307 unsigned Offset = Record[0];
1308 SrcMgr::CharacteristicKind
1309 FileCharacter = (SrcMgr::CharacteristicKind)Record[2];
1310 SourceLocation IncludeLoc = ReadSourceLocation(*F, Record[1]);
Richard Smithe842a472014-10-22 02:05:46 +00001311 if (IncludeLoc.isInvalid() &&
1312 (F->Kind == MK_ImplicitModule || F->Kind == MK_ExplicitModule)) {
Guy Benyei11169dd2012-12-18 14:30:41 +00001313 IncludeLoc = getImportLocation(F);
1314 }
1315 unsigned Code = SLocEntryCursor.ReadCode();
1316 Record.clear();
1317 unsigned RecCode
Chris Lattner0e6c9402013-01-20 02:38:54 +00001318 = SLocEntryCursor.readRecord(Code, Record, &Blob);
Guy Benyei11169dd2012-12-18 14:30:41 +00001319
1320 if (RecCode != SM_SLOC_BUFFER_BLOB) {
1321 Error("AST record has invalid code");
1322 return true;
1323 }
1324
Rafael Espindolad87f8d72014-08-27 20:03:29 +00001325 std::unique_ptr<llvm::MemoryBuffer> Buffer =
1326 llvm::MemoryBuffer::getMemBuffer(Blob.drop_back(1), Name);
David Blaikie50a5f972014-08-29 07:59:55 +00001327 SourceMgr.createFileID(std::move(Buffer), FileCharacter, ID,
Rafael Espindolad87f8d72014-08-27 20:03:29 +00001328 BaseOffset + Offset, IncludeLoc);
Guy Benyei11169dd2012-12-18 14:30:41 +00001329 break;
1330 }
1331
1332 case SM_SLOC_EXPANSION_ENTRY: {
1333 SourceLocation SpellingLoc = ReadSourceLocation(*F, Record[1]);
1334 SourceMgr.createExpansionLoc(SpellingLoc,
1335 ReadSourceLocation(*F, Record[2]),
1336 ReadSourceLocation(*F, Record[3]),
1337 Record[4],
1338 ID,
1339 BaseOffset + Record[0]);
1340 break;
1341 }
1342 }
1343
1344 return false;
1345}
1346
1347std::pair<SourceLocation, StringRef> ASTReader::getModuleImportLoc(int ID) {
1348 if (ID == 0)
1349 return std::make_pair(SourceLocation(), "");
1350
1351 if (unsigned(-ID) - 2 >= getTotalNumSLocs() || ID > 0) {
1352 Error("source location entry ID out-of-range for AST file");
1353 return std::make_pair(SourceLocation(), "");
1354 }
1355
1356 // Find which module file this entry lands in.
1357 ModuleFile *M = GlobalSLocEntryMap.find(-ID)->second;
Richard Smithe842a472014-10-22 02:05:46 +00001358 if (M->Kind != MK_ImplicitModule && M->Kind != MK_ExplicitModule)
Guy Benyei11169dd2012-12-18 14:30:41 +00001359 return std::make_pair(SourceLocation(), "");
1360
1361 // FIXME: Can we map this down to a particular submodule? That would be
1362 // ideal.
Ben Langmuirbeee15e2014-04-14 18:00:01 +00001363 return std::make_pair(M->ImportLoc, StringRef(M->ModuleName));
Guy Benyei11169dd2012-12-18 14:30:41 +00001364}
1365
1366/// \brief Find the location where the module F is imported.
1367SourceLocation ASTReader::getImportLocation(ModuleFile *F) {
1368 if (F->ImportLoc.isValid())
1369 return F->ImportLoc;
1370
1371 // Otherwise we have a PCH. It's considered to be "imported" at the first
1372 // location of its includer.
1373 if (F->ImportedBy.empty() || !F->ImportedBy[0]) {
Ben Langmuirbeee15e2014-04-14 18:00:01 +00001374 // Main file is the importer.
1375 assert(!SourceMgr.getMainFileID().isInvalid() && "missing main file");
1376 return SourceMgr.getLocForStartOfFile(SourceMgr.getMainFileID());
Guy Benyei11169dd2012-12-18 14:30:41 +00001377 }
Guy Benyei11169dd2012-12-18 14:30:41 +00001378 return F->ImportedBy[0]->FirstLoc;
1379}
1380
1381/// ReadBlockAbbrevs - Enter a subblock of the specified BlockID with the
1382/// specified cursor. Read the abbreviations that are at the top of the block
1383/// and then leave the cursor pointing into the block.
Chris Lattner7fb3bef2013-01-20 00:56:42 +00001384bool ASTReader::ReadBlockAbbrevs(BitstreamCursor &Cursor, unsigned BlockID) {
Guy Benyei11169dd2012-12-18 14:30:41 +00001385 if (Cursor.EnterSubBlock(BlockID)) {
1386 Error("malformed block record in AST file");
1387 return Failure;
1388 }
1389
1390 while (true) {
1391 uint64_t Offset = Cursor.GetCurrentBitNo();
1392 unsigned Code = Cursor.ReadCode();
1393
1394 // We expect all abbrevs to be at the start of the block.
1395 if (Code != llvm::bitc::DEFINE_ABBREV) {
1396 Cursor.JumpToBit(Offset);
1397 return false;
1398 }
1399 Cursor.ReadAbbrevRecord();
1400 }
1401}
1402
Richard Smithe40f2ba2013-08-07 21:41:30 +00001403Token ASTReader::ReadToken(ModuleFile &F, const RecordDataImpl &Record,
John McCallf413f5e2013-05-03 00:10:13 +00001404 unsigned &Idx) {
1405 Token Tok;
1406 Tok.startToken();
1407 Tok.setLocation(ReadSourceLocation(F, Record, Idx));
1408 Tok.setLength(Record[Idx++]);
1409 if (IdentifierInfo *II = getLocalIdentifier(F, Record[Idx++]))
1410 Tok.setIdentifierInfo(II);
1411 Tok.setKind((tok::TokenKind)Record[Idx++]);
1412 Tok.setFlag((Token::TokenFlags)Record[Idx++]);
1413 return Tok;
1414}
1415
Argyrios Kyrtzidiseb663da2013-03-22 21:12:57 +00001416MacroInfo *ASTReader::ReadMacroRecord(ModuleFile &F, uint64_t Offset) {
Chris Lattner7fb3bef2013-01-20 00:56:42 +00001417 BitstreamCursor &Stream = F.MacroCursor;
Guy Benyei11169dd2012-12-18 14:30:41 +00001418
1419 // Keep track of where we are in the stream, then jump back there
1420 // after reading this macro.
1421 SavedStreamPosition SavedPosition(Stream);
1422
1423 Stream.JumpToBit(Offset);
1424 RecordData Record;
1425 SmallVector<IdentifierInfo*, 16> MacroArgs;
Craig Toppera13603a2014-05-22 05:54:18 +00001426 MacroInfo *Macro = nullptr;
Guy Benyei11169dd2012-12-18 14:30:41 +00001427
Guy Benyei11169dd2012-12-18 14:30:41 +00001428 while (true) {
Chris Lattnerefa77172013-01-20 00:00:22 +00001429 // Advance to the next record, but if we get to the end of the block, don't
1430 // pop it (removing all the abbreviations from the cursor) since we want to
1431 // be able to reseek within the block and read entries.
Chris Lattner7fb3bef2013-01-20 00:56:42 +00001432 unsigned Flags = BitstreamCursor::AF_DontPopBlockAtEnd;
Chris Lattnerefa77172013-01-20 00:00:22 +00001433 llvm::BitstreamEntry Entry = Stream.advanceSkippingSubblocks(Flags);
1434
1435 switch (Entry.Kind) {
1436 case llvm::BitstreamEntry::SubBlock: // Handled for us already.
1437 case llvm::BitstreamEntry::Error:
1438 Error("malformed block record in AST file");
Argyrios Kyrtzidiseb663da2013-03-22 21:12:57 +00001439 return Macro;
Chris Lattnerefa77172013-01-20 00:00:22 +00001440 case llvm::BitstreamEntry::EndBlock:
Argyrios Kyrtzidiseb663da2013-03-22 21:12:57 +00001441 return Macro;
Chris Lattnerefa77172013-01-20 00:00:22 +00001442 case llvm::BitstreamEntry::Record:
1443 // The interesting case.
1444 break;
Guy Benyei11169dd2012-12-18 14:30:41 +00001445 }
1446
1447 // Read a record.
Guy Benyei11169dd2012-12-18 14:30:41 +00001448 Record.clear();
1449 PreprocessorRecordTypes RecType =
Chris Lattner0e6c9402013-01-20 02:38:54 +00001450 (PreprocessorRecordTypes)Stream.readRecord(Entry.ID, Record);
Guy Benyei11169dd2012-12-18 14:30:41 +00001451 switch (RecType) {
Argyrios Kyrtzidiseb663da2013-03-22 21:12:57 +00001452 case PP_MACRO_DIRECTIVE_HISTORY:
1453 return Macro;
1454
Guy Benyei11169dd2012-12-18 14:30:41 +00001455 case PP_MACRO_OBJECT_LIKE:
1456 case PP_MACRO_FUNCTION_LIKE: {
1457 // If we already have a macro, that means that we've hit the end
1458 // of the definition of the macro we were looking for. We're
1459 // done.
1460 if (Macro)
Argyrios Kyrtzidiseb663da2013-03-22 21:12:57 +00001461 return Macro;
Guy Benyei11169dd2012-12-18 14:30:41 +00001462
Argyrios Kyrtzidiseb663da2013-03-22 21:12:57 +00001463 unsigned NextIndex = 1; // Skip identifier ID.
1464 SubmoduleID SubModID = getGlobalSubmoduleID(F, Record[NextIndex++]);
Guy Benyei11169dd2012-12-18 14:30:41 +00001465 SourceLocation Loc = ReadSourceLocation(F, Record, NextIndex);
Argyrios Kyrtzidiseb663da2013-03-22 21:12:57 +00001466 MacroInfo *MI = PP.AllocateDeserializedMacroInfo(Loc, SubModID);
Argyrios Kyrtzidis7572be22013-01-07 19:16:23 +00001467 MI->setDefinitionEndLoc(ReadSourceLocation(F, Record, NextIndex));
Guy Benyei11169dd2012-12-18 14:30:41 +00001468 MI->setIsUsed(Record[NextIndex++]);
Argyrios Kyrtzidis9ef53ce2014-04-09 18:21:23 +00001469 MI->setUsedForHeaderGuard(Record[NextIndex++]);
Guy Benyei11169dd2012-12-18 14:30:41 +00001470
Guy Benyei11169dd2012-12-18 14:30:41 +00001471 if (RecType == PP_MACRO_FUNCTION_LIKE) {
1472 // Decode function-like macro info.
1473 bool isC99VarArgs = Record[NextIndex++];
1474 bool isGNUVarArgs = Record[NextIndex++];
1475 bool hasCommaPasting = Record[NextIndex++];
1476 MacroArgs.clear();
1477 unsigned NumArgs = Record[NextIndex++];
1478 for (unsigned i = 0; i != NumArgs; ++i)
1479 MacroArgs.push_back(getLocalIdentifier(F, Record[NextIndex++]));
1480
1481 // Install function-like macro info.
1482 MI->setIsFunctionLike();
1483 if (isC99VarArgs) MI->setIsC99Varargs();
1484 if (isGNUVarArgs) MI->setIsGNUVarargs();
1485 if (hasCommaPasting) MI->setHasCommaPasting();
1486 MI->setArgumentList(MacroArgs.data(), MacroArgs.size(),
1487 PP.getPreprocessorAllocator());
1488 }
1489
Guy Benyei11169dd2012-12-18 14:30:41 +00001490 // Remember that we saw this macro last so that we add the tokens that
1491 // form its body to it.
1492 Macro = MI;
1493
1494 if (NextIndex + 1 == Record.size() && PP.getPreprocessingRecord() &&
1495 Record[NextIndex]) {
1496 // We have a macro definition. Register the association
1497 PreprocessedEntityID
1498 GlobalID = getGlobalPreprocessedEntityID(F, Record[NextIndex]);
1499 PreprocessingRecord &PPRec = *PP.getPreprocessingRecord();
Argyrios Kyrtzidis832de9f2013-02-22 18:35:59 +00001500 PreprocessingRecord::PPEntityID
1501 PPID = PPRec.getPPEntityID(GlobalID-1, /*isLoaded=*/true);
1502 MacroDefinition *PPDef =
1503 cast_or_null<MacroDefinition>(PPRec.getPreprocessedEntity(PPID));
1504 if (PPDef)
1505 PPRec.RegisterMacroDefinition(Macro, PPDef);
Guy Benyei11169dd2012-12-18 14:30:41 +00001506 }
1507
1508 ++NumMacrosRead;
1509 break;
1510 }
1511
1512 case PP_TOKEN: {
1513 // If we see a TOKEN before a PP_MACRO_*, then the file is
1514 // erroneous, just pretend we didn't see this.
Craig Toppera13603a2014-05-22 05:54:18 +00001515 if (!Macro) break;
Guy Benyei11169dd2012-12-18 14:30:41 +00001516
John McCallf413f5e2013-05-03 00:10:13 +00001517 unsigned Idx = 0;
1518 Token Tok = ReadToken(F, Record, Idx);
Guy Benyei11169dd2012-12-18 14:30:41 +00001519 Macro->AddTokenToBody(Tok);
1520 break;
1521 }
1522 }
1523 }
1524}
1525
1526PreprocessedEntityID
1527ASTReader::getGlobalPreprocessedEntityID(ModuleFile &M, unsigned LocalID) const {
1528 ContinuousRangeMap<uint32_t, int, 2>::const_iterator
1529 I = M.PreprocessedEntityRemap.find(LocalID - NUM_PREDEF_PP_ENTITY_IDS);
1530 assert(I != M.PreprocessedEntityRemap.end()
1531 && "Invalid index into preprocessed entity index remap");
1532
1533 return LocalID + I->second;
1534}
1535
Argyrios Kyrtzidis5c2a3452013-03-06 18:12:47 +00001536unsigned HeaderFileInfoTrait::ComputeHash(internal_key_ref ikey) {
1537 return llvm::hash_combine(ikey.Size, ikey.ModTime);
Guy Benyei11169dd2012-12-18 14:30:41 +00001538}
Richard Smith7ed1bc92014-12-05 22:42:13 +00001539
Guy Benyei11169dd2012-12-18 14:30:41 +00001540HeaderFileInfoTrait::internal_key_type
Argyrios Kyrtzidis5c2a3452013-03-06 18:12:47 +00001541HeaderFileInfoTrait::GetInternalKey(const FileEntry *FE) {
1542 internal_key_type ikey = { FE->getSize(), FE->getModificationTime(),
Richard Smith7ed1bc92014-12-05 22:42:13 +00001543 FE->getName(), /*Imported*/false };
Argyrios Kyrtzidis5c2a3452013-03-06 18:12:47 +00001544 return ikey;
1545}
Guy Benyei11169dd2012-12-18 14:30:41 +00001546
Argyrios Kyrtzidis5c2a3452013-03-06 18:12:47 +00001547bool HeaderFileInfoTrait::EqualKey(internal_key_ref a, internal_key_ref b) {
1548 if (a.Size != b.Size || a.ModTime != b.ModTime)
Guy Benyei11169dd2012-12-18 14:30:41 +00001549 return false;
1550
Richard Smith7ed1bc92014-12-05 22:42:13 +00001551 if (llvm::sys::path::is_absolute(a.Filename) &&
1552 strcmp(a.Filename, b.Filename) == 0)
Argyrios Kyrtzidis5c2a3452013-03-06 18:12:47 +00001553 return true;
1554
Guy Benyei11169dd2012-12-18 14:30:41 +00001555 // Determine whether the actual files are equivalent.
Argyrios Kyrtzidis2a513e82013-03-04 20:33:40 +00001556 FileManager &FileMgr = Reader.getFileManager();
Richard Smith7ed1bc92014-12-05 22:42:13 +00001557 auto GetFile = [&](const internal_key_type &Key) -> const FileEntry* {
1558 if (!Key.Imported)
1559 return FileMgr.getFile(Key.Filename);
1560
1561 std::string Resolved = Key.Filename;
1562 Reader.ResolveImportedPath(M, Resolved);
1563 return FileMgr.getFile(Resolved);
1564 };
1565
1566 const FileEntry *FEA = GetFile(a);
1567 const FileEntry *FEB = GetFile(b);
1568 return FEA && FEA == FEB;
Guy Benyei11169dd2012-12-18 14:30:41 +00001569}
1570
1571std::pair<unsigned, unsigned>
1572HeaderFileInfoTrait::ReadKeyDataLength(const unsigned char*& d) {
Justin Bogner57ba0b22014-03-28 22:03:24 +00001573 using namespace llvm::support;
1574 unsigned KeyLen = (unsigned) endian::readNext<uint16_t, little, unaligned>(d);
Guy Benyei11169dd2012-12-18 14:30:41 +00001575 unsigned DataLen = (unsigned) *d++;
Argyrios Kyrtzidis5c2a3452013-03-06 18:12:47 +00001576 return std::make_pair(KeyLen, DataLen);
Guy Benyei11169dd2012-12-18 14:30:41 +00001577}
Argyrios Kyrtzidis5c2a3452013-03-06 18:12:47 +00001578
1579HeaderFileInfoTrait::internal_key_type
1580HeaderFileInfoTrait::ReadKey(const unsigned char *d, unsigned) {
Justin Bogner57ba0b22014-03-28 22:03:24 +00001581 using namespace llvm::support;
Argyrios Kyrtzidis5c2a3452013-03-06 18:12:47 +00001582 internal_key_type ikey;
Justin Bogner57ba0b22014-03-28 22:03:24 +00001583 ikey.Size = off_t(endian::readNext<uint64_t, little, unaligned>(d));
1584 ikey.ModTime = time_t(endian::readNext<uint64_t, little, unaligned>(d));
Argyrios Kyrtzidis5c2a3452013-03-06 18:12:47 +00001585 ikey.Filename = (const char *)d;
Richard Smith7ed1bc92014-12-05 22:42:13 +00001586 ikey.Imported = true;
Argyrios Kyrtzidis5c2a3452013-03-06 18:12:47 +00001587 return ikey;
1588}
1589
Guy Benyei11169dd2012-12-18 14:30:41 +00001590HeaderFileInfoTrait::data_type
Argyrios Kyrtzidisb146baa2013-03-13 21:13:51 +00001591HeaderFileInfoTrait::ReadData(internal_key_ref key, const unsigned char *d,
Guy Benyei11169dd2012-12-18 14:30:41 +00001592 unsigned DataLen) {
1593 const unsigned char *End = d + DataLen;
Justin Bogner57ba0b22014-03-28 22:03:24 +00001594 using namespace llvm::support;
Guy Benyei11169dd2012-12-18 14:30:41 +00001595 HeaderFileInfo HFI;
1596 unsigned Flags = *d++;
Lawrence Crowlb53e5482013-06-20 21:14:14 +00001597 HFI.HeaderRole = static_cast<ModuleMap::ModuleHeaderRole>
1598 ((Flags >> 6) & 0x03);
Guy Benyei11169dd2012-12-18 14:30:41 +00001599 HFI.isImport = (Flags >> 5) & 0x01;
1600 HFI.isPragmaOnce = (Flags >> 4) & 0x01;
1601 HFI.DirInfo = (Flags >> 2) & 0x03;
1602 HFI.Resolved = (Flags >> 1) & 0x01;
1603 HFI.IndexHeaderMapHeader = Flags & 0x01;
Justin Bogner57ba0b22014-03-28 22:03:24 +00001604 HFI.NumIncludes = endian::readNext<uint16_t, little, unaligned>(d);
1605 HFI.ControllingMacroID = Reader.getGlobalIdentifierID(
1606 M, endian::readNext<uint32_t, little, unaligned>(d));
1607 if (unsigned FrameworkOffset =
1608 endian::readNext<uint32_t, little, unaligned>(d)) {
Guy Benyei11169dd2012-12-18 14:30:41 +00001609 // The framework offset is 1 greater than the actual offset,
1610 // since 0 is used as an indicator for "no framework name".
1611 StringRef FrameworkName(FrameworkStrings + FrameworkOffset - 1);
1612 HFI.Framework = HS->getUniqueFrameworkName(FrameworkName);
1613 }
1614
Argyrios Kyrtzidisb146baa2013-03-13 21:13:51 +00001615 if (d != End) {
Justin Bogner57ba0b22014-03-28 22:03:24 +00001616 uint32_t LocalSMID = endian::readNext<uint32_t, little, unaligned>(d);
Argyrios Kyrtzidisb146baa2013-03-13 21:13:51 +00001617 if (LocalSMID) {
1618 // This header is part of a module. Associate it with the module to enable
1619 // implicit module import.
1620 SubmoduleID GlobalSMID = Reader.getGlobalSubmoduleID(M, LocalSMID);
1621 Module *Mod = Reader.getSubmodule(GlobalSMID);
1622 HFI.isModuleHeader = true;
1623 FileManager &FileMgr = Reader.getFileManager();
1624 ModuleMap &ModMap =
1625 Reader.getPreprocessor().getHeaderSearchInfo().getModuleMap();
Richard Smith7ed1bc92014-12-05 22:42:13 +00001626 // FIXME: This information should be propagated through the
1627 // SUBMODULE_HEADER etc records rather than from here.
Richard Smith3c1a41a2014-12-02 00:08:08 +00001628 // FIXME: We don't ever mark excluded headers.
Richard Smith7ed1bc92014-12-05 22:42:13 +00001629 std::string Filename = key.Filename;
1630 if (key.Imported)
1631 Reader.ResolveImportedPath(M, Filename);
1632 Module::Header H = { key.Filename, FileMgr.getFile(Filename) };
Hans Wennborg0101b542014-12-02 02:13:09 +00001633 ModMap.addHeader(Mod, H, HFI.getHeaderRole());
Argyrios Kyrtzidisb146baa2013-03-13 21:13:51 +00001634 }
1635 }
1636
Guy Benyei11169dd2012-12-18 14:30:41 +00001637 assert(End == d && "Wrong data length in HeaderFileInfo deserialization");
1638 (void)End;
1639
1640 // This HeaderFileInfo was externally loaded.
1641 HFI.External = true;
1642 return HFI;
1643}
1644
Richard Smith49f906a2014-03-01 00:08:04 +00001645void
1646ASTReader::addPendingMacroFromModule(IdentifierInfo *II, ModuleFile *M,
1647 GlobalMacroID GMacID,
Craig Topper00bbdcf2014-06-28 23:22:23 +00001648 ArrayRef<SubmoduleID> Overrides) {
Guy Benyei11169dd2012-12-18 14:30:41 +00001649 assert(NumCurrentElementsDeserializing > 0 &&"Missing deserialization guard");
Craig Toppera13603a2014-05-22 05:54:18 +00001650 SubmoduleID *OverrideData = nullptr;
Richard Smith49f906a2014-03-01 00:08:04 +00001651 if (!Overrides.empty()) {
1652 OverrideData = new (Context) SubmoduleID[Overrides.size() + 1];
1653 OverrideData[0] = Overrides.size();
1654 for (unsigned I = 0; I != Overrides.size(); ++I)
1655 OverrideData[I + 1] = getGlobalSubmoduleID(*M, Overrides[I]);
1656 }
1657 PendingMacroIDs[II].push_back(PendingMacroInfo(M, GMacID, OverrideData));
Argyrios Kyrtzidiseb663da2013-03-22 21:12:57 +00001658}
1659
1660void ASTReader::addPendingMacroFromPCH(IdentifierInfo *II,
1661 ModuleFile *M,
1662 uint64_t MacroDirectivesOffset) {
1663 assert(NumCurrentElementsDeserializing > 0 &&"Missing deserialization guard");
1664 PendingMacroIDs[II].push_back(PendingMacroInfo(M, MacroDirectivesOffset));
Guy Benyei11169dd2012-12-18 14:30:41 +00001665}
1666
1667void ASTReader::ReadDefinedMacros() {
1668 // Note that we are loading defined macros.
1669 Deserializing Macros(this);
1670
1671 for (ModuleReverseIterator I = ModuleMgr.rbegin(),
1672 E = ModuleMgr.rend(); I != E; ++I) {
Chris Lattner7fb3bef2013-01-20 00:56:42 +00001673 BitstreamCursor &MacroCursor = (*I)->MacroCursor;
Guy Benyei11169dd2012-12-18 14:30:41 +00001674
1675 // If there was no preprocessor block, skip this file.
1676 if (!MacroCursor.getBitStreamReader())
1677 continue;
1678
Chris Lattner7fb3bef2013-01-20 00:56:42 +00001679 BitstreamCursor Cursor = MacroCursor;
Guy Benyei11169dd2012-12-18 14:30:41 +00001680 Cursor.JumpToBit((*I)->MacroStartOffset);
1681
1682 RecordData Record;
1683 while (true) {
Chris Lattnere7b154b2013-01-19 21:39:22 +00001684 llvm::BitstreamEntry E = Cursor.advanceSkippingSubblocks();
1685
1686 switch (E.Kind) {
1687 case llvm::BitstreamEntry::SubBlock: // Handled for us already.
1688 case llvm::BitstreamEntry::Error:
1689 Error("malformed block record in AST file");
1690 return;
1691 case llvm::BitstreamEntry::EndBlock:
1692 goto NextCursor;
1693
1694 case llvm::BitstreamEntry::Record:
Chris Lattnere7b154b2013-01-19 21:39:22 +00001695 Record.clear();
Chris Lattner0e6c9402013-01-20 02:38:54 +00001696 switch (Cursor.readRecord(E.ID, Record)) {
Chris Lattnere7b154b2013-01-19 21:39:22 +00001697 default: // Default behavior: ignore.
1698 break;
1699
1700 case PP_MACRO_OBJECT_LIKE:
1701 case PP_MACRO_FUNCTION_LIKE:
1702 getLocalIdentifier(**I, Record[0]);
1703 break;
1704
1705 case PP_TOKEN:
1706 // Ignore tokens.
1707 break;
Guy Benyei11169dd2012-12-18 14:30:41 +00001708 }
Guy Benyei11169dd2012-12-18 14:30:41 +00001709 break;
1710 }
1711 }
Chris Lattnere7b154b2013-01-19 21:39:22 +00001712 NextCursor: ;
Guy Benyei11169dd2012-12-18 14:30:41 +00001713 }
1714}
1715
1716namespace {
1717 /// \brief Visitor class used to look up identifirs in an AST file.
1718 class IdentifierLookupVisitor {
1719 StringRef Name;
1720 unsigned PriorGeneration;
Douglas Gregor00a50f72013-01-25 00:38:33 +00001721 unsigned &NumIdentifierLookups;
1722 unsigned &NumIdentifierLookupHits;
Guy Benyei11169dd2012-12-18 14:30:41 +00001723 IdentifierInfo *Found;
Douglas Gregor00a50f72013-01-25 00:38:33 +00001724
Guy Benyei11169dd2012-12-18 14:30:41 +00001725 public:
Douglas Gregor00a50f72013-01-25 00:38:33 +00001726 IdentifierLookupVisitor(StringRef Name, unsigned PriorGeneration,
1727 unsigned &NumIdentifierLookups,
1728 unsigned &NumIdentifierLookupHits)
Douglas Gregor7211ac12013-01-25 23:32:03 +00001729 : Name(Name), PriorGeneration(PriorGeneration),
Douglas Gregor00a50f72013-01-25 00:38:33 +00001730 NumIdentifierLookups(NumIdentifierLookups),
1731 NumIdentifierLookupHits(NumIdentifierLookupHits),
1732 Found()
1733 {
1734 }
Guy Benyei11169dd2012-12-18 14:30:41 +00001735
1736 static bool visit(ModuleFile &M, void *UserData) {
1737 IdentifierLookupVisitor *This
1738 = static_cast<IdentifierLookupVisitor *>(UserData);
1739
1740 // If we've already searched this module file, skip it now.
1741 if (M.Generation <= This->PriorGeneration)
1742 return true;
Douglas Gregore060e572013-01-25 01:03:03 +00001743
Guy Benyei11169dd2012-12-18 14:30:41 +00001744 ASTIdentifierLookupTable *IdTable
1745 = (ASTIdentifierLookupTable *)M.IdentifierLookupTable;
1746 if (!IdTable)
1747 return false;
1748
1749 ASTIdentifierLookupTrait Trait(IdTable->getInfoObj().getReader(),
1750 M, This->Found);
Douglas Gregor00a50f72013-01-25 00:38:33 +00001751 ++This->NumIdentifierLookups;
1752 ASTIdentifierLookupTable::iterator Pos = IdTable->find(This->Name,&Trait);
Guy Benyei11169dd2012-12-18 14:30:41 +00001753 if (Pos == IdTable->end())
1754 return false;
1755
1756 // Dereferencing the iterator has the effect of building the
1757 // IdentifierInfo node and populating it with the various
1758 // declarations it needs.
Douglas Gregor00a50f72013-01-25 00:38:33 +00001759 ++This->NumIdentifierLookupHits;
Guy Benyei11169dd2012-12-18 14:30:41 +00001760 This->Found = *Pos;
1761 return true;
1762 }
1763
1764 // \brief Retrieve the identifier info found within the module
1765 // files.
1766 IdentifierInfo *getIdentifierInfo() const { return Found; }
1767 };
1768}
1769
1770void ASTReader::updateOutOfDateIdentifier(IdentifierInfo &II) {
1771 // Note that we are loading an identifier.
1772 Deserializing AnIdentifier(this);
1773
1774 unsigned PriorGeneration = 0;
1775 if (getContext().getLangOpts().Modules)
1776 PriorGeneration = IdentifierGeneration[&II];
Douglas Gregore060e572013-01-25 01:03:03 +00001777
1778 // If there is a global index, look there first to determine which modules
1779 // provably do not have any results for this identifier.
Douglas Gregor7211ac12013-01-25 23:32:03 +00001780 GlobalModuleIndex::HitSet Hits;
Craig Toppera13603a2014-05-22 05:54:18 +00001781 GlobalModuleIndex::HitSet *HitsPtr = nullptr;
Douglas Gregore060e572013-01-25 01:03:03 +00001782 if (!loadGlobalIndex()) {
Douglas Gregor7211ac12013-01-25 23:32:03 +00001783 if (GlobalIndex->lookupIdentifier(II.getName(), Hits)) {
1784 HitsPtr = &Hits;
Douglas Gregore060e572013-01-25 01:03:03 +00001785 }
1786 }
1787
Douglas Gregor7211ac12013-01-25 23:32:03 +00001788 IdentifierLookupVisitor Visitor(II.getName(), PriorGeneration,
Douglas Gregor00a50f72013-01-25 00:38:33 +00001789 NumIdentifierLookups,
1790 NumIdentifierLookupHits);
Douglas Gregor7211ac12013-01-25 23:32:03 +00001791 ModuleMgr.visit(IdentifierLookupVisitor::visit, &Visitor, HitsPtr);
Guy Benyei11169dd2012-12-18 14:30:41 +00001792 markIdentifierUpToDate(&II);
1793}
1794
1795void ASTReader::markIdentifierUpToDate(IdentifierInfo *II) {
1796 if (!II)
1797 return;
1798
1799 II->setOutOfDate(false);
1800
1801 // Update the generation for this identifier.
1802 if (getContext().getLangOpts().Modules)
Richard Smith053f6c62014-05-16 23:01:30 +00001803 IdentifierGeneration[II] = getGeneration();
Guy Benyei11169dd2012-12-18 14:30:41 +00001804}
1805
Richard Smith49f906a2014-03-01 00:08:04 +00001806struct ASTReader::ModuleMacroInfo {
1807 SubmoduleID SubModID;
1808 MacroInfo *MI;
1809 SubmoduleID *Overrides;
1810 // FIXME: Remove this.
1811 ModuleFile *F;
1812
1813 bool isDefine() const { return MI; }
1814
1815 SubmoduleID getSubmoduleID() const { return SubModID; }
1816
Craig Topper00bbdcf2014-06-28 23:22:23 +00001817 ArrayRef<SubmoduleID> getOverriddenSubmodules() const {
Richard Smith49f906a2014-03-01 00:08:04 +00001818 if (!Overrides)
Craig Topper00bbdcf2014-06-28 23:22:23 +00001819 return None;
Richard Smith49f906a2014-03-01 00:08:04 +00001820 return llvm::makeArrayRef(Overrides + 1, *Overrides);
1821 }
1822
Richard Smithdaa69e02014-07-25 04:40:03 +00001823 MacroDirective *import(Preprocessor &PP, SourceLocation ImportLoc) const {
Richard Smith49f906a2014-03-01 00:08:04 +00001824 if (!MI)
Richard Smithdaa69e02014-07-25 04:40:03 +00001825 return PP.AllocateUndefMacroDirective(ImportLoc, SubModID,
1826 getOverriddenSubmodules());
1827 return PP.AllocateDefMacroDirective(MI, ImportLoc, SubModID,
1828 getOverriddenSubmodules());
Richard Smith49f906a2014-03-01 00:08:04 +00001829 }
1830};
1831
1832ASTReader::ModuleMacroInfo *
1833ASTReader::getModuleMacro(const PendingMacroInfo &PMInfo) {
1834 ModuleMacroInfo Info;
1835
1836 uint32_t ID = PMInfo.ModuleMacroData.MacID;
1837 if (ID & 1) {
1838 // Macro undefinition.
1839 Info.SubModID = getGlobalSubmoduleID(*PMInfo.M, ID >> 1);
Craig Toppera13603a2014-05-22 05:54:18 +00001840 Info.MI = nullptr;
Richard Smith49f906a2014-03-01 00:08:04 +00001841 } else {
1842 // Macro definition.
1843 GlobalMacroID GMacID = getGlobalMacroID(*PMInfo.M, ID >> 1);
1844 assert(GMacID);
1845
1846 // If this macro has already been loaded, don't do so again.
1847 // FIXME: This is highly dubious. Multiple macro definitions can have the
1848 // same MacroInfo (and hence the same GMacID) due to #pragma push_macro etc.
1849 if (MacrosLoaded[GMacID - NUM_PREDEF_MACRO_IDS])
Craig Toppera13603a2014-05-22 05:54:18 +00001850 return nullptr;
Richard Smith49f906a2014-03-01 00:08:04 +00001851
1852 Info.MI = getMacro(GMacID);
1853 Info.SubModID = Info.MI->getOwningModuleID();
1854 }
1855 Info.Overrides = PMInfo.ModuleMacroData.Overrides;
1856 Info.F = PMInfo.M;
1857
1858 return new (Context) ModuleMacroInfo(Info);
1859}
1860
Argyrios Kyrtzidiseb663da2013-03-22 21:12:57 +00001861void ASTReader::resolvePendingMacro(IdentifierInfo *II,
1862 const PendingMacroInfo &PMInfo) {
1863 assert(II);
1864
Richard Smithe842a472014-10-22 02:05:46 +00001865 if (PMInfo.M->Kind != MK_ImplicitModule &&
1866 PMInfo.M->Kind != MK_ExplicitModule) {
Argyrios Kyrtzidiseb663da2013-03-22 21:12:57 +00001867 installPCHMacroDirectives(II, *PMInfo.M,
1868 PMInfo.PCHMacroData.MacroDirectivesOffset);
1869 return;
1870 }
Richard Smith49f906a2014-03-01 00:08:04 +00001871
Argyrios Kyrtzidiseb663da2013-03-22 21:12:57 +00001872 // Module Macro.
1873
Richard Smith49f906a2014-03-01 00:08:04 +00001874 ModuleMacroInfo *MMI = getModuleMacro(PMInfo);
1875 if (!MMI)
Argyrios Kyrtzidiseb663da2013-03-22 21:12:57 +00001876 return;
1877
Richard Smith49f906a2014-03-01 00:08:04 +00001878 Module *Owner = getSubmodule(MMI->getSubmoduleID());
1879 if (Owner && Owner->NameVisibility == Module::Hidden) {
1880 // Macros in the owning module are hidden. Just remember this macro to
1881 // install if we make this module visible.
1882 HiddenNamesMap[Owner].HiddenMacros.insert(std::make_pair(II, MMI));
1883 } else {
Richard Smithdaa69e02014-07-25 04:40:03 +00001884 installImportedMacro(II, MMI, Owner);
Argyrios Kyrtzidiseb663da2013-03-22 21:12:57 +00001885 }
Argyrios Kyrtzidiseb663da2013-03-22 21:12:57 +00001886}
1887
1888void ASTReader::installPCHMacroDirectives(IdentifierInfo *II,
1889 ModuleFile &M, uint64_t Offset) {
Richard Smithe842a472014-10-22 02:05:46 +00001890 assert(M.Kind != MK_ImplicitModule && M.Kind != MK_ExplicitModule);
Argyrios Kyrtzidiseb663da2013-03-22 21:12:57 +00001891
1892 BitstreamCursor &Cursor = M.MacroCursor;
1893 SavedStreamPosition SavedPosition(Cursor);
1894 Cursor.JumpToBit(Offset);
1895
1896 llvm::BitstreamEntry Entry =
1897 Cursor.advance(BitstreamCursor::AF_DontPopBlockAtEnd);
1898 if (Entry.Kind != llvm::BitstreamEntry::Record) {
1899 Error("malformed block record in AST file");
1900 return;
1901 }
1902
1903 RecordData Record;
1904 PreprocessorRecordTypes RecType =
1905 (PreprocessorRecordTypes)Cursor.readRecord(Entry.ID, Record);
1906 if (RecType != PP_MACRO_DIRECTIVE_HISTORY) {
1907 Error("malformed block record in AST file");
1908 return;
1909 }
1910
1911 // Deserialize the macro directives history in reverse source-order.
Craig Toppera13603a2014-05-22 05:54:18 +00001912 MacroDirective *Latest = nullptr, *Earliest = nullptr;
Argyrios Kyrtzidiseb663da2013-03-22 21:12:57 +00001913 unsigned Idx = 0, N = Record.size();
1914 while (Idx < N) {
Craig Toppera13603a2014-05-22 05:54:18 +00001915 MacroDirective *MD = nullptr;
Argyrios Kyrtzidiseb663da2013-03-22 21:12:57 +00001916 SourceLocation Loc = ReadSourceLocation(M, Record, Idx);
Argyrios Kyrtzidisb6210df2013-03-26 17:17:01 +00001917 MacroDirective::Kind K = (MacroDirective::Kind)Record[Idx++];
1918 switch (K) {
1919 case MacroDirective::MD_Define: {
1920 GlobalMacroID GMacID = getGlobalMacroID(M, Record[Idx++]);
1921 MacroInfo *MI = getMacro(GMacID);
Richard Smithdaa69e02014-07-25 04:40:03 +00001922 SubmoduleID ImportedFrom = Record[Idx++];
1923 bool IsAmbiguous = Record[Idx++];
1924 llvm::SmallVector<unsigned, 4> Overrides;
1925 if (ImportedFrom) {
1926 Overrides.insert(Overrides.end(),
1927 &Record[Idx] + 1, &Record[Idx] + 1 + Record[Idx]);
1928 Idx += Overrides.size() + 1;
1929 }
Argyrios Kyrtzidisb6210df2013-03-26 17:17:01 +00001930 DefMacroDirective *DefMD =
Richard Smithdaa69e02014-07-25 04:40:03 +00001931 PP.AllocateDefMacroDirective(MI, Loc, ImportedFrom, Overrides);
1932 DefMD->setAmbiguous(IsAmbiguous);
Argyrios Kyrtzidisb6210df2013-03-26 17:17:01 +00001933 MD = DefMD;
1934 break;
1935 }
Richard Smithdaa69e02014-07-25 04:40:03 +00001936 case MacroDirective::MD_Undefine: {
1937 SubmoduleID ImportedFrom = Record[Idx++];
1938 llvm::SmallVector<unsigned, 4> Overrides;
1939 if (ImportedFrom) {
1940 Overrides.insert(Overrides.end(),
1941 &Record[Idx] + 1, &Record[Idx] + 1 + Record[Idx]);
1942 Idx += Overrides.size() + 1;
1943 }
1944 MD = PP.AllocateUndefMacroDirective(Loc, ImportedFrom, Overrides);
Argyrios Kyrtzidisb6210df2013-03-26 17:17:01 +00001945 break;
Richard Smithdaa69e02014-07-25 04:40:03 +00001946 }
1947 case MacroDirective::MD_Visibility:
Argyrios Kyrtzidisb6210df2013-03-26 17:17:01 +00001948 bool isPublic = Record[Idx++];
1949 MD = PP.AllocateVisibilityMacroDirective(Loc, isPublic);
1950 break;
1951 }
Argyrios Kyrtzidiseb663da2013-03-22 21:12:57 +00001952
1953 if (!Latest)
1954 Latest = MD;
1955 if (Earliest)
1956 Earliest->setPrevious(MD);
1957 Earliest = MD;
1958 }
1959
1960 PP.setLoadedMacroDirective(II, Latest);
1961}
1962
Argyrios Kyrtzidis3a9c42c2013-03-27 01:25:34 +00001963/// \brief For the given macro definitions, check if they are both in system
Douglas Gregor0b202052013-04-12 21:00:54 +00001964/// modules.
1965static bool areDefinedInSystemModules(MacroInfo *PrevMI, MacroInfo *NewMI,
Douglas Gregor5e461192013-06-07 22:56:11 +00001966 Module *NewOwner, ASTReader &Reader) {
Argyrios Kyrtzidis3a9c42c2013-03-27 01:25:34 +00001967 assert(PrevMI && NewMI);
Craig Toppera13603a2014-05-22 05:54:18 +00001968 Module *PrevOwner = nullptr;
Argyrios Kyrtzidis3a9c42c2013-03-27 01:25:34 +00001969 if (SubmoduleID PrevModID = PrevMI->getOwningModuleID())
1970 PrevOwner = Reader.getSubmodule(PrevModID);
Douglas Gregor5e461192013-06-07 22:56:11 +00001971 SourceManager &SrcMgr = Reader.getSourceManager();
1972 bool PrevInSystem
1973 = PrevOwner? PrevOwner->IsSystem
1974 : SrcMgr.isInSystemHeader(PrevMI->getDefinitionLoc());
1975 bool NewInSystem
1976 = NewOwner? NewOwner->IsSystem
1977 : SrcMgr.isInSystemHeader(NewMI->getDefinitionLoc());
1978 if (PrevOwner && PrevOwner == NewOwner)
Argyrios Kyrtzidis3a9c42c2013-03-27 01:25:34 +00001979 return false;
Douglas Gregor5e461192013-06-07 22:56:11 +00001980 return PrevInSystem && NewInSystem;
Argyrios Kyrtzidis3a9c42c2013-03-27 01:25:34 +00001981}
1982
Richard Smith49f906a2014-03-01 00:08:04 +00001983void ASTReader::removeOverriddenMacros(IdentifierInfo *II,
Richard Smithdaa69e02014-07-25 04:40:03 +00001984 SourceLocation ImportLoc,
Richard Smith49f906a2014-03-01 00:08:04 +00001985 AmbiguousMacros &Ambig,
Craig Topper00bbdcf2014-06-28 23:22:23 +00001986 ArrayRef<SubmoduleID> Overrides) {
Richard Smith49f906a2014-03-01 00:08:04 +00001987 for (unsigned OI = 0, ON = Overrides.size(); OI != ON; ++OI) {
1988 SubmoduleID OwnerID = Overrides[OI];
Argyrios Kyrtzidiseb663da2013-03-22 21:12:57 +00001989
Richard Smith49f906a2014-03-01 00:08:04 +00001990 // If this macro is not yet visible, remove it from the hidden names list.
Richard Smithbb853c72014-08-13 01:23:33 +00001991 // It won't be there if we're in the middle of making the owner visible.
Richard Smith49f906a2014-03-01 00:08:04 +00001992 Module *Owner = getSubmodule(OwnerID);
Richard Smithbb853c72014-08-13 01:23:33 +00001993 auto HiddenIt = HiddenNamesMap.find(Owner);
1994 if (HiddenIt != HiddenNamesMap.end()) {
1995 HiddenNames &Hidden = HiddenIt->second;
1996 HiddenMacrosMap::iterator HI = Hidden.HiddenMacros.find(II);
1997 if (HI != Hidden.HiddenMacros.end()) {
1998 // Register the macro now so we don't lose it when we re-export.
1999 PP.appendMacroDirective(II, HI->second->import(PP, ImportLoc));
Richard Smithdaa69e02014-07-25 04:40:03 +00002000
Richard Smithbb853c72014-08-13 01:23:33 +00002001 auto SubOverrides = HI->second->getOverriddenSubmodules();
2002 Hidden.HiddenMacros.erase(HI);
2003 removeOverriddenMacros(II, ImportLoc, Ambig, SubOverrides);
2004 }
Richard Smith49f906a2014-03-01 00:08:04 +00002005 }
2006
2007 // If this macro is already in our list of conflicts, remove it from there.
Richard Smithbb29e512014-03-06 00:33:23 +00002008 Ambig.erase(
2009 std::remove_if(Ambig.begin(), Ambig.end(), [&](DefMacroDirective *MD) {
2010 return MD->getInfo()->getOwningModuleID() == OwnerID;
2011 }),
2012 Ambig.end());
Richard Smith49f906a2014-03-01 00:08:04 +00002013 }
2014}
2015
2016ASTReader::AmbiguousMacros *
2017ASTReader::removeOverriddenMacros(IdentifierInfo *II,
Richard Smithdaa69e02014-07-25 04:40:03 +00002018 SourceLocation ImportLoc,
Craig Topper00bbdcf2014-06-28 23:22:23 +00002019 ArrayRef<SubmoduleID> Overrides) {
Argyrios Kyrtzidiseb663da2013-03-22 21:12:57 +00002020 MacroDirective *Prev = PP.getMacroDirective(II);
Richard Smith49f906a2014-03-01 00:08:04 +00002021 if (!Prev && Overrides.empty())
Craig Toppera13603a2014-05-22 05:54:18 +00002022 return nullptr;
Richard Smith49f906a2014-03-01 00:08:04 +00002023
Craig Toppera13603a2014-05-22 05:54:18 +00002024 DefMacroDirective *PrevDef = Prev ? Prev->getDefinition().getDirective()
2025 : nullptr;
Richard Smith49f906a2014-03-01 00:08:04 +00002026 if (PrevDef && PrevDef->isAmbiguous()) {
2027 // We had a prior ambiguity. Check whether we resolve it (or make it worse).
2028 AmbiguousMacros &Ambig = AmbiguousMacroDefs[II];
2029 Ambig.push_back(PrevDef);
2030
Richard Smithdaa69e02014-07-25 04:40:03 +00002031 removeOverriddenMacros(II, ImportLoc, Ambig, Overrides);
Richard Smith49f906a2014-03-01 00:08:04 +00002032
2033 if (!Ambig.empty())
2034 return &Ambig;
2035
2036 AmbiguousMacroDefs.erase(II);
2037 } else {
2038 // There's no ambiguity yet. Maybe we're introducing one.
Benjamin Kramer834652a2014-05-03 18:44:26 +00002039 AmbiguousMacros Ambig;
Richard Smith49f906a2014-03-01 00:08:04 +00002040 if (PrevDef)
2041 Ambig.push_back(PrevDef);
2042
Richard Smithdaa69e02014-07-25 04:40:03 +00002043 removeOverriddenMacros(II, ImportLoc, Ambig, Overrides);
Richard Smith49f906a2014-03-01 00:08:04 +00002044
2045 if (!Ambig.empty()) {
2046 AmbiguousMacros &Result = AmbiguousMacroDefs[II];
Benjamin Kramer834652a2014-05-03 18:44:26 +00002047 std::swap(Result, Ambig);
Richard Smith49f906a2014-03-01 00:08:04 +00002048 return &Result;
Argyrios Kyrtzidisb6210df2013-03-26 17:17:01 +00002049 }
Argyrios Kyrtzidiseb663da2013-03-22 21:12:57 +00002050 }
Richard Smith49f906a2014-03-01 00:08:04 +00002051
2052 // We ended up with no ambiguity.
Craig Toppera13603a2014-05-22 05:54:18 +00002053 return nullptr;
Richard Smith49f906a2014-03-01 00:08:04 +00002054}
2055
2056void ASTReader::installImportedMacro(IdentifierInfo *II, ModuleMacroInfo *MMI,
Richard Smithdaa69e02014-07-25 04:40:03 +00002057 Module *Owner) {
Richard Smith49f906a2014-03-01 00:08:04 +00002058 assert(II && Owner);
2059
2060 SourceLocation ImportLoc = Owner->MacroVisibilityLoc;
Richard Smithdaa69e02014-07-25 04:40:03 +00002061 if (ImportLoc.isInvalid()) {
Richard Smith49f906a2014-03-01 00:08:04 +00002062 // FIXME: If we made macros from this module visible but didn't provide a
2063 // source location for the import, we don't have a location for the macro.
2064 // Use the location at which the containing module file was first imported
2065 // for now.
2066 ImportLoc = MMI->F->DirectImportLoc;
Richard Smith56be7542014-03-21 00:33:59 +00002067 assert(ImportLoc.isValid() && "no import location for a visible macro?");
Richard Smith49f906a2014-03-01 00:08:04 +00002068 }
2069
Benjamin Kramer834652a2014-05-03 18:44:26 +00002070 AmbiguousMacros *Prev =
Richard Smithdaa69e02014-07-25 04:40:03 +00002071 removeOverriddenMacros(II, ImportLoc, MMI->getOverriddenSubmodules());
Richard Smith49f906a2014-03-01 00:08:04 +00002072
Richard Smith49f906a2014-03-01 00:08:04 +00002073 // Create a synthetic macro definition corresponding to the import (or null
2074 // if this was an undefinition of the macro).
Richard Smithdaa69e02014-07-25 04:40:03 +00002075 MacroDirective *Imported = MMI->import(PP, ImportLoc);
2076 DefMacroDirective *MD = dyn_cast<DefMacroDirective>(Imported);
Richard Smith49f906a2014-03-01 00:08:04 +00002077
2078 // If there's no ambiguity, just install the macro.
2079 if (!Prev) {
Richard Smithdaa69e02014-07-25 04:40:03 +00002080 PP.appendMacroDirective(II, Imported);
Richard Smith49f906a2014-03-01 00:08:04 +00002081 return;
2082 }
2083 assert(!Prev->empty());
2084
2085 if (!MD) {
2086 // We imported a #undef that didn't remove all prior definitions. The most
2087 // recent prior definition remains, and we install it in the place of the
Richard Smithdaa69e02014-07-25 04:40:03 +00002088 // imported directive, as if by a local #pragma pop_macro.
Richard Smith49f906a2014-03-01 00:08:04 +00002089 MacroInfo *NewMI = Prev->back()->getInfo();
2090 Prev->pop_back();
Richard Smithdaa69e02014-07-25 04:40:03 +00002091 MD = PP.AllocateDefMacroDirective(NewMI, ImportLoc);
2092
2093 // Install our #undef first so that we don't lose track of it. We'll replace
2094 // this with whichever macro definition ends up winning.
2095 PP.appendMacroDirective(II, Imported);
Richard Smith49f906a2014-03-01 00:08:04 +00002096 }
2097
2098 // We're introducing a macro definition that creates or adds to an ambiguity.
2099 // We can resolve that ambiguity if this macro is token-for-token identical to
2100 // all of the existing definitions.
2101 MacroInfo *NewMI = MD->getInfo();
2102 assert(NewMI && "macro definition with no MacroInfo?");
2103 while (!Prev->empty()) {
2104 MacroInfo *PrevMI = Prev->back()->getInfo();
2105 assert(PrevMI && "macro definition with no MacroInfo?");
2106
2107 // Before marking the macros as ambiguous, check if this is a case where
2108 // both macros are in system headers. If so, we trust that the system
2109 // did not get it wrong. This also handles cases where Clang's own
2110 // headers have a different spelling of certain system macros:
2111 // #define LONG_MAX __LONG_MAX__ (clang's limits.h)
2112 // #define LONG_MAX 0x7fffffffffffffffL (system's limits.h)
2113 //
2114 // FIXME: Remove the defined-in-system-headers check. clang's limits.h
2115 // overrides the system limits.h's macros, so there's no conflict here.
2116 if (NewMI != PrevMI &&
2117 !PrevMI->isIdenticalTo(*NewMI, PP, /*Syntactically=*/true) &&
2118 !areDefinedInSystemModules(PrevMI, NewMI, Owner, *this))
2119 break;
2120
2121 // The previous definition is the same as this one (or both are defined in
2122 // system modules so we can assume they're equivalent); we don't need to
2123 // track it any more.
2124 Prev->pop_back();
2125 }
2126
2127 if (!Prev->empty())
2128 MD->setAmbiguous(true);
2129
Argyrios Kyrtzidisb6210df2013-03-26 17:17:01 +00002130 PP.appendMacroDirective(II, MD);
Argyrios Kyrtzidiseb663da2013-03-22 21:12:57 +00002131}
2132
Argyrios Kyrtzidisce9b49e2014-03-14 02:26:27 +00002133ASTReader::InputFileInfo
2134ASTReader::readInputFileInfo(ModuleFile &F, unsigned ID) {
Ben Langmuir198c1682014-03-07 07:27:49 +00002135 // Go find this input file.
2136 BitstreamCursor &Cursor = F.InputFilesCursor;
2137 SavedStreamPosition SavedPosition(Cursor);
2138 Cursor.JumpToBit(F.InputFileOffsets[ID-1]);
2139
2140 unsigned Code = Cursor.ReadCode();
2141 RecordData Record;
2142 StringRef Blob;
2143
2144 unsigned Result = Cursor.readRecord(Code, Record, &Blob);
2145 assert(static_cast<InputFileRecordTypes>(Result) == INPUT_FILE &&
2146 "invalid record type for input file");
2147 (void)Result;
2148
Argyrios Kyrtzidisce9b49e2014-03-14 02:26:27 +00002149 std::string Filename;
2150 off_t StoredSize;
2151 time_t StoredTime;
2152 bool Overridden;
Richard Smith7ed1bc92014-12-05 22:42:13 +00002153
Ben Langmuir198c1682014-03-07 07:27:49 +00002154 assert(Record[0] == ID && "Bogus stored ID or offset");
2155 StoredSize = static_cast<off_t>(Record[1]);
2156 StoredTime = static_cast<time_t>(Record[2]);
2157 Overridden = static_cast<bool>(Record[3]);
2158 Filename = Blob;
Richard Smith7ed1bc92014-12-05 22:42:13 +00002159 ResolveImportedPath(F, Filename);
2160
Hans Wennborg73945142014-03-14 17:45:06 +00002161 InputFileInfo R = { std::move(Filename), StoredSize, StoredTime, Overridden };
2162 return R;
Ben Langmuir198c1682014-03-07 07:27:49 +00002163}
2164
2165std::string ASTReader::getInputFileName(ModuleFile &F, unsigned int ID) {
Argyrios Kyrtzidisce9b49e2014-03-14 02:26:27 +00002166 return readInputFileInfo(F, ID).Filename;
Ben Langmuir198c1682014-03-07 07:27:49 +00002167}
2168
Argyrios Kyrtzidis61c3d872013-03-01 03:26:04 +00002169InputFile ASTReader::getInputFile(ModuleFile &F, unsigned ID, bool Complain) {
Guy Benyei11169dd2012-12-18 14:30:41 +00002170 // If this ID is bogus, just return an empty input file.
2171 if (ID == 0 || ID > F.InputFilesLoaded.size())
2172 return InputFile();
2173
2174 // If we've already loaded this input file, return it.
Argyrios Kyrtzidis61c3d872013-03-01 03:26:04 +00002175 if (F.InputFilesLoaded[ID-1].getFile())
Guy Benyei11169dd2012-12-18 14:30:41 +00002176 return F.InputFilesLoaded[ID-1];
2177
Argyrios Kyrtzidis9308f0a2014-01-08 19:13:34 +00002178 if (F.InputFilesLoaded[ID-1].isNotFound())
2179 return InputFile();
2180
Guy Benyei11169dd2012-12-18 14:30:41 +00002181 // Go find this input file.
Chris Lattner7fb3bef2013-01-20 00:56:42 +00002182 BitstreamCursor &Cursor = F.InputFilesCursor;
Guy Benyei11169dd2012-12-18 14:30:41 +00002183 SavedStreamPosition SavedPosition(Cursor);
2184 Cursor.JumpToBit(F.InputFileOffsets[ID-1]);
2185
Argyrios Kyrtzidisce9b49e2014-03-14 02:26:27 +00002186 InputFileInfo FI = readInputFileInfo(F, ID);
2187 off_t StoredSize = FI.StoredSize;
2188 time_t StoredTime = FI.StoredTime;
2189 bool Overridden = FI.Overridden;
2190 StringRef Filename = FI.Filename;
Argyrios Kyrtzidis61c3d872013-03-01 03:26:04 +00002191
Ben Langmuir198c1682014-03-07 07:27:49 +00002192 const FileEntry *File
2193 = Overridden? FileMgr.getVirtualFile(Filename, StoredSize, StoredTime)
2194 : FileMgr.getFile(Filename, /*OpenFile=*/false);
2195
2196 // If we didn't find the file, resolve it relative to the
2197 // original directory from which this AST file was created.
Craig Toppera13603a2014-05-22 05:54:18 +00002198 if (File == nullptr && !F.OriginalDir.empty() && !CurrentDir.empty() &&
Ben Langmuir198c1682014-03-07 07:27:49 +00002199 F.OriginalDir != CurrentDir) {
2200 std::string Resolved = resolveFileRelativeToOriginalDir(Filename,
2201 F.OriginalDir,
2202 CurrentDir);
2203 if (!Resolved.empty())
2204 File = FileMgr.getFile(Resolved);
2205 }
2206
2207 // For an overridden file, create a virtual file with the stored
2208 // size/timestamp.
Craig Toppera13603a2014-05-22 05:54:18 +00002209 if (Overridden && File == nullptr) {
Ben Langmuir198c1682014-03-07 07:27:49 +00002210 File = FileMgr.getVirtualFile(Filename, StoredSize, StoredTime);
2211 }
2212
Craig Toppera13603a2014-05-22 05:54:18 +00002213 if (File == nullptr) {
Ben Langmuir198c1682014-03-07 07:27:49 +00002214 if (Complain) {
2215 std::string ErrorStr = "could not find file '";
2216 ErrorStr += Filename;
2217 ErrorStr += "' referenced by AST file";
2218 Error(ErrorStr.c_str());
Guy Benyei11169dd2012-12-18 14:30:41 +00002219 }
Ben Langmuir198c1682014-03-07 07:27:49 +00002220 // Record that we didn't find the file.
2221 F.InputFilesLoaded[ID-1] = InputFile::getNotFound();
2222 return InputFile();
2223 }
Guy Benyei11169dd2012-12-18 14:30:41 +00002224
Ben Langmuir198c1682014-03-07 07:27:49 +00002225 // Check if there was a request to override the contents of the file
2226 // that was part of the precompiled header. Overridding such a file
2227 // can lead to problems when lexing using the source locations from the
2228 // PCH.
2229 SourceManager &SM = getSourceManager();
2230 if (!Overridden && SM.isFileOverridden(File)) {
2231 if (Complain)
2232 Error(diag::err_fe_pch_file_overridden, Filename);
2233 // After emitting the diagnostic, recover by disabling the override so
2234 // that the original file will be used.
2235 SM.disableFileContentsOverride(File);
2236 // The FileEntry is a virtual file entry with the size of the contents
2237 // that would override the original contents. Set it to the original's
2238 // size/time.
2239 FileMgr.modifyFileEntry(const_cast<FileEntry*>(File),
2240 StoredSize, StoredTime);
2241 }
Guy Benyei11169dd2012-12-18 14:30:41 +00002242
Ben Langmuir198c1682014-03-07 07:27:49 +00002243 bool IsOutOfDate = false;
2244
2245 // For an overridden file, there is nothing to validate.
Richard Smith96fdab62014-10-28 16:24:08 +00002246 if (!Overridden && //
2247 (StoredSize != File->getSize() ||
2248#if defined(LLVM_ON_WIN32)
2249 false
2250#else
Ben Langmuir198c1682014-03-07 07:27:49 +00002251 // In our regression testing, the Windows file system seems to
2252 // have inconsistent modification times that sometimes
2253 // erroneously trigger this error-handling path.
Richard Smith96fdab62014-10-28 16:24:08 +00002254 //
2255 // This also happens in networked file systems, so disable this
2256 // check if validation is disabled or if we have an explicitly
2257 // built PCM file.
2258 //
2259 // FIXME: Should we also do this for PCH files? They could also
2260 // reasonably get shared across a network during a distributed build.
2261 (StoredTime != File->getModificationTime() && !DisableValidation &&
2262 F.Kind != MK_ExplicitModule)
Guy Benyei11169dd2012-12-18 14:30:41 +00002263#endif
Ben Langmuir198c1682014-03-07 07:27:49 +00002264 )) {
2265 if (Complain) {
2266 // Build a list of the PCH imports that got us here (in reverse).
2267 SmallVector<ModuleFile *, 4> ImportStack(1, &F);
2268 while (ImportStack.back()->ImportedBy.size() > 0)
2269 ImportStack.push_back(ImportStack.back()->ImportedBy[0]);
Ben Langmuire82630d2014-01-17 00:19:09 +00002270
Ben Langmuir198c1682014-03-07 07:27:49 +00002271 // The top-level PCH is stale.
2272 StringRef TopLevelPCHName(ImportStack.back()->FileName);
2273 Error(diag::err_fe_pch_file_modified, Filename, TopLevelPCHName);
Ben Langmuire82630d2014-01-17 00:19:09 +00002274
Ben Langmuir198c1682014-03-07 07:27:49 +00002275 // Print the import stack.
2276 if (ImportStack.size() > 1 && !Diags.isDiagnosticInFlight()) {
2277 Diag(diag::note_pch_required_by)
2278 << Filename << ImportStack[0]->FileName;
2279 for (unsigned I = 1; I < ImportStack.size(); ++I)
Ben Langmuire82630d2014-01-17 00:19:09 +00002280 Diag(diag::note_pch_required_by)
Ben Langmuir198c1682014-03-07 07:27:49 +00002281 << ImportStack[I-1]->FileName << ImportStack[I]->FileName;
Douglas Gregor7029ce12013-03-19 00:28:20 +00002282 }
2283
Ben Langmuir198c1682014-03-07 07:27:49 +00002284 if (!Diags.isDiagnosticInFlight())
2285 Diag(diag::note_pch_rebuild_required) << TopLevelPCHName;
Guy Benyei11169dd2012-12-18 14:30:41 +00002286 }
2287
Ben Langmuir198c1682014-03-07 07:27:49 +00002288 IsOutOfDate = true;
Guy Benyei11169dd2012-12-18 14:30:41 +00002289 }
2290
Ben Langmuir198c1682014-03-07 07:27:49 +00002291 InputFile IF = InputFile(File, Overridden, IsOutOfDate);
2292
2293 // Note that we've loaded this input file.
2294 F.InputFilesLoaded[ID-1] = IF;
2295 return IF;
Guy Benyei11169dd2012-12-18 14:30:41 +00002296}
2297
Richard Smith7ed1bc92014-12-05 22:42:13 +00002298/// \brief If we are loading a relocatable PCH or module file, and the filename
2299/// is not an absolute path, add the system or module root to the beginning of
2300/// the file name.
2301void ASTReader::ResolveImportedPath(ModuleFile &M, std::string &Filename) {
2302 // Resolve relative to the base directory, if we have one.
2303 if (!M.BaseDirectory.empty())
2304 return ResolveImportedPath(Filename, M.BaseDirectory);
Guy Benyei11169dd2012-12-18 14:30:41 +00002305}
2306
Richard Smith7ed1bc92014-12-05 22:42:13 +00002307void ASTReader::ResolveImportedPath(std::string &Filename, StringRef Prefix) {
Guy Benyei11169dd2012-12-18 14:30:41 +00002308 if (Filename.empty() || llvm::sys::path::is_absolute(Filename))
2309 return;
2310
Richard Smith7ed1bc92014-12-05 22:42:13 +00002311 SmallString<128> Buffer;
2312 llvm::sys::path::append(Buffer, Prefix, Filename);
2313 Filename.assign(Buffer.begin(), Buffer.end());
Guy Benyei11169dd2012-12-18 14:30:41 +00002314}
2315
2316ASTReader::ASTReadResult
2317ASTReader::ReadControlBlock(ModuleFile &F,
Dmitri Gribenkof8579502013-01-12 19:30:44 +00002318 SmallVectorImpl<ImportedModule> &Loaded,
Ben Langmuirbeee15e2014-04-14 18:00:01 +00002319 const ModuleFile *ImportedBy,
Guy Benyei11169dd2012-12-18 14:30:41 +00002320 unsigned ClientLoadCapabilities) {
Chris Lattner7fb3bef2013-01-20 00:56:42 +00002321 BitstreamCursor &Stream = F.Stream;
Guy Benyei11169dd2012-12-18 14:30:41 +00002322
2323 if (Stream.EnterSubBlock(CONTROL_BLOCK_ID)) {
2324 Error("malformed block record in AST file");
2325 return Failure;
2326 }
2327
Richard Smith1e2cf0d2014-10-31 02:28:58 +00002328 // Should we allow the configuration of the module file to differ from the
2329 // configuration of the current translation unit in a compatible way?
2330 //
2331 // FIXME: Allow this for files explicitly specified with -include-pch too.
2332 bool AllowCompatibleConfigurationMismatch = F.Kind == MK_ExplicitModule;
2333
Guy Benyei11169dd2012-12-18 14:30:41 +00002334 // Read all of the records and blocks in the control block.
2335 RecordData Record;
Richard Smitha1825302014-10-23 22:18:29 +00002336 unsigned NumInputs = 0;
2337 unsigned NumUserInputs = 0;
Chris Lattnere7b154b2013-01-19 21:39:22 +00002338 while (1) {
2339 llvm::BitstreamEntry Entry = Stream.advance();
2340
2341 switch (Entry.Kind) {
2342 case llvm::BitstreamEntry::Error:
2343 Error("malformed block record in AST file");
2344 return Failure;
Dmitri Gribenkof430da42014-02-12 10:33:14 +00002345 case llvm::BitstreamEntry::EndBlock: {
2346 // Validate input files.
2347 const HeaderSearchOptions &HSOpts =
2348 PP.getHeaderSearchInfo().getHeaderSearchOpts();
Ben Langmuircb69b572014-03-07 06:40:32 +00002349
Richard Smitha1825302014-10-23 22:18:29 +00002350 // All user input files reside at the index range [0, NumUserInputs), and
2351 // system input files reside at [NumUserInputs, NumInputs).
Ben Langmuiracb803e2014-11-10 22:13:10 +00002352 if (!DisableValidation) {
Guy Benyei11169dd2012-12-18 14:30:41 +00002353 bool Complain = (ClientLoadCapabilities & ARR_OutOfDate) == 0;
Ben Langmuircb69b572014-03-07 06:40:32 +00002354
Dmitri Gribenkof430da42014-02-12 10:33:14 +00002355 // If we are reading a module, we will create a verification timestamp,
2356 // so we verify all input files. Otherwise, verify only user input
2357 // files.
Ben Langmuircb69b572014-03-07 06:40:32 +00002358
2359 unsigned N = NumUserInputs;
2360 if (ValidateSystemInputs ||
Richard Smithe842a472014-10-22 02:05:46 +00002361 (HSOpts.ModulesValidateOncePerBuildSession &&
Ben Langmuiracb803e2014-11-10 22:13:10 +00002362 F.InputFilesValidationTimestamp <= HSOpts.BuildSessionTimestamp &&
Richard Smithe842a472014-10-22 02:05:46 +00002363 F.Kind == MK_ImplicitModule))
Ben Langmuircb69b572014-03-07 06:40:32 +00002364 N = NumInputs;
2365
Ben Langmuir3d4417c2014-02-07 17:31:11 +00002366 for (unsigned I = 0; I < N; ++I) {
Argyrios Kyrtzidis61c3d872013-03-01 03:26:04 +00002367 InputFile IF = getInputFile(F, I+1, Complain);
2368 if (!IF.getFile() || IF.isOutOfDate())
Guy Benyei11169dd2012-12-18 14:30:41 +00002369 return OutOfDate;
Argyrios Kyrtzidis61c3d872013-03-01 03:26:04 +00002370 }
Guy Benyei11169dd2012-12-18 14:30:41 +00002371 }
Ben Langmuircb69b572014-03-07 06:40:32 +00002372
Argyrios Kyrtzidis6d0753d2014-03-14 03:07:38 +00002373 if (Listener)
2374 Listener->visitModuleFile(F.FileName);
2375
Ben Langmuircb69b572014-03-07 06:40:32 +00002376 if (Listener && Listener->needsInputFileVisitation()) {
2377 unsigned N = Listener->needsSystemInputFileVisitation() ? NumInputs
2378 : NumUserInputs;
Argyrios Kyrtzidis68ccbe02014-03-14 02:26:31 +00002379 for (unsigned I = 0; I < N; ++I) {
2380 bool IsSystem = I >= NumUserInputs;
2381 InputFileInfo FI = readInputFileInfo(F, I+1);
2382 Listener->visitInputFile(FI.Filename, IsSystem, FI.Overridden);
2383 }
Ben Langmuircb69b572014-03-07 06:40:32 +00002384 }
2385
Guy Benyei11169dd2012-12-18 14:30:41 +00002386 return Success;
Dmitri Gribenkof430da42014-02-12 10:33:14 +00002387 }
2388
Chris Lattnere7b154b2013-01-19 21:39:22 +00002389 case llvm::BitstreamEntry::SubBlock:
2390 switch (Entry.ID) {
Guy Benyei11169dd2012-12-18 14:30:41 +00002391 case INPUT_FILES_BLOCK_ID:
2392 F.InputFilesCursor = Stream;
2393 if (Stream.SkipBlock() || // Skip with the main cursor
2394 // Read the abbreviations
2395 ReadBlockAbbrevs(F.InputFilesCursor, INPUT_FILES_BLOCK_ID)) {
2396 Error("malformed block record in AST file");
2397 return Failure;
2398 }
2399 continue;
Chris Lattnere7b154b2013-01-19 21:39:22 +00002400
Guy Benyei11169dd2012-12-18 14:30:41 +00002401 default:
Chris Lattnere7b154b2013-01-19 21:39:22 +00002402 if (Stream.SkipBlock()) {
2403 Error("malformed block record in AST file");
2404 return Failure;
2405 }
2406 continue;
Guy Benyei11169dd2012-12-18 14:30:41 +00002407 }
Chris Lattnere7b154b2013-01-19 21:39:22 +00002408
2409 case llvm::BitstreamEntry::Record:
2410 // The interesting case.
2411 break;
Guy Benyei11169dd2012-12-18 14:30:41 +00002412 }
2413
2414 // Read and process a record.
2415 Record.clear();
Chris Lattner0e6c9402013-01-20 02:38:54 +00002416 StringRef Blob;
2417 switch ((ControlRecordTypes)Stream.readRecord(Entry.ID, Record, &Blob)) {
Guy Benyei11169dd2012-12-18 14:30:41 +00002418 case METADATA: {
2419 if (Record[0] != VERSION_MAJOR && !DisableValidation) {
2420 if ((ClientLoadCapabilities & ARR_VersionMismatch) == 0)
Dmitri Gribenko2228cd32014-02-11 15:40:09 +00002421 Diag(Record[0] < VERSION_MAJOR? diag::err_pch_version_too_old
2422 : diag::err_pch_version_too_new);
Guy Benyei11169dd2012-12-18 14:30:41 +00002423 return VersionMismatch;
2424 }
2425
2426 bool hasErrors = Record[5];
2427 if (hasErrors && !DisableValidation && !AllowASTWithCompilerErrors) {
2428 Diag(diag::err_pch_with_compiler_errors);
2429 return HadErrors;
2430 }
2431
2432 F.RelocatablePCH = Record[4];
Richard Smith7ed1bc92014-12-05 22:42:13 +00002433 // Relative paths in a relocatable PCH are relative to our sysroot.
2434 if (F.RelocatablePCH)
2435 F.BaseDirectory = isysroot.empty() ? "/" : isysroot;
Guy Benyei11169dd2012-12-18 14:30:41 +00002436
2437 const std::string &CurBranch = getClangFullRepositoryVersion();
Chris Lattner0e6c9402013-01-20 02:38:54 +00002438 StringRef ASTBranch = Blob;
Guy Benyei11169dd2012-12-18 14:30:41 +00002439 if (StringRef(CurBranch) != ASTBranch && !DisableValidation) {
2440 if ((ClientLoadCapabilities & ARR_VersionMismatch) == 0)
Dmitri Gribenko2228cd32014-02-11 15:40:09 +00002441 Diag(diag::err_pch_different_branch) << ASTBranch << CurBranch;
Guy Benyei11169dd2012-12-18 14:30:41 +00002442 return VersionMismatch;
2443 }
2444 break;
2445 }
2446
Ben Langmuir487ea142014-10-23 18:05:36 +00002447 case SIGNATURE:
2448 assert((!F.Signature || F.Signature == Record[0]) && "signature changed");
2449 F.Signature = Record[0];
2450 break;
2451
Guy Benyei11169dd2012-12-18 14:30:41 +00002452 case IMPORTS: {
2453 // Load each of the imported PCH files.
2454 unsigned Idx = 0, N = Record.size();
2455 while (Idx < N) {
2456 // Read information about the AST file.
2457 ModuleKind ImportedKind = (ModuleKind)Record[Idx++];
2458 // The import location will be the local one for now; we will adjust
2459 // all import locations of module imports after the global source
2460 // location info are setup.
2461 SourceLocation ImportLoc =
2462 SourceLocation::getFromRawEncoding(Record[Idx++]);
Douglas Gregor7029ce12013-03-19 00:28:20 +00002463 off_t StoredSize = (off_t)Record[Idx++];
2464 time_t StoredModTime = (time_t)Record[Idx++];
Ben Langmuir487ea142014-10-23 18:05:36 +00002465 ASTFileSignature StoredSignature = Record[Idx++];
Richard Smith7ed1bc92014-12-05 22:42:13 +00002466 auto ImportedFile = ReadPath(F, Record, Idx);
Guy Benyei11169dd2012-12-18 14:30:41 +00002467
2468 // Load the AST file.
2469 switch(ReadASTCore(ImportedFile, ImportedKind, ImportLoc, &F, Loaded,
Ben Langmuir487ea142014-10-23 18:05:36 +00002470 StoredSize, StoredModTime, StoredSignature,
Guy Benyei11169dd2012-12-18 14:30:41 +00002471 ClientLoadCapabilities)) {
2472 case Failure: return Failure;
2473 // If we have to ignore the dependency, we'll have to ignore this too.
Douglas Gregor2f1806e2013-03-19 00:38:50 +00002474 case Missing:
Guy Benyei11169dd2012-12-18 14:30:41 +00002475 case OutOfDate: return OutOfDate;
2476 case VersionMismatch: return VersionMismatch;
2477 case ConfigurationMismatch: return ConfigurationMismatch;
2478 case HadErrors: return HadErrors;
2479 case Success: break;
2480 }
2481 }
2482 break;
2483 }
2484
2485 case LANGUAGE_OPTIONS: {
2486 bool Complain = (ClientLoadCapabilities & ARR_ConfigurationMismatch) == 0;
Richard Smith1e2cf0d2014-10-31 02:28:58 +00002487 // FIXME: The &F == *ModuleMgr.begin() check is wrong for modules.
Guy Benyei11169dd2012-12-18 14:30:41 +00002488 if (Listener && &F == *ModuleMgr.begin() &&
Richard Smith1e2cf0d2014-10-31 02:28:58 +00002489 ParseLanguageOptions(Record, Complain, *Listener,
2490 AllowCompatibleConfigurationMismatch) &&
Ben Langmuir2cb4a782014-02-05 22:21:15 +00002491 !DisableValidation && !AllowConfigurationMismatch)
Guy Benyei11169dd2012-12-18 14:30:41 +00002492 return ConfigurationMismatch;
2493 break;
2494 }
2495
2496 case TARGET_OPTIONS: {
2497 bool Complain = (ClientLoadCapabilities & ARR_ConfigurationMismatch)==0;
2498 if (Listener && &F == *ModuleMgr.begin() &&
2499 ParseTargetOptions(Record, Complain, *Listener) &&
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 DIAGNOSTIC_OPTIONS: {
Ben Langmuirb92de022014-04-29 16:25:26 +00002506 bool Complain = (ClientLoadCapabilities & ARR_OutOfDate)==0;
Guy Benyei11169dd2012-12-18 14:30:41 +00002507 if (Listener && &F == *ModuleMgr.begin() &&
Richard Smith1e2cf0d2014-10-31 02:28:58 +00002508 !AllowCompatibleConfigurationMismatch &&
Guy Benyei11169dd2012-12-18 14:30:41 +00002509 ParseDiagnosticOptions(Record, Complain, *Listener) &&
Ben Langmuirb92de022014-04-29 16:25:26 +00002510 !DisableValidation)
2511 return OutOfDate;
Guy Benyei11169dd2012-12-18 14:30:41 +00002512 break;
2513 }
2514
2515 case FILE_SYSTEM_OPTIONS: {
2516 bool Complain = (ClientLoadCapabilities & ARR_ConfigurationMismatch)==0;
2517 if (Listener && &F == *ModuleMgr.begin() &&
Richard Smith1e2cf0d2014-10-31 02:28:58 +00002518 !AllowCompatibleConfigurationMismatch &&
Guy Benyei11169dd2012-12-18 14:30:41 +00002519 ParseFileSystemOptions(Record, Complain, *Listener) &&
Ben Langmuir2cb4a782014-02-05 22:21:15 +00002520 !DisableValidation && !AllowConfigurationMismatch)
Guy Benyei11169dd2012-12-18 14:30:41 +00002521 return ConfigurationMismatch;
2522 break;
2523 }
2524
2525 case HEADER_SEARCH_OPTIONS: {
2526 bool Complain = (ClientLoadCapabilities & ARR_ConfigurationMismatch)==0;
2527 if (Listener && &F == *ModuleMgr.begin() &&
Richard Smith1e2cf0d2014-10-31 02:28:58 +00002528 !AllowCompatibleConfigurationMismatch &&
Guy Benyei11169dd2012-12-18 14:30:41 +00002529 ParseHeaderSearchOptions(Record, Complain, *Listener) &&
Ben Langmuir2cb4a782014-02-05 22:21:15 +00002530 !DisableValidation && !AllowConfigurationMismatch)
Guy Benyei11169dd2012-12-18 14:30:41 +00002531 return ConfigurationMismatch;
2532 break;
2533 }
2534
2535 case PREPROCESSOR_OPTIONS: {
2536 bool Complain = (ClientLoadCapabilities & ARR_ConfigurationMismatch)==0;
2537 if (Listener && &F == *ModuleMgr.begin() &&
Richard Smith1e2cf0d2014-10-31 02:28:58 +00002538 !AllowCompatibleConfigurationMismatch &&
Guy Benyei11169dd2012-12-18 14:30:41 +00002539 ParsePreprocessorOptions(Record, Complain, *Listener,
2540 SuggestedPredefines) &&
Ben Langmuir2cb4a782014-02-05 22:21:15 +00002541 !DisableValidation && !AllowConfigurationMismatch)
Guy Benyei11169dd2012-12-18 14:30:41 +00002542 return ConfigurationMismatch;
2543 break;
2544 }
2545
2546 case ORIGINAL_FILE:
2547 F.OriginalSourceFileID = FileID::get(Record[0]);
Chris Lattner0e6c9402013-01-20 02:38:54 +00002548 F.ActualOriginalSourceFileName = Blob;
Guy Benyei11169dd2012-12-18 14:30:41 +00002549 F.OriginalSourceFileName = F.ActualOriginalSourceFileName;
Richard Smith7ed1bc92014-12-05 22:42:13 +00002550 ResolveImportedPath(F, F.OriginalSourceFileName);
Guy Benyei11169dd2012-12-18 14:30:41 +00002551 break;
2552
2553 case ORIGINAL_FILE_ID:
2554 F.OriginalSourceFileID = FileID::get(Record[0]);
2555 break;
2556
2557 case ORIGINAL_PCH_DIR:
Chris Lattner0e6c9402013-01-20 02:38:54 +00002558 F.OriginalDir = Blob;
Guy Benyei11169dd2012-12-18 14:30:41 +00002559 break;
2560
Ben Langmuirbeee15e2014-04-14 18:00:01 +00002561 case MODULE_NAME:
2562 F.ModuleName = Blob;
Ben Langmuir4f5212a2014-04-14 22:12:44 +00002563 if (Listener)
2564 Listener->ReadModuleName(F.ModuleName);
Ben Langmuirbeee15e2014-04-14 18:00:01 +00002565 break;
2566
Richard Smith223d3f22014-12-06 03:21:08 +00002567 case MODULE_DIRECTORY: {
2568 assert(!F.ModuleName.empty() &&
2569 "MODULE_DIRECTORY found before MODULE_NAME");
2570 // If we've already loaded a module map file covering this module, we may
2571 // have a better path for it (relative to the current build).
2572 Module *M = PP.getHeaderSearchInfo().lookupModule(F.ModuleName);
2573 if (M && M->Directory) {
2574 // If we're implicitly loading a module, the base directory can't
2575 // change between the build and use.
2576 if (F.Kind != MK_ExplicitModule) {
2577 const DirectoryEntry *BuildDir =
2578 PP.getFileManager().getDirectory(Blob);
2579 if (!BuildDir || BuildDir != M->Directory) {
2580 if ((ClientLoadCapabilities & ARR_OutOfDate) == 0)
2581 Diag(diag::err_imported_module_relocated)
2582 << F.ModuleName << Blob << M->Directory->getName();
2583 return OutOfDate;
2584 }
2585 }
2586 F.BaseDirectory = M->Directory->getName();
2587 } else {
2588 F.BaseDirectory = Blob;
2589 }
Richard Smith7ed1bc92014-12-05 22:42:13 +00002590 break;
Richard Smith223d3f22014-12-06 03:21:08 +00002591 }
Richard Smith7ed1bc92014-12-05 22:42:13 +00002592
Ben Langmuirbeee15e2014-04-14 18:00:01 +00002593 case MODULE_MAP_FILE:
Ben Langmuir4b8a9e92014-08-12 16:42:33 +00002594 if (ASTReadResult Result =
2595 ReadModuleMapFileBlock(Record, F, ImportedBy, ClientLoadCapabilities))
2596 return Result;
Ben Langmuir264ea152014-11-08 00:06:39 +00002597 break;
2598
Guy Benyei11169dd2012-12-18 14:30:41 +00002599 case INPUT_FILE_OFFSETS:
Richard Smitha1825302014-10-23 22:18:29 +00002600 NumInputs = Record[0];
2601 NumUserInputs = Record[1];
Richard Smithec216502015-02-13 19:48:37 +00002602 F.InputFileOffsets = (const uint64_t *)Blob.data();
Richard Smitha1825302014-10-23 22:18:29 +00002603 F.InputFilesLoaded.resize(NumInputs);
Guy Benyei11169dd2012-12-18 14:30:41 +00002604 break;
2605 }
2606 }
Guy Benyei11169dd2012-12-18 14:30:41 +00002607}
2608
Ben Langmuir2c9af442014-04-10 17:57:43 +00002609ASTReader::ASTReadResult
2610ASTReader::ReadASTBlock(ModuleFile &F, unsigned ClientLoadCapabilities) {
Chris Lattner7fb3bef2013-01-20 00:56:42 +00002611 BitstreamCursor &Stream = F.Stream;
Guy Benyei11169dd2012-12-18 14:30:41 +00002612
2613 if (Stream.EnterSubBlock(AST_BLOCK_ID)) {
2614 Error("malformed block record in AST file");
Ben Langmuir2c9af442014-04-10 17:57:43 +00002615 return Failure;
Guy Benyei11169dd2012-12-18 14:30:41 +00002616 }
2617
2618 // Read all of the records and blocks for the AST file.
2619 RecordData Record;
Chris Lattnere7b154b2013-01-19 21:39:22 +00002620 while (1) {
2621 llvm::BitstreamEntry Entry = Stream.advance();
2622
2623 switch (Entry.Kind) {
2624 case llvm::BitstreamEntry::Error:
2625 Error("error at end of module block in AST file");
Ben Langmuir2c9af442014-04-10 17:57:43 +00002626 return Failure;
Chris Lattnere7b154b2013-01-19 21:39:22 +00002627 case llvm::BitstreamEntry::EndBlock: {
Richard Smithc0fbba72013-04-03 22:49:41 +00002628 // Outside of C++, we do not store a lookup map for the translation unit.
2629 // Instead, mark it as needing a lookup map to be built if this module
2630 // contains any declarations lexically within it (which it always does!).
2631 // This usually has no cost, since we very rarely need the lookup map for
2632 // the translation unit outside C++.
Guy Benyei11169dd2012-12-18 14:30:41 +00002633 DeclContext *DC = Context.getTranslationUnitDecl();
Richard Smithc0fbba72013-04-03 22:49:41 +00002634 if (DC->hasExternalLexicalStorage() &&
2635 !getContext().getLangOpts().CPlusPlus)
Guy Benyei11169dd2012-12-18 14:30:41 +00002636 DC->setMustBuildLookupTable();
Chris Lattnere7b154b2013-01-19 21:39:22 +00002637
Ben Langmuir2c9af442014-04-10 17:57:43 +00002638 return Success;
Guy Benyei11169dd2012-12-18 14:30:41 +00002639 }
Chris Lattnere7b154b2013-01-19 21:39:22 +00002640 case llvm::BitstreamEntry::SubBlock:
2641 switch (Entry.ID) {
Guy Benyei11169dd2012-12-18 14:30:41 +00002642 case DECLTYPES_BLOCK_ID:
2643 // We lazily load the decls block, but we want to set up the
2644 // DeclsCursor cursor to point into it. Clone our current bitcode
2645 // cursor to it, enter the block and read the abbrevs in that block.
2646 // With the main cursor, we just skip over it.
2647 F.DeclsCursor = Stream;
2648 if (Stream.SkipBlock() || // Skip with the main cursor.
2649 // Read the abbrevs.
2650 ReadBlockAbbrevs(F.DeclsCursor, DECLTYPES_BLOCK_ID)) {
2651 Error("malformed block record in AST file");
Ben Langmuir2c9af442014-04-10 17:57:43 +00002652 return Failure;
Guy Benyei11169dd2012-12-18 14:30:41 +00002653 }
2654 break;
Richard Smithb9eab6d2014-03-20 19:44:17 +00002655
Guy Benyei11169dd2012-12-18 14:30:41 +00002656 case PREPROCESSOR_BLOCK_ID:
2657 F.MacroCursor = Stream;
2658 if (!PP.getExternalSource())
2659 PP.setExternalSource(this);
Chris Lattnere7b154b2013-01-19 21:39:22 +00002660
Guy Benyei11169dd2012-12-18 14:30:41 +00002661 if (Stream.SkipBlock() ||
2662 ReadBlockAbbrevs(F.MacroCursor, PREPROCESSOR_BLOCK_ID)) {
2663 Error("malformed block record in AST file");
Ben Langmuir2c9af442014-04-10 17:57:43 +00002664 return Failure;
Guy Benyei11169dd2012-12-18 14:30:41 +00002665 }
2666 F.MacroStartOffset = F.MacroCursor.GetCurrentBitNo();
2667 break;
Chris Lattnere7b154b2013-01-19 21:39:22 +00002668
Guy Benyei11169dd2012-12-18 14:30:41 +00002669 case PREPROCESSOR_DETAIL_BLOCK_ID:
2670 F.PreprocessorDetailCursor = Stream;
2671 if (Stream.SkipBlock() ||
Chris Lattnere7b154b2013-01-19 21:39:22 +00002672 ReadBlockAbbrevs(F.PreprocessorDetailCursor,
Guy Benyei11169dd2012-12-18 14:30:41 +00002673 PREPROCESSOR_DETAIL_BLOCK_ID)) {
Chris Lattnere7b154b2013-01-19 21:39:22 +00002674 Error("malformed preprocessor detail record in AST file");
Ben Langmuir2c9af442014-04-10 17:57:43 +00002675 return Failure;
Chris Lattnere7b154b2013-01-19 21:39:22 +00002676 }
Guy Benyei11169dd2012-12-18 14:30:41 +00002677 F.PreprocessorDetailStartOffset
Chris Lattnere7b154b2013-01-19 21:39:22 +00002678 = F.PreprocessorDetailCursor.GetCurrentBitNo();
2679
Guy Benyei11169dd2012-12-18 14:30:41 +00002680 if (!PP.getPreprocessingRecord())
2681 PP.createPreprocessingRecord();
2682 if (!PP.getPreprocessingRecord()->getExternalSource())
2683 PP.getPreprocessingRecord()->SetExternalSource(*this);
2684 break;
2685
2686 case SOURCE_MANAGER_BLOCK_ID:
2687 if (ReadSourceManagerBlock(F))
Ben Langmuir2c9af442014-04-10 17:57:43 +00002688 return Failure;
Guy Benyei11169dd2012-12-18 14:30:41 +00002689 break;
Chris Lattnere7b154b2013-01-19 21:39:22 +00002690
Guy Benyei11169dd2012-12-18 14:30:41 +00002691 case SUBMODULE_BLOCK_ID:
Ben Langmuir2c9af442014-04-10 17:57:43 +00002692 if (ASTReadResult Result = ReadSubmoduleBlock(F, ClientLoadCapabilities))
2693 return Result;
Guy Benyei11169dd2012-12-18 14:30:41 +00002694 break;
Chris Lattnere7b154b2013-01-19 21:39:22 +00002695
Guy Benyei11169dd2012-12-18 14:30:41 +00002696 case COMMENTS_BLOCK_ID: {
Chris Lattner7fb3bef2013-01-20 00:56:42 +00002697 BitstreamCursor C = Stream;
Guy Benyei11169dd2012-12-18 14:30:41 +00002698 if (Stream.SkipBlock() ||
2699 ReadBlockAbbrevs(C, COMMENTS_BLOCK_ID)) {
2700 Error("malformed comments block in AST file");
Ben Langmuir2c9af442014-04-10 17:57:43 +00002701 return Failure;
Guy Benyei11169dd2012-12-18 14:30:41 +00002702 }
2703 CommentsCursors.push_back(std::make_pair(C, &F));
2704 break;
2705 }
Chris Lattnere7b154b2013-01-19 21:39:22 +00002706
Guy Benyei11169dd2012-12-18 14:30:41 +00002707 default:
Chris Lattnere7b154b2013-01-19 21:39:22 +00002708 if (Stream.SkipBlock()) {
2709 Error("malformed block record in AST file");
Ben Langmuir2c9af442014-04-10 17:57:43 +00002710 return Failure;
Chris Lattnere7b154b2013-01-19 21:39:22 +00002711 }
2712 break;
Guy Benyei11169dd2012-12-18 14:30:41 +00002713 }
2714 continue;
Chris Lattnere7b154b2013-01-19 21:39:22 +00002715
2716 case llvm::BitstreamEntry::Record:
2717 // The interesting case.
2718 break;
Guy Benyei11169dd2012-12-18 14:30:41 +00002719 }
2720
2721 // Read and process a record.
2722 Record.clear();
Chris Lattner0e6c9402013-01-20 02:38:54 +00002723 StringRef Blob;
2724 switch ((ASTRecordTypes)Stream.readRecord(Entry.ID, Record, &Blob)) {
Guy Benyei11169dd2012-12-18 14:30:41 +00002725 default: // Default behavior: ignore.
2726 break;
2727
2728 case TYPE_OFFSET: {
2729 if (F.LocalNumTypes != 0) {
2730 Error("duplicate TYPE_OFFSET record in AST file");
Ben Langmuir2c9af442014-04-10 17:57:43 +00002731 return Failure;
Guy Benyei11169dd2012-12-18 14:30:41 +00002732 }
Chris Lattner0e6c9402013-01-20 02:38:54 +00002733 F.TypeOffsets = (const uint32_t *)Blob.data();
Guy Benyei11169dd2012-12-18 14:30:41 +00002734 F.LocalNumTypes = Record[0];
2735 unsigned LocalBaseTypeIndex = Record[1];
2736 F.BaseTypeIndex = getTotalNumTypes();
2737
2738 if (F.LocalNumTypes > 0) {
2739 // Introduce the global -> local mapping for types within this module.
2740 GlobalTypeMap.insert(std::make_pair(getTotalNumTypes(), &F));
2741
2742 // Introduce the local -> global mapping for types within this module.
2743 F.TypeRemap.insertOrReplace(
2744 std::make_pair(LocalBaseTypeIndex,
2745 F.BaseTypeIndex - LocalBaseTypeIndex));
Ben Langmuir52ca6782014-10-20 16:27:32 +00002746
2747 TypesLoaded.resize(TypesLoaded.size() + F.LocalNumTypes);
Guy Benyei11169dd2012-12-18 14:30:41 +00002748 }
2749 break;
2750 }
2751
2752 case DECL_OFFSET: {
2753 if (F.LocalNumDecls != 0) {
2754 Error("duplicate DECL_OFFSET record in AST file");
Ben Langmuir2c9af442014-04-10 17:57:43 +00002755 return Failure;
Guy Benyei11169dd2012-12-18 14:30:41 +00002756 }
Chris Lattner0e6c9402013-01-20 02:38:54 +00002757 F.DeclOffsets = (const DeclOffset *)Blob.data();
Guy Benyei11169dd2012-12-18 14:30:41 +00002758 F.LocalNumDecls = Record[0];
2759 unsigned LocalBaseDeclID = Record[1];
2760 F.BaseDeclID = getTotalNumDecls();
2761
2762 if (F.LocalNumDecls > 0) {
2763 // Introduce the global -> local mapping for declarations within this
2764 // module.
2765 GlobalDeclMap.insert(
2766 std::make_pair(getTotalNumDecls() + NUM_PREDEF_DECL_IDS, &F));
2767
2768 // Introduce the local -> global mapping for declarations within this
2769 // module.
2770 F.DeclRemap.insertOrReplace(
2771 std::make_pair(LocalBaseDeclID, F.BaseDeclID - LocalBaseDeclID));
2772
2773 // Introduce the global -> local mapping for declarations within this
2774 // module.
2775 F.GlobalToLocalDeclIDs[&F] = LocalBaseDeclID;
Ben Langmuirfe971d92014-08-16 04:54:18 +00002776
Ben Langmuir52ca6782014-10-20 16:27:32 +00002777 DeclsLoaded.resize(DeclsLoaded.size() + F.LocalNumDecls);
2778 }
Guy Benyei11169dd2012-12-18 14:30:41 +00002779 break;
2780 }
2781
2782 case TU_UPDATE_LEXICAL: {
2783 DeclContext *TU = Context.getTranslationUnitDecl();
2784 DeclContextInfo &Info = F.DeclContextInfos[TU];
Chris Lattner0e6c9402013-01-20 02:38:54 +00002785 Info.LexicalDecls = reinterpret_cast<const KindDeclIDPair *>(Blob.data());
Guy Benyei11169dd2012-12-18 14:30:41 +00002786 Info.NumLexicalDecls
Chris Lattner0e6c9402013-01-20 02:38:54 +00002787 = static_cast<unsigned int>(Blob.size() / sizeof(KindDeclIDPair));
Guy Benyei11169dd2012-12-18 14:30:41 +00002788 TU->setHasExternalLexicalStorage(true);
2789 break;
2790 }
2791
2792 case UPDATE_VISIBLE: {
2793 unsigned Idx = 0;
2794 serialization::DeclID ID = ReadDeclID(F, Record, Idx);
2795 ASTDeclContextNameLookupTable *Table =
Justin Bognerda4e6502014-04-14 16:34:29 +00002796 ASTDeclContextNameLookupTable::Create(
2797 (const unsigned char *)Blob.data() + Record[Idx++],
2798 (const unsigned char *)Blob.data() + sizeof(uint32_t),
2799 (const unsigned char *)Blob.data(),
2800 ASTDeclContextNameLookupTrait(*this, F));
Richard Smithcd45dbc2014-04-19 03:48:30 +00002801 if (Decl *D = GetExistingDecl(ID)) {
Richard Smithd9174792014-03-11 03:10:46 +00002802 auto *DC = cast<DeclContext>(D);
2803 DC->getPrimaryContext()->setHasExternalVisibleStorage(true);
Richard Smith52e3fba2014-03-11 07:17:35 +00002804 auto *&LookupTable = F.DeclContextInfos[DC].NameLookupTableData;
2805 delete LookupTable;
2806 LookupTable = Table;
Guy Benyei11169dd2012-12-18 14:30:41 +00002807 } else
2808 PendingVisibleUpdates[ID].push_back(std::make_pair(Table, &F));
2809 break;
2810 }
2811
2812 case IDENTIFIER_TABLE:
Chris Lattner0e6c9402013-01-20 02:38:54 +00002813 F.IdentifierTableData = Blob.data();
Guy Benyei11169dd2012-12-18 14:30:41 +00002814 if (Record[0]) {
Justin Bognerda4e6502014-04-14 16:34:29 +00002815 F.IdentifierLookupTable = ASTIdentifierLookupTable::Create(
2816 (const unsigned char *)F.IdentifierTableData + Record[0],
2817 (const unsigned char *)F.IdentifierTableData + sizeof(uint32_t),
2818 (const unsigned char *)F.IdentifierTableData,
2819 ASTIdentifierLookupTrait(*this, F));
Guy Benyei11169dd2012-12-18 14:30:41 +00002820
2821 PP.getIdentifierTable().setExternalIdentifierLookup(this);
2822 }
2823 break;
2824
2825 case IDENTIFIER_OFFSET: {
2826 if (F.LocalNumIdentifiers != 0) {
2827 Error("duplicate IDENTIFIER_OFFSET record in AST file");
Ben Langmuir2c9af442014-04-10 17:57:43 +00002828 return Failure;
Guy Benyei11169dd2012-12-18 14:30:41 +00002829 }
Chris Lattner0e6c9402013-01-20 02:38:54 +00002830 F.IdentifierOffsets = (const uint32_t *)Blob.data();
Guy Benyei11169dd2012-12-18 14:30:41 +00002831 F.LocalNumIdentifiers = Record[0];
2832 unsigned LocalBaseIdentifierID = Record[1];
2833 F.BaseIdentifierID = getTotalNumIdentifiers();
2834
2835 if (F.LocalNumIdentifiers > 0) {
2836 // Introduce the global -> local mapping for identifiers within this
2837 // module.
2838 GlobalIdentifierMap.insert(std::make_pair(getTotalNumIdentifiers() + 1,
2839 &F));
2840
2841 // Introduce the local -> global mapping for identifiers within this
2842 // module.
2843 F.IdentifierRemap.insertOrReplace(
2844 std::make_pair(LocalBaseIdentifierID,
2845 F.BaseIdentifierID - LocalBaseIdentifierID));
Ben Langmuirfe971d92014-08-16 04:54:18 +00002846
Ben Langmuir52ca6782014-10-20 16:27:32 +00002847 IdentifiersLoaded.resize(IdentifiersLoaded.size()
2848 + F.LocalNumIdentifiers);
2849 }
Guy Benyei11169dd2012-12-18 14:30:41 +00002850 break;
2851 }
2852
Ben Langmuir332aafe2014-01-31 01:06:56 +00002853 case EAGERLY_DESERIALIZED_DECLS:
Guy Benyei11169dd2012-12-18 14:30:41 +00002854 for (unsigned I = 0, N = Record.size(); I != N; ++I)
Ben Langmuir332aafe2014-01-31 01:06:56 +00002855 EagerlyDeserializedDecls.push_back(getGlobalDeclID(F, Record[I]));
Guy Benyei11169dd2012-12-18 14:30:41 +00002856 break;
2857
2858 case SPECIAL_TYPES:
Douglas Gregor44180f82013-02-01 23:45:03 +00002859 if (SpecialTypes.empty()) {
2860 for (unsigned I = 0, N = Record.size(); I != N; ++I)
2861 SpecialTypes.push_back(getGlobalTypeID(F, Record[I]));
2862 break;
2863 }
2864
2865 if (SpecialTypes.size() != Record.size()) {
2866 Error("invalid special-types record");
Ben Langmuir2c9af442014-04-10 17:57:43 +00002867 return Failure;
Douglas Gregor44180f82013-02-01 23:45:03 +00002868 }
2869
2870 for (unsigned I = 0, N = Record.size(); I != N; ++I) {
2871 serialization::TypeID ID = getGlobalTypeID(F, Record[I]);
2872 if (!SpecialTypes[I])
2873 SpecialTypes[I] = ID;
2874 // FIXME: If ID && SpecialTypes[I] != ID, do we need a separate
2875 // merge step?
2876 }
Guy Benyei11169dd2012-12-18 14:30:41 +00002877 break;
2878
2879 case STATISTICS:
2880 TotalNumStatements += Record[0];
2881 TotalNumMacros += Record[1];
2882 TotalLexicalDeclContexts += Record[2];
2883 TotalVisibleDeclContexts += Record[3];
2884 break;
2885
2886 case UNUSED_FILESCOPED_DECLS:
2887 for (unsigned I = 0, N = Record.size(); I != N; ++I)
2888 UnusedFileScopedDecls.push_back(getGlobalDeclID(F, Record[I]));
2889 break;
2890
2891 case DELEGATING_CTORS:
2892 for (unsigned I = 0, N = Record.size(); I != N; ++I)
2893 DelegatingCtorDecls.push_back(getGlobalDeclID(F, Record[I]));
2894 break;
2895
2896 case WEAK_UNDECLARED_IDENTIFIERS:
2897 if (Record.size() % 4 != 0) {
2898 Error("invalid weak identifiers record");
Ben Langmuir2c9af442014-04-10 17:57:43 +00002899 return Failure;
Guy Benyei11169dd2012-12-18 14:30:41 +00002900 }
2901
2902 // FIXME: Ignore weak undeclared identifiers from non-original PCH
2903 // files. This isn't the way to do it :)
2904 WeakUndeclaredIdentifiers.clear();
2905
2906 // Translate the weak, undeclared identifiers into global IDs.
2907 for (unsigned I = 0, N = Record.size(); I < N; /* in loop */) {
2908 WeakUndeclaredIdentifiers.push_back(
2909 getGlobalIdentifierID(F, Record[I++]));
2910 WeakUndeclaredIdentifiers.push_back(
2911 getGlobalIdentifierID(F, Record[I++]));
2912 WeakUndeclaredIdentifiers.push_back(
2913 ReadSourceLocation(F, Record, I).getRawEncoding());
2914 WeakUndeclaredIdentifiers.push_back(Record[I++]);
2915 }
2916 break;
2917
Richard Smith78165b52013-01-10 23:43:47 +00002918 case LOCALLY_SCOPED_EXTERN_C_DECLS:
Guy Benyei11169dd2012-12-18 14:30:41 +00002919 for (unsigned I = 0, N = Record.size(); I != N; ++I)
Richard Smith78165b52013-01-10 23:43:47 +00002920 LocallyScopedExternCDecls.push_back(getGlobalDeclID(F, Record[I]));
Guy Benyei11169dd2012-12-18 14:30:41 +00002921 break;
2922
2923 case SELECTOR_OFFSETS: {
Chris Lattner0e6c9402013-01-20 02:38:54 +00002924 F.SelectorOffsets = (const uint32_t *)Blob.data();
Guy Benyei11169dd2012-12-18 14:30:41 +00002925 F.LocalNumSelectors = Record[0];
2926 unsigned LocalBaseSelectorID = Record[1];
2927 F.BaseSelectorID = getTotalNumSelectors();
2928
2929 if (F.LocalNumSelectors > 0) {
2930 // Introduce the global -> local mapping for selectors within this
2931 // module.
2932 GlobalSelectorMap.insert(std::make_pair(getTotalNumSelectors()+1, &F));
2933
2934 // Introduce the local -> global mapping for selectors within this
2935 // module.
2936 F.SelectorRemap.insertOrReplace(
2937 std::make_pair(LocalBaseSelectorID,
2938 F.BaseSelectorID - LocalBaseSelectorID));
Ben Langmuir52ca6782014-10-20 16:27:32 +00002939
2940 SelectorsLoaded.resize(SelectorsLoaded.size() + F.LocalNumSelectors);
Guy Benyei11169dd2012-12-18 14:30:41 +00002941 }
2942 break;
2943 }
2944
2945 case METHOD_POOL:
Chris Lattner0e6c9402013-01-20 02:38:54 +00002946 F.SelectorLookupTableData = (const unsigned char *)Blob.data();
Guy Benyei11169dd2012-12-18 14:30:41 +00002947 if (Record[0])
2948 F.SelectorLookupTable
2949 = ASTSelectorLookupTable::Create(
2950 F.SelectorLookupTableData + Record[0],
2951 F.SelectorLookupTableData,
2952 ASTSelectorLookupTrait(*this, F));
2953 TotalNumMethodPoolEntries += Record[1];
2954 break;
2955
2956 case REFERENCED_SELECTOR_POOL:
2957 if (!Record.empty()) {
2958 for (unsigned Idx = 0, N = Record.size() - 1; Idx < N; /* in loop */) {
2959 ReferencedSelectorsData.push_back(getGlobalSelectorID(F,
2960 Record[Idx++]));
2961 ReferencedSelectorsData.push_back(ReadSourceLocation(F, Record, Idx).
2962 getRawEncoding());
2963 }
2964 }
2965 break;
2966
2967 case PP_COUNTER_VALUE:
2968 if (!Record.empty() && Listener)
2969 Listener->ReadCounter(F, Record[0]);
2970 break;
2971
2972 case FILE_SORTED_DECLS:
Chris Lattner0e6c9402013-01-20 02:38:54 +00002973 F.FileSortedDecls = (const DeclID *)Blob.data();
Guy Benyei11169dd2012-12-18 14:30:41 +00002974 F.NumFileSortedDecls = Record[0];
2975 break;
2976
2977 case SOURCE_LOCATION_OFFSETS: {
Chris Lattner0e6c9402013-01-20 02:38:54 +00002978 F.SLocEntryOffsets = (const uint32_t *)Blob.data();
Guy Benyei11169dd2012-12-18 14:30:41 +00002979 F.LocalNumSLocEntries = Record[0];
2980 unsigned SLocSpaceSize = Record[1];
Benjamin Kramer867ea1d2014-03-02 13:01:17 +00002981 std::tie(F.SLocEntryBaseID, F.SLocEntryBaseOffset) =
Ben Langmuir52ca6782014-10-20 16:27:32 +00002982 SourceMgr.AllocateLoadedSLocEntries(F.LocalNumSLocEntries,
Guy Benyei11169dd2012-12-18 14:30:41 +00002983 SLocSpaceSize);
2984 // Make our entry in the range map. BaseID is negative and growing, so
2985 // we invert it. Because we invert it, though, we need the other end of
2986 // the range.
2987 unsigned RangeStart =
2988 unsigned(-F.SLocEntryBaseID) - F.LocalNumSLocEntries + 1;
2989 GlobalSLocEntryMap.insert(std::make_pair(RangeStart, &F));
2990 F.FirstLoc = SourceLocation::getFromRawEncoding(F.SLocEntryBaseOffset);
2991
2992 // SLocEntryBaseOffset is lower than MaxLoadedOffset and decreasing.
2993 assert((F.SLocEntryBaseOffset & (1U << 31U)) == 0);
2994 GlobalSLocOffsetMap.insert(
2995 std::make_pair(SourceManager::MaxLoadedOffset - F.SLocEntryBaseOffset
2996 - SLocSpaceSize,&F));
2997
2998 // Initialize the remapping table.
2999 // Invalid stays invalid.
Richard Smithb9eab6d2014-03-20 19:44:17 +00003000 F.SLocRemap.insertOrReplace(std::make_pair(0U, 0));
Guy Benyei11169dd2012-12-18 14:30:41 +00003001 // This module. Base was 2 when being compiled.
Richard Smithb9eab6d2014-03-20 19:44:17 +00003002 F.SLocRemap.insertOrReplace(std::make_pair(2U,
Guy Benyei11169dd2012-12-18 14:30:41 +00003003 static_cast<int>(F.SLocEntryBaseOffset - 2)));
3004
3005 TotalNumSLocEntries += F.LocalNumSLocEntries;
3006 break;
3007 }
3008
3009 case MODULE_OFFSET_MAP: {
3010 // Additional remapping information.
Chris Lattner0e6c9402013-01-20 02:38:54 +00003011 const unsigned char *Data = (const unsigned char*)Blob.data();
3012 const unsigned char *DataEnd = Data + Blob.size();
Richard Smithb9eab6d2014-03-20 19:44:17 +00003013
3014 // If we see this entry before SOURCE_LOCATION_OFFSETS, add placeholders.
3015 if (F.SLocRemap.find(0) == F.SLocRemap.end()) {
3016 F.SLocRemap.insert(std::make_pair(0U, 0));
3017 F.SLocRemap.insert(std::make_pair(2U, 1));
3018 }
3019
Guy Benyei11169dd2012-12-18 14:30:41 +00003020 // Continuous range maps we may be updating in our module.
Ben Langmuir785180e2014-10-20 16:27:30 +00003021 typedef ContinuousRangeMap<uint32_t, int, 2>::Builder
3022 RemapBuilder;
3023 RemapBuilder SLocRemap(F.SLocRemap);
3024 RemapBuilder IdentifierRemap(F.IdentifierRemap);
3025 RemapBuilder MacroRemap(F.MacroRemap);
3026 RemapBuilder PreprocessedEntityRemap(F.PreprocessedEntityRemap);
3027 RemapBuilder SubmoduleRemap(F.SubmoduleRemap);
3028 RemapBuilder SelectorRemap(F.SelectorRemap);
3029 RemapBuilder DeclRemap(F.DeclRemap);
3030 RemapBuilder TypeRemap(F.TypeRemap);
Guy Benyei11169dd2012-12-18 14:30:41 +00003031
3032 while(Data < DataEnd) {
Justin Bogner57ba0b22014-03-28 22:03:24 +00003033 using namespace llvm::support;
3034 uint16_t Len = endian::readNext<uint16_t, little, unaligned>(Data);
Guy Benyei11169dd2012-12-18 14:30:41 +00003035 StringRef Name = StringRef((const char*)Data, Len);
3036 Data += Len;
3037 ModuleFile *OM = ModuleMgr.lookup(Name);
3038 if (!OM) {
3039 Error("SourceLocation remap refers to unknown module");
Ben Langmuir2c9af442014-04-10 17:57:43 +00003040 return Failure;
Guy Benyei11169dd2012-12-18 14:30:41 +00003041 }
3042
Justin Bogner57ba0b22014-03-28 22:03:24 +00003043 uint32_t SLocOffset =
3044 endian::readNext<uint32_t, little, unaligned>(Data);
3045 uint32_t IdentifierIDOffset =
3046 endian::readNext<uint32_t, little, unaligned>(Data);
3047 uint32_t MacroIDOffset =
3048 endian::readNext<uint32_t, little, unaligned>(Data);
3049 uint32_t PreprocessedEntityIDOffset =
3050 endian::readNext<uint32_t, little, unaligned>(Data);
3051 uint32_t SubmoduleIDOffset =
3052 endian::readNext<uint32_t, little, unaligned>(Data);
3053 uint32_t SelectorIDOffset =
3054 endian::readNext<uint32_t, little, unaligned>(Data);
3055 uint32_t DeclIDOffset =
3056 endian::readNext<uint32_t, little, unaligned>(Data);
3057 uint32_t TypeIndexOffset =
3058 endian::readNext<uint32_t, little, unaligned>(Data);
3059
Ben Langmuir785180e2014-10-20 16:27:30 +00003060 uint32_t None = std::numeric_limits<uint32_t>::max();
3061
3062 auto mapOffset = [&](uint32_t Offset, uint32_t BaseOffset,
3063 RemapBuilder &Remap) {
3064 if (Offset != None)
3065 Remap.insert(std::make_pair(Offset,
3066 static_cast<int>(BaseOffset - Offset)));
3067 };
3068 mapOffset(SLocOffset, OM->SLocEntryBaseOffset, SLocRemap);
3069 mapOffset(IdentifierIDOffset, OM->BaseIdentifierID, IdentifierRemap);
3070 mapOffset(MacroIDOffset, OM->BaseMacroID, MacroRemap);
3071 mapOffset(PreprocessedEntityIDOffset, OM->BasePreprocessedEntityID,
3072 PreprocessedEntityRemap);
3073 mapOffset(SubmoduleIDOffset, OM->BaseSubmoduleID, SubmoduleRemap);
3074 mapOffset(SelectorIDOffset, OM->BaseSelectorID, SelectorRemap);
3075 mapOffset(DeclIDOffset, OM->BaseDeclID, DeclRemap);
3076 mapOffset(TypeIndexOffset, OM->BaseTypeIndex, TypeRemap);
Guy Benyei11169dd2012-12-18 14:30:41 +00003077
3078 // Global -> local mappings.
3079 F.GlobalToLocalDeclIDs[OM] = DeclIDOffset;
3080 }
3081 break;
3082 }
3083
3084 case SOURCE_MANAGER_LINE_TABLE:
3085 if (ParseLineTable(F, Record))
Ben Langmuir2c9af442014-04-10 17:57:43 +00003086 return Failure;
Guy Benyei11169dd2012-12-18 14:30:41 +00003087 break;
3088
3089 case SOURCE_LOCATION_PRELOADS: {
3090 // Need to transform from the local view (1-based IDs) to the global view,
3091 // which is based off F.SLocEntryBaseID.
3092 if (!F.PreloadSLocEntries.empty()) {
3093 Error("Multiple SOURCE_LOCATION_PRELOADS records in AST file");
Ben Langmuir2c9af442014-04-10 17:57:43 +00003094 return Failure;
Guy Benyei11169dd2012-12-18 14:30:41 +00003095 }
3096
3097 F.PreloadSLocEntries.swap(Record);
3098 break;
3099 }
3100
3101 case EXT_VECTOR_DECLS:
3102 for (unsigned I = 0, N = Record.size(); I != N; ++I)
3103 ExtVectorDecls.push_back(getGlobalDeclID(F, Record[I]));
3104 break;
3105
3106 case VTABLE_USES:
3107 if (Record.size() % 3 != 0) {
3108 Error("Invalid VTABLE_USES record");
Ben Langmuir2c9af442014-04-10 17:57:43 +00003109 return Failure;
Guy Benyei11169dd2012-12-18 14:30:41 +00003110 }
3111
3112 // Later tables overwrite earlier ones.
3113 // FIXME: Modules will have some trouble with this. This is clearly not
3114 // the right way to do this.
3115 VTableUses.clear();
3116
3117 for (unsigned Idx = 0, N = Record.size(); Idx != N; /* In loop */) {
3118 VTableUses.push_back(getGlobalDeclID(F, Record[Idx++]));
3119 VTableUses.push_back(
3120 ReadSourceLocation(F, Record, Idx).getRawEncoding());
3121 VTableUses.push_back(Record[Idx++]);
3122 }
3123 break;
3124
3125 case DYNAMIC_CLASSES:
3126 for (unsigned I = 0, N = Record.size(); I != N; ++I)
3127 DynamicClasses.push_back(getGlobalDeclID(F, Record[I]));
3128 break;
3129
3130 case PENDING_IMPLICIT_INSTANTIATIONS:
3131 if (PendingInstantiations.size() % 2 != 0) {
3132 Error("Invalid existing PendingInstantiations");
Ben Langmuir2c9af442014-04-10 17:57:43 +00003133 return Failure;
Guy Benyei11169dd2012-12-18 14:30:41 +00003134 }
3135
3136 if (Record.size() % 2 != 0) {
3137 Error("Invalid PENDING_IMPLICIT_INSTANTIATIONS block");
Ben Langmuir2c9af442014-04-10 17:57:43 +00003138 return Failure;
Guy Benyei11169dd2012-12-18 14:30:41 +00003139 }
3140
3141 for (unsigned I = 0, N = Record.size(); I != N; /* in loop */) {
3142 PendingInstantiations.push_back(getGlobalDeclID(F, Record[I++]));
3143 PendingInstantiations.push_back(
3144 ReadSourceLocation(F, Record, I).getRawEncoding());
3145 }
3146 break;
3147
3148 case SEMA_DECL_REFS:
Richard Smith3d8e97e2013-10-18 06:54:39 +00003149 if (Record.size() != 2) {
3150 Error("Invalid SEMA_DECL_REFS block");
Ben Langmuir2c9af442014-04-10 17:57:43 +00003151 return Failure;
Richard Smith3d8e97e2013-10-18 06:54:39 +00003152 }
Guy Benyei11169dd2012-12-18 14:30:41 +00003153 for (unsigned I = 0, N = Record.size(); I != N; ++I)
3154 SemaDeclRefs.push_back(getGlobalDeclID(F, Record[I]));
3155 break;
3156
3157 case PPD_ENTITIES_OFFSETS: {
Chris Lattner0e6c9402013-01-20 02:38:54 +00003158 F.PreprocessedEntityOffsets = (const PPEntityOffset *)Blob.data();
3159 assert(Blob.size() % sizeof(PPEntityOffset) == 0);
3160 F.NumPreprocessedEntities = Blob.size() / sizeof(PPEntityOffset);
Guy Benyei11169dd2012-12-18 14:30:41 +00003161
3162 unsigned LocalBasePreprocessedEntityID = Record[0];
3163
3164 unsigned StartingID;
3165 if (!PP.getPreprocessingRecord())
3166 PP.createPreprocessingRecord();
3167 if (!PP.getPreprocessingRecord()->getExternalSource())
3168 PP.getPreprocessingRecord()->SetExternalSource(*this);
3169 StartingID
3170 = PP.getPreprocessingRecord()
Ben Langmuir52ca6782014-10-20 16:27:32 +00003171 ->allocateLoadedEntities(F.NumPreprocessedEntities);
Guy Benyei11169dd2012-12-18 14:30:41 +00003172 F.BasePreprocessedEntityID = StartingID;
3173
3174 if (F.NumPreprocessedEntities > 0) {
3175 // Introduce the global -> local mapping for preprocessed entities in
3176 // this module.
3177 GlobalPreprocessedEntityMap.insert(std::make_pair(StartingID, &F));
3178
3179 // Introduce the local -> global mapping for preprocessed entities in
3180 // this module.
3181 F.PreprocessedEntityRemap.insertOrReplace(
3182 std::make_pair(LocalBasePreprocessedEntityID,
3183 F.BasePreprocessedEntityID - LocalBasePreprocessedEntityID));
3184 }
3185
3186 break;
3187 }
3188
3189 case DECL_UPDATE_OFFSETS: {
3190 if (Record.size() % 2 != 0) {
3191 Error("invalid DECL_UPDATE_OFFSETS block in AST file");
Ben Langmuir2c9af442014-04-10 17:57:43 +00003192 return Failure;
Guy Benyei11169dd2012-12-18 14:30:41 +00003193 }
Richard Smithcd45dbc2014-04-19 03:48:30 +00003194 for (unsigned I = 0, N = Record.size(); I != N; I += 2) {
3195 GlobalDeclID ID = getGlobalDeclID(F, Record[I]);
3196 DeclUpdateOffsets[ID].push_back(std::make_pair(&F, Record[I + 1]));
3197
3198 // If we've already loaded the decl, perform the updates when we finish
3199 // loading this block.
3200 if (Decl *D = GetExistingDecl(ID))
3201 PendingUpdateRecords.push_back(std::make_pair(ID, D));
3202 }
Guy Benyei11169dd2012-12-18 14:30:41 +00003203 break;
3204 }
3205
3206 case DECL_REPLACEMENTS: {
3207 if (Record.size() % 3 != 0) {
3208 Error("invalid DECL_REPLACEMENTS block in AST file");
Ben Langmuir2c9af442014-04-10 17:57:43 +00003209 return Failure;
Guy Benyei11169dd2012-12-18 14:30:41 +00003210 }
3211 for (unsigned I = 0, N = Record.size(); I != N; I += 3)
3212 ReplacedDecls[getGlobalDeclID(F, Record[I])]
3213 = ReplacedDeclInfo(&F, Record[I+1], Record[I+2]);
3214 break;
3215 }
3216
3217 case OBJC_CATEGORIES_MAP: {
3218 if (F.LocalNumObjCCategoriesInMap != 0) {
3219 Error("duplicate OBJC_CATEGORIES_MAP record in AST file");
Ben Langmuir2c9af442014-04-10 17:57:43 +00003220 return Failure;
Guy Benyei11169dd2012-12-18 14:30:41 +00003221 }
3222
3223 F.LocalNumObjCCategoriesInMap = Record[0];
Chris Lattner0e6c9402013-01-20 02:38:54 +00003224 F.ObjCCategoriesMap = (const ObjCCategoriesInfo *)Blob.data();
Guy Benyei11169dd2012-12-18 14:30:41 +00003225 break;
3226 }
3227
3228 case OBJC_CATEGORIES:
3229 F.ObjCCategories.swap(Record);
3230 break;
3231
3232 case CXX_BASE_SPECIFIER_OFFSETS: {
3233 if (F.LocalNumCXXBaseSpecifiers != 0) {
3234 Error("duplicate CXX_BASE_SPECIFIER_OFFSETS record in AST file");
Ben Langmuir2c9af442014-04-10 17:57:43 +00003235 return Failure;
Guy Benyei11169dd2012-12-18 14:30:41 +00003236 }
3237
3238 F.LocalNumCXXBaseSpecifiers = Record[0];
Chris Lattner0e6c9402013-01-20 02:38:54 +00003239 F.CXXBaseSpecifiersOffsets = (const uint32_t *)Blob.data();
Guy Benyei11169dd2012-12-18 14:30:41 +00003240 NumCXXBaseSpecifiersLoaded += F.LocalNumCXXBaseSpecifiers;
3241 break;
3242 }
3243
3244 case DIAG_PRAGMA_MAPPINGS:
3245 if (F.PragmaDiagMappings.empty())
3246 F.PragmaDiagMappings.swap(Record);
3247 else
3248 F.PragmaDiagMappings.insert(F.PragmaDiagMappings.end(),
3249 Record.begin(), Record.end());
3250 break;
3251
3252 case CUDA_SPECIAL_DECL_REFS:
3253 // Later tables overwrite earlier ones.
3254 // FIXME: Modules will have trouble with this.
3255 CUDASpecialDeclRefs.clear();
3256 for (unsigned I = 0, N = Record.size(); I != N; ++I)
3257 CUDASpecialDeclRefs.push_back(getGlobalDeclID(F, Record[I]));
3258 break;
3259
3260 case HEADER_SEARCH_TABLE: {
Chris Lattner0e6c9402013-01-20 02:38:54 +00003261 F.HeaderFileInfoTableData = Blob.data();
Guy Benyei11169dd2012-12-18 14:30:41 +00003262 F.LocalNumHeaderFileInfos = Record[1];
Guy Benyei11169dd2012-12-18 14:30:41 +00003263 if (Record[0]) {
3264 F.HeaderFileInfoTable
3265 = HeaderFileInfoLookupTable::Create(
3266 (const unsigned char *)F.HeaderFileInfoTableData + Record[0],
3267 (const unsigned char *)F.HeaderFileInfoTableData,
3268 HeaderFileInfoTrait(*this, F,
3269 &PP.getHeaderSearchInfo(),
Chris Lattner0e6c9402013-01-20 02:38:54 +00003270 Blob.data() + Record[2]));
Guy Benyei11169dd2012-12-18 14:30:41 +00003271
3272 PP.getHeaderSearchInfo().SetExternalSource(this);
3273 if (!PP.getHeaderSearchInfo().getExternalLookup())
3274 PP.getHeaderSearchInfo().SetExternalLookup(this);
3275 }
3276 break;
3277 }
3278
3279 case FP_PRAGMA_OPTIONS:
3280 // Later tables overwrite earlier ones.
3281 FPPragmaOptions.swap(Record);
3282 break;
3283
3284 case OPENCL_EXTENSIONS:
3285 // Later tables overwrite earlier ones.
3286 OpenCLExtensions.swap(Record);
3287 break;
3288
3289 case TENTATIVE_DEFINITIONS:
3290 for (unsigned I = 0, N = Record.size(); I != N; ++I)
3291 TentativeDefinitions.push_back(getGlobalDeclID(F, Record[I]));
3292 break;
3293
3294 case KNOWN_NAMESPACES:
3295 for (unsigned I = 0, N = Record.size(); I != N; ++I)
3296 KnownNamespaces.push_back(getGlobalDeclID(F, Record[I]));
3297 break;
Nick Lewycky8334af82013-01-26 00:35:08 +00003298
Nick Lewycky9c7eb1d2013-02-01 08:13:20 +00003299 case UNDEFINED_BUT_USED:
3300 if (UndefinedButUsed.size() % 2 != 0) {
3301 Error("Invalid existing UndefinedButUsed");
Ben Langmuir2c9af442014-04-10 17:57:43 +00003302 return Failure;
Nick Lewycky8334af82013-01-26 00:35:08 +00003303 }
3304
3305 if (Record.size() % 2 != 0) {
Nick Lewycky9c7eb1d2013-02-01 08:13:20 +00003306 Error("invalid undefined-but-used record");
Ben Langmuir2c9af442014-04-10 17:57:43 +00003307 return Failure;
Nick Lewycky8334af82013-01-26 00:35:08 +00003308 }
3309 for (unsigned I = 0, N = Record.size(); I != N; /* in loop */) {
Nick Lewycky9c7eb1d2013-02-01 08:13:20 +00003310 UndefinedButUsed.push_back(getGlobalDeclID(F, Record[I++]));
3311 UndefinedButUsed.push_back(
Nick Lewycky8334af82013-01-26 00:35:08 +00003312 ReadSourceLocation(F, Record, I).getRawEncoding());
3313 }
3314 break;
3315
Guy Benyei11169dd2012-12-18 14:30:41 +00003316 case IMPORTED_MODULES: {
Richard Smithe842a472014-10-22 02:05:46 +00003317 if (F.Kind != MK_ImplicitModule && F.Kind != MK_ExplicitModule) {
Guy Benyei11169dd2012-12-18 14:30:41 +00003318 // If we aren't loading a module (which has its own exports), make
3319 // all of the imported modules visible.
3320 // FIXME: Deal with macros-only imports.
Richard Smith56be7542014-03-21 00:33:59 +00003321 for (unsigned I = 0, N = Record.size(); I != N; /**/) {
3322 unsigned GlobalID = getGlobalSubmoduleID(F, Record[I++]);
3323 SourceLocation Loc = ReadSourceLocation(F, Record, I);
3324 if (GlobalID)
Aaron Ballman4f45b712014-03-21 15:22:56 +00003325 ImportedModules.push_back(ImportedSubmodule(GlobalID, Loc));
Guy Benyei11169dd2012-12-18 14:30:41 +00003326 }
3327 }
3328 break;
3329 }
3330
3331 case LOCAL_REDECLARATIONS: {
3332 F.RedeclarationChains.swap(Record);
3333 break;
3334 }
3335
3336 case LOCAL_REDECLARATIONS_MAP: {
3337 if (F.LocalNumRedeclarationsInMap != 0) {
3338 Error("duplicate LOCAL_REDECLARATIONS_MAP record in AST file");
Ben Langmuir2c9af442014-04-10 17:57:43 +00003339 return Failure;
Guy Benyei11169dd2012-12-18 14:30:41 +00003340 }
3341
3342 F.LocalNumRedeclarationsInMap = Record[0];
Chris Lattner0e6c9402013-01-20 02:38:54 +00003343 F.RedeclarationsMap = (const LocalRedeclarationsInfo *)Blob.data();
Guy Benyei11169dd2012-12-18 14:30:41 +00003344 break;
3345 }
3346
3347 case MERGED_DECLARATIONS: {
3348 for (unsigned Idx = 0; Idx < Record.size(); /* increment in loop */) {
3349 GlobalDeclID CanonID = getGlobalDeclID(F, Record[Idx++]);
3350 SmallVectorImpl<GlobalDeclID> &Decls = StoredMergedDecls[CanonID];
3351 for (unsigned N = Record[Idx++]; N > 0; --N)
3352 Decls.push_back(getGlobalDeclID(F, Record[Idx++]));
3353 }
3354 break;
3355 }
3356
3357 case MACRO_OFFSET: {
3358 if (F.LocalNumMacros != 0) {
3359 Error("duplicate MACRO_OFFSET record in AST file");
Ben Langmuir2c9af442014-04-10 17:57:43 +00003360 return Failure;
Guy Benyei11169dd2012-12-18 14:30:41 +00003361 }
Chris Lattner0e6c9402013-01-20 02:38:54 +00003362 F.MacroOffsets = (const uint32_t *)Blob.data();
Guy Benyei11169dd2012-12-18 14:30:41 +00003363 F.LocalNumMacros = Record[0];
3364 unsigned LocalBaseMacroID = Record[1];
3365 F.BaseMacroID = getTotalNumMacros();
3366
3367 if (F.LocalNumMacros > 0) {
3368 // Introduce the global -> local mapping for macros within this module.
3369 GlobalMacroMap.insert(std::make_pair(getTotalNumMacros() + 1, &F));
3370
3371 // Introduce the local -> global mapping for macros within this module.
3372 F.MacroRemap.insertOrReplace(
3373 std::make_pair(LocalBaseMacroID,
3374 F.BaseMacroID - LocalBaseMacroID));
Ben Langmuir52ca6782014-10-20 16:27:32 +00003375
3376 MacrosLoaded.resize(MacrosLoaded.size() + F.LocalNumMacros);
Guy Benyei11169dd2012-12-18 14:30:41 +00003377 }
3378 break;
3379 }
3380
Argyrios Kyrtzidiseb663da2013-03-22 21:12:57 +00003381 case MACRO_TABLE: {
3382 // FIXME: Not used yet.
Guy Benyei11169dd2012-12-18 14:30:41 +00003383 break;
3384 }
Richard Smithe40f2ba2013-08-07 21:41:30 +00003385
3386 case LATE_PARSED_TEMPLATE: {
3387 LateParsedTemplates.append(Record.begin(), Record.end());
3388 break;
3389 }
Dario Domizioli13a0a382014-05-23 12:13:25 +00003390
3391 case OPTIMIZE_PRAGMA_OPTIONS:
3392 if (Record.size() != 1) {
3393 Error("invalid pragma optimize record");
3394 return Failure;
3395 }
3396 OptimizeOffPragmaLocation = ReadSourceLocation(F, Record[0]);
3397 break;
Nico Weber72889432014-09-06 01:25:55 +00003398
3399 case UNUSED_LOCAL_TYPEDEF_NAME_CANDIDATES:
3400 for (unsigned I = 0, N = Record.size(); I != N; ++I)
3401 UnusedLocalTypedefNameCandidates.push_back(
3402 getGlobalDeclID(F, Record[I]));
3403 break;
Guy Benyei11169dd2012-12-18 14:30:41 +00003404 }
3405 }
Guy Benyei11169dd2012-12-18 14:30:41 +00003406}
3407
Ben Langmuir4b8a9e92014-08-12 16:42:33 +00003408ASTReader::ASTReadResult
3409ASTReader::ReadModuleMapFileBlock(RecordData &Record, ModuleFile &F,
3410 const ModuleFile *ImportedBy,
3411 unsigned ClientLoadCapabilities) {
3412 unsigned Idx = 0;
Richard Smith7ed1bc92014-12-05 22:42:13 +00003413 F.ModuleMapPath = ReadPath(F, Record, Idx);
Ben Langmuir4b8a9e92014-08-12 16:42:33 +00003414
Richard Smithe842a472014-10-22 02:05:46 +00003415 if (F.Kind == MK_ExplicitModule) {
3416 // For an explicitly-loaded module, we don't care whether the original
3417 // module map file exists or matches.
3418 return Success;
3419 }
3420
Ben Langmuir4b8a9e92014-08-12 16:42:33 +00003421 // Try to resolve ModuleName in the current header search context and
3422 // verify that it is found in the same module map file as we saved. If the
3423 // top-level AST file is a main file, skip this check because there is no
3424 // usable header search context.
3425 assert(!F.ModuleName.empty() &&
Richard Smithe842a472014-10-22 02:05:46 +00003426 "MODULE_NAME should come before MODULE_MAP_FILE");
3427 if (F.Kind == MK_ImplicitModule &&
3428 (*ModuleMgr.begin())->Kind != MK_MainFile) {
3429 // An implicitly-loaded module file should have its module listed in some
3430 // module map file that we've already loaded.
Ben Langmuir4b8a9e92014-08-12 16:42:33 +00003431 Module *M = PP.getHeaderSearchInfo().lookupModule(F.ModuleName);
Richard Smithe842a472014-10-22 02:05:46 +00003432 auto &Map = PP.getHeaderSearchInfo().getModuleMap();
3433 const FileEntry *ModMap = M ? Map.getModuleMapFileForUniquing(M) : nullptr;
3434 if (!ModMap) {
Ben Langmuir4b8a9e92014-08-12 16:42:33 +00003435 assert(ImportedBy && "top-level import should be verified");
3436 if ((ClientLoadCapabilities & ARR_Missing) == 0)
Richard Smithe842a472014-10-22 02:05:46 +00003437 Diag(diag::err_imported_module_not_found) << F.ModuleName << F.FileName
3438 << ImportedBy->FileName
3439 << F.ModuleMapPath;
Ben Langmuir4b8a9e92014-08-12 16:42:33 +00003440 return Missing;
3441 }
3442
Richard Smithe842a472014-10-22 02:05:46 +00003443 assert(M->Name == F.ModuleName && "found module with different name");
3444
Ben Langmuir4b8a9e92014-08-12 16:42:33 +00003445 // Check the primary module map file.
Ben Langmuir4b8a9e92014-08-12 16:42:33 +00003446 const FileEntry *StoredModMap = FileMgr.getFile(F.ModuleMapPath);
Ben Langmuir4b8a9e92014-08-12 16:42:33 +00003447 if (StoredModMap == nullptr || StoredModMap != ModMap) {
3448 assert(ModMap && "found module is missing module map file");
Ben Langmuir4b8a9e92014-08-12 16:42:33 +00003449 assert(ImportedBy && "top-level import should be verified");
3450 if ((ClientLoadCapabilities & ARR_OutOfDate) == 0)
3451 Diag(diag::err_imported_module_modmap_changed)
3452 << F.ModuleName << ImportedBy->FileName
3453 << ModMap->getName() << F.ModuleMapPath;
3454 return OutOfDate;
3455 }
3456
3457 llvm::SmallPtrSet<const FileEntry *, 1> AdditionalStoredMaps;
3458 for (unsigned I = 0, N = Record[Idx++]; I < N; ++I) {
3459 // FIXME: we should use input files rather than storing names.
Richard Smith7ed1bc92014-12-05 22:42:13 +00003460 std::string Filename = ReadPath(F, Record, Idx);
Ben Langmuir4b8a9e92014-08-12 16:42:33 +00003461 const FileEntry *F =
3462 FileMgr.getFile(Filename, false, false);
3463 if (F == nullptr) {
3464 if ((ClientLoadCapabilities & ARR_OutOfDate) == 0)
3465 Error("could not find file '" + Filename +"' referenced by AST file");
3466 return OutOfDate;
3467 }
3468 AdditionalStoredMaps.insert(F);
3469 }
3470
3471 // Check any additional module map files (e.g. module.private.modulemap)
3472 // that are not in the pcm.
3473 if (auto *AdditionalModuleMaps = Map.getAdditionalModuleMapFiles(M)) {
3474 for (const FileEntry *ModMap : *AdditionalModuleMaps) {
3475 // Remove files that match
3476 // Note: SmallPtrSet::erase is really remove
3477 if (!AdditionalStoredMaps.erase(ModMap)) {
3478 if ((ClientLoadCapabilities & ARR_OutOfDate) == 0)
3479 Diag(diag::err_module_different_modmap)
3480 << F.ModuleName << /*new*/0 << ModMap->getName();
3481 return OutOfDate;
3482 }
3483 }
3484 }
3485
3486 // Check any additional module map files that are in the pcm, but not
3487 // found in header search. Cases that match are already removed.
3488 for (const FileEntry *ModMap : AdditionalStoredMaps) {
3489 if ((ClientLoadCapabilities & ARR_OutOfDate) == 0)
3490 Diag(diag::err_module_different_modmap)
3491 << F.ModuleName << /*not new*/1 << ModMap->getName();
3492 return OutOfDate;
3493 }
3494 }
3495
3496 if (Listener)
3497 Listener->ReadModuleMapFile(F.ModuleMapPath);
3498 return Success;
3499}
3500
3501
Douglas Gregorc1489562013-02-12 23:36:21 +00003502/// \brief Move the given method to the back of the global list of methods.
3503static void moveMethodToBackOfGlobalList(Sema &S, ObjCMethodDecl *Method) {
3504 // Find the entry for this selector in the method pool.
3505 Sema::GlobalMethodPool::iterator Known
3506 = S.MethodPool.find(Method->getSelector());
3507 if (Known == S.MethodPool.end())
3508 return;
3509
3510 // Retrieve the appropriate method list.
3511 ObjCMethodList &Start = Method->isInstanceMethod()? Known->second.first
3512 : Known->second.second;
3513 bool Found = false;
Argyrios Kyrtzidisd3da6e02013-04-17 00:08:58 +00003514 for (ObjCMethodList *List = &Start; List; List = List->getNext()) {
Douglas Gregorc1489562013-02-12 23:36:21 +00003515 if (!Found) {
Nico Weber2e0c8f72014-12-27 03:58:08 +00003516 if (List->getMethod() == Method) {
Douglas Gregorc1489562013-02-12 23:36:21 +00003517 Found = true;
3518 } else {
3519 // Keep searching.
3520 continue;
3521 }
3522 }
3523
Argyrios Kyrtzidisd3da6e02013-04-17 00:08:58 +00003524 if (List->getNext())
Nico Weber2e0c8f72014-12-27 03:58:08 +00003525 List->setMethod(List->getNext()->getMethod());
Douglas Gregorc1489562013-02-12 23:36:21 +00003526 else
Nico Weber2e0c8f72014-12-27 03:58:08 +00003527 List->setMethod(Method);
Douglas Gregorc1489562013-02-12 23:36:21 +00003528 }
3529}
3530
Richard Smithe657bbd2014-07-18 22:13:40 +00003531void ASTReader::makeNamesVisible(const HiddenNames &Names, Module *Owner,
3532 bool FromFinalization) {
3533 // FIXME: Only do this if Owner->NameVisibility == AllVisible.
Richard Smith57721ac2014-07-21 04:10:40 +00003534 for (Decl *D : Names.HiddenDecls) {
Richard Smith49f906a2014-03-01 00:08:04 +00003535 bool wasHidden = D->Hidden;
3536 D->Hidden = false;
Guy Benyei11169dd2012-12-18 14:30:41 +00003537
Richard Smith49f906a2014-03-01 00:08:04 +00003538 if (wasHidden && SemaObj) {
3539 if (ObjCMethodDecl *Method = dyn_cast<ObjCMethodDecl>(D)) {
3540 moveMethodToBackOfGlobalList(*SemaObj, Method);
Douglas Gregorc1489562013-02-12 23:36:21 +00003541 }
Guy Benyei11169dd2012-12-18 14:30:41 +00003542 }
3543 }
Richard Smith49f906a2014-03-01 00:08:04 +00003544
Richard Smithe657bbd2014-07-18 22:13:40 +00003545 assert((FromFinalization || Owner->NameVisibility >= Module::MacrosVisible) &&
3546 "nothing to make visible?");
Richard Smithdaa69e02014-07-25 04:40:03 +00003547 for (const auto &Macro : Names.HiddenMacros) {
3548 if (FromFinalization)
3549 PP.appendMacroDirective(Macro.first,
3550 Macro.second->import(PP, SourceLocation()));
3551 else
3552 installImportedMacro(Macro.first, Macro.second, Owner);
3553 }
Guy Benyei11169dd2012-12-18 14:30:41 +00003554}
3555
Richard Smith49f906a2014-03-01 00:08:04 +00003556void ASTReader::makeModuleVisible(Module *Mod,
Argyrios Kyrtzidis125df052013-02-01 16:36:12 +00003557 Module::NameVisibilityKind NameVisibility,
Douglas Gregorfb912652013-03-20 21:10:35 +00003558 SourceLocation ImportLoc,
3559 bool Complain) {
Guy Benyei11169dd2012-12-18 14:30:41 +00003560 llvm::SmallPtrSet<Module *, 4> Visited;
Dmitri Gribenkof8579502013-01-12 19:30:44 +00003561 SmallVector<Module *, 4> Stack;
Robert Wilhelm25284cc2013-08-23 16:11:15 +00003562 Stack.push_back(Mod);
Guy Benyei11169dd2012-12-18 14:30:41 +00003563 while (!Stack.empty()) {
Robert Wilhelm25284cc2013-08-23 16:11:15 +00003564 Mod = Stack.pop_back_val();
Guy Benyei11169dd2012-12-18 14:30:41 +00003565
3566 if (NameVisibility <= Mod->NameVisibility) {
Robert Wilhelm25284cc2013-08-23 16:11:15 +00003567 // This module already has this level of visibility (or greater), so
Guy Benyei11169dd2012-12-18 14:30:41 +00003568 // there is nothing more to do.
3569 continue;
3570 }
Richard Smith49f906a2014-03-01 00:08:04 +00003571
Guy Benyei11169dd2012-12-18 14:30:41 +00003572 if (!Mod->isAvailable()) {
3573 // Modules that aren't available cannot be made visible.
3574 continue;
3575 }
3576
3577 // Update the module's name visibility.
Richard Smith49f906a2014-03-01 00:08:04 +00003578 if (NameVisibility >= Module::MacrosVisible &&
3579 Mod->NameVisibility < Module::MacrosVisible)
3580 Mod->MacroVisibilityLoc = ImportLoc;
Guy Benyei11169dd2012-12-18 14:30:41 +00003581 Mod->NameVisibility = NameVisibility;
Richard Smith49f906a2014-03-01 00:08:04 +00003582
Guy Benyei11169dd2012-12-18 14:30:41 +00003583 // If we've already deserialized any names from this module,
3584 // mark them as visible.
3585 HiddenNamesMapType::iterator Hidden = HiddenNamesMap.find(Mod);
3586 if (Hidden != HiddenNamesMap.end()) {
Richard Smith57721ac2014-07-21 04:10:40 +00003587 auto HiddenNames = std::move(*Hidden);
Guy Benyei11169dd2012-12-18 14:30:41 +00003588 HiddenNamesMap.erase(Hidden);
Richard Smith57721ac2014-07-21 04:10:40 +00003589 makeNamesVisible(HiddenNames.second, HiddenNames.first,
3590 /*FromFinalization*/false);
3591 assert(HiddenNamesMap.find(Mod) == HiddenNamesMap.end() &&
3592 "making names visible added hidden names");
Guy Benyei11169dd2012-12-18 14:30:41 +00003593 }
Dmitri Gribenkoe9bcf5b2013-11-04 21:51:33 +00003594
Guy Benyei11169dd2012-12-18 14:30:41 +00003595 // Push any exported modules onto the stack to be marked as visible.
Argyrios Kyrtzidis8739f7b2013-02-19 19:34:40 +00003596 SmallVector<Module *, 16> Exports;
3597 Mod->getExportedModules(Exports);
3598 for (SmallVectorImpl<Module *>::iterator
3599 I = Exports.begin(), E = Exports.end(); I != E; ++I) {
3600 Module *Exported = *I;
David Blaikie82e95a32014-11-19 07:49:47 +00003601 if (Visited.insert(Exported).second)
Argyrios Kyrtzidis8739f7b2013-02-19 19:34:40 +00003602 Stack.push_back(Exported);
Guy Benyei11169dd2012-12-18 14:30:41 +00003603 }
Douglas Gregorfb912652013-03-20 21:10:35 +00003604
3605 // Detect any conflicts.
3606 if (Complain) {
3607 assert(ImportLoc.isValid() && "Missing import location");
3608 for (unsigned I = 0, N = Mod->Conflicts.size(); I != N; ++I) {
3609 if (Mod->Conflicts[I].Other->NameVisibility >= NameVisibility) {
3610 Diag(ImportLoc, diag::warn_module_conflict)
3611 << Mod->getFullModuleName()
3612 << Mod->Conflicts[I].Other->getFullModuleName()
3613 << Mod->Conflicts[I].Message;
3614 // FIXME: Need note where the other module was imported.
3615 }
3616 }
3617 }
Guy Benyei11169dd2012-12-18 14:30:41 +00003618 }
3619}
3620
Douglas Gregore060e572013-01-25 01:03:03 +00003621bool ASTReader::loadGlobalIndex() {
3622 if (GlobalIndex)
3623 return false;
3624
3625 if (TriedLoadingGlobalIndex || !UseGlobalIndex ||
3626 !Context.getLangOpts().Modules)
3627 return true;
3628
3629 // Try to load the global index.
3630 TriedLoadingGlobalIndex = true;
3631 StringRef ModuleCachePath
3632 = getPreprocessor().getHeaderSearchInfo().getModuleCachePath();
3633 std::pair<GlobalModuleIndex *, GlobalModuleIndex::ErrorCode> Result
Douglas Gregor7029ce12013-03-19 00:28:20 +00003634 = GlobalModuleIndex::readIndex(ModuleCachePath);
Douglas Gregore060e572013-01-25 01:03:03 +00003635 if (!Result.first)
3636 return true;
3637
3638 GlobalIndex.reset(Result.first);
Douglas Gregor7211ac12013-01-25 23:32:03 +00003639 ModuleMgr.setGlobalIndex(GlobalIndex.get());
Douglas Gregore060e572013-01-25 01:03:03 +00003640 return false;
3641}
3642
3643bool ASTReader::isGlobalIndexUnavailable() const {
3644 return Context.getLangOpts().Modules && UseGlobalIndex &&
3645 !hasGlobalIndex() && TriedLoadingGlobalIndex;
3646}
3647
Dmitri Gribenkof430da42014-02-12 10:33:14 +00003648static void updateModuleTimestamp(ModuleFile &MF) {
3649 // Overwrite the timestamp file contents so that file's mtime changes.
3650 std::string TimestampFilename = MF.getTimestampFilename();
Rafael Espindoladae941a2014-08-25 18:17:04 +00003651 std::error_code EC;
3652 llvm::raw_fd_ostream OS(TimestampFilename, EC, llvm::sys::fs::F_Text);
3653 if (EC)
Dmitri Gribenkof430da42014-02-12 10:33:14 +00003654 return;
3655 OS << "Timestamp file\n";
3656}
3657
Guy Benyei11169dd2012-12-18 14:30:41 +00003658ASTReader::ASTReadResult ASTReader::ReadAST(const std::string &FileName,
3659 ModuleKind Type,
3660 SourceLocation ImportLoc,
3661 unsigned ClientLoadCapabilities) {
Argyrios Kyrtzidisdc9fdaf2013-05-24 05:44:08 +00003662 llvm::SaveAndRestore<SourceLocation>
3663 SetCurImportLocRAII(CurrentImportLoc, ImportLoc);
3664
Richard Smithd1c46742014-04-30 02:24:17 +00003665 // Defer any pending actions until we get to the end of reading the AST file.
3666 Deserializing AnASTFile(this);
3667
Guy Benyei11169dd2012-12-18 14:30:41 +00003668 // Bump the generation number.
Richard Smith053f6c62014-05-16 23:01:30 +00003669 unsigned PreviousGeneration = incrementGeneration(Context);
Guy Benyei11169dd2012-12-18 14:30:41 +00003670
3671 unsigned NumModules = ModuleMgr.size();
Dmitri Gribenkof8579502013-01-12 19:30:44 +00003672 SmallVector<ImportedModule, 4> Loaded;
Guy Benyei11169dd2012-12-18 14:30:41 +00003673 switch(ASTReadResult ReadResult = ReadASTCore(FileName, Type, ImportLoc,
Craig Toppera13603a2014-05-22 05:54:18 +00003674 /*ImportedBy=*/nullptr, Loaded,
Ben Langmuir487ea142014-10-23 18:05:36 +00003675 0, 0, 0,
Guy Benyei11169dd2012-12-18 14:30:41 +00003676 ClientLoadCapabilities)) {
3677 case Failure:
Douglas Gregor7029ce12013-03-19 00:28:20 +00003678 case Missing:
Guy Benyei11169dd2012-12-18 14:30:41 +00003679 case OutOfDate:
3680 case VersionMismatch:
3681 case ConfigurationMismatch:
Ben Langmuir9801b252014-06-20 00:24:56 +00003682 case HadErrors: {
3683 llvm::SmallPtrSet<ModuleFile *, 4> LoadedSet;
3684 for (const ImportedModule &IM : Loaded)
3685 LoadedSet.insert(IM.Mod);
3686
Douglas Gregor7029ce12013-03-19 00:28:20 +00003687 ModuleMgr.removeModules(ModuleMgr.begin() + NumModules, ModuleMgr.end(),
Ben Langmuir9801b252014-06-20 00:24:56 +00003688 LoadedSet,
Douglas Gregor7029ce12013-03-19 00:28:20 +00003689 Context.getLangOpts().Modules
3690 ? &PP.getHeaderSearchInfo().getModuleMap()
Craig Toppera13603a2014-05-22 05:54:18 +00003691 : nullptr);
Douglas Gregore060e572013-01-25 01:03:03 +00003692
3693 // If we find that any modules are unusable, the global index is going
3694 // to be out-of-date. Just remove it.
3695 GlobalIndex.reset();
Craig Toppera13603a2014-05-22 05:54:18 +00003696 ModuleMgr.setGlobalIndex(nullptr);
Guy Benyei11169dd2012-12-18 14:30:41 +00003697 return ReadResult;
Ben Langmuir9801b252014-06-20 00:24:56 +00003698 }
Guy Benyei11169dd2012-12-18 14:30:41 +00003699 case Success:
3700 break;
3701 }
3702
3703 // Here comes stuff that we only do once the entire chain is loaded.
3704
3705 // Load the AST blocks of all of the modules that we loaded.
Dmitri Gribenkof8579502013-01-12 19:30:44 +00003706 for (SmallVectorImpl<ImportedModule>::iterator M = Loaded.begin(),
3707 MEnd = Loaded.end();
Guy Benyei11169dd2012-12-18 14:30:41 +00003708 M != MEnd; ++M) {
3709 ModuleFile &F = *M->Mod;
3710
3711 // Read the AST block.
Ben Langmuir2c9af442014-04-10 17:57:43 +00003712 if (ASTReadResult Result = ReadASTBlock(F, ClientLoadCapabilities))
3713 return Result;
Guy Benyei11169dd2012-12-18 14:30:41 +00003714
3715 // Once read, set the ModuleFile bit base offset and update the size in
3716 // bits of all files we've seen.
3717 F.GlobalBitOffset = TotalModulesSizeInBits;
3718 TotalModulesSizeInBits += F.SizeInBits;
3719 GlobalBitOffsetsMap.insert(std::make_pair(F.GlobalBitOffset, &F));
3720
3721 // Preload SLocEntries.
3722 for (unsigned I = 0, N = F.PreloadSLocEntries.size(); I != N; ++I) {
3723 int Index = int(F.PreloadSLocEntries[I] - 1) + F.SLocEntryBaseID;
3724 // Load it through the SourceManager and don't call ReadSLocEntry()
3725 // directly because the entry may have already been loaded in which case
3726 // calling ReadSLocEntry() directly would trigger an assertion in
3727 // SourceManager.
3728 SourceMgr.getLoadedSLocEntryByID(Index);
3729 }
3730 }
3731
Douglas Gregor603cd862013-03-22 18:50:14 +00003732 // Setup the import locations and notify the module manager that we've
3733 // committed to these module files.
Dmitri Gribenkof8579502013-01-12 19:30:44 +00003734 for (SmallVectorImpl<ImportedModule>::iterator M = Loaded.begin(),
3735 MEnd = Loaded.end();
Guy Benyei11169dd2012-12-18 14:30:41 +00003736 M != MEnd; ++M) {
3737 ModuleFile &F = *M->Mod;
Douglas Gregor603cd862013-03-22 18:50:14 +00003738
3739 ModuleMgr.moduleFileAccepted(&F);
3740
3741 // Set the import location.
Argyrios Kyrtzidis71c1af82013-02-01 16:36:14 +00003742 F.DirectImportLoc = ImportLoc;
Guy Benyei11169dd2012-12-18 14:30:41 +00003743 if (!M->ImportedBy)
3744 F.ImportLoc = M->ImportLoc;
3745 else
3746 F.ImportLoc = ReadSourceLocation(*M->ImportedBy,
3747 M->ImportLoc.getRawEncoding());
3748 }
3749
3750 // Mark all of the identifiers in the identifier table as being out of date,
3751 // so that various accessors know to check the loaded modules when the
3752 // identifier is used.
3753 for (IdentifierTable::iterator Id = PP.getIdentifierTable().begin(),
3754 IdEnd = PP.getIdentifierTable().end();
3755 Id != IdEnd; ++Id)
3756 Id->second->setOutOfDate(true);
3757
3758 // Resolve any unresolved module exports.
Douglas Gregorfb912652013-03-20 21:10:35 +00003759 for (unsigned I = 0, N = UnresolvedModuleRefs.size(); I != N; ++I) {
3760 UnresolvedModuleRef &Unresolved = UnresolvedModuleRefs[I];
Guy Benyei11169dd2012-12-18 14:30:41 +00003761 SubmoduleID GlobalID = getGlobalSubmoduleID(*Unresolved.File,Unresolved.ID);
3762 Module *ResolvedMod = getSubmodule(GlobalID);
Douglas Gregorfb912652013-03-20 21:10:35 +00003763
3764 switch (Unresolved.Kind) {
3765 case UnresolvedModuleRef::Conflict:
3766 if (ResolvedMod) {
3767 Module::Conflict Conflict;
3768 Conflict.Other = ResolvedMod;
3769 Conflict.Message = Unresolved.String.str();
3770 Unresolved.Mod->Conflicts.push_back(Conflict);
3771 }
3772 continue;
3773
3774 case UnresolvedModuleRef::Import:
Guy Benyei11169dd2012-12-18 14:30:41 +00003775 if (ResolvedMod)
3776 Unresolved.Mod->Imports.push_back(ResolvedMod);
3777 continue;
Guy Benyei11169dd2012-12-18 14:30:41 +00003778
Douglas Gregorfb912652013-03-20 21:10:35 +00003779 case UnresolvedModuleRef::Export:
3780 if (ResolvedMod || Unresolved.IsWildcard)
3781 Unresolved.Mod->Exports.push_back(
3782 Module::ExportDecl(ResolvedMod, Unresolved.IsWildcard));
3783 continue;
3784 }
Guy Benyei11169dd2012-12-18 14:30:41 +00003785 }
Douglas Gregorfb912652013-03-20 21:10:35 +00003786 UnresolvedModuleRefs.clear();
Daniel Jasperba7f2f72013-09-24 09:14:14 +00003787
3788 // FIXME: How do we load the 'use'd modules? They may not be submodules.
3789 // Might be unnecessary as use declarations are only used to build the
3790 // module itself.
Guy Benyei11169dd2012-12-18 14:30:41 +00003791
3792 InitializeContext();
3793
Richard Smith3d8e97e2013-10-18 06:54:39 +00003794 if (SemaObj)
3795 UpdateSema();
3796
Guy Benyei11169dd2012-12-18 14:30:41 +00003797 if (DeserializationListener)
3798 DeserializationListener->ReaderInitialized(this);
3799
3800 ModuleFile &PrimaryModule = ModuleMgr.getPrimaryModule();
3801 if (!PrimaryModule.OriginalSourceFileID.isInvalid()) {
3802 PrimaryModule.OriginalSourceFileID
3803 = FileID::get(PrimaryModule.SLocEntryBaseID
3804 + PrimaryModule.OriginalSourceFileID.getOpaqueValue() - 1);
3805
3806 // If this AST file is a precompiled preamble, then set the
3807 // preamble file ID of the source manager to the file source file
3808 // from which the preamble was built.
3809 if (Type == MK_Preamble) {
3810 SourceMgr.setPreambleFileID(PrimaryModule.OriginalSourceFileID);
3811 } else if (Type == MK_MainFile) {
3812 SourceMgr.setMainFileID(PrimaryModule.OriginalSourceFileID);
3813 }
3814 }
3815
3816 // For any Objective-C class definitions we have already loaded, make sure
3817 // that we load any additional categories.
3818 for (unsigned I = 0, N = ObjCClassesLoaded.size(); I != N; ++I) {
3819 loadObjCCategories(ObjCClassesLoaded[I]->getGlobalID(),
3820 ObjCClassesLoaded[I],
3821 PreviousGeneration);
3822 }
Douglas Gregore060e572013-01-25 01:03:03 +00003823
Dmitri Gribenkof430da42014-02-12 10:33:14 +00003824 if (PP.getHeaderSearchInfo()
3825 .getHeaderSearchOpts()
3826 .ModulesValidateOncePerBuildSession) {
3827 // Now we are certain that the module and all modules it depends on are
3828 // up to date. Create or update timestamp files for modules that are
3829 // located in the module cache (not for PCH files that could be anywhere
3830 // in the filesystem).
3831 for (unsigned I = 0, N = Loaded.size(); I != N; ++I) {
3832 ImportedModule &M = Loaded[I];
Richard Smithe842a472014-10-22 02:05:46 +00003833 if (M.Mod->Kind == MK_ImplicitModule) {
Dmitri Gribenkof430da42014-02-12 10:33:14 +00003834 updateModuleTimestamp(*M.Mod);
3835 }
3836 }
3837 }
3838
Guy Benyei11169dd2012-12-18 14:30:41 +00003839 return Success;
3840}
3841
Ben Langmuir487ea142014-10-23 18:05:36 +00003842static ASTFileSignature readASTFileSignature(llvm::BitstreamReader &StreamFile);
3843
Guy Benyei11169dd2012-12-18 14:30:41 +00003844ASTReader::ASTReadResult
3845ASTReader::ReadASTCore(StringRef FileName,
3846 ModuleKind Type,
3847 SourceLocation ImportLoc,
3848 ModuleFile *ImportedBy,
Dmitri Gribenkof8579502013-01-12 19:30:44 +00003849 SmallVectorImpl<ImportedModule> &Loaded,
Douglas Gregor7029ce12013-03-19 00:28:20 +00003850 off_t ExpectedSize, time_t ExpectedModTime,
Ben Langmuir487ea142014-10-23 18:05:36 +00003851 ASTFileSignature ExpectedSignature,
Guy Benyei11169dd2012-12-18 14:30:41 +00003852 unsigned ClientLoadCapabilities) {
3853 ModuleFile *M;
Guy Benyei11169dd2012-12-18 14:30:41 +00003854 std::string ErrorStr;
Douglas Gregor7029ce12013-03-19 00:28:20 +00003855 ModuleManager::AddModuleResult AddResult
3856 = ModuleMgr.addModule(FileName, Type, ImportLoc, ImportedBy,
Richard Smith053f6c62014-05-16 23:01:30 +00003857 getGeneration(), ExpectedSize, ExpectedModTime,
Ben Langmuir487ea142014-10-23 18:05:36 +00003858 ExpectedSignature, readASTFileSignature,
Douglas Gregor7029ce12013-03-19 00:28:20 +00003859 M, ErrorStr);
Guy Benyei11169dd2012-12-18 14:30:41 +00003860
Douglas Gregor7029ce12013-03-19 00:28:20 +00003861 switch (AddResult) {
3862 case ModuleManager::AlreadyLoaded:
3863 return Success;
3864
3865 case ModuleManager::NewlyLoaded:
3866 // Load module file below.
3867 break;
3868
3869 case ModuleManager::Missing:
Richard Smithe842a472014-10-22 02:05:46 +00003870 // The module file was missing; if the client can handle that, return
Douglas Gregor7029ce12013-03-19 00:28:20 +00003871 // it.
3872 if (ClientLoadCapabilities & ARR_Missing)
3873 return Missing;
3874
3875 // Otherwise, return an error.
3876 {
3877 std::string Msg = "Unable to load module \"" + FileName.str() + "\": "
3878 + ErrorStr;
3879 Error(Msg);
3880 }
3881 return Failure;
3882
3883 case ModuleManager::OutOfDate:
3884 // We couldn't load the module file because it is out-of-date. If the
3885 // client can handle out-of-date, return it.
3886 if (ClientLoadCapabilities & ARR_OutOfDate)
3887 return OutOfDate;
3888
3889 // Otherwise, return an error.
3890 {
3891 std::string Msg = "Unable to load module \"" + FileName.str() + "\": "
3892 + ErrorStr;
3893 Error(Msg);
3894 }
Guy Benyei11169dd2012-12-18 14:30:41 +00003895 return Failure;
3896 }
3897
Douglas Gregor7029ce12013-03-19 00:28:20 +00003898 assert(M && "Missing module file");
Guy Benyei11169dd2012-12-18 14:30:41 +00003899
3900 // FIXME: This seems rather a hack. Should CurrentDir be part of the
3901 // module?
3902 if (FileName != "-") {
3903 CurrentDir = llvm::sys::path::parent_path(FileName);
3904 if (CurrentDir.empty()) CurrentDir = ".";
3905 }
3906
3907 ModuleFile &F = *M;
Chris Lattner7fb3bef2013-01-20 00:56:42 +00003908 BitstreamCursor &Stream = F.Stream;
Adrian Prantl8bf7af32015-02-25 01:31:45 +00003909 InitStreamFileWithModule(F.Buffer->getMemBufferRef(), F.StreamFile);
Rafael Espindolafd832392014-11-12 14:48:44 +00003910 Stream.init(&F.StreamFile);
Adrian Prantl8bf7af32015-02-25 01:31:45 +00003911 F.SizeInBits = F.StreamFile.getBitcodeBytes().getExtent() * 8;
3912
Guy Benyei11169dd2012-12-18 14:30:41 +00003913 // Sniff for the signature.
3914 if (Stream.Read(8) != 'C' ||
3915 Stream.Read(8) != 'P' ||
3916 Stream.Read(8) != 'C' ||
3917 Stream.Read(8) != 'H') {
3918 Diag(diag::err_not_a_pch_file) << FileName;
3919 return Failure;
3920 }
3921
3922 // This is used for compatibility with older PCH formats.
3923 bool HaveReadControlBlock = false;
3924
Chris Lattnerefa77172013-01-20 00:00:22 +00003925 while (1) {
3926 llvm::BitstreamEntry Entry = Stream.advance();
3927
3928 switch (Entry.Kind) {
3929 case llvm::BitstreamEntry::Error:
3930 case llvm::BitstreamEntry::EndBlock:
3931 case llvm::BitstreamEntry::Record:
Guy Benyei11169dd2012-12-18 14:30:41 +00003932 Error("invalid record at top-level of AST file");
3933 return Failure;
Chris Lattnerefa77172013-01-20 00:00:22 +00003934
3935 case llvm::BitstreamEntry::SubBlock:
3936 break;
Guy Benyei11169dd2012-12-18 14:30:41 +00003937 }
3938
Guy Benyei11169dd2012-12-18 14:30:41 +00003939 // We only know the control subblock ID.
Chris Lattnerefa77172013-01-20 00:00:22 +00003940 switch (Entry.ID) {
Guy Benyei11169dd2012-12-18 14:30:41 +00003941 case llvm::bitc::BLOCKINFO_BLOCK_ID:
3942 if (Stream.ReadBlockInfoBlock()) {
3943 Error("malformed BlockInfoBlock in AST file");
3944 return Failure;
3945 }
3946 break;
3947 case CONTROL_BLOCK_ID:
3948 HaveReadControlBlock = true;
Ben Langmuirbeee15e2014-04-14 18:00:01 +00003949 switch (ReadControlBlock(F, Loaded, ImportedBy, ClientLoadCapabilities)) {
Guy Benyei11169dd2012-12-18 14:30:41 +00003950 case Success:
3951 break;
3952
3953 case Failure: return Failure;
Douglas Gregor7029ce12013-03-19 00:28:20 +00003954 case Missing: return Missing;
Guy Benyei11169dd2012-12-18 14:30:41 +00003955 case OutOfDate: return OutOfDate;
3956 case VersionMismatch: return VersionMismatch;
3957 case ConfigurationMismatch: return ConfigurationMismatch;
3958 case HadErrors: return HadErrors;
3959 }
3960 break;
3961 case AST_BLOCK_ID:
3962 if (!HaveReadControlBlock) {
3963 if ((ClientLoadCapabilities & ARR_VersionMismatch) == 0)
Dmitri Gribenko2228cd32014-02-11 15:40:09 +00003964 Diag(diag::err_pch_version_too_old);
Guy Benyei11169dd2012-12-18 14:30:41 +00003965 return VersionMismatch;
3966 }
3967
3968 // Record that we've loaded this module.
3969 Loaded.push_back(ImportedModule(M, ImportedBy, ImportLoc));
3970 return Success;
3971
3972 default:
3973 if (Stream.SkipBlock()) {
3974 Error("malformed block record in AST file");
3975 return Failure;
3976 }
3977 break;
3978 }
3979 }
3980
3981 return Success;
3982}
3983
3984void ASTReader::InitializeContext() {
3985 // If there's a listener, notify them that we "read" the translation unit.
3986 if (DeserializationListener)
3987 DeserializationListener->DeclRead(PREDEF_DECL_TRANSLATION_UNIT_ID,
3988 Context.getTranslationUnitDecl());
3989
Guy Benyei11169dd2012-12-18 14:30:41 +00003990 // FIXME: Find a better way to deal with collisions between these
3991 // built-in types. Right now, we just ignore the problem.
3992
3993 // Load the special types.
3994 if (SpecialTypes.size() >= NumSpecialTypeIDs) {
3995 if (unsigned String = SpecialTypes[SPECIAL_TYPE_CF_CONSTANT_STRING]) {
3996 if (!Context.CFConstantStringTypeDecl)
3997 Context.setCFConstantStringType(GetType(String));
3998 }
3999
4000 if (unsigned File = SpecialTypes[SPECIAL_TYPE_FILE]) {
4001 QualType FileType = GetType(File);
4002 if (FileType.isNull()) {
4003 Error("FILE type is NULL");
4004 return;
4005 }
4006
4007 if (!Context.FILEDecl) {
4008 if (const TypedefType *Typedef = FileType->getAs<TypedefType>())
4009 Context.setFILEDecl(Typedef->getDecl());
4010 else {
4011 const TagType *Tag = FileType->getAs<TagType>();
4012 if (!Tag) {
4013 Error("Invalid FILE type in AST file");
4014 return;
4015 }
4016 Context.setFILEDecl(Tag->getDecl());
4017 }
4018 }
4019 }
4020
4021 if (unsigned Jmp_buf = SpecialTypes[SPECIAL_TYPE_JMP_BUF]) {
4022 QualType Jmp_bufType = GetType(Jmp_buf);
4023 if (Jmp_bufType.isNull()) {
4024 Error("jmp_buf type is NULL");
4025 return;
4026 }
4027
4028 if (!Context.jmp_bufDecl) {
4029 if (const TypedefType *Typedef = Jmp_bufType->getAs<TypedefType>())
4030 Context.setjmp_bufDecl(Typedef->getDecl());
4031 else {
4032 const TagType *Tag = Jmp_bufType->getAs<TagType>();
4033 if (!Tag) {
4034 Error("Invalid jmp_buf type in AST file");
4035 return;
4036 }
4037 Context.setjmp_bufDecl(Tag->getDecl());
4038 }
4039 }
4040 }
4041
4042 if (unsigned Sigjmp_buf = SpecialTypes[SPECIAL_TYPE_SIGJMP_BUF]) {
4043 QualType Sigjmp_bufType = GetType(Sigjmp_buf);
4044 if (Sigjmp_bufType.isNull()) {
4045 Error("sigjmp_buf type is NULL");
4046 return;
4047 }
4048
4049 if (!Context.sigjmp_bufDecl) {
4050 if (const TypedefType *Typedef = Sigjmp_bufType->getAs<TypedefType>())
4051 Context.setsigjmp_bufDecl(Typedef->getDecl());
4052 else {
4053 const TagType *Tag = Sigjmp_bufType->getAs<TagType>();
4054 assert(Tag && "Invalid sigjmp_buf type in AST file");
4055 Context.setsigjmp_bufDecl(Tag->getDecl());
4056 }
4057 }
4058 }
4059
4060 if (unsigned ObjCIdRedef
4061 = SpecialTypes[SPECIAL_TYPE_OBJC_ID_REDEFINITION]) {
4062 if (Context.ObjCIdRedefinitionType.isNull())
4063 Context.ObjCIdRedefinitionType = GetType(ObjCIdRedef);
4064 }
4065
4066 if (unsigned ObjCClassRedef
4067 = SpecialTypes[SPECIAL_TYPE_OBJC_CLASS_REDEFINITION]) {
4068 if (Context.ObjCClassRedefinitionType.isNull())
4069 Context.ObjCClassRedefinitionType = GetType(ObjCClassRedef);
4070 }
4071
4072 if (unsigned ObjCSelRedef
4073 = SpecialTypes[SPECIAL_TYPE_OBJC_SEL_REDEFINITION]) {
4074 if (Context.ObjCSelRedefinitionType.isNull())
4075 Context.ObjCSelRedefinitionType = GetType(ObjCSelRedef);
4076 }
4077
4078 if (unsigned Ucontext_t = SpecialTypes[SPECIAL_TYPE_UCONTEXT_T]) {
4079 QualType Ucontext_tType = GetType(Ucontext_t);
4080 if (Ucontext_tType.isNull()) {
4081 Error("ucontext_t type is NULL");
4082 return;
4083 }
4084
4085 if (!Context.ucontext_tDecl) {
4086 if (const TypedefType *Typedef = Ucontext_tType->getAs<TypedefType>())
4087 Context.setucontext_tDecl(Typedef->getDecl());
4088 else {
4089 const TagType *Tag = Ucontext_tType->getAs<TagType>();
4090 assert(Tag && "Invalid ucontext_t type in AST file");
4091 Context.setucontext_tDecl(Tag->getDecl());
4092 }
4093 }
4094 }
4095 }
4096
4097 ReadPragmaDiagnosticMappings(Context.getDiagnostics());
4098
4099 // If there were any CUDA special declarations, deserialize them.
4100 if (!CUDASpecialDeclRefs.empty()) {
4101 assert(CUDASpecialDeclRefs.size() == 1 && "More decl refs than expected!");
4102 Context.setcudaConfigureCallDecl(
4103 cast<FunctionDecl>(GetDecl(CUDASpecialDeclRefs[0])));
4104 }
Richard Smith56be7542014-03-21 00:33:59 +00004105
Guy Benyei11169dd2012-12-18 14:30:41 +00004106 // Re-export any modules that were imported by a non-module AST file.
Richard Smith56be7542014-03-21 00:33:59 +00004107 // FIXME: This does not make macro-only imports visible again. It also doesn't
4108 // make #includes mapped to module imports visible.
4109 for (auto &Import : ImportedModules) {
4110 if (Module *Imported = getSubmodule(Import.ID))
Argyrios Kyrtzidis125df052013-02-01 16:36:12 +00004111 makeModuleVisible(Imported, Module::AllVisible,
Richard Smith56be7542014-03-21 00:33:59 +00004112 /*ImportLoc=*/Import.ImportLoc,
Douglas Gregorfb912652013-03-20 21:10:35 +00004113 /*Complain=*/false);
Guy Benyei11169dd2012-12-18 14:30:41 +00004114 }
4115 ImportedModules.clear();
4116}
4117
4118void ASTReader::finalizeForWriting() {
Richard Smith57721ac2014-07-21 04:10:40 +00004119 while (!HiddenNamesMap.empty()) {
4120 auto HiddenNames = std::move(*HiddenNamesMap.begin());
4121 HiddenNamesMap.erase(HiddenNamesMap.begin());
4122 makeNamesVisible(HiddenNames.second, HiddenNames.first,
4123 /*FromFinalization*/true);
Guy Benyei11169dd2012-12-18 14:30:41 +00004124 }
Guy Benyei11169dd2012-12-18 14:30:41 +00004125}
4126
Argyrios Kyrtzidisc4cd2c42013-05-06 19:23:40 +00004127/// \brief Given a cursor at the start of an AST file, scan ahead and drop the
4128/// cursor into the start of the given block ID, returning false on success and
4129/// true on failure.
4130static bool SkipCursorToBlock(BitstreamCursor &Cursor, unsigned BlockID) {
Chris Lattner7fb3bef2013-01-20 00:56:42 +00004131 while (1) {
4132 llvm::BitstreamEntry Entry = Cursor.advance();
4133 switch (Entry.Kind) {
4134 case llvm::BitstreamEntry::Error:
4135 case llvm::BitstreamEntry::EndBlock:
4136 return true;
4137
4138 case llvm::BitstreamEntry::Record:
4139 // Ignore top-level records.
4140 Cursor.skipRecord(Entry.ID);
4141 break;
4142
4143 case llvm::BitstreamEntry::SubBlock:
Argyrios Kyrtzidisc4cd2c42013-05-06 19:23:40 +00004144 if (Entry.ID == BlockID) {
4145 if (Cursor.EnterSubBlock(BlockID))
Chris Lattner7fb3bef2013-01-20 00:56:42 +00004146 return true;
4147 // Found it!
4148 return false;
4149 }
4150
4151 if (Cursor.SkipBlock())
4152 return true;
4153 }
4154 }
4155}
4156
Ben Langmuir487ea142014-10-23 18:05:36 +00004157static ASTFileSignature readASTFileSignature(llvm::BitstreamReader &StreamFile){
4158 BitstreamCursor Stream(StreamFile);
4159 if (Stream.Read(8) != 'C' ||
4160 Stream.Read(8) != 'P' ||
4161 Stream.Read(8) != 'C' ||
4162 Stream.Read(8) != 'H') {
4163 return 0;
4164 }
4165
4166 // Scan for the CONTROL_BLOCK_ID block.
4167 if (SkipCursorToBlock(Stream, CONTROL_BLOCK_ID))
4168 return 0;
4169
4170 // Scan for SIGNATURE inside the control block.
4171 ASTReader::RecordData Record;
4172 while (1) {
4173 llvm::BitstreamEntry Entry = Stream.advanceSkippingSubblocks();
4174 if (Entry.Kind == llvm::BitstreamEntry::EndBlock ||
4175 Entry.Kind != llvm::BitstreamEntry::Record)
4176 return 0;
4177
4178 Record.clear();
4179 StringRef Blob;
4180 if (SIGNATURE == Stream.readRecord(Entry.ID, Record, &Blob))
4181 return Record[0];
4182 }
4183}
4184
Guy Benyei11169dd2012-12-18 14:30:41 +00004185/// \brief Retrieve the name of the original source file name
4186/// directly from the AST file, without actually loading the AST
4187/// file.
4188std::string ASTReader::getOriginalSourceFile(const std::string &ASTFileName,
4189 FileManager &FileMgr,
4190 DiagnosticsEngine &Diags) {
4191 // Open the AST file.
Benjamin Kramera8857962014-10-26 22:44:13 +00004192 auto Buffer = FileMgr.getBufferForFile(ASTFileName);
Guy Benyei11169dd2012-12-18 14:30:41 +00004193 if (!Buffer) {
Benjamin Kramera8857962014-10-26 22:44:13 +00004194 Diags.Report(diag::err_fe_unable_to_read_pch_file)
4195 << ASTFileName << Buffer.getError().message();
Guy Benyei11169dd2012-12-18 14:30:41 +00004196 return std::string();
4197 }
4198
4199 // Initialize the stream
4200 llvm::BitstreamReader StreamFile;
Adrian Prantl8bf7af32015-02-25 01:31:45 +00004201 InitStreamFileWithModule((*Buffer)->getMemBufferRef(), StreamFile);
Rafael Espindolaaf0e40a2014-11-12 14:42:25 +00004202 BitstreamCursor Stream(StreamFile);
Guy Benyei11169dd2012-12-18 14:30:41 +00004203
4204 // Sniff for the signature.
4205 if (Stream.Read(8) != 'C' ||
4206 Stream.Read(8) != 'P' ||
4207 Stream.Read(8) != 'C' ||
4208 Stream.Read(8) != 'H') {
4209 Diags.Report(diag::err_fe_not_a_pch_file) << ASTFileName;
4210 return std::string();
4211 }
Chris Lattner7fb3bef2013-01-20 00:56:42 +00004212
Chris Lattnere7b154b2013-01-19 21:39:22 +00004213 // Scan for the CONTROL_BLOCK_ID block.
Argyrios Kyrtzidisc4cd2c42013-05-06 19:23:40 +00004214 if (SkipCursorToBlock(Stream, CONTROL_BLOCK_ID)) {
Chris Lattner7fb3bef2013-01-20 00:56:42 +00004215 Diags.Report(diag::err_fe_pch_malformed_block) << ASTFileName;
4216 return std::string();
Chris Lattnere7b154b2013-01-19 21:39:22 +00004217 }
Guy Benyei11169dd2012-12-18 14:30:41 +00004218
Chris Lattner7fb3bef2013-01-20 00:56:42 +00004219 // Scan for ORIGINAL_FILE inside the control block.
4220 RecordData Record;
Chris Lattnere7b154b2013-01-19 21:39:22 +00004221 while (1) {
Chris Lattner7fb3bef2013-01-20 00:56:42 +00004222 llvm::BitstreamEntry Entry = Stream.advanceSkippingSubblocks();
Chris Lattnere7b154b2013-01-19 21:39:22 +00004223 if (Entry.Kind == llvm::BitstreamEntry::EndBlock)
4224 return std::string();
4225
4226 if (Entry.Kind != llvm::BitstreamEntry::Record) {
4227 Diags.Report(diag::err_fe_pch_malformed_block) << ASTFileName;
4228 return std::string();
Guy Benyei11169dd2012-12-18 14:30:41 +00004229 }
Chris Lattnere7b154b2013-01-19 21:39:22 +00004230
Guy Benyei11169dd2012-12-18 14:30:41 +00004231 Record.clear();
Chris Lattner0e6c9402013-01-20 02:38:54 +00004232 StringRef Blob;
4233 if (Stream.readRecord(Entry.ID, Record, &Blob) == ORIGINAL_FILE)
4234 return Blob.str();
Guy Benyei11169dd2012-12-18 14:30:41 +00004235 }
Guy Benyei11169dd2012-12-18 14:30:41 +00004236}
4237
4238namespace {
4239 class SimplePCHValidator : public ASTReaderListener {
4240 const LangOptions &ExistingLangOpts;
4241 const TargetOptions &ExistingTargetOpts;
4242 const PreprocessorOptions &ExistingPPOpts;
Argyrios Kyrtzidisbd0b6512015-02-19 20:12:20 +00004243 std::string ExistingModuleCachePath;
Guy Benyei11169dd2012-12-18 14:30:41 +00004244 FileManager &FileMgr;
Argyrios Kyrtzidisbd0b6512015-02-19 20:12:20 +00004245
Guy Benyei11169dd2012-12-18 14:30:41 +00004246 public:
4247 SimplePCHValidator(const LangOptions &ExistingLangOpts,
4248 const TargetOptions &ExistingTargetOpts,
4249 const PreprocessorOptions &ExistingPPOpts,
Argyrios Kyrtzidisbd0b6512015-02-19 20:12:20 +00004250 StringRef ExistingModuleCachePath,
Guy Benyei11169dd2012-12-18 14:30:41 +00004251 FileManager &FileMgr)
4252 : ExistingLangOpts(ExistingLangOpts),
4253 ExistingTargetOpts(ExistingTargetOpts),
4254 ExistingPPOpts(ExistingPPOpts),
Argyrios Kyrtzidisbd0b6512015-02-19 20:12:20 +00004255 ExistingModuleCachePath(ExistingModuleCachePath),
Guy Benyei11169dd2012-12-18 14:30:41 +00004256 FileMgr(FileMgr)
4257 {
4258 }
4259
Richard Smith1e2cf0d2014-10-31 02:28:58 +00004260 bool ReadLanguageOptions(const LangOptions &LangOpts, bool Complain,
4261 bool AllowCompatibleDifferences) override {
4262 return checkLanguageOptions(ExistingLangOpts, LangOpts, nullptr,
4263 AllowCompatibleDifferences);
Guy Benyei11169dd2012-12-18 14:30:41 +00004264 }
Craig Topper3e89dfe2014-03-13 02:13:41 +00004265 bool ReadTargetOptions(const TargetOptions &TargetOpts,
4266 bool Complain) override {
Craig Toppera13603a2014-05-22 05:54:18 +00004267 return checkTargetOptions(ExistingTargetOpts, TargetOpts, nullptr);
Guy Benyei11169dd2012-12-18 14:30:41 +00004268 }
Argyrios Kyrtzidisbd0b6512015-02-19 20:12:20 +00004269 bool ReadHeaderSearchOptions(const HeaderSearchOptions &HSOpts,
4270 StringRef SpecificModuleCachePath,
4271 bool Complain) override {
4272 return checkHeaderSearchOptions(HSOpts, SpecificModuleCachePath,
4273 ExistingModuleCachePath,
4274 nullptr, ExistingLangOpts);
4275 }
Craig Topper3e89dfe2014-03-13 02:13:41 +00004276 bool ReadPreprocessorOptions(const PreprocessorOptions &PPOpts,
4277 bool Complain,
4278 std::string &SuggestedPredefines) override {
Craig Toppera13603a2014-05-22 05:54:18 +00004279 return checkPreprocessorOptions(ExistingPPOpts, PPOpts, nullptr, FileMgr,
Argyrios Kyrtzidisd3afa0c2013-04-26 21:33:40 +00004280 SuggestedPredefines, ExistingLangOpts);
Guy Benyei11169dd2012-12-18 14:30:41 +00004281 }
4282 };
4283}
4284
4285bool ASTReader::readASTFileControlBlock(StringRef Filename,
4286 FileManager &FileMgr,
4287 ASTReaderListener &Listener) {
4288 // Open the AST file.
Benjamin Kramera8857962014-10-26 22:44:13 +00004289 auto Buffer = FileMgr.getBufferForFile(Filename);
Guy Benyei11169dd2012-12-18 14:30:41 +00004290 if (!Buffer) {
4291 return true;
4292 }
4293
4294 // Initialize the stream
4295 llvm::BitstreamReader StreamFile;
Adrian Prantl8bf7af32015-02-25 01:31:45 +00004296 InitStreamFileWithModule((*Buffer)->getMemBufferRef(), StreamFile);
Rafael Espindolaaf0e40a2014-11-12 14:42:25 +00004297 BitstreamCursor Stream(StreamFile);
Guy Benyei11169dd2012-12-18 14:30:41 +00004298
4299 // Sniff for the signature.
4300 if (Stream.Read(8) != 'C' ||
4301 Stream.Read(8) != 'P' ||
4302 Stream.Read(8) != 'C' ||
4303 Stream.Read(8) != 'H') {
4304 return true;
4305 }
4306
Chris Lattner7fb3bef2013-01-20 00:56:42 +00004307 // Scan for the CONTROL_BLOCK_ID block.
Argyrios Kyrtzidisc4cd2c42013-05-06 19:23:40 +00004308 if (SkipCursorToBlock(Stream, CONTROL_BLOCK_ID))
Chris Lattner7fb3bef2013-01-20 00:56:42 +00004309 return true;
Argyrios Kyrtzidisc4cd2c42013-05-06 19:23:40 +00004310
4311 bool NeedsInputFiles = Listener.needsInputFileVisitation();
Ben Langmuircb69b572014-03-07 06:40:32 +00004312 bool NeedsSystemInputFiles = Listener.needsSystemInputFileVisitation();
Richard Smithd4b230b2014-10-27 23:01:16 +00004313 bool NeedsImports = Listener.needsImportVisitation();
Argyrios Kyrtzidisc4cd2c42013-05-06 19:23:40 +00004314 BitstreamCursor InputFilesCursor;
4315 if (NeedsInputFiles) {
4316 InputFilesCursor = Stream;
4317 if (SkipCursorToBlock(InputFilesCursor, INPUT_FILES_BLOCK_ID))
4318 return true;
4319
4320 // Read the abbreviations
4321 while (true) {
4322 uint64_t Offset = InputFilesCursor.GetCurrentBitNo();
4323 unsigned Code = InputFilesCursor.ReadCode();
4324
4325 // We expect all abbrevs to be at the start of the block.
4326 if (Code != llvm::bitc::DEFINE_ABBREV) {
4327 InputFilesCursor.JumpToBit(Offset);
4328 break;
4329 }
4330 InputFilesCursor.ReadAbbrevRecord();
4331 }
4332 }
Chris Lattner7fb3bef2013-01-20 00:56:42 +00004333
4334 // Scan for ORIGINAL_FILE inside the control block.
Guy Benyei11169dd2012-12-18 14:30:41 +00004335 RecordData Record;
Richard Smith7ed1bc92014-12-05 22:42:13 +00004336 std::string ModuleDir;
Chris Lattner7fb3bef2013-01-20 00:56:42 +00004337 while (1) {
4338 llvm::BitstreamEntry Entry = Stream.advanceSkippingSubblocks();
4339 if (Entry.Kind == llvm::BitstreamEntry::EndBlock)
4340 return false;
4341
4342 if (Entry.Kind != llvm::BitstreamEntry::Record)
4343 return true;
4344
Guy Benyei11169dd2012-12-18 14:30:41 +00004345 Record.clear();
Chris Lattner0e6c9402013-01-20 02:38:54 +00004346 StringRef Blob;
4347 unsigned RecCode = Stream.readRecord(Entry.ID, Record, &Blob);
Chris Lattner7fb3bef2013-01-20 00:56:42 +00004348 switch ((ControlRecordTypes)RecCode) {
4349 case METADATA: {
4350 if (Record[0] != VERSION_MAJOR)
4351 return true;
Guy Benyei11169dd2012-12-18 14:30:41 +00004352
Douglas Gregorbf7fc9c2013-03-27 16:47:18 +00004353 if (Listener.ReadFullVersionInformation(Blob))
Chris Lattner7fb3bef2013-01-20 00:56:42 +00004354 return true;
Douglas Gregorbf7fc9c2013-03-27 16:47:18 +00004355
Chris Lattner7fb3bef2013-01-20 00:56:42 +00004356 break;
4357 }
Ben Langmuir4f5212a2014-04-14 22:12:44 +00004358 case MODULE_NAME:
4359 Listener.ReadModuleName(Blob);
4360 break;
Richard Smith7ed1bc92014-12-05 22:42:13 +00004361 case MODULE_DIRECTORY:
4362 ModuleDir = Blob;
4363 break;
Ben Langmuir4b8a9e92014-08-12 16:42:33 +00004364 case MODULE_MAP_FILE: {
4365 unsigned Idx = 0;
Richard Smith7ed1bc92014-12-05 22:42:13 +00004366 auto Path = ReadString(Record, Idx);
4367 ResolveImportedPath(Path, ModuleDir);
4368 Listener.ReadModuleMapFile(Path);
Ben Langmuir4f5212a2014-04-14 22:12:44 +00004369 break;
Ben Langmuir4b8a9e92014-08-12 16:42:33 +00004370 }
Chris Lattner7fb3bef2013-01-20 00:56:42 +00004371 case LANGUAGE_OPTIONS:
Richard Smith1e2cf0d2014-10-31 02:28:58 +00004372 if (ParseLanguageOptions(Record, false, Listener,
4373 /*AllowCompatibleConfigurationMismatch*/false))
Chris Lattner7fb3bef2013-01-20 00:56:42 +00004374 return true;
4375 break;
Guy Benyei11169dd2012-12-18 14:30:41 +00004376
Chris Lattner7fb3bef2013-01-20 00:56:42 +00004377 case TARGET_OPTIONS:
4378 if (ParseTargetOptions(Record, false, Listener))
4379 return true;
4380 break;
Guy Benyei11169dd2012-12-18 14:30:41 +00004381
Chris Lattner7fb3bef2013-01-20 00:56:42 +00004382 case DIAGNOSTIC_OPTIONS:
4383 if (ParseDiagnosticOptions(Record, false, Listener))
4384 return true;
4385 break;
Guy Benyei11169dd2012-12-18 14:30:41 +00004386
Chris Lattner7fb3bef2013-01-20 00:56:42 +00004387 case FILE_SYSTEM_OPTIONS:
4388 if (ParseFileSystemOptions(Record, false, Listener))
4389 return true;
4390 break;
Guy Benyei11169dd2012-12-18 14:30:41 +00004391
Chris Lattner7fb3bef2013-01-20 00:56:42 +00004392 case HEADER_SEARCH_OPTIONS:
4393 if (ParseHeaderSearchOptions(Record, false, Listener))
4394 return true;
4395 break;
Guy Benyei11169dd2012-12-18 14:30:41 +00004396
Chris Lattner7fb3bef2013-01-20 00:56:42 +00004397 case PREPROCESSOR_OPTIONS: {
4398 std::string IgnoredSuggestedPredefines;
4399 if (ParsePreprocessorOptions(Record, false, Listener,
4400 IgnoredSuggestedPredefines))
4401 return true;
4402 break;
4403 }
Guy Benyei11169dd2012-12-18 14:30:41 +00004404
Argyrios Kyrtzidisc4cd2c42013-05-06 19:23:40 +00004405 case INPUT_FILE_OFFSETS: {
4406 if (!NeedsInputFiles)
4407 break;
4408
4409 unsigned NumInputFiles = Record[0];
4410 unsigned NumUserFiles = Record[1];
Richard Smithec216502015-02-13 19:48:37 +00004411 const uint64_t *InputFileOffs = (const uint64_t *)Blob.data();
Argyrios Kyrtzidisc4cd2c42013-05-06 19:23:40 +00004412 for (unsigned I = 0; I != NumInputFiles; ++I) {
4413 // Go find this input file.
4414 bool isSystemFile = I >= NumUserFiles;
Ben Langmuircb69b572014-03-07 06:40:32 +00004415
4416 if (isSystemFile && !NeedsSystemInputFiles)
4417 break; // the rest are system input files
4418
Argyrios Kyrtzidisc4cd2c42013-05-06 19:23:40 +00004419 BitstreamCursor &Cursor = InputFilesCursor;
4420 SavedStreamPosition SavedPosition(Cursor);
4421 Cursor.JumpToBit(InputFileOffs[I]);
4422
4423 unsigned Code = Cursor.ReadCode();
4424 RecordData Record;
4425 StringRef Blob;
4426 bool shouldContinue = false;
4427 switch ((InputFileRecordTypes)Cursor.readRecord(Code, Record, &Blob)) {
4428 case INPUT_FILE:
Argyrios Kyrtzidis68ccbe02014-03-14 02:26:31 +00004429 bool Overridden = static_cast<bool>(Record[3]);
Richard Smith7ed1bc92014-12-05 22:42:13 +00004430 std::string Filename = Blob;
4431 ResolveImportedPath(Filename, ModuleDir);
4432 shouldContinue =
4433 Listener.visitInputFile(Filename, isSystemFile, Overridden);
Argyrios Kyrtzidisc4cd2c42013-05-06 19:23:40 +00004434 break;
4435 }
4436 if (!shouldContinue)
4437 break;
4438 }
4439 break;
4440 }
4441
Richard Smithd4b230b2014-10-27 23:01:16 +00004442 case IMPORTS: {
4443 if (!NeedsImports)
4444 break;
4445
4446 unsigned Idx = 0, N = Record.size();
4447 while (Idx < N) {
4448 // Read information about the AST file.
Richard Smith79c98cc2014-10-27 23:25:15 +00004449 Idx += 5; // ImportLoc, Size, ModTime, Signature
Richard Smith7ed1bc92014-12-05 22:42:13 +00004450 std::string Filename = ReadString(Record, Idx);
4451 ResolveImportedPath(Filename, ModuleDir);
4452 Listener.visitImport(Filename);
Richard Smithd4b230b2014-10-27 23:01:16 +00004453 }
4454 break;
4455 }
4456
Chris Lattner7fb3bef2013-01-20 00:56:42 +00004457 default:
4458 // No other validation to perform.
4459 break;
Guy Benyei11169dd2012-12-18 14:30:41 +00004460 }
4461 }
Guy Benyei11169dd2012-12-18 14:30:41 +00004462}
4463
4464
4465bool ASTReader::isAcceptableASTFile(StringRef Filename,
4466 FileManager &FileMgr,
4467 const LangOptions &LangOpts,
4468 const TargetOptions &TargetOpts,
Argyrios Kyrtzidisbd0b6512015-02-19 20:12:20 +00004469 const PreprocessorOptions &PPOpts,
4470 std::string ExistingModuleCachePath) {
4471 SimplePCHValidator validator(LangOpts, TargetOpts, PPOpts,
4472 ExistingModuleCachePath, FileMgr);
Guy Benyei11169dd2012-12-18 14:30:41 +00004473 return !readASTFileControlBlock(Filename, FileMgr, validator);
4474}
4475
Ben Langmuir2c9af442014-04-10 17:57:43 +00004476ASTReader::ASTReadResult
4477ASTReader::ReadSubmoduleBlock(ModuleFile &F, unsigned ClientLoadCapabilities) {
Guy Benyei11169dd2012-12-18 14:30:41 +00004478 // Enter the submodule block.
4479 if (F.Stream.EnterSubBlock(SUBMODULE_BLOCK_ID)) {
4480 Error("malformed submodule block record in AST file");
Ben Langmuir2c9af442014-04-10 17:57:43 +00004481 return Failure;
Guy Benyei11169dd2012-12-18 14:30:41 +00004482 }
4483
4484 ModuleMap &ModMap = PP.getHeaderSearchInfo().getModuleMap();
4485 bool First = true;
Craig Toppera13603a2014-05-22 05:54:18 +00004486 Module *CurrentModule = nullptr;
Guy Benyei11169dd2012-12-18 14:30:41 +00004487 RecordData Record;
4488 while (true) {
Chris Lattner7fb3bef2013-01-20 00:56:42 +00004489 llvm::BitstreamEntry Entry = F.Stream.advanceSkippingSubblocks();
4490
4491 switch (Entry.Kind) {
4492 case llvm::BitstreamEntry::SubBlock: // Handled for us already.
4493 case llvm::BitstreamEntry::Error:
4494 Error("malformed block record in AST file");
Ben Langmuir2c9af442014-04-10 17:57:43 +00004495 return Failure;
Chris Lattner7fb3bef2013-01-20 00:56:42 +00004496 case llvm::BitstreamEntry::EndBlock:
Ben Langmuir2c9af442014-04-10 17:57:43 +00004497 return Success;
Chris Lattner7fb3bef2013-01-20 00:56:42 +00004498 case llvm::BitstreamEntry::Record:
4499 // The interesting case.
4500 break;
Guy Benyei11169dd2012-12-18 14:30:41 +00004501 }
Chris Lattner7fb3bef2013-01-20 00:56:42 +00004502
Guy Benyei11169dd2012-12-18 14:30:41 +00004503 // Read a record.
Chris Lattner0e6c9402013-01-20 02:38:54 +00004504 StringRef Blob;
Guy Benyei11169dd2012-12-18 14:30:41 +00004505 Record.clear();
Richard Smith03478d92014-10-23 22:12:14 +00004506 auto Kind = F.Stream.readRecord(Entry.ID, Record, &Blob);
4507
4508 if ((Kind == SUBMODULE_METADATA) != First) {
4509 Error("submodule metadata record should be at beginning of block");
4510 return Failure;
4511 }
4512 First = false;
4513
4514 // Submodule information is only valid if we have a current module.
4515 // FIXME: Should we error on these cases?
4516 if (!CurrentModule && Kind != SUBMODULE_METADATA &&
4517 Kind != SUBMODULE_DEFINITION)
4518 continue;
4519
4520 switch (Kind) {
Guy Benyei11169dd2012-12-18 14:30:41 +00004521 default: // Default behavior: ignore.
4522 break;
Guy Benyei11169dd2012-12-18 14:30:41 +00004523
Richard Smith03478d92014-10-23 22:12:14 +00004524 case SUBMODULE_DEFINITION: {
Douglas Gregor8d932422013-03-20 03:59:18 +00004525 if (Record.size() < 8) {
Guy Benyei11169dd2012-12-18 14:30:41 +00004526 Error("malformed module definition");
Ben Langmuir2c9af442014-04-10 17:57:43 +00004527 return Failure;
Guy Benyei11169dd2012-12-18 14:30:41 +00004528 }
Richard Smith03478d92014-10-23 22:12:14 +00004529
Chris Lattner0e6c9402013-01-20 02:38:54 +00004530 StringRef Name = Blob;
Richard Smith9bca2982014-03-08 00:03:56 +00004531 unsigned Idx = 0;
4532 SubmoduleID GlobalID = getGlobalSubmoduleID(F, Record[Idx++]);
4533 SubmoduleID Parent = getGlobalSubmoduleID(F, Record[Idx++]);
4534 bool IsFramework = Record[Idx++];
4535 bool IsExplicit = Record[Idx++];
4536 bool IsSystem = Record[Idx++];
4537 bool IsExternC = Record[Idx++];
4538 bool InferSubmodules = Record[Idx++];
4539 bool InferExplicitSubmodules = Record[Idx++];
4540 bool InferExportWildcard = Record[Idx++];
4541 bool ConfigMacrosExhaustive = Record[Idx++];
Douglas Gregor8d932422013-03-20 03:59:18 +00004542
Ben Langmuirbeee15e2014-04-14 18:00:01 +00004543 Module *ParentModule = nullptr;
Ben Langmuir9d6448b2014-08-09 00:57:23 +00004544 if (Parent)
Guy Benyei11169dd2012-12-18 14:30:41 +00004545 ParentModule = getSubmodule(Parent);
Ben Langmuirbeee15e2014-04-14 18:00:01 +00004546
Guy Benyei11169dd2012-12-18 14:30:41 +00004547 // Retrieve this (sub)module from the module map, creating it if
4548 // necessary.
Ben Langmuir9d6448b2014-08-09 00:57:23 +00004549 CurrentModule = ModMap.findOrCreateModule(Name, ParentModule, IsFramework,
Guy Benyei11169dd2012-12-18 14:30:41 +00004550 IsExplicit).first;
Ben Langmuir9d6448b2014-08-09 00:57:23 +00004551
4552 // FIXME: set the definition loc for CurrentModule, or call
4553 // ModMap.setInferredModuleAllowedBy()
4554
Guy Benyei11169dd2012-12-18 14:30:41 +00004555 SubmoduleID GlobalIndex = GlobalID - NUM_PREDEF_SUBMODULE_IDS;
4556 if (GlobalIndex >= SubmodulesLoaded.size() ||
4557 SubmodulesLoaded[GlobalIndex]) {
4558 Error("too many submodules");
Ben Langmuir2c9af442014-04-10 17:57:43 +00004559 return Failure;
Guy Benyei11169dd2012-12-18 14:30:41 +00004560 }
Douglas Gregor8a114ab2013-02-06 22:40:31 +00004561
Douglas Gregor7029ce12013-03-19 00:28:20 +00004562 if (!ParentModule) {
4563 if (const FileEntry *CurFile = CurrentModule->getASTFile()) {
4564 if (CurFile != F.File) {
4565 if (!Diags.isDiagnosticInFlight()) {
4566 Diag(diag::err_module_file_conflict)
4567 << CurrentModule->getTopLevelModuleName()
4568 << CurFile->getName()
4569 << F.File->getName();
4570 }
Ben Langmuir2c9af442014-04-10 17:57:43 +00004571 return Failure;
Douglas Gregor8a114ab2013-02-06 22:40:31 +00004572 }
Douglas Gregor8a114ab2013-02-06 22:40:31 +00004573 }
Douglas Gregor7029ce12013-03-19 00:28:20 +00004574
4575 CurrentModule->setASTFile(F.File);
Douglas Gregor8a114ab2013-02-06 22:40:31 +00004576 }
Ben Langmuirbeee15e2014-04-14 18:00:01 +00004577
Guy Benyei11169dd2012-12-18 14:30:41 +00004578 CurrentModule->IsFromModuleFile = true;
4579 CurrentModule->IsSystem = IsSystem || CurrentModule->IsSystem;
Richard Smith9bca2982014-03-08 00:03:56 +00004580 CurrentModule->IsExternC = IsExternC;
Guy Benyei11169dd2012-12-18 14:30:41 +00004581 CurrentModule->InferSubmodules = InferSubmodules;
4582 CurrentModule->InferExplicitSubmodules = InferExplicitSubmodules;
4583 CurrentModule->InferExportWildcard = InferExportWildcard;
Douglas Gregor8d932422013-03-20 03:59:18 +00004584 CurrentModule->ConfigMacrosExhaustive = ConfigMacrosExhaustive;
Guy Benyei11169dd2012-12-18 14:30:41 +00004585 if (DeserializationListener)
4586 DeserializationListener->ModuleRead(GlobalID, CurrentModule);
4587
4588 SubmodulesLoaded[GlobalIndex] = CurrentModule;
Douglas Gregor6ddfca92013-01-14 17:21:00 +00004589
Douglas Gregorfb912652013-03-20 21:10:35 +00004590 // Clear out data that will be replaced by what is the module file.
Douglas Gregor6ddfca92013-01-14 17:21:00 +00004591 CurrentModule->LinkLibraries.clear();
Douglas Gregor8d932422013-03-20 03:59:18 +00004592 CurrentModule->ConfigMacros.clear();
Douglas Gregorfb912652013-03-20 21:10:35 +00004593 CurrentModule->UnresolvedConflicts.clear();
4594 CurrentModule->Conflicts.clear();
Guy Benyei11169dd2012-12-18 14:30:41 +00004595 break;
4596 }
4597
4598 case SUBMODULE_UMBRELLA_HEADER: {
Chris Lattner0e6c9402013-01-20 02:38:54 +00004599 if (const FileEntry *Umbrella = PP.getFileManager().getFile(Blob)) {
Guy Benyei11169dd2012-12-18 14:30:41 +00004600 if (!CurrentModule->getUmbrellaHeader())
4601 ModMap.setUmbrellaHeader(CurrentModule, Umbrella);
4602 else if (CurrentModule->getUmbrellaHeader() != Umbrella) {
Ben Langmuirbc35fbe2015-02-20 21:46:39 +00004603 // This can be a spurious difference caused by changing the VFS to
4604 // point to a different copy of the file, and it is too late to
4605 // to rebuild safely.
4606 // FIXME: If we wrote the virtual paths instead of the 'real' paths,
4607 // after input file validation only real problems would remain and we
4608 // could just error. For now, assume it's okay.
4609 break;
Guy Benyei11169dd2012-12-18 14:30:41 +00004610 }
4611 }
4612 break;
4613 }
4614
Richard Smith202210b2014-10-24 20:23:01 +00004615 case SUBMODULE_HEADER:
4616 case SUBMODULE_EXCLUDED_HEADER:
4617 case SUBMODULE_PRIVATE_HEADER:
4618 // We lazily associate headers with their modules via the HeaderInfo table.
Argyrios Kyrtzidisb146baa2013-03-13 21:13:51 +00004619 // FIXME: Re-evaluate this section; maybe only store InputFile IDs instead
4620 // of complete filenames or remove it entirely.
Richard Smith202210b2014-10-24 20:23:01 +00004621 break;
Guy Benyei11169dd2012-12-18 14:30:41 +00004622
Richard Smith202210b2014-10-24 20:23:01 +00004623 case SUBMODULE_TEXTUAL_HEADER:
4624 case SUBMODULE_PRIVATE_TEXTUAL_HEADER:
4625 // FIXME: Textual headers are not marked in the HeaderInfo table. Load
4626 // them here.
4627 break;
Lawrence Crowlb53e5482013-06-20 21:14:14 +00004628
Guy Benyei11169dd2012-12-18 14:30:41 +00004629 case SUBMODULE_TOPHEADER: {
Argyrios Kyrtzidis3c5305c2013-03-13 21:13:43 +00004630 CurrentModule->addTopHeaderFilename(Blob);
Guy Benyei11169dd2012-12-18 14:30:41 +00004631 break;
4632 }
4633
4634 case SUBMODULE_UMBRELLA_DIR: {
Guy Benyei11169dd2012-12-18 14:30:41 +00004635 if (const DirectoryEntry *Umbrella
Chris Lattner0e6c9402013-01-20 02:38:54 +00004636 = PP.getFileManager().getDirectory(Blob)) {
Guy Benyei11169dd2012-12-18 14:30:41 +00004637 if (!CurrentModule->getUmbrellaDir())
4638 ModMap.setUmbrellaDir(CurrentModule, Umbrella);
4639 else if (CurrentModule->getUmbrellaDir() != Umbrella) {
Ben Langmuir2c9af442014-04-10 17:57:43 +00004640 if ((ClientLoadCapabilities & ARR_OutOfDate) == 0)
4641 Error("mismatched umbrella directories in submodule");
4642 return OutOfDate;
Guy Benyei11169dd2012-12-18 14:30:41 +00004643 }
4644 }
4645 break;
4646 }
4647
4648 case SUBMODULE_METADATA: {
Guy Benyei11169dd2012-12-18 14:30:41 +00004649 F.BaseSubmoduleID = getTotalNumSubmodules();
4650 F.LocalNumSubmodules = Record[0];
4651 unsigned LocalBaseSubmoduleID = Record[1];
4652 if (F.LocalNumSubmodules > 0) {
4653 // Introduce the global -> local mapping for submodules within this
4654 // module.
4655 GlobalSubmoduleMap.insert(std::make_pair(getTotalNumSubmodules()+1,&F));
4656
4657 // Introduce the local -> global mapping for submodules within this
4658 // module.
4659 F.SubmoduleRemap.insertOrReplace(
4660 std::make_pair(LocalBaseSubmoduleID,
4661 F.BaseSubmoduleID - LocalBaseSubmoduleID));
Ben Langmuirfe971d92014-08-16 04:54:18 +00004662
Ben Langmuir52ca6782014-10-20 16:27:32 +00004663 SubmodulesLoaded.resize(SubmodulesLoaded.size() + F.LocalNumSubmodules);
4664 }
Guy Benyei11169dd2012-12-18 14:30:41 +00004665 break;
4666 }
4667
4668 case SUBMODULE_IMPORTS: {
Guy Benyei11169dd2012-12-18 14:30:41 +00004669 for (unsigned Idx = 0; Idx != Record.size(); ++Idx) {
Douglas Gregorfb912652013-03-20 21:10:35 +00004670 UnresolvedModuleRef Unresolved;
Guy Benyei11169dd2012-12-18 14:30:41 +00004671 Unresolved.File = &F;
4672 Unresolved.Mod = CurrentModule;
4673 Unresolved.ID = Record[Idx];
Douglas Gregorfb912652013-03-20 21:10:35 +00004674 Unresolved.Kind = UnresolvedModuleRef::Import;
Guy Benyei11169dd2012-12-18 14:30:41 +00004675 Unresolved.IsWildcard = false;
Douglas Gregorfb912652013-03-20 21:10:35 +00004676 UnresolvedModuleRefs.push_back(Unresolved);
Guy Benyei11169dd2012-12-18 14:30:41 +00004677 }
4678 break;
4679 }
4680
4681 case SUBMODULE_EXPORTS: {
Guy Benyei11169dd2012-12-18 14:30:41 +00004682 for (unsigned Idx = 0; Idx + 1 < Record.size(); Idx += 2) {
Douglas Gregorfb912652013-03-20 21:10:35 +00004683 UnresolvedModuleRef Unresolved;
Guy Benyei11169dd2012-12-18 14:30:41 +00004684 Unresolved.File = &F;
4685 Unresolved.Mod = CurrentModule;
4686 Unresolved.ID = Record[Idx];
Douglas Gregorfb912652013-03-20 21:10:35 +00004687 Unresolved.Kind = UnresolvedModuleRef::Export;
Guy Benyei11169dd2012-12-18 14:30:41 +00004688 Unresolved.IsWildcard = Record[Idx + 1];
Douglas Gregorfb912652013-03-20 21:10:35 +00004689 UnresolvedModuleRefs.push_back(Unresolved);
Guy Benyei11169dd2012-12-18 14:30:41 +00004690 }
4691
4692 // Once we've loaded the set of exports, there's no reason to keep
4693 // the parsed, unresolved exports around.
4694 CurrentModule->UnresolvedExports.clear();
4695 break;
4696 }
4697 case SUBMODULE_REQUIRES: {
Richard Smitha3feee22013-10-28 22:18:19 +00004698 CurrentModule->addRequirement(Blob, Record[0], Context.getLangOpts(),
Guy Benyei11169dd2012-12-18 14:30:41 +00004699 Context.getTargetInfo());
4700 break;
4701 }
Douglas Gregor6ddfca92013-01-14 17:21:00 +00004702
4703 case SUBMODULE_LINK_LIBRARY:
Douglas Gregor6ddfca92013-01-14 17:21:00 +00004704 CurrentModule->LinkLibraries.push_back(
Chris Lattner0e6c9402013-01-20 02:38:54 +00004705 Module::LinkLibrary(Blob, Record[0]));
Douglas Gregor6ddfca92013-01-14 17:21:00 +00004706 break;
Douglas Gregor35b13ec2013-03-20 00:22:05 +00004707
4708 case SUBMODULE_CONFIG_MACRO:
Douglas Gregor35b13ec2013-03-20 00:22:05 +00004709 CurrentModule->ConfigMacros.push_back(Blob.str());
4710 break;
Douglas Gregorfb912652013-03-20 21:10:35 +00004711
4712 case SUBMODULE_CONFLICT: {
Douglas Gregorfb912652013-03-20 21:10:35 +00004713 UnresolvedModuleRef Unresolved;
4714 Unresolved.File = &F;
4715 Unresolved.Mod = CurrentModule;
4716 Unresolved.ID = Record[0];
4717 Unresolved.Kind = UnresolvedModuleRef::Conflict;
4718 Unresolved.IsWildcard = false;
4719 Unresolved.String = Blob;
4720 UnresolvedModuleRefs.push_back(Unresolved);
4721 break;
4722 }
Guy Benyei11169dd2012-12-18 14:30:41 +00004723 }
4724 }
4725}
4726
4727/// \brief Parse the record that corresponds to a LangOptions data
4728/// structure.
4729///
4730/// This routine parses the language options from the AST file and then gives
4731/// them to the AST listener if one is set.
4732///
4733/// \returns true if the listener deems the file unacceptable, false otherwise.
4734bool ASTReader::ParseLanguageOptions(const RecordData &Record,
4735 bool Complain,
Richard Smith1e2cf0d2014-10-31 02:28:58 +00004736 ASTReaderListener &Listener,
4737 bool AllowCompatibleDifferences) {
Guy Benyei11169dd2012-12-18 14:30:41 +00004738 LangOptions LangOpts;
4739 unsigned Idx = 0;
4740#define LANGOPT(Name, Bits, Default, Description) \
4741 LangOpts.Name = Record[Idx++];
4742#define ENUM_LANGOPT(Name, Type, Bits, Default, Description) \
4743 LangOpts.set##Name(static_cast<LangOptions::Type>(Record[Idx++]));
4744#include "clang/Basic/LangOptions.def"
Alexey Samsonovedf99a92014-11-07 22:29:38 +00004745#define SANITIZER(NAME, ID) \
4746 LangOpts.Sanitize.set(SanitizerKind::ID, Record[Idx++]);
Will Dietzf54319c2013-01-18 11:30:38 +00004747#include "clang/Basic/Sanitizers.def"
Guy Benyei11169dd2012-12-18 14:30:41 +00004748
4749 ObjCRuntime::Kind runtimeKind = (ObjCRuntime::Kind) Record[Idx++];
4750 VersionTuple runtimeVersion = ReadVersionTuple(Record, Idx);
4751 LangOpts.ObjCRuntime = ObjCRuntime(runtimeKind, runtimeVersion);
4752
4753 unsigned Length = Record[Idx++];
4754 LangOpts.CurrentModule.assign(Record.begin() + Idx,
4755 Record.begin() + Idx + Length);
Dmitri Gribenkoacf2e782013-02-22 14:21:27 +00004756
4757 Idx += Length;
4758
4759 // Comment options.
4760 for (unsigned N = Record[Idx++]; N; --N) {
4761 LangOpts.CommentOpts.BlockCommandNames.push_back(
4762 ReadString(Record, Idx));
4763 }
Dmitri Gribenkoa7d16ce2013-04-10 15:35:17 +00004764 LangOpts.CommentOpts.ParseAllComments = Record[Idx++];
Dmitri Gribenkoacf2e782013-02-22 14:21:27 +00004765
Richard Smith1e2cf0d2014-10-31 02:28:58 +00004766 return Listener.ReadLanguageOptions(LangOpts, Complain,
4767 AllowCompatibleDifferences);
Guy Benyei11169dd2012-12-18 14:30:41 +00004768}
4769
4770bool ASTReader::ParseTargetOptions(const RecordData &Record,
4771 bool Complain,
4772 ASTReaderListener &Listener) {
4773 unsigned Idx = 0;
4774 TargetOptions TargetOpts;
4775 TargetOpts.Triple = ReadString(Record, Idx);
4776 TargetOpts.CPU = ReadString(Record, Idx);
4777 TargetOpts.ABI = ReadString(Record, Idx);
Guy Benyei11169dd2012-12-18 14:30:41 +00004778 for (unsigned N = Record[Idx++]; N; --N) {
4779 TargetOpts.FeaturesAsWritten.push_back(ReadString(Record, Idx));
4780 }
4781 for (unsigned N = Record[Idx++]; N; --N) {
4782 TargetOpts.Features.push_back(ReadString(Record, Idx));
4783 }
4784
4785 return Listener.ReadTargetOptions(TargetOpts, Complain);
4786}
4787
4788bool ASTReader::ParseDiagnosticOptions(const RecordData &Record, bool Complain,
4789 ASTReaderListener &Listener) {
Ben Langmuirb92de022014-04-29 16:25:26 +00004790 IntrusiveRefCntPtr<DiagnosticOptions> DiagOpts(new DiagnosticOptions);
Guy Benyei11169dd2012-12-18 14:30:41 +00004791 unsigned Idx = 0;
Ben Langmuirb92de022014-04-29 16:25:26 +00004792#define DIAGOPT(Name, Bits, Default) DiagOpts->Name = Record[Idx++];
Guy Benyei11169dd2012-12-18 14:30:41 +00004793#define ENUM_DIAGOPT(Name, Type, Bits, Default) \
Ben Langmuirb92de022014-04-29 16:25:26 +00004794 DiagOpts->set##Name(static_cast<Type>(Record[Idx++]));
Guy Benyei11169dd2012-12-18 14:30:41 +00004795#include "clang/Basic/DiagnosticOptions.def"
4796
Richard Smith3be1cb22014-08-07 00:24:21 +00004797 for (unsigned N = Record[Idx++]; N; --N)
Ben Langmuirb92de022014-04-29 16:25:26 +00004798 DiagOpts->Warnings.push_back(ReadString(Record, Idx));
Richard Smith3be1cb22014-08-07 00:24:21 +00004799 for (unsigned N = Record[Idx++]; N; --N)
4800 DiagOpts->Remarks.push_back(ReadString(Record, Idx));
Guy Benyei11169dd2012-12-18 14:30:41 +00004801
4802 return Listener.ReadDiagnosticOptions(DiagOpts, Complain);
4803}
4804
4805bool ASTReader::ParseFileSystemOptions(const RecordData &Record, bool Complain,
4806 ASTReaderListener &Listener) {
4807 FileSystemOptions FSOpts;
4808 unsigned Idx = 0;
4809 FSOpts.WorkingDir = ReadString(Record, Idx);
4810 return Listener.ReadFileSystemOptions(FSOpts, Complain);
4811}
4812
4813bool ASTReader::ParseHeaderSearchOptions(const RecordData &Record,
4814 bool Complain,
4815 ASTReaderListener &Listener) {
4816 HeaderSearchOptions HSOpts;
4817 unsigned Idx = 0;
4818 HSOpts.Sysroot = ReadString(Record, Idx);
4819
4820 // Include entries.
4821 for (unsigned N = Record[Idx++]; N; --N) {
4822 std::string Path = ReadString(Record, Idx);
4823 frontend::IncludeDirGroup Group
4824 = static_cast<frontend::IncludeDirGroup>(Record[Idx++]);
Guy Benyei11169dd2012-12-18 14:30:41 +00004825 bool IsFramework = Record[Idx++];
4826 bool IgnoreSysRoot = Record[Idx++];
Guy Benyei11169dd2012-12-18 14:30:41 +00004827 HSOpts.UserEntries.push_back(
Daniel Dunbar53681732013-01-30 00:34:26 +00004828 HeaderSearchOptions::Entry(Path, Group, IsFramework, IgnoreSysRoot));
Guy Benyei11169dd2012-12-18 14:30:41 +00004829 }
4830
4831 // System header prefixes.
4832 for (unsigned N = Record[Idx++]; N; --N) {
4833 std::string Prefix = ReadString(Record, Idx);
4834 bool IsSystemHeader = Record[Idx++];
4835 HSOpts.SystemHeaderPrefixes.push_back(
4836 HeaderSearchOptions::SystemHeaderPrefix(Prefix, IsSystemHeader));
4837 }
4838
4839 HSOpts.ResourceDir = ReadString(Record, Idx);
4840 HSOpts.ModuleCachePath = ReadString(Record, Idx);
Argyrios Kyrtzidis1594c152014-03-03 08:12:05 +00004841 HSOpts.ModuleUserBuildPath = ReadString(Record, Idx);
Guy Benyei11169dd2012-12-18 14:30:41 +00004842 HSOpts.DisableModuleHash = Record[Idx++];
4843 HSOpts.UseBuiltinIncludes = Record[Idx++];
4844 HSOpts.UseStandardSystemIncludes = Record[Idx++];
4845 HSOpts.UseStandardCXXIncludes = Record[Idx++];
4846 HSOpts.UseLibcxx = Record[Idx++];
Argyrios Kyrtzidisbd0b6512015-02-19 20:12:20 +00004847 std::string SpecificModuleCachePath = ReadString(Record, Idx);
Guy Benyei11169dd2012-12-18 14:30:41 +00004848
Argyrios Kyrtzidisbd0b6512015-02-19 20:12:20 +00004849 return Listener.ReadHeaderSearchOptions(HSOpts, SpecificModuleCachePath,
4850 Complain);
Guy Benyei11169dd2012-12-18 14:30:41 +00004851}
4852
4853bool ASTReader::ParsePreprocessorOptions(const RecordData &Record,
4854 bool Complain,
4855 ASTReaderListener &Listener,
4856 std::string &SuggestedPredefines) {
4857 PreprocessorOptions PPOpts;
4858 unsigned Idx = 0;
4859
4860 // Macro definitions/undefs
4861 for (unsigned N = Record[Idx++]; N; --N) {
4862 std::string Macro = ReadString(Record, Idx);
4863 bool IsUndef = Record[Idx++];
4864 PPOpts.Macros.push_back(std::make_pair(Macro, IsUndef));
4865 }
4866
4867 // Includes
4868 for (unsigned N = Record[Idx++]; N; --N) {
4869 PPOpts.Includes.push_back(ReadString(Record, Idx));
4870 }
4871
4872 // Macro Includes
4873 for (unsigned N = Record[Idx++]; N; --N) {
4874 PPOpts.MacroIncludes.push_back(ReadString(Record, Idx));
4875 }
4876
4877 PPOpts.UsePredefines = Record[Idx++];
Argyrios Kyrtzidisd3afa0c2013-04-26 21:33:40 +00004878 PPOpts.DetailedRecord = Record[Idx++];
Guy Benyei11169dd2012-12-18 14:30:41 +00004879 PPOpts.ImplicitPCHInclude = ReadString(Record, Idx);
4880 PPOpts.ImplicitPTHInclude = ReadString(Record, Idx);
4881 PPOpts.ObjCXXARCStandardLibrary =
4882 static_cast<ObjCXXARCStandardLibraryKind>(Record[Idx++]);
4883 SuggestedPredefines.clear();
4884 return Listener.ReadPreprocessorOptions(PPOpts, Complain,
4885 SuggestedPredefines);
4886}
4887
4888std::pair<ModuleFile *, unsigned>
4889ASTReader::getModulePreprocessedEntity(unsigned GlobalIndex) {
4890 GlobalPreprocessedEntityMapType::iterator
4891 I = GlobalPreprocessedEntityMap.find(GlobalIndex);
4892 assert(I != GlobalPreprocessedEntityMap.end() &&
4893 "Corrupted global preprocessed entity map");
4894 ModuleFile *M = I->second;
4895 unsigned LocalIndex = GlobalIndex - M->BasePreprocessedEntityID;
4896 return std::make_pair(M, LocalIndex);
4897}
4898
Benjamin Kramerb4ef6682015-02-06 17:25:10 +00004899llvm::iterator_range<PreprocessingRecord::iterator>
Guy Benyei11169dd2012-12-18 14:30:41 +00004900ASTReader::getModulePreprocessedEntities(ModuleFile &Mod) const {
4901 if (PreprocessingRecord *PPRec = PP.getPreprocessingRecord())
4902 return PPRec->getIteratorsForLoadedRange(Mod.BasePreprocessedEntityID,
4903 Mod.NumPreprocessedEntities);
4904
Benjamin Kramerb4ef6682015-02-06 17:25:10 +00004905 return llvm::make_range(PreprocessingRecord::iterator(),
4906 PreprocessingRecord::iterator());
Guy Benyei11169dd2012-12-18 14:30:41 +00004907}
4908
Benjamin Kramerb4ef6682015-02-06 17:25:10 +00004909llvm::iterator_range<ASTReader::ModuleDeclIterator>
Guy Benyei11169dd2012-12-18 14:30:41 +00004910ASTReader::getModuleFileLevelDecls(ModuleFile &Mod) {
Benjamin Kramerb4ef6682015-02-06 17:25:10 +00004911 return llvm::make_range(
4912 ModuleDeclIterator(this, &Mod, Mod.FileSortedDecls),
4913 ModuleDeclIterator(this, &Mod,
4914 Mod.FileSortedDecls + Mod.NumFileSortedDecls));
Guy Benyei11169dd2012-12-18 14:30:41 +00004915}
4916
4917PreprocessedEntity *ASTReader::ReadPreprocessedEntity(unsigned Index) {
4918 PreprocessedEntityID PPID = Index+1;
4919 std::pair<ModuleFile *, unsigned> PPInfo = getModulePreprocessedEntity(Index);
4920 ModuleFile &M = *PPInfo.first;
4921 unsigned LocalIndex = PPInfo.second;
4922 const PPEntityOffset &PPOffs = M.PreprocessedEntityOffsets[LocalIndex];
4923
Guy Benyei11169dd2012-12-18 14:30:41 +00004924 if (!PP.getPreprocessingRecord()) {
4925 Error("no preprocessing record");
Craig Toppera13603a2014-05-22 05:54:18 +00004926 return nullptr;
Guy Benyei11169dd2012-12-18 14:30:41 +00004927 }
4928
Chris Lattner7fb3bef2013-01-20 00:56:42 +00004929 SavedStreamPosition SavedPosition(M.PreprocessorDetailCursor);
4930 M.PreprocessorDetailCursor.JumpToBit(PPOffs.BitOffset);
4931
4932 llvm::BitstreamEntry Entry =
4933 M.PreprocessorDetailCursor.advance(BitstreamCursor::AF_DontPopBlockAtEnd);
4934 if (Entry.Kind != llvm::BitstreamEntry::Record)
Craig Toppera13603a2014-05-22 05:54:18 +00004935 return nullptr;
Chris Lattner7fb3bef2013-01-20 00:56:42 +00004936
Guy Benyei11169dd2012-12-18 14:30:41 +00004937 // Read the record.
4938 SourceRange Range(ReadSourceLocation(M, PPOffs.Begin),
4939 ReadSourceLocation(M, PPOffs.End));
4940 PreprocessingRecord &PPRec = *PP.getPreprocessingRecord();
Chris Lattner0e6c9402013-01-20 02:38:54 +00004941 StringRef Blob;
Guy Benyei11169dd2012-12-18 14:30:41 +00004942 RecordData Record;
4943 PreprocessorDetailRecordTypes RecType =
Chris Lattner0e6c9402013-01-20 02:38:54 +00004944 (PreprocessorDetailRecordTypes)M.PreprocessorDetailCursor.readRecord(
4945 Entry.ID, Record, &Blob);
Guy Benyei11169dd2012-12-18 14:30:41 +00004946 switch (RecType) {
4947 case PPD_MACRO_EXPANSION: {
4948 bool isBuiltin = Record[0];
Craig Toppera13603a2014-05-22 05:54:18 +00004949 IdentifierInfo *Name = nullptr;
4950 MacroDefinition *Def = nullptr;
Guy Benyei11169dd2012-12-18 14:30:41 +00004951 if (isBuiltin)
4952 Name = getLocalIdentifier(M, Record[1]);
4953 else {
4954 PreprocessedEntityID
4955 GlobalID = getGlobalPreprocessedEntityID(M, Record[1]);
4956 Def =cast<MacroDefinition>(PPRec.getLoadedPreprocessedEntity(GlobalID-1));
4957 }
4958
4959 MacroExpansion *ME;
4960 if (isBuiltin)
4961 ME = new (PPRec) MacroExpansion(Name, Range);
4962 else
4963 ME = new (PPRec) MacroExpansion(Def, Range);
4964
4965 return ME;
4966 }
4967
4968 case PPD_MACRO_DEFINITION: {
4969 // Decode the identifier info and then check again; if the macro is
4970 // still defined and associated with the identifier,
4971 IdentifierInfo *II = getLocalIdentifier(M, Record[0]);
4972 MacroDefinition *MD
4973 = new (PPRec) MacroDefinition(II, Range);
4974
4975 if (DeserializationListener)
4976 DeserializationListener->MacroDefinitionRead(PPID, MD);
4977
4978 return MD;
4979 }
4980
4981 case PPD_INCLUSION_DIRECTIVE: {
Chris Lattner0e6c9402013-01-20 02:38:54 +00004982 const char *FullFileNameStart = Blob.data() + Record[0];
4983 StringRef FullFileName(FullFileNameStart, Blob.size() - Record[0]);
Craig Toppera13603a2014-05-22 05:54:18 +00004984 const FileEntry *File = nullptr;
Guy Benyei11169dd2012-12-18 14:30:41 +00004985 if (!FullFileName.empty())
4986 File = PP.getFileManager().getFile(FullFileName);
4987
4988 // FIXME: Stable encoding
4989 InclusionDirective::InclusionKind Kind
4990 = static_cast<InclusionDirective::InclusionKind>(Record[2]);
4991 InclusionDirective *ID
4992 = new (PPRec) InclusionDirective(PPRec, Kind,
Chris Lattner0e6c9402013-01-20 02:38:54 +00004993 StringRef(Blob.data(), Record[0]),
Guy Benyei11169dd2012-12-18 14:30:41 +00004994 Record[1], Record[3],
4995 File,
4996 Range);
4997 return ID;
4998 }
4999 }
5000
5001 llvm_unreachable("Invalid PreprocessorDetailRecordTypes");
5002}
5003
5004/// \brief \arg SLocMapI points at a chunk of a module that contains no
5005/// preprocessed entities or the entities it contains are not the ones we are
5006/// looking for. Find the next module that contains entities and return the ID
5007/// of the first entry.
5008PreprocessedEntityID ASTReader::findNextPreprocessedEntity(
5009 GlobalSLocOffsetMapType::const_iterator SLocMapI) const {
5010 ++SLocMapI;
5011 for (GlobalSLocOffsetMapType::const_iterator
5012 EndI = GlobalSLocOffsetMap.end(); SLocMapI != EndI; ++SLocMapI) {
5013 ModuleFile &M = *SLocMapI->second;
5014 if (M.NumPreprocessedEntities)
5015 return M.BasePreprocessedEntityID;
5016 }
5017
5018 return getTotalNumPreprocessedEntities();
5019}
5020
5021namespace {
5022
5023template <unsigned PPEntityOffset::*PPLoc>
5024struct PPEntityComp {
5025 const ASTReader &Reader;
5026 ModuleFile &M;
5027
5028 PPEntityComp(const ASTReader &Reader, ModuleFile &M) : Reader(Reader), M(M) { }
5029
5030 bool operator()(const PPEntityOffset &L, const PPEntityOffset &R) const {
5031 SourceLocation LHS = getLoc(L);
5032 SourceLocation RHS = getLoc(R);
5033 return Reader.getSourceManager().isBeforeInTranslationUnit(LHS, RHS);
5034 }
5035
5036 bool operator()(const PPEntityOffset &L, SourceLocation RHS) const {
5037 SourceLocation LHS = getLoc(L);
5038 return Reader.getSourceManager().isBeforeInTranslationUnit(LHS, RHS);
5039 }
5040
5041 bool operator()(SourceLocation LHS, const PPEntityOffset &R) const {
5042 SourceLocation RHS = getLoc(R);
5043 return Reader.getSourceManager().isBeforeInTranslationUnit(LHS, RHS);
5044 }
5045
5046 SourceLocation getLoc(const PPEntityOffset &PPE) const {
5047 return Reader.ReadSourceLocation(M, PPE.*PPLoc);
5048 }
5049};
5050
5051}
5052
Alp Toker2e9ce4c2014-05-16 18:59:21 +00005053PreprocessedEntityID ASTReader::findPreprocessedEntity(SourceLocation Loc,
5054 bool EndsAfter) const {
5055 if (SourceMgr.isLocalSourceLocation(Loc))
Guy Benyei11169dd2012-12-18 14:30:41 +00005056 return getTotalNumPreprocessedEntities();
5057
Alp Toker2e9ce4c2014-05-16 18:59:21 +00005058 GlobalSLocOffsetMapType::const_iterator SLocMapI = GlobalSLocOffsetMap.find(
5059 SourceManager::MaxLoadedOffset - Loc.getOffset() - 1);
Guy Benyei11169dd2012-12-18 14:30:41 +00005060 assert(SLocMapI != GlobalSLocOffsetMap.end() &&
5061 "Corrupted global sloc offset map");
5062
5063 if (SLocMapI->second->NumPreprocessedEntities == 0)
5064 return findNextPreprocessedEntity(SLocMapI);
5065
5066 ModuleFile &M = *SLocMapI->second;
5067 typedef const PPEntityOffset *pp_iterator;
5068 pp_iterator pp_begin = M.PreprocessedEntityOffsets;
5069 pp_iterator pp_end = pp_begin + M.NumPreprocessedEntities;
5070
5071 size_t Count = M.NumPreprocessedEntities;
5072 size_t Half;
5073 pp_iterator First = pp_begin;
5074 pp_iterator PPI;
5075
Alp Toker2e9ce4c2014-05-16 18:59:21 +00005076 if (EndsAfter) {
5077 PPI = std::upper_bound(pp_begin, pp_end, Loc,
5078 PPEntityComp<&PPEntityOffset::Begin>(*this, M));
5079 } else {
5080 // Do a binary search manually instead of using std::lower_bound because
5081 // The end locations of entities may be unordered (when a macro expansion
5082 // is inside another macro argument), but for this case it is not important
5083 // whether we get the first macro expansion or its containing macro.
5084 while (Count > 0) {
5085 Half = Count / 2;
5086 PPI = First;
5087 std::advance(PPI, Half);
5088 if (SourceMgr.isBeforeInTranslationUnit(ReadSourceLocation(M, PPI->End),
5089 Loc)) {
5090 First = PPI;
5091 ++First;
5092 Count = Count - Half - 1;
5093 } else
5094 Count = Half;
5095 }
Guy Benyei11169dd2012-12-18 14:30:41 +00005096 }
5097
5098 if (PPI == pp_end)
5099 return findNextPreprocessedEntity(SLocMapI);
5100
5101 return M.BasePreprocessedEntityID + (PPI - pp_begin);
5102}
5103
Guy Benyei11169dd2012-12-18 14:30:41 +00005104/// \brief Returns a pair of [Begin, End) indices of preallocated
5105/// preprocessed entities that \arg Range encompasses.
5106std::pair<unsigned, unsigned>
5107 ASTReader::findPreprocessedEntitiesInRange(SourceRange Range) {
5108 if (Range.isInvalid())
5109 return std::make_pair(0,0);
5110 assert(!SourceMgr.isBeforeInTranslationUnit(Range.getEnd(),Range.getBegin()));
5111
Alp Toker2e9ce4c2014-05-16 18:59:21 +00005112 PreprocessedEntityID BeginID =
5113 findPreprocessedEntity(Range.getBegin(), false);
5114 PreprocessedEntityID EndID = findPreprocessedEntity(Range.getEnd(), true);
Guy Benyei11169dd2012-12-18 14:30:41 +00005115 return std::make_pair(BeginID, EndID);
5116}
5117
5118/// \brief Optionally returns true or false if the preallocated preprocessed
5119/// entity with index \arg Index came from file \arg FID.
David Blaikie05785d12013-02-20 22:23:23 +00005120Optional<bool> ASTReader::isPreprocessedEntityInFileID(unsigned Index,
Guy Benyei11169dd2012-12-18 14:30:41 +00005121 FileID FID) {
5122 if (FID.isInvalid())
5123 return false;
5124
5125 std::pair<ModuleFile *, unsigned> PPInfo = getModulePreprocessedEntity(Index);
5126 ModuleFile &M = *PPInfo.first;
5127 unsigned LocalIndex = PPInfo.second;
5128 const PPEntityOffset &PPOffs = M.PreprocessedEntityOffsets[LocalIndex];
5129
5130 SourceLocation Loc = ReadSourceLocation(M, PPOffs.Begin);
5131 if (Loc.isInvalid())
5132 return false;
5133
5134 if (SourceMgr.isInFileID(SourceMgr.getFileLoc(Loc), FID))
5135 return true;
5136 else
5137 return false;
5138}
5139
5140namespace {
5141 /// \brief Visitor used to search for information about a header file.
5142 class HeaderFileInfoVisitor {
Guy Benyei11169dd2012-12-18 14:30:41 +00005143 const FileEntry *FE;
5144
David Blaikie05785d12013-02-20 22:23:23 +00005145 Optional<HeaderFileInfo> HFI;
Guy Benyei11169dd2012-12-18 14:30:41 +00005146
5147 public:
Argyrios Kyrtzidis61a38962013-03-06 18:12:44 +00005148 explicit HeaderFileInfoVisitor(const FileEntry *FE)
5149 : FE(FE) { }
Guy Benyei11169dd2012-12-18 14:30:41 +00005150
5151 static bool visit(ModuleFile &M, void *UserData) {
5152 HeaderFileInfoVisitor *This
5153 = static_cast<HeaderFileInfoVisitor *>(UserData);
5154
Guy Benyei11169dd2012-12-18 14:30:41 +00005155 HeaderFileInfoLookupTable *Table
5156 = static_cast<HeaderFileInfoLookupTable *>(M.HeaderFileInfoTable);
5157 if (!Table)
5158 return false;
5159
5160 // Look in the on-disk hash table for an entry for this file name.
Argyrios Kyrtzidis5c2a3452013-03-06 18:12:47 +00005161 HeaderFileInfoLookupTable::iterator Pos = Table->find(This->FE);
Guy Benyei11169dd2012-12-18 14:30:41 +00005162 if (Pos == Table->end())
5163 return false;
5164
5165 This->HFI = *Pos;
5166 return true;
5167 }
5168
David Blaikie05785d12013-02-20 22:23:23 +00005169 Optional<HeaderFileInfo> getHeaderFileInfo() const { return HFI; }
Guy Benyei11169dd2012-12-18 14:30:41 +00005170 };
5171}
5172
5173HeaderFileInfo ASTReader::GetHeaderFileInfo(const FileEntry *FE) {
Argyrios Kyrtzidis61a38962013-03-06 18:12:44 +00005174 HeaderFileInfoVisitor Visitor(FE);
Guy Benyei11169dd2012-12-18 14:30:41 +00005175 ModuleMgr.visit(&HeaderFileInfoVisitor::visit, &Visitor);
Argyrios Kyrtzidis1054bbf2013-05-08 23:46:55 +00005176 if (Optional<HeaderFileInfo> HFI = Visitor.getHeaderFileInfo())
Guy Benyei11169dd2012-12-18 14:30:41 +00005177 return *HFI;
Guy Benyei11169dd2012-12-18 14:30:41 +00005178
5179 return HeaderFileInfo();
5180}
5181
5182void ASTReader::ReadPragmaDiagnosticMappings(DiagnosticsEngine &Diag) {
5183 // FIXME: Make it work properly with modules.
Dmitri Gribenkof8579502013-01-12 19:30:44 +00005184 SmallVector<DiagnosticsEngine::DiagState *, 32> DiagStates;
Guy Benyei11169dd2012-12-18 14:30:41 +00005185 for (ModuleIterator I = ModuleMgr.begin(), E = ModuleMgr.end(); I != E; ++I) {
5186 ModuleFile &F = *(*I);
5187 unsigned Idx = 0;
5188 DiagStates.clear();
5189 assert(!Diag.DiagStates.empty());
5190 DiagStates.push_back(&Diag.DiagStates.front()); // the command-line one.
5191 while (Idx < F.PragmaDiagMappings.size()) {
5192 SourceLocation Loc = ReadSourceLocation(F, F.PragmaDiagMappings[Idx++]);
5193 unsigned DiagStateID = F.PragmaDiagMappings[Idx++];
5194 if (DiagStateID != 0) {
5195 Diag.DiagStatePoints.push_back(
5196 DiagnosticsEngine::DiagStatePoint(DiagStates[DiagStateID-1],
5197 FullSourceLoc(Loc, SourceMgr)));
5198 continue;
5199 }
5200
5201 assert(DiagStateID == 0);
5202 // A new DiagState was created here.
5203 Diag.DiagStates.push_back(*Diag.GetCurDiagState());
5204 DiagnosticsEngine::DiagState *NewState = &Diag.DiagStates.back();
5205 DiagStates.push_back(NewState);
5206 Diag.DiagStatePoints.push_back(
5207 DiagnosticsEngine::DiagStatePoint(NewState,
5208 FullSourceLoc(Loc, SourceMgr)));
5209 while (1) {
5210 assert(Idx < F.PragmaDiagMappings.size() &&
5211 "Invalid data, didn't find '-1' marking end of diag/map pairs");
5212 if (Idx >= F.PragmaDiagMappings.size()) {
5213 break; // Something is messed up but at least avoid infinite loop in
5214 // release build.
5215 }
5216 unsigned DiagID = F.PragmaDiagMappings[Idx++];
5217 if (DiagID == (unsigned)-1) {
5218 break; // no more diag/map pairs for this location.
5219 }
Alp Tokerc726c362014-06-10 09:31:37 +00005220 diag::Severity Map = (diag::Severity)F.PragmaDiagMappings[Idx++];
5221 DiagnosticMapping Mapping = Diag.makeUserMapping(Map, Loc);
5222 Diag.GetCurDiagState()->setMapping(DiagID, Mapping);
Guy Benyei11169dd2012-12-18 14:30:41 +00005223 }
5224 }
5225 }
5226}
5227
5228/// \brief Get the correct cursor and offset for loading a type.
5229ASTReader::RecordLocation ASTReader::TypeCursorForIndex(unsigned Index) {
5230 GlobalTypeMapType::iterator I = GlobalTypeMap.find(Index);
5231 assert(I != GlobalTypeMap.end() && "Corrupted global type map");
5232 ModuleFile *M = I->second;
5233 return RecordLocation(M, M->TypeOffsets[Index - M->BaseTypeIndex]);
5234}
5235
5236/// \brief Read and return the type with the given index..
5237///
5238/// The index is the type ID, shifted and minus the number of predefs. This
5239/// routine actually reads the record corresponding to the type at the given
5240/// location. It is a helper routine for GetType, which deals with reading type
5241/// IDs.
5242QualType ASTReader::readTypeRecord(unsigned Index) {
5243 RecordLocation Loc = TypeCursorForIndex(Index);
Chris Lattner7fb3bef2013-01-20 00:56:42 +00005244 BitstreamCursor &DeclsCursor = Loc.F->DeclsCursor;
Guy Benyei11169dd2012-12-18 14:30:41 +00005245
5246 // Keep track of where we are in the stream, then jump back there
5247 // after reading this type.
5248 SavedStreamPosition SavedPosition(DeclsCursor);
5249
5250 ReadingKindTracker ReadingKind(Read_Type, *this);
5251
5252 // Note that we are loading a type record.
5253 Deserializing AType(this);
5254
5255 unsigned Idx = 0;
5256 DeclsCursor.JumpToBit(Loc.Offset);
5257 RecordData Record;
5258 unsigned Code = DeclsCursor.ReadCode();
Chris Lattner0e6c9402013-01-20 02:38:54 +00005259 switch ((TypeCode)DeclsCursor.readRecord(Code, Record)) {
Guy Benyei11169dd2012-12-18 14:30:41 +00005260 case TYPE_EXT_QUAL: {
5261 if (Record.size() != 2) {
5262 Error("Incorrect encoding of extended qualifier type");
5263 return QualType();
5264 }
5265 QualType Base = readType(*Loc.F, Record, Idx);
5266 Qualifiers Quals = Qualifiers::fromOpaqueValue(Record[Idx++]);
5267 return Context.getQualifiedType(Base, Quals);
5268 }
5269
5270 case TYPE_COMPLEX: {
5271 if (Record.size() != 1) {
5272 Error("Incorrect encoding of complex type");
5273 return QualType();
5274 }
5275 QualType ElemType = readType(*Loc.F, Record, Idx);
5276 return Context.getComplexType(ElemType);
5277 }
5278
5279 case TYPE_POINTER: {
5280 if (Record.size() != 1) {
5281 Error("Incorrect encoding of pointer type");
5282 return QualType();
5283 }
5284 QualType PointeeType = readType(*Loc.F, Record, Idx);
5285 return Context.getPointerType(PointeeType);
5286 }
5287
Reid Kleckner8a365022013-06-24 17:51:48 +00005288 case TYPE_DECAYED: {
5289 if (Record.size() != 1) {
5290 Error("Incorrect encoding of decayed type");
5291 return QualType();
5292 }
5293 QualType OriginalType = readType(*Loc.F, Record, Idx);
5294 QualType DT = Context.getAdjustedParameterType(OriginalType);
5295 if (!isa<DecayedType>(DT))
5296 Error("Decayed type does not decay");
5297 return DT;
5298 }
5299
Reid Kleckner0503a872013-12-05 01:23:43 +00005300 case TYPE_ADJUSTED: {
5301 if (Record.size() != 2) {
5302 Error("Incorrect encoding of adjusted type");
5303 return QualType();
5304 }
5305 QualType OriginalTy = readType(*Loc.F, Record, Idx);
5306 QualType AdjustedTy = readType(*Loc.F, Record, Idx);
5307 return Context.getAdjustedType(OriginalTy, AdjustedTy);
5308 }
5309
Guy Benyei11169dd2012-12-18 14:30:41 +00005310 case TYPE_BLOCK_POINTER: {
5311 if (Record.size() != 1) {
5312 Error("Incorrect encoding of block pointer type");
5313 return QualType();
5314 }
5315 QualType PointeeType = readType(*Loc.F, Record, Idx);
5316 return Context.getBlockPointerType(PointeeType);
5317 }
5318
5319 case TYPE_LVALUE_REFERENCE: {
5320 if (Record.size() != 2) {
5321 Error("Incorrect encoding of lvalue reference type");
5322 return QualType();
5323 }
5324 QualType PointeeType = readType(*Loc.F, Record, Idx);
5325 return Context.getLValueReferenceType(PointeeType, Record[1]);
5326 }
5327
5328 case TYPE_RVALUE_REFERENCE: {
5329 if (Record.size() != 1) {
5330 Error("Incorrect encoding of rvalue reference type");
5331 return QualType();
5332 }
5333 QualType PointeeType = readType(*Loc.F, Record, Idx);
5334 return Context.getRValueReferenceType(PointeeType);
5335 }
5336
5337 case TYPE_MEMBER_POINTER: {
5338 if (Record.size() != 2) {
5339 Error("Incorrect encoding of member pointer type");
5340 return QualType();
5341 }
5342 QualType PointeeType = readType(*Loc.F, Record, Idx);
5343 QualType ClassType = readType(*Loc.F, Record, Idx);
5344 if (PointeeType.isNull() || ClassType.isNull())
5345 return QualType();
5346
5347 return Context.getMemberPointerType(PointeeType, ClassType.getTypePtr());
5348 }
5349
5350 case TYPE_CONSTANT_ARRAY: {
5351 QualType ElementType = readType(*Loc.F, Record, Idx);
5352 ArrayType::ArraySizeModifier ASM = (ArrayType::ArraySizeModifier)Record[1];
5353 unsigned IndexTypeQuals = Record[2];
5354 unsigned Idx = 3;
5355 llvm::APInt Size = ReadAPInt(Record, Idx);
5356 return Context.getConstantArrayType(ElementType, Size,
5357 ASM, IndexTypeQuals);
5358 }
5359
5360 case TYPE_INCOMPLETE_ARRAY: {
5361 QualType ElementType = readType(*Loc.F, Record, Idx);
5362 ArrayType::ArraySizeModifier ASM = (ArrayType::ArraySizeModifier)Record[1];
5363 unsigned IndexTypeQuals = Record[2];
5364 return Context.getIncompleteArrayType(ElementType, ASM, IndexTypeQuals);
5365 }
5366
5367 case TYPE_VARIABLE_ARRAY: {
5368 QualType ElementType = readType(*Loc.F, Record, Idx);
5369 ArrayType::ArraySizeModifier ASM = (ArrayType::ArraySizeModifier)Record[1];
5370 unsigned IndexTypeQuals = Record[2];
5371 SourceLocation LBLoc = ReadSourceLocation(*Loc.F, Record[3]);
5372 SourceLocation RBLoc = ReadSourceLocation(*Loc.F, Record[4]);
5373 return Context.getVariableArrayType(ElementType, ReadExpr(*Loc.F),
5374 ASM, IndexTypeQuals,
5375 SourceRange(LBLoc, RBLoc));
5376 }
5377
5378 case TYPE_VECTOR: {
5379 if (Record.size() != 3) {
5380 Error("incorrect encoding of vector type in AST file");
5381 return QualType();
5382 }
5383
5384 QualType ElementType = readType(*Loc.F, Record, Idx);
5385 unsigned NumElements = Record[1];
5386 unsigned VecKind = Record[2];
5387 return Context.getVectorType(ElementType, NumElements,
5388 (VectorType::VectorKind)VecKind);
5389 }
5390
5391 case TYPE_EXT_VECTOR: {
5392 if (Record.size() != 3) {
5393 Error("incorrect encoding of extended vector type in AST file");
5394 return QualType();
5395 }
5396
5397 QualType ElementType = readType(*Loc.F, Record, Idx);
5398 unsigned NumElements = Record[1];
5399 return Context.getExtVectorType(ElementType, NumElements);
5400 }
5401
5402 case TYPE_FUNCTION_NO_PROTO: {
5403 if (Record.size() != 6) {
5404 Error("incorrect encoding of no-proto function type");
5405 return QualType();
5406 }
5407 QualType ResultType = readType(*Loc.F, Record, Idx);
5408 FunctionType::ExtInfo Info(Record[1], Record[2], Record[3],
5409 (CallingConv)Record[4], Record[5]);
5410 return Context.getFunctionNoProtoType(ResultType, Info);
5411 }
5412
5413 case TYPE_FUNCTION_PROTO: {
5414 QualType ResultType = readType(*Loc.F, Record, Idx);
5415
5416 FunctionProtoType::ExtProtoInfo EPI;
5417 EPI.ExtInfo = FunctionType::ExtInfo(/*noreturn*/ Record[1],
5418 /*hasregparm*/ Record[2],
5419 /*regparm*/ Record[3],
5420 static_cast<CallingConv>(Record[4]),
5421 /*produces*/ Record[5]);
5422
5423 unsigned Idx = 6;
Guy Benyei11169dd2012-12-18 14:30:41 +00005424
5425 EPI.Variadic = Record[Idx++];
5426 EPI.HasTrailingReturn = Record[Idx++];
5427 EPI.TypeQuals = Record[Idx++];
5428 EPI.RefQualifier = static_cast<RefQualifierKind>(Record[Idx++]);
Richard Smith564417a2014-03-20 21:47:22 +00005429 SmallVector<QualType, 8> ExceptionStorage;
Richard Smith8acb4282014-07-31 21:57:55 +00005430 readExceptionSpec(*Loc.F, ExceptionStorage, EPI.ExceptionSpec, Record, Idx);
Richard Smith01b2cb42014-07-26 06:37:51 +00005431
5432 unsigned NumParams = Record[Idx++];
5433 SmallVector<QualType, 16> ParamTypes;
5434 for (unsigned I = 0; I != NumParams; ++I)
5435 ParamTypes.push_back(readType(*Loc.F, Record, Idx));
5436
Jordan Rose5c382722013-03-08 21:51:21 +00005437 return Context.getFunctionType(ResultType, ParamTypes, EPI);
Guy Benyei11169dd2012-12-18 14:30:41 +00005438 }
5439
5440 case TYPE_UNRESOLVED_USING: {
5441 unsigned Idx = 0;
5442 return Context.getTypeDeclType(
5443 ReadDeclAs<UnresolvedUsingTypenameDecl>(*Loc.F, Record, Idx));
5444 }
5445
5446 case TYPE_TYPEDEF: {
5447 if (Record.size() != 2) {
5448 Error("incorrect encoding of typedef type");
5449 return QualType();
5450 }
5451 unsigned Idx = 0;
5452 TypedefNameDecl *Decl = ReadDeclAs<TypedefNameDecl>(*Loc.F, Record, Idx);
5453 QualType Canonical = readType(*Loc.F, Record, Idx);
5454 if (!Canonical.isNull())
5455 Canonical = Context.getCanonicalType(Canonical);
5456 return Context.getTypedefType(Decl, Canonical);
5457 }
5458
5459 case TYPE_TYPEOF_EXPR:
5460 return Context.getTypeOfExprType(ReadExpr(*Loc.F));
5461
5462 case TYPE_TYPEOF: {
5463 if (Record.size() != 1) {
5464 Error("incorrect encoding of typeof(type) in AST file");
5465 return QualType();
5466 }
5467 QualType UnderlyingType = readType(*Loc.F, Record, Idx);
5468 return Context.getTypeOfType(UnderlyingType);
5469 }
5470
5471 case TYPE_DECLTYPE: {
5472 QualType UnderlyingType = readType(*Loc.F, Record, Idx);
5473 return Context.getDecltypeType(ReadExpr(*Loc.F), UnderlyingType);
5474 }
5475
5476 case TYPE_UNARY_TRANSFORM: {
5477 QualType BaseType = readType(*Loc.F, Record, Idx);
5478 QualType UnderlyingType = readType(*Loc.F, Record, Idx);
5479 UnaryTransformType::UTTKind UKind = (UnaryTransformType::UTTKind)Record[2];
5480 return Context.getUnaryTransformType(BaseType, UnderlyingType, UKind);
5481 }
5482
Richard Smith74aeef52013-04-26 16:15:35 +00005483 case TYPE_AUTO: {
5484 QualType Deduced = readType(*Loc.F, Record, Idx);
5485 bool IsDecltypeAuto = Record[Idx++];
Richard Smith27d807c2013-04-30 13:56:41 +00005486 bool IsDependent = Deduced.isNull() ? Record[Idx++] : false;
Manuel Klimek2fdbea22013-08-22 12:12:24 +00005487 return Context.getAutoType(Deduced, IsDecltypeAuto, IsDependent);
Richard Smith74aeef52013-04-26 16:15:35 +00005488 }
Guy Benyei11169dd2012-12-18 14:30:41 +00005489
5490 case TYPE_RECORD: {
5491 if (Record.size() != 2) {
5492 Error("incorrect encoding of record type");
5493 return QualType();
5494 }
5495 unsigned Idx = 0;
5496 bool IsDependent = Record[Idx++];
5497 RecordDecl *RD = ReadDeclAs<RecordDecl>(*Loc.F, Record, Idx);
5498 RD = cast_or_null<RecordDecl>(RD->getCanonicalDecl());
5499 QualType T = Context.getRecordType(RD);
5500 const_cast<Type*>(T.getTypePtr())->setDependent(IsDependent);
5501 return T;
5502 }
5503
5504 case TYPE_ENUM: {
5505 if (Record.size() != 2) {
5506 Error("incorrect encoding of enum type");
5507 return QualType();
5508 }
5509 unsigned Idx = 0;
5510 bool IsDependent = Record[Idx++];
5511 QualType T
5512 = Context.getEnumType(ReadDeclAs<EnumDecl>(*Loc.F, Record, Idx));
5513 const_cast<Type*>(T.getTypePtr())->setDependent(IsDependent);
5514 return T;
5515 }
5516
5517 case TYPE_ATTRIBUTED: {
5518 if (Record.size() != 3) {
5519 Error("incorrect encoding of attributed type");
5520 return QualType();
5521 }
5522 QualType modifiedType = readType(*Loc.F, Record, Idx);
5523 QualType equivalentType = readType(*Loc.F, Record, Idx);
5524 AttributedType::Kind kind = static_cast<AttributedType::Kind>(Record[2]);
5525 return Context.getAttributedType(kind, modifiedType, equivalentType);
5526 }
5527
5528 case TYPE_PAREN: {
5529 if (Record.size() != 1) {
5530 Error("incorrect encoding of paren type");
5531 return QualType();
5532 }
5533 QualType InnerType = readType(*Loc.F, Record, Idx);
5534 return Context.getParenType(InnerType);
5535 }
5536
5537 case TYPE_PACK_EXPANSION: {
5538 if (Record.size() != 2) {
5539 Error("incorrect encoding of pack expansion type");
5540 return QualType();
5541 }
5542 QualType Pattern = readType(*Loc.F, Record, Idx);
5543 if (Pattern.isNull())
5544 return QualType();
David Blaikie05785d12013-02-20 22:23:23 +00005545 Optional<unsigned> NumExpansions;
Guy Benyei11169dd2012-12-18 14:30:41 +00005546 if (Record[1])
5547 NumExpansions = Record[1] - 1;
5548 return Context.getPackExpansionType(Pattern, NumExpansions);
5549 }
5550
5551 case TYPE_ELABORATED: {
5552 unsigned Idx = 0;
5553 ElaboratedTypeKeyword Keyword = (ElaboratedTypeKeyword)Record[Idx++];
5554 NestedNameSpecifier *NNS = ReadNestedNameSpecifier(*Loc.F, Record, Idx);
5555 QualType NamedType = readType(*Loc.F, Record, Idx);
5556 return Context.getElaboratedType(Keyword, NNS, NamedType);
5557 }
5558
5559 case TYPE_OBJC_INTERFACE: {
5560 unsigned Idx = 0;
5561 ObjCInterfaceDecl *ItfD
5562 = ReadDeclAs<ObjCInterfaceDecl>(*Loc.F, Record, Idx);
5563 return Context.getObjCInterfaceType(ItfD->getCanonicalDecl());
5564 }
5565
5566 case TYPE_OBJC_OBJECT: {
5567 unsigned Idx = 0;
5568 QualType Base = readType(*Loc.F, Record, Idx);
5569 unsigned NumProtos = Record[Idx++];
5570 SmallVector<ObjCProtocolDecl*, 4> Protos;
5571 for (unsigned I = 0; I != NumProtos; ++I)
5572 Protos.push_back(ReadDeclAs<ObjCProtocolDecl>(*Loc.F, Record, Idx));
5573 return Context.getObjCObjectType(Base, Protos.data(), NumProtos);
5574 }
5575
5576 case TYPE_OBJC_OBJECT_POINTER: {
5577 unsigned Idx = 0;
5578 QualType Pointee = readType(*Loc.F, Record, Idx);
5579 return Context.getObjCObjectPointerType(Pointee);
5580 }
5581
5582 case TYPE_SUBST_TEMPLATE_TYPE_PARM: {
5583 unsigned Idx = 0;
5584 QualType Parm = readType(*Loc.F, Record, Idx);
5585 QualType Replacement = readType(*Loc.F, Record, Idx);
Stephan Tolksdorfe96f8b32014-03-15 10:23:27 +00005586 return Context.getSubstTemplateTypeParmType(
5587 cast<TemplateTypeParmType>(Parm),
5588 Context.getCanonicalType(Replacement));
Guy Benyei11169dd2012-12-18 14:30:41 +00005589 }
5590
5591 case TYPE_SUBST_TEMPLATE_TYPE_PARM_PACK: {
5592 unsigned Idx = 0;
5593 QualType Parm = readType(*Loc.F, Record, Idx);
5594 TemplateArgument ArgPack = ReadTemplateArgument(*Loc.F, Record, Idx);
5595 return Context.getSubstTemplateTypeParmPackType(
5596 cast<TemplateTypeParmType>(Parm),
5597 ArgPack);
5598 }
5599
5600 case TYPE_INJECTED_CLASS_NAME: {
5601 CXXRecordDecl *D = ReadDeclAs<CXXRecordDecl>(*Loc.F, Record, Idx);
5602 QualType TST = readType(*Loc.F, Record, Idx); // probably derivable
5603 // FIXME: ASTContext::getInjectedClassNameType is not currently suitable
5604 // for AST reading, too much interdependencies.
Richard Smith6377f8f2014-10-21 21:15:18 +00005605 const Type *T = nullptr;
5606 for (auto *DI = D; DI; DI = DI->getPreviousDecl()) {
5607 if (const Type *Existing = DI->getTypeForDecl()) {
5608 T = Existing;
5609 break;
5610 }
5611 }
5612 if (!T) {
Richard Smithf17fdbd2014-04-24 02:25:27 +00005613 T = new (Context, TypeAlignment) InjectedClassNameType(D, TST);
Richard Smith6377f8f2014-10-21 21:15:18 +00005614 for (auto *DI = D; DI; DI = DI->getPreviousDecl())
5615 DI->setTypeForDecl(T);
5616 }
Richard Smithf17fdbd2014-04-24 02:25:27 +00005617 return QualType(T, 0);
Guy Benyei11169dd2012-12-18 14:30:41 +00005618 }
5619
5620 case TYPE_TEMPLATE_TYPE_PARM: {
5621 unsigned Idx = 0;
5622 unsigned Depth = Record[Idx++];
5623 unsigned Index = Record[Idx++];
5624 bool Pack = Record[Idx++];
5625 TemplateTypeParmDecl *D
5626 = ReadDeclAs<TemplateTypeParmDecl>(*Loc.F, Record, Idx);
5627 return Context.getTemplateTypeParmType(Depth, Index, Pack, D);
5628 }
5629
5630 case TYPE_DEPENDENT_NAME: {
5631 unsigned Idx = 0;
5632 ElaboratedTypeKeyword Keyword = (ElaboratedTypeKeyword)Record[Idx++];
5633 NestedNameSpecifier *NNS = ReadNestedNameSpecifier(*Loc.F, Record, Idx);
5634 const IdentifierInfo *Name = this->GetIdentifierInfo(*Loc.F, Record, Idx);
5635 QualType Canon = readType(*Loc.F, Record, Idx);
5636 if (!Canon.isNull())
5637 Canon = Context.getCanonicalType(Canon);
5638 return Context.getDependentNameType(Keyword, NNS, Name, Canon);
5639 }
5640
5641 case TYPE_DEPENDENT_TEMPLATE_SPECIALIZATION: {
5642 unsigned Idx = 0;
5643 ElaboratedTypeKeyword Keyword = (ElaboratedTypeKeyword)Record[Idx++];
5644 NestedNameSpecifier *NNS = ReadNestedNameSpecifier(*Loc.F, Record, Idx);
5645 const IdentifierInfo *Name = this->GetIdentifierInfo(*Loc.F, Record, Idx);
5646 unsigned NumArgs = Record[Idx++];
5647 SmallVector<TemplateArgument, 8> Args;
5648 Args.reserve(NumArgs);
5649 while (NumArgs--)
5650 Args.push_back(ReadTemplateArgument(*Loc.F, Record, Idx));
5651 return Context.getDependentTemplateSpecializationType(Keyword, NNS, Name,
5652 Args.size(), Args.data());
5653 }
5654
5655 case TYPE_DEPENDENT_SIZED_ARRAY: {
5656 unsigned Idx = 0;
5657
5658 // ArrayType
5659 QualType ElementType = readType(*Loc.F, Record, Idx);
5660 ArrayType::ArraySizeModifier ASM
5661 = (ArrayType::ArraySizeModifier)Record[Idx++];
5662 unsigned IndexTypeQuals = Record[Idx++];
5663
5664 // DependentSizedArrayType
5665 Expr *NumElts = ReadExpr(*Loc.F);
5666 SourceRange Brackets = ReadSourceRange(*Loc.F, Record, Idx);
5667
5668 return Context.getDependentSizedArrayType(ElementType, NumElts, ASM,
5669 IndexTypeQuals, Brackets);
5670 }
5671
5672 case TYPE_TEMPLATE_SPECIALIZATION: {
5673 unsigned Idx = 0;
5674 bool IsDependent = Record[Idx++];
5675 TemplateName Name = ReadTemplateName(*Loc.F, Record, Idx);
5676 SmallVector<TemplateArgument, 8> Args;
5677 ReadTemplateArgumentList(Args, *Loc.F, Record, Idx);
5678 QualType Underlying = readType(*Loc.F, Record, Idx);
5679 QualType T;
5680 if (Underlying.isNull())
5681 T = Context.getCanonicalTemplateSpecializationType(Name, Args.data(),
5682 Args.size());
5683 else
5684 T = Context.getTemplateSpecializationType(Name, Args.data(),
5685 Args.size(), Underlying);
5686 const_cast<Type*>(T.getTypePtr())->setDependent(IsDependent);
5687 return T;
5688 }
5689
5690 case TYPE_ATOMIC: {
5691 if (Record.size() != 1) {
5692 Error("Incorrect encoding of atomic type");
5693 return QualType();
5694 }
5695 QualType ValueType = readType(*Loc.F, Record, Idx);
5696 return Context.getAtomicType(ValueType);
5697 }
5698 }
5699 llvm_unreachable("Invalid TypeCode!");
5700}
5701
Richard Smith564417a2014-03-20 21:47:22 +00005702void ASTReader::readExceptionSpec(ModuleFile &ModuleFile,
5703 SmallVectorImpl<QualType> &Exceptions,
Richard Smith8acb4282014-07-31 21:57:55 +00005704 FunctionProtoType::ExceptionSpecInfo &ESI,
Richard Smith564417a2014-03-20 21:47:22 +00005705 const RecordData &Record, unsigned &Idx) {
5706 ExceptionSpecificationType EST =
5707 static_cast<ExceptionSpecificationType>(Record[Idx++]);
Richard Smith8acb4282014-07-31 21:57:55 +00005708 ESI.Type = EST;
Richard Smith564417a2014-03-20 21:47:22 +00005709 if (EST == EST_Dynamic) {
Richard Smith8acb4282014-07-31 21:57:55 +00005710 for (unsigned I = 0, N = Record[Idx++]; I != N; ++I)
Richard Smith564417a2014-03-20 21:47:22 +00005711 Exceptions.push_back(readType(ModuleFile, Record, Idx));
Richard Smith8acb4282014-07-31 21:57:55 +00005712 ESI.Exceptions = Exceptions;
Richard Smith564417a2014-03-20 21:47:22 +00005713 } else if (EST == EST_ComputedNoexcept) {
Richard Smith8acb4282014-07-31 21:57:55 +00005714 ESI.NoexceptExpr = ReadExpr(ModuleFile);
Richard Smith564417a2014-03-20 21:47:22 +00005715 } else if (EST == EST_Uninstantiated) {
Richard Smith8acb4282014-07-31 21:57:55 +00005716 ESI.SourceDecl = ReadDeclAs<FunctionDecl>(ModuleFile, Record, Idx);
5717 ESI.SourceTemplate = ReadDeclAs<FunctionDecl>(ModuleFile, Record, Idx);
Richard Smith564417a2014-03-20 21:47:22 +00005718 } else if (EST == EST_Unevaluated) {
Richard Smith8acb4282014-07-31 21:57:55 +00005719 ESI.SourceDecl = ReadDeclAs<FunctionDecl>(ModuleFile, Record, Idx);
Richard Smith564417a2014-03-20 21:47:22 +00005720 }
5721}
5722
Guy Benyei11169dd2012-12-18 14:30:41 +00005723class clang::TypeLocReader : public TypeLocVisitor<TypeLocReader> {
5724 ASTReader &Reader;
5725 ModuleFile &F;
5726 const ASTReader::RecordData &Record;
5727 unsigned &Idx;
5728
5729 SourceLocation ReadSourceLocation(const ASTReader::RecordData &R,
5730 unsigned &I) {
5731 return Reader.ReadSourceLocation(F, R, I);
5732 }
5733
5734 template<typename T>
5735 T *ReadDeclAs(const ASTReader::RecordData &Record, unsigned &Idx) {
5736 return Reader.ReadDeclAs<T>(F, Record, Idx);
5737 }
5738
5739public:
5740 TypeLocReader(ASTReader &Reader, ModuleFile &F,
5741 const ASTReader::RecordData &Record, unsigned &Idx)
5742 : Reader(Reader), F(F), Record(Record), Idx(Idx)
5743 { }
5744
5745 // We want compile-time assurance that we've enumerated all of
5746 // these, so unfortunately we have to declare them first, then
5747 // define them out-of-line.
5748#define ABSTRACT_TYPELOC(CLASS, PARENT)
5749#define TYPELOC(CLASS, PARENT) \
5750 void Visit##CLASS##TypeLoc(CLASS##TypeLoc TyLoc);
5751#include "clang/AST/TypeLocNodes.def"
5752
5753 void VisitFunctionTypeLoc(FunctionTypeLoc);
5754 void VisitArrayTypeLoc(ArrayTypeLoc);
5755};
5756
5757void TypeLocReader::VisitQualifiedTypeLoc(QualifiedTypeLoc TL) {
5758 // nothing to do
5759}
5760void TypeLocReader::VisitBuiltinTypeLoc(BuiltinTypeLoc TL) {
5761 TL.setBuiltinLoc(ReadSourceLocation(Record, Idx));
5762 if (TL.needsExtraLocalData()) {
5763 TL.setWrittenTypeSpec(static_cast<DeclSpec::TST>(Record[Idx++]));
5764 TL.setWrittenSignSpec(static_cast<DeclSpec::TSS>(Record[Idx++]));
5765 TL.setWrittenWidthSpec(static_cast<DeclSpec::TSW>(Record[Idx++]));
5766 TL.setModeAttr(Record[Idx++]);
5767 }
5768}
5769void TypeLocReader::VisitComplexTypeLoc(ComplexTypeLoc TL) {
5770 TL.setNameLoc(ReadSourceLocation(Record, Idx));
5771}
5772void TypeLocReader::VisitPointerTypeLoc(PointerTypeLoc TL) {
5773 TL.setStarLoc(ReadSourceLocation(Record, Idx));
5774}
Reid Kleckner8a365022013-06-24 17:51:48 +00005775void TypeLocReader::VisitDecayedTypeLoc(DecayedTypeLoc TL) {
5776 // nothing to do
5777}
Reid Kleckner0503a872013-12-05 01:23:43 +00005778void TypeLocReader::VisitAdjustedTypeLoc(AdjustedTypeLoc TL) {
5779 // nothing to do
5780}
Guy Benyei11169dd2012-12-18 14:30:41 +00005781void TypeLocReader::VisitBlockPointerTypeLoc(BlockPointerTypeLoc TL) {
5782 TL.setCaretLoc(ReadSourceLocation(Record, Idx));
5783}
5784void TypeLocReader::VisitLValueReferenceTypeLoc(LValueReferenceTypeLoc TL) {
5785 TL.setAmpLoc(ReadSourceLocation(Record, Idx));
5786}
5787void TypeLocReader::VisitRValueReferenceTypeLoc(RValueReferenceTypeLoc TL) {
5788 TL.setAmpAmpLoc(ReadSourceLocation(Record, Idx));
5789}
5790void TypeLocReader::VisitMemberPointerTypeLoc(MemberPointerTypeLoc TL) {
5791 TL.setStarLoc(ReadSourceLocation(Record, Idx));
5792 TL.setClassTInfo(Reader.GetTypeSourceInfo(F, Record, Idx));
5793}
5794void TypeLocReader::VisitArrayTypeLoc(ArrayTypeLoc TL) {
5795 TL.setLBracketLoc(ReadSourceLocation(Record, Idx));
5796 TL.setRBracketLoc(ReadSourceLocation(Record, Idx));
5797 if (Record[Idx++])
5798 TL.setSizeExpr(Reader.ReadExpr(F));
5799 else
Craig Toppera13603a2014-05-22 05:54:18 +00005800 TL.setSizeExpr(nullptr);
Guy Benyei11169dd2012-12-18 14:30:41 +00005801}
5802void TypeLocReader::VisitConstantArrayTypeLoc(ConstantArrayTypeLoc TL) {
5803 VisitArrayTypeLoc(TL);
5804}
5805void TypeLocReader::VisitIncompleteArrayTypeLoc(IncompleteArrayTypeLoc TL) {
5806 VisitArrayTypeLoc(TL);
5807}
5808void TypeLocReader::VisitVariableArrayTypeLoc(VariableArrayTypeLoc TL) {
5809 VisitArrayTypeLoc(TL);
5810}
5811void TypeLocReader::VisitDependentSizedArrayTypeLoc(
5812 DependentSizedArrayTypeLoc TL) {
5813 VisitArrayTypeLoc(TL);
5814}
5815void TypeLocReader::VisitDependentSizedExtVectorTypeLoc(
5816 DependentSizedExtVectorTypeLoc TL) {
5817 TL.setNameLoc(ReadSourceLocation(Record, Idx));
5818}
5819void TypeLocReader::VisitVectorTypeLoc(VectorTypeLoc TL) {
5820 TL.setNameLoc(ReadSourceLocation(Record, Idx));
5821}
5822void TypeLocReader::VisitExtVectorTypeLoc(ExtVectorTypeLoc TL) {
5823 TL.setNameLoc(ReadSourceLocation(Record, Idx));
5824}
5825void TypeLocReader::VisitFunctionTypeLoc(FunctionTypeLoc TL) {
5826 TL.setLocalRangeBegin(ReadSourceLocation(Record, Idx));
5827 TL.setLParenLoc(ReadSourceLocation(Record, Idx));
5828 TL.setRParenLoc(ReadSourceLocation(Record, Idx));
5829 TL.setLocalRangeEnd(ReadSourceLocation(Record, Idx));
Alp Tokerb3fd5cf2014-01-21 00:32:38 +00005830 for (unsigned i = 0, e = TL.getNumParams(); i != e; ++i) {
5831 TL.setParam(i, ReadDeclAs<ParmVarDecl>(Record, Idx));
Guy Benyei11169dd2012-12-18 14:30:41 +00005832 }
5833}
5834void TypeLocReader::VisitFunctionProtoTypeLoc(FunctionProtoTypeLoc TL) {
5835 VisitFunctionTypeLoc(TL);
5836}
5837void TypeLocReader::VisitFunctionNoProtoTypeLoc(FunctionNoProtoTypeLoc TL) {
5838 VisitFunctionTypeLoc(TL);
5839}
5840void TypeLocReader::VisitUnresolvedUsingTypeLoc(UnresolvedUsingTypeLoc TL) {
5841 TL.setNameLoc(ReadSourceLocation(Record, Idx));
5842}
5843void TypeLocReader::VisitTypedefTypeLoc(TypedefTypeLoc TL) {
5844 TL.setNameLoc(ReadSourceLocation(Record, Idx));
5845}
5846void TypeLocReader::VisitTypeOfExprTypeLoc(TypeOfExprTypeLoc TL) {
5847 TL.setTypeofLoc(ReadSourceLocation(Record, Idx));
5848 TL.setLParenLoc(ReadSourceLocation(Record, Idx));
5849 TL.setRParenLoc(ReadSourceLocation(Record, Idx));
5850}
5851void TypeLocReader::VisitTypeOfTypeLoc(TypeOfTypeLoc TL) {
5852 TL.setTypeofLoc(ReadSourceLocation(Record, Idx));
5853 TL.setLParenLoc(ReadSourceLocation(Record, Idx));
5854 TL.setRParenLoc(ReadSourceLocation(Record, Idx));
5855 TL.setUnderlyingTInfo(Reader.GetTypeSourceInfo(F, Record, Idx));
5856}
5857void TypeLocReader::VisitDecltypeTypeLoc(DecltypeTypeLoc TL) {
5858 TL.setNameLoc(ReadSourceLocation(Record, Idx));
5859}
5860void TypeLocReader::VisitUnaryTransformTypeLoc(UnaryTransformTypeLoc TL) {
5861 TL.setKWLoc(ReadSourceLocation(Record, Idx));
5862 TL.setLParenLoc(ReadSourceLocation(Record, Idx));
5863 TL.setRParenLoc(ReadSourceLocation(Record, Idx));
5864 TL.setUnderlyingTInfo(Reader.GetTypeSourceInfo(F, Record, Idx));
5865}
5866void TypeLocReader::VisitAutoTypeLoc(AutoTypeLoc TL) {
5867 TL.setNameLoc(ReadSourceLocation(Record, Idx));
5868}
5869void TypeLocReader::VisitRecordTypeLoc(RecordTypeLoc TL) {
5870 TL.setNameLoc(ReadSourceLocation(Record, Idx));
5871}
5872void TypeLocReader::VisitEnumTypeLoc(EnumTypeLoc TL) {
5873 TL.setNameLoc(ReadSourceLocation(Record, Idx));
5874}
5875void TypeLocReader::VisitAttributedTypeLoc(AttributedTypeLoc TL) {
5876 TL.setAttrNameLoc(ReadSourceLocation(Record, Idx));
5877 if (TL.hasAttrOperand()) {
5878 SourceRange range;
5879 range.setBegin(ReadSourceLocation(Record, Idx));
5880 range.setEnd(ReadSourceLocation(Record, Idx));
5881 TL.setAttrOperandParensRange(range);
5882 }
5883 if (TL.hasAttrExprOperand()) {
5884 if (Record[Idx++])
5885 TL.setAttrExprOperand(Reader.ReadExpr(F));
5886 else
Craig Toppera13603a2014-05-22 05:54:18 +00005887 TL.setAttrExprOperand(nullptr);
Guy Benyei11169dd2012-12-18 14:30:41 +00005888 } else if (TL.hasAttrEnumOperand())
5889 TL.setAttrEnumOperandLoc(ReadSourceLocation(Record, Idx));
5890}
5891void TypeLocReader::VisitTemplateTypeParmTypeLoc(TemplateTypeParmTypeLoc TL) {
5892 TL.setNameLoc(ReadSourceLocation(Record, Idx));
5893}
5894void TypeLocReader::VisitSubstTemplateTypeParmTypeLoc(
5895 SubstTemplateTypeParmTypeLoc TL) {
5896 TL.setNameLoc(ReadSourceLocation(Record, Idx));
5897}
5898void TypeLocReader::VisitSubstTemplateTypeParmPackTypeLoc(
5899 SubstTemplateTypeParmPackTypeLoc TL) {
5900 TL.setNameLoc(ReadSourceLocation(Record, Idx));
5901}
5902void TypeLocReader::VisitTemplateSpecializationTypeLoc(
5903 TemplateSpecializationTypeLoc TL) {
5904 TL.setTemplateKeywordLoc(ReadSourceLocation(Record, Idx));
5905 TL.setTemplateNameLoc(ReadSourceLocation(Record, Idx));
5906 TL.setLAngleLoc(ReadSourceLocation(Record, Idx));
5907 TL.setRAngleLoc(ReadSourceLocation(Record, Idx));
5908 for (unsigned i = 0, e = TL.getNumArgs(); i != e; ++i)
5909 TL.setArgLocInfo(i,
5910 Reader.GetTemplateArgumentLocInfo(F,
5911 TL.getTypePtr()->getArg(i).getKind(),
5912 Record, Idx));
5913}
5914void TypeLocReader::VisitParenTypeLoc(ParenTypeLoc TL) {
5915 TL.setLParenLoc(ReadSourceLocation(Record, Idx));
5916 TL.setRParenLoc(ReadSourceLocation(Record, Idx));
5917}
5918void TypeLocReader::VisitElaboratedTypeLoc(ElaboratedTypeLoc TL) {
5919 TL.setElaboratedKeywordLoc(ReadSourceLocation(Record, Idx));
5920 TL.setQualifierLoc(Reader.ReadNestedNameSpecifierLoc(F, Record, Idx));
5921}
5922void TypeLocReader::VisitInjectedClassNameTypeLoc(InjectedClassNameTypeLoc TL) {
5923 TL.setNameLoc(ReadSourceLocation(Record, Idx));
5924}
5925void TypeLocReader::VisitDependentNameTypeLoc(DependentNameTypeLoc TL) {
5926 TL.setElaboratedKeywordLoc(ReadSourceLocation(Record, Idx));
5927 TL.setQualifierLoc(Reader.ReadNestedNameSpecifierLoc(F, Record, Idx));
5928 TL.setNameLoc(ReadSourceLocation(Record, Idx));
5929}
5930void TypeLocReader::VisitDependentTemplateSpecializationTypeLoc(
5931 DependentTemplateSpecializationTypeLoc TL) {
5932 TL.setElaboratedKeywordLoc(ReadSourceLocation(Record, Idx));
5933 TL.setQualifierLoc(Reader.ReadNestedNameSpecifierLoc(F, Record, Idx));
5934 TL.setTemplateKeywordLoc(ReadSourceLocation(Record, Idx));
5935 TL.setTemplateNameLoc(ReadSourceLocation(Record, Idx));
5936 TL.setLAngleLoc(ReadSourceLocation(Record, Idx));
5937 TL.setRAngleLoc(ReadSourceLocation(Record, Idx));
5938 for (unsigned I = 0, E = TL.getNumArgs(); I != E; ++I)
5939 TL.setArgLocInfo(I,
5940 Reader.GetTemplateArgumentLocInfo(F,
5941 TL.getTypePtr()->getArg(I).getKind(),
5942 Record, Idx));
5943}
5944void TypeLocReader::VisitPackExpansionTypeLoc(PackExpansionTypeLoc TL) {
5945 TL.setEllipsisLoc(ReadSourceLocation(Record, Idx));
5946}
5947void TypeLocReader::VisitObjCInterfaceTypeLoc(ObjCInterfaceTypeLoc TL) {
5948 TL.setNameLoc(ReadSourceLocation(Record, Idx));
5949}
5950void TypeLocReader::VisitObjCObjectTypeLoc(ObjCObjectTypeLoc TL) {
5951 TL.setHasBaseTypeAsWritten(Record[Idx++]);
5952 TL.setLAngleLoc(ReadSourceLocation(Record, Idx));
5953 TL.setRAngleLoc(ReadSourceLocation(Record, Idx));
5954 for (unsigned i = 0, e = TL.getNumProtocols(); i != e; ++i)
5955 TL.setProtocolLoc(i, ReadSourceLocation(Record, Idx));
5956}
5957void TypeLocReader::VisitObjCObjectPointerTypeLoc(ObjCObjectPointerTypeLoc TL) {
5958 TL.setStarLoc(ReadSourceLocation(Record, Idx));
5959}
5960void TypeLocReader::VisitAtomicTypeLoc(AtomicTypeLoc TL) {
5961 TL.setKWLoc(ReadSourceLocation(Record, Idx));
5962 TL.setLParenLoc(ReadSourceLocation(Record, Idx));
5963 TL.setRParenLoc(ReadSourceLocation(Record, Idx));
5964}
5965
5966TypeSourceInfo *ASTReader::GetTypeSourceInfo(ModuleFile &F,
5967 const RecordData &Record,
5968 unsigned &Idx) {
5969 QualType InfoTy = readType(F, Record, Idx);
5970 if (InfoTy.isNull())
Craig Toppera13603a2014-05-22 05:54:18 +00005971 return nullptr;
Guy Benyei11169dd2012-12-18 14:30:41 +00005972
5973 TypeSourceInfo *TInfo = getContext().CreateTypeSourceInfo(InfoTy);
5974 TypeLocReader TLR(*this, F, Record, Idx);
5975 for (TypeLoc TL = TInfo->getTypeLoc(); !TL.isNull(); TL = TL.getNextTypeLoc())
5976 TLR.Visit(TL);
5977 return TInfo;
5978}
5979
5980QualType ASTReader::GetType(TypeID ID) {
5981 unsigned FastQuals = ID & Qualifiers::FastMask;
5982 unsigned Index = ID >> Qualifiers::FastWidth;
5983
5984 if (Index < NUM_PREDEF_TYPE_IDS) {
5985 QualType T;
5986 switch ((PredefinedTypeIDs)Index) {
5987 case PREDEF_TYPE_NULL_ID: return QualType();
5988 case PREDEF_TYPE_VOID_ID: T = Context.VoidTy; break;
5989 case PREDEF_TYPE_BOOL_ID: T = Context.BoolTy; break;
5990
5991 case PREDEF_TYPE_CHAR_U_ID:
5992 case PREDEF_TYPE_CHAR_S_ID:
5993 // FIXME: Check that the signedness of CharTy is correct!
5994 T = Context.CharTy;
5995 break;
5996
5997 case PREDEF_TYPE_UCHAR_ID: T = Context.UnsignedCharTy; break;
5998 case PREDEF_TYPE_USHORT_ID: T = Context.UnsignedShortTy; break;
5999 case PREDEF_TYPE_UINT_ID: T = Context.UnsignedIntTy; break;
6000 case PREDEF_TYPE_ULONG_ID: T = Context.UnsignedLongTy; break;
6001 case PREDEF_TYPE_ULONGLONG_ID: T = Context.UnsignedLongLongTy; break;
6002 case PREDEF_TYPE_UINT128_ID: T = Context.UnsignedInt128Ty; break;
6003 case PREDEF_TYPE_SCHAR_ID: T = Context.SignedCharTy; break;
6004 case PREDEF_TYPE_WCHAR_ID: T = Context.WCharTy; break;
6005 case PREDEF_TYPE_SHORT_ID: T = Context.ShortTy; break;
6006 case PREDEF_TYPE_INT_ID: T = Context.IntTy; break;
6007 case PREDEF_TYPE_LONG_ID: T = Context.LongTy; break;
6008 case PREDEF_TYPE_LONGLONG_ID: T = Context.LongLongTy; break;
6009 case PREDEF_TYPE_INT128_ID: T = Context.Int128Ty; break;
6010 case PREDEF_TYPE_HALF_ID: T = Context.HalfTy; break;
6011 case PREDEF_TYPE_FLOAT_ID: T = Context.FloatTy; break;
6012 case PREDEF_TYPE_DOUBLE_ID: T = Context.DoubleTy; break;
6013 case PREDEF_TYPE_LONGDOUBLE_ID: T = Context.LongDoubleTy; break;
6014 case PREDEF_TYPE_OVERLOAD_ID: T = Context.OverloadTy; break;
6015 case PREDEF_TYPE_BOUND_MEMBER: T = Context.BoundMemberTy; break;
6016 case PREDEF_TYPE_PSEUDO_OBJECT: T = Context.PseudoObjectTy; break;
6017 case PREDEF_TYPE_DEPENDENT_ID: T = Context.DependentTy; break;
6018 case PREDEF_TYPE_UNKNOWN_ANY: T = Context.UnknownAnyTy; break;
6019 case PREDEF_TYPE_NULLPTR_ID: T = Context.NullPtrTy; break;
6020 case PREDEF_TYPE_CHAR16_ID: T = Context.Char16Ty; break;
6021 case PREDEF_TYPE_CHAR32_ID: T = Context.Char32Ty; break;
6022 case PREDEF_TYPE_OBJC_ID: T = Context.ObjCBuiltinIdTy; break;
6023 case PREDEF_TYPE_OBJC_CLASS: T = Context.ObjCBuiltinClassTy; break;
6024 case PREDEF_TYPE_OBJC_SEL: T = Context.ObjCBuiltinSelTy; break;
Guy Benyeid8a08ea2012-12-18 14:38:23 +00006025 case PREDEF_TYPE_IMAGE1D_ID: T = Context.OCLImage1dTy; break;
6026 case PREDEF_TYPE_IMAGE1D_ARR_ID: T = Context.OCLImage1dArrayTy; break;
6027 case PREDEF_TYPE_IMAGE1D_BUFF_ID: T = Context.OCLImage1dBufferTy; break;
6028 case PREDEF_TYPE_IMAGE2D_ID: T = Context.OCLImage2dTy; break;
6029 case PREDEF_TYPE_IMAGE2D_ARR_ID: T = Context.OCLImage2dArrayTy; break;
6030 case PREDEF_TYPE_IMAGE3D_ID: T = Context.OCLImage3dTy; break;
Guy Benyei61054192013-02-07 10:55:47 +00006031 case PREDEF_TYPE_SAMPLER_ID: T = Context.OCLSamplerTy; break;
Guy Benyei1b4fb3e2013-01-20 12:31:11 +00006032 case PREDEF_TYPE_EVENT_ID: T = Context.OCLEventTy; break;
Guy Benyei11169dd2012-12-18 14:30:41 +00006033 case PREDEF_TYPE_AUTO_DEDUCT: T = Context.getAutoDeductType(); break;
6034
6035 case PREDEF_TYPE_AUTO_RREF_DEDUCT:
6036 T = Context.getAutoRRefDeductType();
6037 break;
6038
6039 case PREDEF_TYPE_ARC_UNBRIDGED_CAST:
6040 T = Context.ARCUnbridgedCastTy;
6041 break;
6042
6043 case PREDEF_TYPE_VA_LIST_TAG:
6044 T = Context.getVaListTagType();
6045 break;
6046
6047 case PREDEF_TYPE_BUILTIN_FN:
6048 T = Context.BuiltinFnTy;
6049 break;
6050 }
6051
6052 assert(!T.isNull() && "Unknown predefined type");
6053 return T.withFastQualifiers(FastQuals);
6054 }
6055
6056 Index -= NUM_PREDEF_TYPE_IDS;
6057 assert(Index < TypesLoaded.size() && "Type index out-of-range");
6058 if (TypesLoaded[Index].isNull()) {
6059 TypesLoaded[Index] = readTypeRecord(Index);
6060 if (TypesLoaded[Index].isNull())
6061 return QualType();
6062
6063 TypesLoaded[Index]->setFromAST();
6064 if (DeserializationListener)
6065 DeserializationListener->TypeRead(TypeIdx::fromTypeID(ID),
6066 TypesLoaded[Index]);
6067 }
6068
6069 return TypesLoaded[Index].withFastQualifiers(FastQuals);
6070}
6071
6072QualType ASTReader::getLocalType(ModuleFile &F, unsigned LocalID) {
6073 return GetType(getGlobalTypeID(F, LocalID));
6074}
6075
6076serialization::TypeID
6077ASTReader::getGlobalTypeID(ModuleFile &F, unsigned LocalID) const {
6078 unsigned FastQuals = LocalID & Qualifiers::FastMask;
6079 unsigned LocalIndex = LocalID >> Qualifiers::FastWidth;
6080
6081 if (LocalIndex < NUM_PREDEF_TYPE_IDS)
6082 return LocalID;
6083
6084 ContinuousRangeMap<uint32_t, int, 2>::iterator I
6085 = F.TypeRemap.find(LocalIndex - NUM_PREDEF_TYPE_IDS);
6086 assert(I != F.TypeRemap.end() && "Invalid index into type index remap");
6087
6088 unsigned GlobalIndex = LocalIndex + I->second;
6089 return (GlobalIndex << Qualifiers::FastWidth) | FastQuals;
6090}
6091
6092TemplateArgumentLocInfo
6093ASTReader::GetTemplateArgumentLocInfo(ModuleFile &F,
6094 TemplateArgument::ArgKind Kind,
6095 const RecordData &Record,
6096 unsigned &Index) {
6097 switch (Kind) {
6098 case TemplateArgument::Expression:
6099 return ReadExpr(F);
6100 case TemplateArgument::Type:
6101 return GetTypeSourceInfo(F, Record, Index);
6102 case TemplateArgument::Template: {
6103 NestedNameSpecifierLoc QualifierLoc = ReadNestedNameSpecifierLoc(F, Record,
6104 Index);
6105 SourceLocation TemplateNameLoc = ReadSourceLocation(F, Record, Index);
6106 return TemplateArgumentLocInfo(QualifierLoc, TemplateNameLoc,
6107 SourceLocation());
6108 }
6109 case TemplateArgument::TemplateExpansion: {
6110 NestedNameSpecifierLoc QualifierLoc = ReadNestedNameSpecifierLoc(F, Record,
6111 Index);
6112 SourceLocation TemplateNameLoc = ReadSourceLocation(F, Record, Index);
6113 SourceLocation EllipsisLoc = ReadSourceLocation(F, Record, Index);
6114 return TemplateArgumentLocInfo(QualifierLoc, TemplateNameLoc,
6115 EllipsisLoc);
6116 }
6117 case TemplateArgument::Null:
6118 case TemplateArgument::Integral:
6119 case TemplateArgument::Declaration:
6120 case TemplateArgument::NullPtr:
6121 case TemplateArgument::Pack:
6122 // FIXME: Is this right?
6123 return TemplateArgumentLocInfo();
6124 }
6125 llvm_unreachable("unexpected template argument loc");
6126}
6127
6128TemplateArgumentLoc
6129ASTReader::ReadTemplateArgumentLoc(ModuleFile &F,
6130 const RecordData &Record, unsigned &Index) {
6131 TemplateArgument Arg = ReadTemplateArgument(F, Record, Index);
6132
6133 if (Arg.getKind() == TemplateArgument::Expression) {
6134 if (Record[Index++]) // bool InfoHasSameExpr.
6135 return TemplateArgumentLoc(Arg, TemplateArgumentLocInfo(Arg.getAsExpr()));
6136 }
6137 return TemplateArgumentLoc(Arg, GetTemplateArgumentLocInfo(F, Arg.getKind(),
6138 Record, Index));
6139}
6140
Enea Zaffanella6dbe1872013-08-10 07:24:53 +00006141const ASTTemplateArgumentListInfo*
6142ASTReader::ReadASTTemplateArgumentListInfo(ModuleFile &F,
6143 const RecordData &Record,
6144 unsigned &Index) {
6145 SourceLocation LAngleLoc = ReadSourceLocation(F, Record, Index);
6146 SourceLocation RAngleLoc = ReadSourceLocation(F, Record, Index);
6147 unsigned NumArgsAsWritten = Record[Index++];
6148 TemplateArgumentListInfo TemplArgsInfo(LAngleLoc, RAngleLoc);
6149 for (unsigned i = 0; i != NumArgsAsWritten; ++i)
6150 TemplArgsInfo.addArgument(ReadTemplateArgumentLoc(F, Record, Index));
6151 return ASTTemplateArgumentListInfo::Create(getContext(), TemplArgsInfo);
6152}
6153
Guy Benyei11169dd2012-12-18 14:30:41 +00006154Decl *ASTReader::GetExternalDecl(uint32_t ID) {
6155 return GetDecl(ID);
6156}
6157
Richard Smith50895422015-01-31 03:04:55 +00006158template<typename TemplateSpecializationDecl>
6159static void completeRedeclChainForTemplateSpecialization(Decl *D) {
6160 if (auto *TSD = dyn_cast<TemplateSpecializationDecl>(D))
6161 TSD->getSpecializedTemplate()->LoadLazySpecializations();
6162}
6163
Richard Smith053f6c62014-05-16 23:01:30 +00006164void ASTReader::CompleteRedeclChain(const Decl *D) {
Richard Smith851072e2014-05-19 20:59:20 +00006165 if (NumCurrentElementsDeserializing) {
6166 // We arrange to not care about the complete redeclaration chain while we're
6167 // deserializing. Just remember that the AST has marked this one as complete
6168 // but that it's not actually complete yet, so we know we still need to
6169 // complete it later.
6170 PendingIncompleteDeclChains.push_back(const_cast<Decl*>(D));
6171 return;
6172 }
6173
Richard Smith053f6c62014-05-16 23:01:30 +00006174 const DeclContext *DC = D->getDeclContext()->getRedeclContext();
6175
Richard Smith053f6c62014-05-16 23:01:30 +00006176 // If this is a named declaration, complete it by looking it up
6177 // within its context.
6178 //
Richard Smith01bdb7a2014-08-28 05:44:07 +00006179 // FIXME: Merging a function definition should merge
Richard Smith053f6c62014-05-16 23:01:30 +00006180 // all mergeable entities within it.
6181 if (isa<TranslationUnitDecl>(DC) || isa<NamespaceDecl>(DC) ||
6182 isa<CXXRecordDecl>(DC) || isa<EnumDecl>(DC)) {
6183 if (DeclarationName Name = cast<NamedDecl>(D)->getDeclName()) {
6184 auto *II = Name.getAsIdentifierInfo();
6185 if (isa<TranslationUnitDecl>(DC) && II) {
6186 // Outside of C++, we don't have a lookup table for the TU, so update
6187 // the identifier instead. In C++, either way should work fine.
6188 if (II->isOutOfDate())
6189 updateOutOfDateIdentifier(*II);
6190 } else
6191 DC->lookup(Name);
Richard Smith01bdb7a2014-08-28 05:44:07 +00006192 } else if (needsAnonymousDeclarationNumber(cast<NamedDecl>(D))) {
6193 // FIXME: It'd be nice to do something a bit more targeted here.
6194 D->getDeclContext()->decls_begin();
Richard Smith053f6c62014-05-16 23:01:30 +00006195 }
6196 }
Richard Smith50895422015-01-31 03:04:55 +00006197
6198 if (auto *CTSD = dyn_cast<ClassTemplateSpecializationDecl>(D))
6199 CTSD->getSpecializedTemplate()->LoadLazySpecializations();
6200 if (auto *VTSD = dyn_cast<VarTemplateSpecializationDecl>(D))
6201 VTSD->getSpecializedTemplate()->LoadLazySpecializations();
6202 if (auto *FD = dyn_cast<FunctionDecl>(D)) {
6203 if (auto *Template = FD->getPrimaryTemplate())
6204 Template->LoadLazySpecializations();
6205 }
Richard Smith053f6c62014-05-16 23:01:30 +00006206}
6207
Richard Smithcd45dbc2014-04-19 03:48:30 +00006208uint64_t ASTReader::readCXXBaseSpecifiers(ModuleFile &M,
6209 const RecordData &Record,
6210 unsigned &Idx) {
6211 if (Idx >= Record.size() || Record[Idx] > M.LocalNumCXXBaseSpecifiers) {
6212 Error("malformed AST file: missing C++ base specifier");
Guy Benyei11169dd2012-12-18 14:30:41 +00006213 return 0;
Richard Smithcd45dbc2014-04-19 03:48:30 +00006214 }
6215
Guy Benyei11169dd2012-12-18 14:30:41 +00006216 unsigned LocalID = Record[Idx++];
6217 return getGlobalBitOffset(M, M.CXXBaseSpecifiersOffsets[LocalID - 1]);
6218}
6219
6220CXXBaseSpecifier *ASTReader::GetExternalCXXBaseSpecifiers(uint64_t Offset) {
6221 RecordLocation Loc = getLocalBitOffset(Offset);
Chris Lattner7fb3bef2013-01-20 00:56:42 +00006222 BitstreamCursor &Cursor = Loc.F->DeclsCursor;
Guy Benyei11169dd2012-12-18 14:30:41 +00006223 SavedStreamPosition SavedPosition(Cursor);
6224 Cursor.JumpToBit(Loc.Offset);
6225 ReadingKindTracker ReadingKind(Read_Decl, *this);
6226 RecordData Record;
6227 unsigned Code = Cursor.ReadCode();
Chris Lattner0e6c9402013-01-20 02:38:54 +00006228 unsigned RecCode = Cursor.readRecord(Code, Record);
Guy Benyei11169dd2012-12-18 14:30:41 +00006229 if (RecCode != DECL_CXX_BASE_SPECIFIERS) {
Richard Smithcd45dbc2014-04-19 03:48:30 +00006230 Error("malformed AST file: missing C++ base specifiers");
Craig Toppera13603a2014-05-22 05:54:18 +00006231 return nullptr;
Guy Benyei11169dd2012-12-18 14:30:41 +00006232 }
6233
6234 unsigned Idx = 0;
6235 unsigned NumBases = Record[Idx++];
6236 void *Mem = Context.Allocate(sizeof(CXXBaseSpecifier) * NumBases);
6237 CXXBaseSpecifier *Bases = new (Mem) CXXBaseSpecifier [NumBases];
6238 for (unsigned I = 0; I != NumBases; ++I)
6239 Bases[I] = ReadCXXBaseSpecifier(*Loc.F, Record, Idx);
6240 return Bases;
6241}
6242
6243serialization::DeclID
6244ASTReader::getGlobalDeclID(ModuleFile &F, LocalDeclID LocalID) const {
6245 if (LocalID < NUM_PREDEF_DECL_IDS)
6246 return LocalID;
6247
6248 ContinuousRangeMap<uint32_t, int, 2>::iterator I
6249 = F.DeclRemap.find(LocalID - NUM_PREDEF_DECL_IDS);
6250 assert(I != F.DeclRemap.end() && "Invalid index into decl index remap");
6251
6252 return LocalID + I->second;
6253}
6254
6255bool ASTReader::isDeclIDFromModule(serialization::GlobalDeclID ID,
6256 ModuleFile &M) const {
6257 GlobalDeclMapType::const_iterator I = GlobalDeclMap.find(ID);
6258 assert(I != GlobalDeclMap.end() && "Corrupted global declaration map");
6259 return &M == I->second;
6260}
6261
Douglas Gregor9f782892013-01-21 15:25:38 +00006262ModuleFile *ASTReader::getOwningModuleFile(const Decl *D) {
Guy Benyei11169dd2012-12-18 14:30:41 +00006263 if (!D->isFromASTFile())
Craig Toppera13603a2014-05-22 05:54:18 +00006264 return nullptr;
Guy Benyei11169dd2012-12-18 14:30:41 +00006265 GlobalDeclMapType::const_iterator I = GlobalDeclMap.find(D->getGlobalID());
6266 assert(I != GlobalDeclMap.end() && "Corrupted global declaration map");
6267 return I->second;
6268}
6269
6270SourceLocation ASTReader::getSourceLocationForDeclID(GlobalDeclID ID) {
6271 if (ID < NUM_PREDEF_DECL_IDS)
6272 return SourceLocation();
Richard Smithcd45dbc2014-04-19 03:48:30 +00006273
Guy Benyei11169dd2012-12-18 14:30:41 +00006274 unsigned Index = ID - NUM_PREDEF_DECL_IDS;
6275
6276 if (Index > DeclsLoaded.size()) {
6277 Error("declaration ID out-of-range for AST file");
6278 return SourceLocation();
6279 }
Richard Smithcd45dbc2014-04-19 03:48:30 +00006280
Guy Benyei11169dd2012-12-18 14:30:41 +00006281 if (Decl *D = DeclsLoaded[Index])
6282 return D->getLocation();
6283
6284 unsigned RawLocation = 0;
6285 RecordLocation Rec = DeclCursorForID(ID, RawLocation);
6286 return ReadSourceLocation(*Rec.F, RawLocation);
6287}
6288
Richard Smithcd45dbc2014-04-19 03:48:30 +00006289Decl *ASTReader::GetExistingDecl(DeclID ID) {
6290 if (ID < NUM_PREDEF_DECL_IDS) {
Guy Benyei11169dd2012-12-18 14:30:41 +00006291 switch ((PredefinedDeclIDs)ID) {
6292 case PREDEF_DECL_NULL_ID:
Craig Toppera13603a2014-05-22 05:54:18 +00006293 return nullptr;
Richard Smithcd45dbc2014-04-19 03:48:30 +00006294
Guy Benyei11169dd2012-12-18 14:30:41 +00006295 case PREDEF_DECL_TRANSLATION_UNIT_ID:
6296 return Context.getTranslationUnitDecl();
Richard Smithcd45dbc2014-04-19 03:48:30 +00006297
Guy Benyei11169dd2012-12-18 14:30:41 +00006298 case PREDEF_DECL_OBJC_ID_ID:
6299 return Context.getObjCIdDecl();
6300
6301 case PREDEF_DECL_OBJC_SEL_ID:
6302 return Context.getObjCSelDecl();
6303
6304 case PREDEF_DECL_OBJC_CLASS_ID:
6305 return Context.getObjCClassDecl();
Richard Smithcd45dbc2014-04-19 03:48:30 +00006306
Guy Benyei11169dd2012-12-18 14:30:41 +00006307 case PREDEF_DECL_OBJC_PROTOCOL_ID:
6308 return Context.getObjCProtocolDecl();
Richard Smithcd45dbc2014-04-19 03:48:30 +00006309
Guy Benyei11169dd2012-12-18 14:30:41 +00006310 case PREDEF_DECL_INT_128_ID:
6311 return Context.getInt128Decl();
6312
6313 case PREDEF_DECL_UNSIGNED_INT_128_ID:
6314 return Context.getUInt128Decl();
Richard Smithcd45dbc2014-04-19 03:48:30 +00006315
Guy Benyei11169dd2012-12-18 14:30:41 +00006316 case PREDEF_DECL_OBJC_INSTANCETYPE_ID:
6317 return Context.getObjCInstanceTypeDecl();
6318
6319 case PREDEF_DECL_BUILTIN_VA_LIST_ID:
6320 return Context.getBuiltinVaListDecl();
6321 }
6322 }
Richard Smithcd45dbc2014-04-19 03:48:30 +00006323
Guy Benyei11169dd2012-12-18 14:30:41 +00006324 unsigned Index = ID - NUM_PREDEF_DECL_IDS;
6325
6326 if (Index >= DeclsLoaded.size()) {
6327 assert(0 && "declaration ID out-of-range for AST file");
6328 Error("declaration ID out-of-range for AST file");
Craig Toppera13603a2014-05-22 05:54:18 +00006329 return nullptr;
Guy Benyei11169dd2012-12-18 14:30:41 +00006330 }
Richard Smithcd45dbc2014-04-19 03:48:30 +00006331
6332 return DeclsLoaded[Index];
6333}
6334
6335Decl *ASTReader::GetDecl(DeclID ID) {
6336 if (ID < NUM_PREDEF_DECL_IDS)
6337 return GetExistingDecl(ID);
6338
6339 unsigned Index = ID - NUM_PREDEF_DECL_IDS;
6340
6341 if (Index >= DeclsLoaded.size()) {
6342 assert(0 && "declaration ID out-of-range for AST file");
6343 Error("declaration ID out-of-range for AST file");
Craig Toppera13603a2014-05-22 05:54:18 +00006344 return nullptr;
Richard Smithcd45dbc2014-04-19 03:48:30 +00006345 }
6346
Guy Benyei11169dd2012-12-18 14:30:41 +00006347 if (!DeclsLoaded[Index]) {
6348 ReadDeclRecord(ID);
6349 if (DeserializationListener)
6350 DeserializationListener->DeclRead(ID, DeclsLoaded[Index]);
6351 }
6352
6353 return DeclsLoaded[Index];
6354}
6355
6356DeclID ASTReader::mapGlobalIDToModuleFileGlobalID(ModuleFile &M,
6357 DeclID GlobalID) {
6358 if (GlobalID < NUM_PREDEF_DECL_IDS)
6359 return GlobalID;
6360
6361 GlobalDeclMapType::const_iterator I = GlobalDeclMap.find(GlobalID);
6362 assert(I != GlobalDeclMap.end() && "Corrupted global declaration map");
6363 ModuleFile *Owner = I->second;
6364
6365 llvm::DenseMap<ModuleFile *, serialization::DeclID>::iterator Pos
6366 = M.GlobalToLocalDeclIDs.find(Owner);
6367 if (Pos == M.GlobalToLocalDeclIDs.end())
6368 return 0;
6369
6370 return GlobalID - Owner->BaseDeclID + Pos->second;
6371}
6372
6373serialization::DeclID ASTReader::ReadDeclID(ModuleFile &F,
6374 const RecordData &Record,
6375 unsigned &Idx) {
6376 if (Idx >= Record.size()) {
6377 Error("Corrupted AST file");
6378 return 0;
6379 }
6380
6381 return getGlobalDeclID(F, Record[Idx++]);
6382}
6383
6384/// \brief Resolve the offset of a statement into a statement.
6385///
6386/// This operation will read a new statement from the external
6387/// source each time it is called, and is meant to be used via a
6388/// LazyOffsetPtr (which is used by Decls for the body of functions, etc).
6389Stmt *ASTReader::GetExternalDeclStmt(uint64_t Offset) {
6390 // Switch case IDs are per Decl.
6391 ClearSwitchCaseIDs();
6392
6393 // Offset here is a global offset across the entire chain.
6394 RecordLocation Loc = getLocalBitOffset(Offset);
6395 Loc.F->DeclsCursor.JumpToBit(Loc.Offset);
6396 return ReadStmtFromStream(*Loc.F);
6397}
6398
6399namespace {
6400 class FindExternalLexicalDeclsVisitor {
6401 ASTReader &Reader;
6402 const DeclContext *DC;
6403 bool (*isKindWeWant)(Decl::Kind);
6404
6405 SmallVectorImpl<Decl*> &Decls;
6406 bool PredefsVisited[NUM_PREDEF_DECL_IDS];
6407
6408 public:
6409 FindExternalLexicalDeclsVisitor(ASTReader &Reader, const DeclContext *DC,
6410 bool (*isKindWeWant)(Decl::Kind),
6411 SmallVectorImpl<Decl*> &Decls)
6412 : Reader(Reader), DC(DC), isKindWeWant(isKindWeWant), Decls(Decls)
6413 {
6414 for (unsigned I = 0; I != NUM_PREDEF_DECL_IDS; ++I)
6415 PredefsVisited[I] = false;
6416 }
6417
6418 static bool visit(ModuleFile &M, bool Preorder, void *UserData) {
6419 if (Preorder)
6420 return false;
6421
6422 FindExternalLexicalDeclsVisitor *This
6423 = static_cast<FindExternalLexicalDeclsVisitor *>(UserData);
6424
6425 ModuleFile::DeclContextInfosMap::iterator Info
6426 = M.DeclContextInfos.find(This->DC);
6427 if (Info == M.DeclContextInfos.end() || !Info->second.LexicalDecls)
6428 return false;
6429
6430 // Load all of the declaration IDs
6431 for (const KindDeclIDPair *ID = Info->second.LexicalDecls,
6432 *IDE = ID + Info->second.NumLexicalDecls;
6433 ID != IDE; ++ID) {
6434 if (This->isKindWeWant && !This->isKindWeWant((Decl::Kind)ID->first))
6435 continue;
6436
6437 // Don't add predefined declarations to the lexical context more
6438 // than once.
6439 if (ID->second < NUM_PREDEF_DECL_IDS) {
6440 if (This->PredefsVisited[ID->second])
6441 continue;
6442
6443 This->PredefsVisited[ID->second] = true;
6444 }
6445
6446 if (Decl *D = This->Reader.GetLocalDecl(M, ID->second)) {
6447 if (!This->DC->isDeclInLexicalTraversal(D))
6448 This->Decls.push_back(D);
6449 }
6450 }
6451
6452 return false;
6453 }
6454 };
6455}
6456
6457ExternalLoadResult ASTReader::FindExternalLexicalDecls(const DeclContext *DC,
6458 bool (*isKindWeWant)(Decl::Kind),
6459 SmallVectorImpl<Decl*> &Decls) {
6460 // There might be lexical decls in multiple modules, for the TU at
6461 // least. Walk all of the modules in the order they were loaded.
6462 FindExternalLexicalDeclsVisitor Visitor(*this, DC, isKindWeWant, Decls);
6463 ModuleMgr.visitDepthFirst(&FindExternalLexicalDeclsVisitor::visit, &Visitor);
6464 ++NumLexicalDeclContextsRead;
6465 return ELR_Success;
6466}
6467
6468namespace {
6469
6470class DeclIDComp {
6471 ASTReader &Reader;
6472 ModuleFile &Mod;
6473
6474public:
6475 DeclIDComp(ASTReader &Reader, ModuleFile &M) : Reader(Reader), Mod(M) {}
6476
6477 bool operator()(LocalDeclID L, LocalDeclID R) const {
6478 SourceLocation LHS = getLocation(L);
6479 SourceLocation RHS = getLocation(R);
6480 return Reader.getSourceManager().isBeforeInTranslationUnit(LHS, RHS);
6481 }
6482
6483 bool operator()(SourceLocation LHS, LocalDeclID R) const {
6484 SourceLocation RHS = getLocation(R);
6485 return Reader.getSourceManager().isBeforeInTranslationUnit(LHS, RHS);
6486 }
6487
6488 bool operator()(LocalDeclID L, SourceLocation RHS) const {
6489 SourceLocation LHS = getLocation(L);
6490 return Reader.getSourceManager().isBeforeInTranslationUnit(LHS, RHS);
6491 }
6492
6493 SourceLocation getLocation(LocalDeclID ID) const {
6494 return Reader.getSourceManager().getFileLoc(
6495 Reader.getSourceLocationForDeclID(Reader.getGlobalDeclID(Mod, ID)));
6496 }
6497};
6498
6499}
6500
6501void ASTReader::FindFileRegionDecls(FileID File,
6502 unsigned Offset, unsigned Length,
6503 SmallVectorImpl<Decl *> &Decls) {
6504 SourceManager &SM = getSourceManager();
6505
6506 llvm::DenseMap<FileID, FileDeclsInfo>::iterator I = FileDeclIDs.find(File);
6507 if (I == FileDeclIDs.end())
6508 return;
6509
6510 FileDeclsInfo &DInfo = I->second;
6511 if (DInfo.Decls.empty())
6512 return;
6513
6514 SourceLocation
6515 BeginLoc = SM.getLocForStartOfFile(File).getLocWithOffset(Offset);
6516 SourceLocation EndLoc = BeginLoc.getLocWithOffset(Length);
6517
6518 DeclIDComp DIDComp(*this, *DInfo.Mod);
6519 ArrayRef<serialization::LocalDeclID>::iterator
6520 BeginIt = std::lower_bound(DInfo.Decls.begin(), DInfo.Decls.end(),
6521 BeginLoc, DIDComp);
6522 if (BeginIt != DInfo.Decls.begin())
6523 --BeginIt;
6524
6525 // If we are pointing at a top-level decl inside an objc container, we need
6526 // to backtrack until we find it otherwise we will fail to report that the
6527 // region overlaps with an objc container.
6528 while (BeginIt != DInfo.Decls.begin() &&
6529 GetDecl(getGlobalDeclID(*DInfo.Mod, *BeginIt))
6530 ->isTopLevelDeclInObjCContainer())
6531 --BeginIt;
6532
6533 ArrayRef<serialization::LocalDeclID>::iterator
6534 EndIt = std::upper_bound(DInfo.Decls.begin(), DInfo.Decls.end(),
6535 EndLoc, DIDComp);
6536 if (EndIt != DInfo.Decls.end())
6537 ++EndIt;
6538
6539 for (ArrayRef<serialization::LocalDeclID>::iterator
6540 DIt = BeginIt; DIt != EndIt; ++DIt)
6541 Decls.push_back(GetDecl(getGlobalDeclID(*DInfo.Mod, *DIt)));
6542}
6543
6544namespace {
6545 /// \brief ModuleFile visitor used to perform name lookup into a
6546 /// declaration context.
6547 class DeclContextNameLookupVisitor {
6548 ASTReader &Reader;
Richard Smith8c913ec2014-08-14 02:21:01 +00006549 ArrayRef<const DeclContext *> Contexts;
Guy Benyei11169dd2012-12-18 14:30:41 +00006550 DeclarationName Name;
6551 SmallVectorImpl<NamedDecl *> &Decls;
Richard Smith52874ec2015-02-13 20:17:14 +00006552 llvm::SmallPtrSetImpl<NamedDecl *> &DeclSet;
Guy Benyei11169dd2012-12-18 14:30:41 +00006553
6554 public:
Richard Smith8c913ec2014-08-14 02:21:01 +00006555 DeclContextNameLookupVisitor(ASTReader &Reader,
6556 ArrayRef<const DeclContext *> Contexts,
Guy Benyei11169dd2012-12-18 14:30:41 +00006557 DeclarationName Name,
Richard Smith52874ec2015-02-13 20:17:14 +00006558 SmallVectorImpl<NamedDecl *> &Decls,
6559 llvm::SmallPtrSetImpl<NamedDecl *> &DeclSet)
6560 : Reader(Reader), Contexts(Contexts), Name(Name), Decls(Decls),
6561 DeclSet(DeclSet) { }
Guy Benyei11169dd2012-12-18 14:30:41 +00006562
6563 static bool visit(ModuleFile &M, void *UserData) {
6564 DeclContextNameLookupVisitor *This
6565 = static_cast<DeclContextNameLookupVisitor *>(UserData);
6566
6567 // Check whether we have any visible declaration information for
6568 // this context in this module.
6569 ModuleFile::DeclContextInfosMap::iterator Info;
6570 bool FoundInfo = false;
Richard Smith8c913ec2014-08-14 02:21:01 +00006571 for (auto *DC : This->Contexts) {
6572 Info = M.DeclContextInfos.find(DC);
6573 if (Info != M.DeclContextInfos.end() &&
Guy Benyei11169dd2012-12-18 14:30:41 +00006574 Info->second.NameLookupTableData) {
6575 FoundInfo = true;
6576 break;
6577 }
6578 }
6579
6580 if (!FoundInfo)
6581 return false;
Richard Smith8c913ec2014-08-14 02:21:01 +00006582
Guy Benyei11169dd2012-12-18 14:30:41 +00006583 // Look for this name within this module.
Richard Smith52e3fba2014-03-11 07:17:35 +00006584 ASTDeclContextNameLookupTable *LookupTable =
Guy Benyei11169dd2012-12-18 14:30:41 +00006585 Info->second.NameLookupTableData;
6586 ASTDeclContextNameLookupTable::iterator Pos
6587 = LookupTable->find(This->Name);
6588 if (Pos == LookupTable->end())
6589 return false;
6590
6591 bool FoundAnything = false;
6592 ASTDeclContextNameLookupTrait::data_type Data = *Pos;
6593 for (; Data.first != Data.second; ++Data.first) {
6594 NamedDecl *ND = This->Reader.GetLocalDeclAs<NamedDecl>(M, *Data.first);
6595 if (!ND)
6596 continue;
6597
6598 if (ND->getDeclName() != This->Name) {
6599 // A name might be null because the decl's redeclarable part is
6600 // currently read before reading its name. The lookup is triggered by
6601 // building that decl (likely indirectly), and so it is later in the
6602 // sense of "already existing" and can be ignored here.
Richard Smith8c913ec2014-08-14 02:21:01 +00006603 // FIXME: This should not happen; deserializing declarations should
6604 // not perform lookups since that can lead to deserialization cycles.
Guy Benyei11169dd2012-12-18 14:30:41 +00006605 continue;
6606 }
Richard Smith8c913ec2014-08-14 02:21:01 +00006607
Guy Benyei11169dd2012-12-18 14:30:41 +00006608 // Record this declaration.
6609 FoundAnything = true;
Richard Smith52874ec2015-02-13 20:17:14 +00006610 if (This->DeclSet.insert(ND).second)
6611 This->Decls.push_back(ND);
Guy Benyei11169dd2012-12-18 14:30:41 +00006612 }
6613
6614 return FoundAnything;
6615 }
6616 };
6617}
6618
Douglas Gregor9f782892013-01-21 15:25:38 +00006619/// \brief Retrieve the "definitive" module file for the definition of the
6620/// given declaration context, if there is one.
6621///
6622/// The "definitive" module file is the only place where we need to look to
6623/// find information about the declarations within the given declaration
6624/// context. For example, C++ and Objective-C classes, C structs/unions, and
6625/// Objective-C protocols, categories, and extensions are all defined in a
6626/// single place in the source code, so they have definitive module files
6627/// associated with them. C++ namespaces, on the other hand, can have
6628/// definitions in multiple different module files.
6629///
6630/// Note: this needs to be kept in sync with ASTWriter::AddedVisibleDecl's
6631/// NDEBUG checking.
6632static ModuleFile *getDefinitiveModuleFileFor(const DeclContext *DC,
6633 ASTReader &Reader) {
Douglas Gregor7a6e2002013-01-22 17:08:30 +00006634 if (const DeclContext *DefDC = getDefinitiveDeclContext(DC))
6635 return Reader.getOwningModuleFile(cast<Decl>(DefDC));
Douglas Gregor9f782892013-01-21 15:25:38 +00006636
Craig Toppera13603a2014-05-22 05:54:18 +00006637 return nullptr;
Douglas Gregor9f782892013-01-21 15:25:38 +00006638}
6639
Richard Smith9ce12e32013-02-07 03:30:24 +00006640bool
Guy Benyei11169dd2012-12-18 14:30:41 +00006641ASTReader::FindExternalVisibleDeclsByName(const DeclContext *DC,
6642 DeclarationName Name) {
6643 assert(DC->hasExternalVisibleStorage() &&
6644 "DeclContext has no visible decls in storage");
6645 if (!Name)
Richard Smith9ce12e32013-02-07 03:30:24 +00006646 return false;
Guy Benyei11169dd2012-12-18 14:30:41 +00006647
Richard Smith8c913ec2014-08-14 02:21:01 +00006648 Deserializing LookupResults(this);
6649
Guy Benyei11169dd2012-12-18 14:30:41 +00006650 SmallVector<NamedDecl *, 64> Decls;
Richard Smith52874ec2015-02-13 20:17:14 +00006651 llvm::SmallPtrSet<NamedDecl*, 64> DeclSet;
Richard Smith8c913ec2014-08-14 02:21:01 +00006652
Guy Benyei11169dd2012-12-18 14:30:41 +00006653 // Compute the declaration contexts we need to look into. Multiple such
6654 // declaration contexts occur when two declaration contexts from disjoint
6655 // modules get merged, e.g., when two namespaces with the same name are
6656 // independently defined in separate modules.
6657 SmallVector<const DeclContext *, 2> Contexts;
6658 Contexts.push_back(DC);
Richard Smith8c913ec2014-08-14 02:21:01 +00006659
Guy Benyei11169dd2012-12-18 14:30:41 +00006660 if (DC->isNamespace()) {
Richard Smithcd45dbc2014-04-19 03:48:30 +00006661 auto Merged = MergedDecls.find(const_cast<Decl *>(cast<Decl>(DC)));
Guy Benyei11169dd2012-12-18 14:30:41 +00006662 if (Merged != MergedDecls.end()) {
6663 for (unsigned I = 0, N = Merged->second.size(); I != N; ++I)
6664 Contexts.push_back(cast<DeclContext>(GetDecl(Merged->second[I])));
6665 }
6666 }
Richard Smith8c913ec2014-08-14 02:21:01 +00006667
6668 auto LookUpInContexts = [&](ArrayRef<const DeclContext*> Contexts) {
Richard Smith52874ec2015-02-13 20:17:14 +00006669 DeclContextNameLookupVisitor Visitor(*this, Contexts, Name, Decls, DeclSet);
Richard Smith8c913ec2014-08-14 02:21:01 +00006670
6671 // If we can definitively determine which module file to look into,
6672 // only look there. Otherwise, look in all module files.
6673 ModuleFile *Definitive;
6674 if (Contexts.size() == 1 &&
6675 (Definitive = getDefinitiveModuleFileFor(Contexts[0], *this))) {
6676 DeclContextNameLookupVisitor::visit(*Definitive, &Visitor);
6677 } else {
6678 ModuleMgr.visit(&DeclContextNameLookupVisitor::visit, &Visitor);
6679 }
6680 };
6681
6682 LookUpInContexts(Contexts);
6683
6684 // If this might be an implicit special member function, then also search
6685 // all merged definitions of the surrounding class. We need to search them
6686 // individually, because finding an entity in one of them doesn't imply that
6687 // we can't find a different entity in another one.
Richard Smithcd45dbc2014-04-19 03:48:30 +00006688 if (isa<CXXRecordDecl>(DC)) {
Richard Smith8c913ec2014-08-14 02:21:01 +00006689 auto Kind = Name.getNameKind();
6690 if (Kind == DeclarationName::CXXConstructorName ||
6691 Kind == DeclarationName::CXXDestructorName ||
6692 (Kind == DeclarationName::CXXOperatorName &&
6693 Name.getCXXOverloadedOperator() == OO_Equal)) {
6694 auto Merged = MergedLookups.find(DC);
Richard Smithe0612472014-11-21 05:16:13 +00006695 if (Merged != MergedLookups.end()) {
6696 for (unsigned I = 0; I != Merged->second.size(); ++I) {
Daniel Jasperc0b7c802015-02-18 14:13:46 +00006697 const DeclContext *Context = Merged->second[I];
6698 LookUpInContexts(Context);
Richard Smithe0612472014-11-21 05:16:13 +00006699 // We might have just added some more merged lookups. If so, our
6700 // iterator is now invalid, so grab a fresh one before continuing.
6701 Merged = MergedLookups.find(DC);
6702 }
6703 }
Richard Smith8c913ec2014-08-14 02:21:01 +00006704 }
Richard Smithcd45dbc2014-04-19 03:48:30 +00006705 }
6706
Guy Benyei11169dd2012-12-18 14:30:41 +00006707 ++NumVisibleDeclContextsRead;
6708 SetExternalVisibleDeclsForName(DC, Name, Decls);
Richard Smith9ce12e32013-02-07 03:30:24 +00006709 return !Decls.empty();
Guy Benyei11169dd2012-12-18 14:30:41 +00006710}
6711
6712namespace {
6713 /// \brief ModuleFile visitor used to retrieve all visible names in a
6714 /// declaration context.
6715 class DeclContextAllNamesVisitor {
6716 ASTReader &Reader;
Dmitri Gribenkof8579502013-01-12 19:30:44 +00006717 SmallVectorImpl<const DeclContext *> &Contexts;
Craig Topper3598eb72013-07-05 04:43:31 +00006718 DeclsMap &Decls;
Richard Smith52874ec2015-02-13 20:17:14 +00006719 llvm::SmallPtrSet<NamedDecl *, 256> DeclSet;
Argyrios Kyrtzidis2810e9d2012-12-19 22:21:18 +00006720 bool VisitAll;
Guy Benyei11169dd2012-12-18 14:30:41 +00006721
6722 public:
6723 DeclContextAllNamesVisitor(ASTReader &Reader,
6724 SmallVectorImpl<const DeclContext *> &Contexts,
Craig Topper3598eb72013-07-05 04:43:31 +00006725 DeclsMap &Decls, bool VisitAll)
Argyrios Kyrtzidis2810e9d2012-12-19 22:21:18 +00006726 : Reader(Reader), Contexts(Contexts), Decls(Decls), VisitAll(VisitAll) { }
Guy Benyei11169dd2012-12-18 14:30:41 +00006727
6728 static bool visit(ModuleFile &M, void *UserData) {
6729 DeclContextAllNamesVisitor *This
6730 = static_cast<DeclContextAllNamesVisitor *>(UserData);
6731
6732 // Check whether we have any visible declaration information for
6733 // this context in this module.
6734 ModuleFile::DeclContextInfosMap::iterator Info;
6735 bool FoundInfo = false;
6736 for (unsigned I = 0, N = This->Contexts.size(); I != N; ++I) {
6737 Info = M.DeclContextInfos.find(This->Contexts[I]);
6738 if (Info != M.DeclContextInfos.end() &&
6739 Info->second.NameLookupTableData) {
6740 FoundInfo = true;
6741 break;
6742 }
6743 }
6744
6745 if (!FoundInfo)
6746 return false;
6747
Richard Smith52e3fba2014-03-11 07:17:35 +00006748 ASTDeclContextNameLookupTable *LookupTable =
Guy Benyei11169dd2012-12-18 14:30:41 +00006749 Info->second.NameLookupTableData;
6750 bool FoundAnything = false;
6751 for (ASTDeclContextNameLookupTable::data_iterator
Douglas Gregor5e306b12013-01-23 22:38:11 +00006752 I = LookupTable->data_begin(), E = LookupTable->data_end();
6753 I != E;
6754 ++I) {
Guy Benyei11169dd2012-12-18 14:30:41 +00006755 ASTDeclContextNameLookupTrait::data_type Data = *I;
6756 for (; Data.first != Data.second; ++Data.first) {
6757 NamedDecl *ND = This->Reader.GetLocalDeclAs<NamedDecl>(M,
6758 *Data.first);
6759 if (!ND)
6760 continue;
6761
6762 // Record this declaration.
6763 FoundAnything = true;
Richard Smith52874ec2015-02-13 20:17:14 +00006764 if (This->DeclSet.insert(ND).second)
6765 This->Decls[ND->getDeclName()].push_back(ND);
Guy Benyei11169dd2012-12-18 14:30:41 +00006766 }
6767 }
6768
Argyrios Kyrtzidis2810e9d2012-12-19 22:21:18 +00006769 return FoundAnything && !This->VisitAll;
Guy Benyei11169dd2012-12-18 14:30:41 +00006770 }
6771 };
6772}
6773
6774void ASTReader::completeVisibleDeclsMap(const DeclContext *DC) {
6775 if (!DC->hasExternalVisibleStorage())
6776 return;
Craig Topper79be4cd2013-07-05 04:33:53 +00006777 DeclsMap Decls;
Guy Benyei11169dd2012-12-18 14:30:41 +00006778
6779 // Compute the declaration contexts we need to look into. Multiple such
6780 // declaration contexts occur when two declaration contexts from disjoint
6781 // modules get merged, e.g., when two namespaces with the same name are
6782 // independently defined in separate modules.
6783 SmallVector<const DeclContext *, 2> Contexts;
6784 Contexts.push_back(DC);
6785
6786 if (DC->isNamespace()) {
6787 MergedDeclsMap::iterator Merged
6788 = MergedDecls.find(const_cast<Decl *>(cast<Decl>(DC)));
6789 if (Merged != MergedDecls.end()) {
6790 for (unsigned I = 0, N = Merged->second.size(); I != N; ++I)
6791 Contexts.push_back(cast<DeclContext>(GetDecl(Merged->second[I])));
6792 }
6793 }
6794
Argyrios Kyrtzidis2810e9d2012-12-19 22:21:18 +00006795 DeclContextAllNamesVisitor Visitor(*this, Contexts, Decls,
6796 /*VisitAll=*/DC->isFileContext());
Guy Benyei11169dd2012-12-18 14:30:41 +00006797 ModuleMgr.visit(&DeclContextAllNamesVisitor::visit, &Visitor);
6798 ++NumVisibleDeclContextsRead;
6799
Craig Topper79be4cd2013-07-05 04:33:53 +00006800 for (DeclsMap::iterator I = Decls.begin(), E = Decls.end(); I != E; ++I) {
Guy Benyei11169dd2012-12-18 14:30:41 +00006801 SetExternalVisibleDeclsForName(DC, I->first, I->second);
6802 }
6803 const_cast<DeclContext *>(DC)->setHasExternalVisibleStorage(false);
6804}
6805
6806/// \brief Under non-PCH compilation the consumer receives the objc methods
6807/// before receiving the implementation, and codegen depends on this.
6808/// We simulate this by deserializing and passing to consumer the methods of the
6809/// implementation before passing the deserialized implementation decl.
6810static void PassObjCImplDeclToConsumer(ObjCImplDecl *ImplD,
6811 ASTConsumer *Consumer) {
6812 assert(ImplD && Consumer);
6813
Aaron Ballmanaff18c02014-03-13 19:03:34 +00006814 for (auto *I : ImplD->methods())
6815 Consumer->HandleInterestingDecl(DeclGroupRef(I));
Guy Benyei11169dd2012-12-18 14:30:41 +00006816
6817 Consumer->HandleInterestingDecl(DeclGroupRef(ImplD));
6818}
6819
6820void ASTReader::PassInterestingDeclsToConsumer() {
6821 assert(Consumer);
Richard Smith04d05b52014-03-23 00:27:18 +00006822
6823 if (PassingDeclsToConsumer)
6824 return;
6825
6826 // Guard variable to avoid recursively redoing the process of passing
6827 // decls to consumer.
6828 SaveAndRestore<bool> GuardPassingDeclsToConsumer(PassingDeclsToConsumer,
6829 true);
6830
Guy Benyei11169dd2012-12-18 14:30:41 +00006831 while (!InterestingDecls.empty()) {
6832 Decl *D = InterestingDecls.front();
6833 InterestingDecls.pop_front();
6834
6835 PassInterestingDeclToConsumer(D);
6836 }
6837}
6838
6839void ASTReader::PassInterestingDeclToConsumer(Decl *D) {
6840 if (ObjCImplDecl *ImplD = dyn_cast<ObjCImplDecl>(D))
6841 PassObjCImplDeclToConsumer(ImplD, Consumer);
6842 else
6843 Consumer->HandleInterestingDecl(DeclGroupRef(D));
6844}
6845
6846void ASTReader::StartTranslationUnit(ASTConsumer *Consumer) {
6847 this->Consumer = Consumer;
6848
6849 if (!Consumer)
6850 return;
6851
Ben Langmuir332aafe2014-01-31 01:06:56 +00006852 for (unsigned I = 0, N = EagerlyDeserializedDecls.size(); I != N; ++I) {
Guy Benyei11169dd2012-12-18 14:30:41 +00006853 // Force deserialization of this decl, which will cause it to be queued for
6854 // passing to the consumer.
Ben Langmuir332aafe2014-01-31 01:06:56 +00006855 GetDecl(EagerlyDeserializedDecls[I]);
Guy Benyei11169dd2012-12-18 14:30:41 +00006856 }
Ben Langmuir332aafe2014-01-31 01:06:56 +00006857 EagerlyDeserializedDecls.clear();
Guy Benyei11169dd2012-12-18 14:30:41 +00006858
6859 PassInterestingDeclsToConsumer();
6860}
6861
6862void ASTReader::PrintStats() {
6863 std::fprintf(stderr, "*** AST File Statistics:\n");
6864
6865 unsigned NumTypesLoaded
6866 = TypesLoaded.size() - std::count(TypesLoaded.begin(), TypesLoaded.end(),
6867 QualType());
6868 unsigned NumDeclsLoaded
6869 = DeclsLoaded.size() - std::count(DeclsLoaded.begin(), DeclsLoaded.end(),
Craig Toppera13603a2014-05-22 05:54:18 +00006870 (Decl *)nullptr);
Guy Benyei11169dd2012-12-18 14:30:41 +00006871 unsigned NumIdentifiersLoaded
6872 = IdentifiersLoaded.size() - std::count(IdentifiersLoaded.begin(),
6873 IdentifiersLoaded.end(),
Craig Toppera13603a2014-05-22 05:54:18 +00006874 (IdentifierInfo *)nullptr);
Guy Benyei11169dd2012-12-18 14:30:41 +00006875 unsigned NumMacrosLoaded
6876 = MacrosLoaded.size() - std::count(MacrosLoaded.begin(),
6877 MacrosLoaded.end(),
Craig Toppera13603a2014-05-22 05:54:18 +00006878 (MacroInfo *)nullptr);
Guy Benyei11169dd2012-12-18 14:30:41 +00006879 unsigned NumSelectorsLoaded
6880 = SelectorsLoaded.size() - std::count(SelectorsLoaded.begin(),
6881 SelectorsLoaded.end(),
6882 Selector());
6883
6884 if (unsigned TotalNumSLocEntries = getTotalNumSLocs())
6885 std::fprintf(stderr, " %u/%u source location entries read (%f%%)\n",
6886 NumSLocEntriesRead, TotalNumSLocEntries,
6887 ((float)NumSLocEntriesRead/TotalNumSLocEntries * 100));
6888 if (!TypesLoaded.empty())
6889 std::fprintf(stderr, " %u/%u types read (%f%%)\n",
6890 NumTypesLoaded, (unsigned)TypesLoaded.size(),
6891 ((float)NumTypesLoaded/TypesLoaded.size() * 100));
6892 if (!DeclsLoaded.empty())
6893 std::fprintf(stderr, " %u/%u declarations read (%f%%)\n",
6894 NumDeclsLoaded, (unsigned)DeclsLoaded.size(),
6895 ((float)NumDeclsLoaded/DeclsLoaded.size() * 100));
6896 if (!IdentifiersLoaded.empty())
6897 std::fprintf(stderr, " %u/%u identifiers read (%f%%)\n",
6898 NumIdentifiersLoaded, (unsigned)IdentifiersLoaded.size(),
6899 ((float)NumIdentifiersLoaded/IdentifiersLoaded.size() * 100));
6900 if (!MacrosLoaded.empty())
6901 std::fprintf(stderr, " %u/%u macros read (%f%%)\n",
6902 NumMacrosLoaded, (unsigned)MacrosLoaded.size(),
6903 ((float)NumMacrosLoaded/MacrosLoaded.size() * 100));
6904 if (!SelectorsLoaded.empty())
6905 std::fprintf(stderr, " %u/%u selectors read (%f%%)\n",
6906 NumSelectorsLoaded, (unsigned)SelectorsLoaded.size(),
6907 ((float)NumSelectorsLoaded/SelectorsLoaded.size() * 100));
6908 if (TotalNumStatements)
6909 std::fprintf(stderr, " %u/%u statements read (%f%%)\n",
6910 NumStatementsRead, TotalNumStatements,
6911 ((float)NumStatementsRead/TotalNumStatements * 100));
6912 if (TotalNumMacros)
6913 std::fprintf(stderr, " %u/%u macros read (%f%%)\n",
6914 NumMacrosRead, TotalNumMacros,
6915 ((float)NumMacrosRead/TotalNumMacros * 100));
6916 if (TotalLexicalDeclContexts)
6917 std::fprintf(stderr, " %u/%u lexical declcontexts read (%f%%)\n",
6918 NumLexicalDeclContextsRead, TotalLexicalDeclContexts,
6919 ((float)NumLexicalDeclContextsRead/TotalLexicalDeclContexts
6920 * 100));
6921 if (TotalVisibleDeclContexts)
6922 std::fprintf(stderr, " %u/%u visible declcontexts read (%f%%)\n",
6923 NumVisibleDeclContextsRead, TotalVisibleDeclContexts,
6924 ((float)NumVisibleDeclContextsRead/TotalVisibleDeclContexts
6925 * 100));
6926 if (TotalNumMethodPoolEntries) {
6927 std::fprintf(stderr, " %u/%u method pool entries read (%f%%)\n",
6928 NumMethodPoolEntriesRead, TotalNumMethodPoolEntries,
6929 ((float)NumMethodPoolEntriesRead/TotalNumMethodPoolEntries
6930 * 100));
Guy Benyei11169dd2012-12-18 14:30:41 +00006931 }
Douglas Gregorad2f7a52013-01-28 17:54:36 +00006932 if (NumMethodPoolLookups) {
6933 std::fprintf(stderr, " %u/%u method pool lookups succeeded (%f%%)\n",
6934 NumMethodPoolHits, NumMethodPoolLookups,
6935 ((float)NumMethodPoolHits/NumMethodPoolLookups * 100.0));
6936 }
6937 if (NumMethodPoolTableLookups) {
6938 std::fprintf(stderr, " %u/%u method pool table lookups succeeded (%f%%)\n",
6939 NumMethodPoolTableHits, NumMethodPoolTableLookups,
6940 ((float)NumMethodPoolTableHits/NumMethodPoolTableLookups
6941 * 100.0));
6942 }
6943
Douglas Gregor00a50f72013-01-25 00:38:33 +00006944 if (NumIdentifierLookupHits) {
6945 std::fprintf(stderr,
6946 " %u / %u identifier table lookups succeeded (%f%%)\n",
6947 NumIdentifierLookupHits, NumIdentifierLookups,
6948 (double)NumIdentifierLookupHits*100.0/NumIdentifierLookups);
6949 }
6950
Douglas Gregore060e572013-01-25 01:03:03 +00006951 if (GlobalIndex) {
6952 std::fprintf(stderr, "\n");
6953 GlobalIndex->printStats();
6954 }
6955
Guy Benyei11169dd2012-12-18 14:30:41 +00006956 std::fprintf(stderr, "\n");
6957 dump();
6958 std::fprintf(stderr, "\n");
6959}
6960
6961template<typename Key, typename ModuleFile, unsigned InitialCapacity>
6962static void
6963dumpModuleIDMap(StringRef Name,
6964 const ContinuousRangeMap<Key, ModuleFile *,
6965 InitialCapacity> &Map) {
6966 if (Map.begin() == Map.end())
6967 return;
6968
6969 typedef ContinuousRangeMap<Key, ModuleFile *, InitialCapacity> MapType;
6970 llvm::errs() << Name << ":\n";
6971 for (typename MapType::const_iterator I = Map.begin(), IEnd = Map.end();
6972 I != IEnd; ++I) {
6973 llvm::errs() << " " << I->first << " -> " << I->second->FileName
6974 << "\n";
6975 }
6976}
6977
6978void ASTReader::dump() {
6979 llvm::errs() << "*** PCH/ModuleFile Remappings:\n";
6980 dumpModuleIDMap("Global bit offset map", GlobalBitOffsetsMap);
6981 dumpModuleIDMap("Global source location entry map", GlobalSLocEntryMap);
6982 dumpModuleIDMap("Global type map", GlobalTypeMap);
6983 dumpModuleIDMap("Global declaration map", GlobalDeclMap);
6984 dumpModuleIDMap("Global identifier map", GlobalIdentifierMap);
6985 dumpModuleIDMap("Global macro map", GlobalMacroMap);
6986 dumpModuleIDMap("Global submodule map", GlobalSubmoduleMap);
6987 dumpModuleIDMap("Global selector map", GlobalSelectorMap);
6988 dumpModuleIDMap("Global preprocessed entity map",
6989 GlobalPreprocessedEntityMap);
6990
6991 llvm::errs() << "\n*** PCH/Modules Loaded:";
6992 for (ModuleManager::ModuleConstIterator M = ModuleMgr.begin(),
6993 MEnd = ModuleMgr.end();
6994 M != MEnd; ++M)
6995 (*M)->dump();
6996}
6997
6998/// Return the amount of memory used by memory buffers, breaking down
6999/// by heap-backed versus mmap'ed memory.
7000void ASTReader::getMemoryBufferSizes(MemoryBufferSizes &sizes) const {
7001 for (ModuleConstIterator I = ModuleMgr.begin(),
7002 E = ModuleMgr.end(); I != E; ++I) {
7003 if (llvm::MemoryBuffer *buf = (*I)->Buffer.get()) {
7004 size_t bytes = buf->getBufferSize();
7005 switch (buf->getBufferKind()) {
7006 case llvm::MemoryBuffer::MemoryBuffer_Malloc:
7007 sizes.malloc_bytes += bytes;
7008 break;
7009 case llvm::MemoryBuffer::MemoryBuffer_MMap:
7010 sizes.mmap_bytes += bytes;
7011 break;
7012 }
7013 }
7014 }
7015}
7016
7017void ASTReader::InitializeSema(Sema &S) {
7018 SemaObj = &S;
7019 S.addExternalSource(this);
7020
7021 // Makes sure any declarations that were deserialized "too early"
7022 // still get added to the identifier's declaration chains.
Ben Langmuir5418f402014-09-10 21:29:41 +00007023 for (uint64_t ID : PreloadedDeclIDs) {
7024 NamedDecl *D = cast<NamedDecl>(GetDecl(ID));
7025 pushExternalDeclIntoScope(D, D->getDeclName());
Guy Benyei11169dd2012-12-18 14:30:41 +00007026 }
Ben Langmuir5418f402014-09-10 21:29:41 +00007027 PreloadedDeclIDs.clear();
Guy Benyei11169dd2012-12-18 14:30:41 +00007028
Richard Smith3d8e97e2013-10-18 06:54:39 +00007029 // FIXME: What happens if these are changed by a module import?
Guy Benyei11169dd2012-12-18 14:30:41 +00007030 if (!FPPragmaOptions.empty()) {
7031 assert(FPPragmaOptions.size() == 1 && "Wrong number of FP_PRAGMA_OPTIONS");
7032 SemaObj->FPFeatures.fp_contract = FPPragmaOptions[0];
7033 }
7034
Richard Smith3d8e97e2013-10-18 06:54:39 +00007035 // FIXME: What happens if these are changed by a module import?
Guy Benyei11169dd2012-12-18 14:30:41 +00007036 if (!OpenCLExtensions.empty()) {
7037 unsigned I = 0;
7038#define OPENCLEXT(nm) SemaObj->OpenCLFeatures.nm = OpenCLExtensions[I++];
7039#include "clang/Basic/OpenCLExtensions.def"
7040
7041 assert(OpenCLExtensions.size() == I && "Wrong number of OPENCL_EXTENSIONS");
7042 }
Richard Smith3d8e97e2013-10-18 06:54:39 +00007043
7044 UpdateSema();
7045}
7046
7047void ASTReader::UpdateSema() {
7048 assert(SemaObj && "no Sema to update");
7049
7050 // Load the offsets of the declarations that Sema references.
7051 // They will be lazily deserialized when needed.
7052 if (!SemaDeclRefs.empty()) {
7053 assert(SemaDeclRefs.size() % 2 == 0);
7054 for (unsigned I = 0; I != SemaDeclRefs.size(); I += 2) {
7055 if (!SemaObj->StdNamespace)
7056 SemaObj->StdNamespace = SemaDeclRefs[I];
7057 if (!SemaObj->StdBadAlloc)
7058 SemaObj->StdBadAlloc = SemaDeclRefs[I+1];
7059 }
7060 SemaDeclRefs.clear();
7061 }
Dario Domizioli13a0a382014-05-23 12:13:25 +00007062
7063 // Update the state of 'pragma clang optimize'. Use the same API as if we had
7064 // encountered the pragma in the source.
7065 if(OptimizeOffPragmaLocation.isValid())
7066 SemaObj->ActOnPragmaOptimize(/* IsOn = */ false, OptimizeOffPragmaLocation);
Guy Benyei11169dd2012-12-18 14:30:41 +00007067}
7068
7069IdentifierInfo* ASTReader::get(const char *NameStart, const char *NameEnd) {
7070 // Note that we are loading an identifier.
7071 Deserializing AnIdentifier(this);
Douglas Gregore060e572013-01-25 01:03:03 +00007072 StringRef Name(NameStart, NameEnd - NameStart);
7073
7074 // If there is a global index, look there first to determine which modules
7075 // provably do not have any results for this identifier.
Douglas Gregor7211ac12013-01-25 23:32:03 +00007076 GlobalModuleIndex::HitSet Hits;
Craig Toppera13603a2014-05-22 05:54:18 +00007077 GlobalModuleIndex::HitSet *HitsPtr = nullptr;
Douglas Gregore060e572013-01-25 01:03:03 +00007078 if (!loadGlobalIndex()) {
Douglas Gregor7211ac12013-01-25 23:32:03 +00007079 if (GlobalIndex->lookupIdentifier(Name, Hits)) {
7080 HitsPtr = &Hits;
Douglas Gregore060e572013-01-25 01:03:03 +00007081 }
7082 }
Douglas Gregor7211ac12013-01-25 23:32:03 +00007083 IdentifierLookupVisitor Visitor(Name, /*PriorGeneration=*/0,
Douglas Gregor00a50f72013-01-25 00:38:33 +00007084 NumIdentifierLookups,
7085 NumIdentifierLookupHits);
Douglas Gregor7211ac12013-01-25 23:32:03 +00007086 ModuleMgr.visit(IdentifierLookupVisitor::visit, &Visitor, HitsPtr);
Guy Benyei11169dd2012-12-18 14:30:41 +00007087 IdentifierInfo *II = Visitor.getIdentifierInfo();
7088 markIdentifierUpToDate(II);
7089 return II;
7090}
7091
7092namespace clang {
7093 /// \brief An identifier-lookup iterator that enumerates all of the
7094 /// identifiers stored within a set of AST files.
7095 class ASTIdentifierIterator : public IdentifierIterator {
7096 /// \brief The AST reader whose identifiers are being enumerated.
7097 const ASTReader &Reader;
7098
7099 /// \brief The current index into the chain of AST files stored in
7100 /// the AST reader.
7101 unsigned Index;
7102
7103 /// \brief The current position within the identifier lookup table
7104 /// of the current AST file.
7105 ASTIdentifierLookupTable::key_iterator Current;
7106
7107 /// \brief The end position within the identifier lookup table of
7108 /// the current AST file.
7109 ASTIdentifierLookupTable::key_iterator End;
7110
7111 public:
7112 explicit ASTIdentifierIterator(const ASTReader &Reader);
7113
Craig Topper3e89dfe2014-03-13 02:13:41 +00007114 StringRef Next() override;
Guy Benyei11169dd2012-12-18 14:30:41 +00007115 };
7116}
7117
7118ASTIdentifierIterator::ASTIdentifierIterator(const ASTReader &Reader)
7119 : Reader(Reader), Index(Reader.ModuleMgr.size() - 1) {
7120 ASTIdentifierLookupTable *IdTable
7121 = (ASTIdentifierLookupTable *)Reader.ModuleMgr[Index].IdentifierLookupTable;
7122 Current = IdTable->key_begin();
7123 End = IdTable->key_end();
7124}
7125
7126StringRef ASTIdentifierIterator::Next() {
7127 while (Current == End) {
7128 // If we have exhausted all of our AST files, we're done.
7129 if (Index == 0)
7130 return StringRef();
7131
7132 --Index;
7133 ASTIdentifierLookupTable *IdTable
7134 = (ASTIdentifierLookupTable *)Reader.ModuleMgr[Index].
7135 IdentifierLookupTable;
7136 Current = IdTable->key_begin();
7137 End = IdTable->key_end();
7138 }
7139
7140 // We have any identifiers remaining in the current AST file; return
7141 // the next one.
Douglas Gregorbfd73d72013-01-23 18:53:14 +00007142 StringRef Result = *Current;
Guy Benyei11169dd2012-12-18 14:30:41 +00007143 ++Current;
Douglas Gregorbfd73d72013-01-23 18:53:14 +00007144 return Result;
Guy Benyei11169dd2012-12-18 14:30:41 +00007145}
7146
Argyrios Kyrtzidis9aca3c62013-04-17 22:10:55 +00007147IdentifierIterator *ASTReader::getIdentifiers() {
7148 if (!loadGlobalIndex())
7149 return GlobalIndex->createIdentifierIterator();
7150
Guy Benyei11169dd2012-12-18 14:30:41 +00007151 return new ASTIdentifierIterator(*this);
7152}
7153
7154namespace clang { namespace serialization {
7155 class ReadMethodPoolVisitor {
7156 ASTReader &Reader;
7157 Selector Sel;
7158 unsigned PriorGeneration;
Argyrios Kyrtzidisd3da6e02013-04-17 00:08:58 +00007159 unsigned InstanceBits;
7160 unsigned FactoryBits;
Nico Weberff4b35e2014-12-27 22:14:15 +00007161 bool InstanceHasMoreThanOneDecl;
7162 bool FactoryHasMoreThanOneDecl;
Dmitri Gribenkof8579502013-01-12 19:30:44 +00007163 SmallVector<ObjCMethodDecl *, 4> InstanceMethods;
7164 SmallVector<ObjCMethodDecl *, 4> FactoryMethods;
Guy Benyei11169dd2012-12-18 14:30:41 +00007165
7166 public:
Nico Weber2e0c8f72014-12-27 03:58:08 +00007167 ReadMethodPoolVisitor(ASTReader &Reader, Selector Sel,
Guy Benyei11169dd2012-12-18 14:30:41 +00007168 unsigned PriorGeneration)
Nico Weber2e0c8f72014-12-27 03:58:08 +00007169 : Reader(Reader), Sel(Sel), PriorGeneration(PriorGeneration),
Nico Weberff4b35e2014-12-27 22:14:15 +00007170 InstanceBits(0), FactoryBits(0), InstanceHasMoreThanOneDecl(false),
7171 FactoryHasMoreThanOneDecl(false) {}
Nico Weber2e0c8f72014-12-27 03:58:08 +00007172
Guy Benyei11169dd2012-12-18 14:30:41 +00007173 static bool visit(ModuleFile &M, void *UserData) {
7174 ReadMethodPoolVisitor *This
7175 = static_cast<ReadMethodPoolVisitor *>(UserData);
7176
7177 if (!M.SelectorLookupTable)
7178 return false;
7179
7180 // If we've already searched this module file, skip it now.
7181 if (M.Generation <= This->PriorGeneration)
7182 return true;
7183
Douglas Gregorad2f7a52013-01-28 17:54:36 +00007184 ++This->Reader.NumMethodPoolTableLookups;
Guy Benyei11169dd2012-12-18 14:30:41 +00007185 ASTSelectorLookupTable *PoolTable
7186 = (ASTSelectorLookupTable*)M.SelectorLookupTable;
7187 ASTSelectorLookupTable::iterator Pos = PoolTable->find(This->Sel);
7188 if (Pos == PoolTable->end())
7189 return false;
Douglas Gregorad2f7a52013-01-28 17:54:36 +00007190
7191 ++This->Reader.NumMethodPoolTableHits;
Guy Benyei11169dd2012-12-18 14:30:41 +00007192 ++This->Reader.NumSelectorsRead;
7193 // FIXME: Not quite happy with the statistics here. We probably should
7194 // disable this tracking when called via LoadSelector.
7195 // Also, should entries without methods count as misses?
7196 ++This->Reader.NumMethodPoolEntriesRead;
7197 ASTSelectorLookupTrait::data_type Data = *Pos;
7198 if (This->Reader.DeserializationListener)
7199 This->Reader.DeserializationListener->SelectorRead(Data.ID,
7200 This->Sel);
7201
7202 This->InstanceMethods.append(Data.Instance.begin(), Data.Instance.end());
7203 This->FactoryMethods.append(Data.Factory.begin(), Data.Factory.end());
Argyrios Kyrtzidisd3da6e02013-04-17 00:08:58 +00007204 This->InstanceBits = Data.InstanceBits;
7205 This->FactoryBits = Data.FactoryBits;
Nico Weberff4b35e2014-12-27 22:14:15 +00007206 This->InstanceHasMoreThanOneDecl = Data.InstanceHasMoreThanOneDecl;
7207 This->FactoryHasMoreThanOneDecl = Data.FactoryHasMoreThanOneDecl;
Guy Benyei11169dd2012-12-18 14:30:41 +00007208 return true;
7209 }
7210
7211 /// \brief Retrieve the instance methods found by this visitor.
7212 ArrayRef<ObjCMethodDecl *> getInstanceMethods() const {
7213 return InstanceMethods;
7214 }
7215
7216 /// \brief Retrieve the instance methods found by this visitor.
7217 ArrayRef<ObjCMethodDecl *> getFactoryMethods() const {
7218 return FactoryMethods;
7219 }
Argyrios Kyrtzidisd3da6e02013-04-17 00:08:58 +00007220
7221 unsigned getInstanceBits() const { return InstanceBits; }
7222 unsigned getFactoryBits() const { return FactoryBits; }
Nico Weberff4b35e2014-12-27 22:14:15 +00007223 bool instanceHasMoreThanOneDecl() const {
7224 return InstanceHasMoreThanOneDecl;
7225 }
7226 bool factoryHasMoreThanOneDecl() const { return FactoryHasMoreThanOneDecl; }
Guy Benyei11169dd2012-12-18 14:30:41 +00007227 };
7228} } // end namespace clang::serialization
7229
7230/// \brief Add the given set of methods to the method list.
7231static void addMethodsToPool(Sema &S, ArrayRef<ObjCMethodDecl *> Methods,
7232 ObjCMethodList &List) {
7233 for (unsigned I = 0, N = Methods.size(); I != N; ++I) {
7234 S.addMethodToGlobalList(&List, Methods[I]);
7235 }
7236}
7237
7238void ASTReader::ReadMethodPool(Selector Sel) {
7239 // Get the selector generation and update it to the current generation.
7240 unsigned &Generation = SelectorGeneration[Sel];
7241 unsigned PriorGeneration = Generation;
Richard Smith053f6c62014-05-16 23:01:30 +00007242 Generation = getGeneration();
Guy Benyei11169dd2012-12-18 14:30:41 +00007243
7244 // Search for methods defined with this selector.
Douglas Gregorad2f7a52013-01-28 17:54:36 +00007245 ++NumMethodPoolLookups;
Guy Benyei11169dd2012-12-18 14:30:41 +00007246 ReadMethodPoolVisitor Visitor(*this, Sel, PriorGeneration);
7247 ModuleMgr.visit(&ReadMethodPoolVisitor::visit, &Visitor);
7248
7249 if (Visitor.getInstanceMethods().empty() &&
Douglas Gregorad2f7a52013-01-28 17:54:36 +00007250 Visitor.getFactoryMethods().empty())
Guy Benyei11169dd2012-12-18 14:30:41 +00007251 return;
Douglas Gregorad2f7a52013-01-28 17:54:36 +00007252
7253 ++NumMethodPoolHits;
7254
Guy Benyei11169dd2012-12-18 14:30:41 +00007255 if (!getSema())
7256 return;
7257
7258 Sema &S = *getSema();
7259 Sema::GlobalMethodPool::iterator Pos
7260 = S.MethodPool.insert(std::make_pair(Sel, Sema::GlobalMethods())).first;
Ben Langmuira0c32e92015-01-12 19:27:00 +00007261
Argyrios Kyrtzidisd3da6e02013-04-17 00:08:58 +00007262 Pos->second.first.setBits(Visitor.getInstanceBits());
Nico Weberff4b35e2014-12-27 22:14:15 +00007263 Pos->second.first.setHasMoreThanOneDecl(Visitor.instanceHasMoreThanOneDecl());
Argyrios Kyrtzidisd3da6e02013-04-17 00:08:58 +00007264 Pos->second.second.setBits(Visitor.getFactoryBits());
Nico Weberff4b35e2014-12-27 22:14:15 +00007265 Pos->second.second.setHasMoreThanOneDecl(Visitor.factoryHasMoreThanOneDecl());
Ben Langmuira0c32e92015-01-12 19:27:00 +00007266
7267 // Add methods to the global pool *after* setting hasMoreThanOneDecl, since
7268 // when building a module we keep every method individually and may need to
7269 // update hasMoreThanOneDecl as we add the methods.
7270 addMethodsToPool(S, Visitor.getInstanceMethods(), Pos->second.first);
7271 addMethodsToPool(S, Visitor.getFactoryMethods(), Pos->second.second);
Guy Benyei11169dd2012-12-18 14:30:41 +00007272}
7273
7274void ASTReader::ReadKnownNamespaces(
7275 SmallVectorImpl<NamespaceDecl *> &Namespaces) {
7276 Namespaces.clear();
7277
7278 for (unsigned I = 0, N = KnownNamespaces.size(); I != N; ++I) {
7279 if (NamespaceDecl *Namespace
7280 = dyn_cast_or_null<NamespaceDecl>(GetDecl(KnownNamespaces[I])))
7281 Namespaces.push_back(Namespace);
7282 }
7283}
7284
Nick Lewycky9c7eb1d2013-02-01 08:13:20 +00007285void ASTReader::ReadUndefinedButUsed(
Nick Lewyckyf0f56162013-01-31 03:23:57 +00007286 llvm::DenseMap<NamedDecl*, SourceLocation> &Undefined) {
Nick Lewycky9c7eb1d2013-02-01 08:13:20 +00007287 for (unsigned Idx = 0, N = UndefinedButUsed.size(); Idx != N;) {
7288 NamedDecl *D = cast<NamedDecl>(GetDecl(UndefinedButUsed[Idx++]));
Nick Lewycky8334af82013-01-26 00:35:08 +00007289 SourceLocation Loc =
Nick Lewycky9c7eb1d2013-02-01 08:13:20 +00007290 SourceLocation::getFromRawEncoding(UndefinedButUsed[Idx++]);
Nick Lewycky8334af82013-01-26 00:35:08 +00007291 Undefined.insert(std::make_pair(D, Loc));
7292 }
7293}
Nick Lewycky8334af82013-01-26 00:35:08 +00007294
Guy Benyei11169dd2012-12-18 14:30:41 +00007295void ASTReader::ReadTentativeDefinitions(
7296 SmallVectorImpl<VarDecl *> &TentativeDefs) {
7297 for (unsigned I = 0, N = TentativeDefinitions.size(); I != N; ++I) {
7298 VarDecl *Var = dyn_cast_or_null<VarDecl>(GetDecl(TentativeDefinitions[I]));
7299 if (Var)
7300 TentativeDefs.push_back(Var);
7301 }
7302 TentativeDefinitions.clear();
7303}
7304
7305void ASTReader::ReadUnusedFileScopedDecls(
7306 SmallVectorImpl<const DeclaratorDecl *> &Decls) {
7307 for (unsigned I = 0, N = UnusedFileScopedDecls.size(); I != N; ++I) {
7308 DeclaratorDecl *D
7309 = dyn_cast_or_null<DeclaratorDecl>(GetDecl(UnusedFileScopedDecls[I]));
7310 if (D)
7311 Decls.push_back(D);
7312 }
7313 UnusedFileScopedDecls.clear();
7314}
7315
7316void ASTReader::ReadDelegatingConstructors(
7317 SmallVectorImpl<CXXConstructorDecl *> &Decls) {
7318 for (unsigned I = 0, N = DelegatingCtorDecls.size(); I != N; ++I) {
7319 CXXConstructorDecl *D
7320 = dyn_cast_or_null<CXXConstructorDecl>(GetDecl(DelegatingCtorDecls[I]));
7321 if (D)
7322 Decls.push_back(D);
7323 }
7324 DelegatingCtorDecls.clear();
7325}
7326
7327void ASTReader::ReadExtVectorDecls(SmallVectorImpl<TypedefNameDecl *> &Decls) {
7328 for (unsigned I = 0, N = ExtVectorDecls.size(); I != N; ++I) {
7329 TypedefNameDecl *D
7330 = dyn_cast_or_null<TypedefNameDecl>(GetDecl(ExtVectorDecls[I]));
7331 if (D)
7332 Decls.push_back(D);
7333 }
7334 ExtVectorDecls.clear();
7335}
7336
7337void ASTReader::ReadDynamicClasses(SmallVectorImpl<CXXRecordDecl *> &Decls) {
7338 for (unsigned I = 0, N = DynamicClasses.size(); I != N; ++I) {
7339 CXXRecordDecl *D
7340 = dyn_cast_or_null<CXXRecordDecl>(GetDecl(DynamicClasses[I]));
7341 if (D)
7342 Decls.push_back(D);
7343 }
7344 DynamicClasses.clear();
7345}
7346
Nico Weber72889432014-09-06 01:25:55 +00007347void ASTReader::ReadUnusedLocalTypedefNameCandidates(
7348 llvm::SmallSetVector<const TypedefNameDecl *, 4> &Decls) {
7349 for (unsigned I = 0, N = UnusedLocalTypedefNameCandidates.size(); I != N;
7350 ++I) {
7351 TypedefNameDecl *D = dyn_cast_or_null<TypedefNameDecl>(
7352 GetDecl(UnusedLocalTypedefNameCandidates[I]));
7353 if (D)
7354 Decls.insert(D);
7355 }
7356 UnusedLocalTypedefNameCandidates.clear();
7357}
7358
Guy Benyei11169dd2012-12-18 14:30:41 +00007359void
Richard Smith78165b52013-01-10 23:43:47 +00007360ASTReader::ReadLocallyScopedExternCDecls(SmallVectorImpl<NamedDecl *> &Decls) {
7361 for (unsigned I = 0, N = LocallyScopedExternCDecls.size(); I != N; ++I) {
7362 NamedDecl *D
7363 = dyn_cast_or_null<NamedDecl>(GetDecl(LocallyScopedExternCDecls[I]));
Guy Benyei11169dd2012-12-18 14:30:41 +00007364 if (D)
7365 Decls.push_back(D);
7366 }
Richard Smith78165b52013-01-10 23:43:47 +00007367 LocallyScopedExternCDecls.clear();
Guy Benyei11169dd2012-12-18 14:30:41 +00007368}
7369
7370void ASTReader::ReadReferencedSelectors(
7371 SmallVectorImpl<std::pair<Selector, SourceLocation> > &Sels) {
7372 if (ReferencedSelectorsData.empty())
7373 return;
7374
7375 // If there are @selector references added them to its pool. This is for
7376 // implementation of -Wselector.
7377 unsigned int DataSize = ReferencedSelectorsData.size()-1;
7378 unsigned I = 0;
7379 while (I < DataSize) {
7380 Selector Sel = DecodeSelector(ReferencedSelectorsData[I++]);
7381 SourceLocation SelLoc
7382 = SourceLocation::getFromRawEncoding(ReferencedSelectorsData[I++]);
7383 Sels.push_back(std::make_pair(Sel, SelLoc));
7384 }
7385 ReferencedSelectorsData.clear();
7386}
7387
7388void ASTReader::ReadWeakUndeclaredIdentifiers(
7389 SmallVectorImpl<std::pair<IdentifierInfo *, WeakInfo> > &WeakIDs) {
7390 if (WeakUndeclaredIdentifiers.empty())
7391 return;
7392
7393 for (unsigned I = 0, N = WeakUndeclaredIdentifiers.size(); I < N; /*none*/) {
7394 IdentifierInfo *WeakId
7395 = DecodeIdentifierInfo(WeakUndeclaredIdentifiers[I++]);
7396 IdentifierInfo *AliasId
7397 = DecodeIdentifierInfo(WeakUndeclaredIdentifiers[I++]);
7398 SourceLocation Loc
7399 = SourceLocation::getFromRawEncoding(WeakUndeclaredIdentifiers[I++]);
7400 bool Used = WeakUndeclaredIdentifiers[I++];
7401 WeakInfo WI(AliasId, Loc);
7402 WI.setUsed(Used);
7403 WeakIDs.push_back(std::make_pair(WeakId, WI));
7404 }
7405 WeakUndeclaredIdentifiers.clear();
7406}
7407
7408void ASTReader::ReadUsedVTables(SmallVectorImpl<ExternalVTableUse> &VTables) {
7409 for (unsigned Idx = 0, N = VTableUses.size(); Idx < N; /* In loop */) {
7410 ExternalVTableUse VT;
7411 VT.Record = dyn_cast_or_null<CXXRecordDecl>(GetDecl(VTableUses[Idx++]));
7412 VT.Location = SourceLocation::getFromRawEncoding(VTableUses[Idx++]);
7413 VT.DefinitionRequired = VTableUses[Idx++];
7414 VTables.push_back(VT);
7415 }
7416
7417 VTableUses.clear();
7418}
7419
7420void ASTReader::ReadPendingInstantiations(
7421 SmallVectorImpl<std::pair<ValueDecl *, SourceLocation> > &Pending) {
7422 for (unsigned Idx = 0, N = PendingInstantiations.size(); Idx < N;) {
7423 ValueDecl *D = cast<ValueDecl>(GetDecl(PendingInstantiations[Idx++]));
7424 SourceLocation Loc
7425 = SourceLocation::getFromRawEncoding(PendingInstantiations[Idx++]);
7426
7427 Pending.push_back(std::make_pair(D, Loc));
7428 }
7429 PendingInstantiations.clear();
7430}
7431
Richard Smithe40f2ba2013-08-07 21:41:30 +00007432void ASTReader::ReadLateParsedTemplates(
7433 llvm::DenseMap<const FunctionDecl *, LateParsedTemplate *> &LPTMap) {
7434 for (unsigned Idx = 0, N = LateParsedTemplates.size(); Idx < N;
7435 /* In loop */) {
7436 FunctionDecl *FD = cast<FunctionDecl>(GetDecl(LateParsedTemplates[Idx++]));
7437
7438 LateParsedTemplate *LT = new LateParsedTemplate;
7439 LT->D = GetDecl(LateParsedTemplates[Idx++]);
7440
7441 ModuleFile *F = getOwningModuleFile(LT->D);
7442 assert(F && "No module");
7443
7444 unsigned TokN = LateParsedTemplates[Idx++];
7445 LT->Toks.reserve(TokN);
7446 for (unsigned T = 0; T < TokN; ++T)
7447 LT->Toks.push_back(ReadToken(*F, LateParsedTemplates, Idx));
7448
7449 LPTMap[FD] = LT;
7450 }
7451
7452 LateParsedTemplates.clear();
7453}
7454
Guy Benyei11169dd2012-12-18 14:30:41 +00007455void ASTReader::LoadSelector(Selector Sel) {
7456 // It would be complicated to avoid reading the methods anyway. So don't.
7457 ReadMethodPool(Sel);
7458}
7459
7460void ASTReader::SetIdentifierInfo(IdentifierID ID, IdentifierInfo *II) {
7461 assert(ID && "Non-zero identifier ID required");
7462 assert(ID <= IdentifiersLoaded.size() && "identifier ID out of range");
7463 IdentifiersLoaded[ID - 1] = II;
7464 if (DeserializationListener)
7465 DeserializationListener->IdentifierRead(ID, II);
7466}
7467
7468/// \brief Set the globally-visible declarations associated with the given
7469/// identifier.
7470///
7471/// If the AST reader is currently in a state where the given declaration IDs
7472/// cannot safely be resolved, they are queued until it is safe to resolve
7473/// them.
7474///
7475/// \param II an IdentifierInfo that refers to one or more globally-visible
7476/// declarations.
7477///
7478/// \param DeclIDs the set of declaration IDs with the name @p II that are
7479/// visible at global scope.
7480///
Douglas Gregor6168bd22013-02-18 15:53:43 +00007481/// \param Decls if non-null, this vector will be populated with the set of
7482/// deserialized declarations. These declarations will not be pushed into
7483/// scope.
Guy Benyei11169dd2012-12-18 14:30:41 +00007484void
7485ASTReader::SetGloballyVisibleDecls(IdentifierInfo *II,
7486 const SmallVectorImpl<uint32_t> &DeclIDs,
Douglas Gregor6168bd22013-02-18 15:53:43 +00007487 SmallVectorImpl<Decl *> *Decls) {
7488 if (NumCurrentElementsDeserializing && !Decls) {
7489 PendingIdentifierInfos[II].append(DeclIDs.begin(), DeclIDs.end());
Guy Benyei11169dd2012-12-18 14:30:41 +00007490 return;
7491 }
7492
7493 for (unsigned I = 0, N = DeclIDs.size(); I != N; ++I) {
Ben Langmuir5418f402014-09-10 21:29:41 +00007494 if (!SemaObj) {
Guy Benyei11169dd2012-12-18 14:30:41 +00007495 // Queue this declaration so that it will be added to the
7496 // translation unit scope and identifier's declaration chain
7497 // once a Sema object is known.
Ben Langmuir5418f402014-09-10 21:29:41 +00007498 PreloadedDeclIDs.push_back(DeclIDs[I]);
7499 continue;
Guy Benyei11169dd2012-12-18 14:30:41 +00007500 }
Ben Langmuir5418f402014-09-10 21:29:41 +00007501
7502 NamedDecl *D = cast<NamedDecl>(GetDecl(DeclIDs[I]));
7503
7504 // If we're simply supposed to record the declarations, do so now.
7505 if (Decls) {
7506 Decls->push_back(D);
7507 continue;
7508 }
7509
7510 // Introduce this declaration into the translation-unit scope
7511 // and add it to the declaration chain for this identifier, so
7512 // that (unqualified) name lookup will find it.
7513 pushExternalDeclIntoScope(D, II);
Guy Benyei11169dd2012-12-18 14:30:41 +00007514 }
7515}
7516
Douglas Gregorc8a992f2013-01-21 16:52:34 +00007517IdentifierInfo *ASTReader::DecodeIdentifierInfo(IdentifierID ID) {
Guy Benyei11169dd2012-12-18 14:30:41 +00007518 if (ID == 0)
Craig Toppera13603a2014-05-22 05:54:18 +00007519 return nullptr;
Guy Benyei11169dd2012-12-18 14:30:41 +00007520
7521 if (IdentifiersLoaded.empty()) {
7522 Error("no identifier table in AST file");
Craig Toppera13603a2014-05-22 05:54:18 +00007523 return nullptr;
Guy Benyei11169dd2012-12-18 14:30:41 +00007524 }
7525
7526 ID -= 1;
7527 if (!IdentifiersLoaded[ID]) {
7528 GlobalIdentifierMapType::iterator I = GlobalIdentifierMap.find(ID + 1);
7529 assert(I != GlobalIdentifierMap.end() && "Corrupted global identifier map");
7530 ModuleFile *M = I->second;
7531 unsigned Index = ID - M->BaseIdentifierID;
7532 const char *Str = M->IdentifierTableData + M->IdentifierOffsets[Index];
7533
7534 // All of the strings in the AST file are preceded by a 16-bit length.
7535 // Extract that 16-bit length to avoid having to execute strlen().
7536 // NOTE: 'StrLenPtr' is an 'unsigned char*' so that we load bytes as
7537 // unsigned integers. This is important to avoid integer overflow when
7538 // we cast them to 'unsigned'.
7539 const unsigned char *StrLenPtr = (const unsigned char*) Str - 2;
7540 unsigned StrLen = (((unsigned) StrLenPtr[0])
7541 | (((unsigned) StrLenPtr[1]) << 8)) - 1;
Douglas Gregorc8a992f2013-01-21 16:52:34 +00007542 IdentifiersLoaded[ID]
7543 = &PP.getIdentifierTable().get(StringRef(Str, StrLen));
Guy Benyei11169dd2012-12-18 14:30:41 +00007544 if (DeserializationListener)
7545 DeserializationListener->IdentifierRead(ID + 1, IdentifiersLoaded[ID]);
7546 }
7547
7548 return IdentifiersLoaded[ID];
7549}
7550
Douglas Gregorc8a992f2013-01-21 16:52:34 +00007551IdentifierInfo *ASTReader::getLocalIdentifier(ModuleFile &M, unsigned LocalID) {
7552 return DecodeIdentifierInfo(getGlobalIdentifierID(M, LocalID));
Guy Benyei11169dd2012-12-18 14:30:41 +00007553}
7554
7555IdentifierID ASTReader::getGlobalIdentifierID(ModuleFile &M, unsigned LocalID) {
7556 if (LocalID < NUM_PREDEF_IDENT_IDS)
7557 return LocalID;
7558
7559 ContinuousRangeMap<uint32_t, int, 2>::iterator I
7560 = M.IdentifierRemap.find(LocalID - NUM_PREDEF_IDENT_IDS);
7561 assert(I != M.IdentifierRemap.end()
7562 && "Invalid index into identifier index remap");
7563
7564 return LocalID + I->second;
7565}
7566
Argyrios Kyrtzidiseb663da2013-03-22 21:12:57 +00007567MacroInfo *ASTReader::getMacro(MacroID ID) {
Guy Benyei11169dd2012-12-18 14:30:41 +00007568 if (ID == 0)
Craig Toppera13603a2014-05-22 05:54:18 +00007569 return nullptr;
Guy Benyei11169dd2012-12-18 14:30:41 +00007570
7571 if (MacrosLoaded.empty()) {
7572 Error("no macro table in AST file");
Craig Toppera13603a2014-05-22 05:54:18 +00007573 return nullptr;
Guy Benyei11169dd2012-12-18 14:30:41 +00007574 }
7575
7576 ID -= NUM_PREDEF_MACRO_IDS;
7577 if (!MacrosLoaded[ID]) {
7578 GlobalMacroMapType::iterator I
7579 = GlobalMacroMap.find(ID + NUM_PREDEF_MACRO_IDS);
7580 assert(I != GlobalMacroMap.end() && "Corrupted global macro map");
7581 ModuleFile *M = I->second;
7582 unsigned Index = ID - M->BaseMacroID;
Argyrios Kyrtzidiseb663da2013-03-22 21:12:57 +00007583 MacrosLoaded[ID] = ReadMacroRecord(*M, M->MacroOffsets[Index]);
7584
7585 if (DeserializationListener)
7586 DeserializationListener->MacroRead(ID + NUM_PREDEF_MACRO_IDS,
7587 MacrosLoaded[ID]);
Guy Benyei11169dd2012-12-18 14:30:41 +00007588 }
7589
7590 return MacrosLoaded[ID];
7591}
7592
7593MacroID ASTReader::getGlobalMacroID(ModuleFile &M, unsigned LocalID) {
7594 if (LocalID < NUM_PREDEF_MACRO_IDS)
7595 return LocalID;
7596
7597 ContinuousRangeMap<uint32_t, int, 2>::iterator I
7598 = M.MacroRemap.find(LocalID - NUM_PREDEF_MACRO_IDS);
7599 assert(I != M.MacroRemap.end() && "Invalid index into macro index remap");
7600
7601 return LocalID + I->second;
7602}
7603
7604serialization::SubmoduleID
7605ASTReader::getGlobalSubmoduleID(ModuleFile &M, unsigned LocalID) {
7606 if (LocalID < NUM_PREDEF_SUBMODULE_IDS)
7607 return LocalID;
7608
7609 ContinuousRangeMap<uint32_t, int, 2>::iterator I
7610 = M.SubmoduleRemap.find(LocalID - NUM_PREDEF_SUBMODULE_IDS);
7611 assert(I != M.SubmoduleRemap.end()
7612 && "Invalid index into submodule index remap");
7613
7614 return LocalID + I->second;
7615}
7616
7617Module *ASTReader::getSubmodule(SubmoduleID GlobalID) {
7618 if (GlobalID < NUM_PREDEF_SUBMODULE_IDS) {
7619 assert(GlobalID == 0 && "Unhandled global submodule ID");
Craig Toppera13603a2014-05-22 05:54:18 +00007620 return nullptr;
Guy Benyei11169dd2012-12-18 14:30:41 +00007621 }
7622
7623 if (GlobalID > SubmodulesLoaded.size()) {
7624 Error("submodule ID out of range in AST file");
Craig Toppera13603a2014-05-22 05:54:18 +00007625 return nullptr;
Guy Benyei11169dd2012-12-18 14:30:41 +00007626 }
7627
7628 return SubmodulesLoaded[GlobalID - NUM_PREDEF_SUBMODULE_IDS];
7629}
Douglas Gregorc147b0b2013-01-12 01:29:50 +00007630
7631Module *ASTReader::getModule(unsigned ID) {
7632 return getSubmodule(ID);
7633}
7634
Guy Benyei11169dd2012-12-18 14:30:41 +00007635Selector ASTReader::getLocalSelector(ModuleFile &M, unsigned LocalID) {
7636 return DecodeSelector(getGlobalSelectorID(M, LocalID));
7637}
7638
7639Selector ASTReader::DecodeSelector(serialization::SelectorID ID) {
7640 if (ID == 0)
7641 return Selector();
7642
7643 if (ID > SelectorsLoaded.size()) {
7644 Error("selector ID out of range in AST file");
7645 return Selector();
7646 }
7647
Craig Toppera13603a2014-05-22 05:54:18 +00007648 if (SelectorsLoaded[ID - 1].getAsOpaquePtr() == nullptr) {
Guy Benyei11169dd2012-12-18 14:30:41 +00007649 // Load this selector from the selector table.
7650 GlobalSelectorMapType::iterator I = GlobalSelectorMap.find(ID);
7651 assert(I != GlobalSelectorMap.end() && "Corrupted global selector map");
7652 ModuleFile &M = *I->second;
7653 ASTSelectorLookupTrait Trait(*this, M);
7654 unsigned Idx = ID - M.BaseSelectorID - NUM_PREDEF_SELECTOR_IDS;
7655 SelectorsLoaded[ID - 1] =
7656 Trait.ReadKey(M.SelectorLookupTableData + M.SelectorOffsets[Idx], 0);
7657 if (DeserializationListener)
7658 DeserializationListener->SelectorRead(ID, SelectorsLoaded[ID - 1]);
7659 }
7660
7661 return SelectorsLoaded[ID - 1];
7662}
7663
7664Selector ASTReader::GetExternalSelector(serialization::SelectorID ID) {
7665 return DecodeSelector(ID);
7666}
7667
7668uint32_t ASTReader::GetNumExternalSelectors() {
7669 // ID 0 (the null selector) is considered an external selector.
7670 return getTotalNumSelectors() + 1;
7671}
7672
7673serialization::SelectorID
7674ASTReader::getGlobalSelectorID(ModuleFile &M, unsigned LocalID) const {
7675 if (LocalID < NUM_PREDEF_SELECTOR_IDS)
7676 return LocalID;
7677
7678 ContinuousRangeMap<uint32_t, int, 2>::iterator I
7679 = M.SelectorRemap.find(LocalID - NUM_PREDEF_SELECTOR_IDS);
7680 assert(I != M.SelectorRemap.end()
7681 && "Invalid index into selector index remap");
7682
7683 return LocalID + I->second;
7684}
7685
7686DeclarationName
7687ASTReader::ReadDeclarationName(ModuleFile &F,
7688 const RecordData &Record, unsigned &Idx) {
7689 DeclarationName::NameKind Kind = (DeclarationName::NameKind)Record[Idx++];
7690 switch (Kind) {
7691 case DeclarationName::Identifier:
Douglas Gregorc8a992f2013-01-21 16:52:34 +00007692 return DeclarationName(GetIdentifierInfo(F, Record, Idx));
Guy Benyei11169dd2012-12-18 14:30:41 +00007693
7694 case DeclarationName::ObjCZeroArgSelector:
7695 case DeclarationName::ObjCOneArgSelector:
7696 case DeclarationName::ObjCMultiArgSelector:
7697 return DeclarationName(ReadSelector(F, Record, Idx));
7698
7699 case DeclarationName::CXXConstructorName:
7700 return Context.DeclarationNames.getCXXConstructorName(
7701 Context.getCanonicalType(readType(F, Record, Idx)));
7702
7703 case DeclarationName::CXXDestructorName:
7704 return Context.DeclarationNames.getCXXDestructorName(
7705 Context.getCanonicalType(readType(F, Record, Idx)));
7706
7707 case DeclarationName::CXXConversionFunctionName:
7708 return Context.DeclarationNames.getCXXConversionFunctionName(
7709 Context.getCanonicalType(readType(F, Record, Idx)));
7710
7711 case DeclarationName::CXXOperatorName:
7712 return Context.DeclarationNames.getCXXOperatorName(
7713 (OverloadedOperatorKind)Record[Idx++]);
7714
7715 case DeclarationName::CXXLiteralOperatorName:
7716 return Context.DeclarationNames.getCXXLiteralOperatorName(
7717 GetIdentifierInfo(F, Record, Idx));
7718
7719 case DeclarationName::CXXUsingDirective:
7720 return DeclarationName::getUsingDirectiveName();
7721 }
7722
7723 llvm_unreachable("Invalid NameKind!");
7724}
7725
7726void ASTReader::ReadDeclarationNameLoc(ModuleFile &F,
7727 DeclarationNameLoc &DNLoc,
7728 DeclarationName Name,
7729 const RecordData &Record, unsigned &Idx) {
7730 switch (Name.getNameKind()) {
7731 case DeclarationName::CXXConstructorName:
7732 case DeclarationName::CXXDestructorName:
7733 case DeclarationName::CXXConversionFunctionName:
7734 DNLoc.NamedType.TInfo = GetTypeSourceInfo(F, Record, Idx);
7735 break;
7736
7737 case DeclarationName::CXXOperatorName:
7738 DNLoc.CXXOperatorName.BeginOpNameLoc
7739 = ReadSourceLocation(F, Record, Idx).getRawEncoding();
7740 DNLoc.CXXOperatorName.EndOpNameLoc
7741 = ReadSourceLocation(F, Record, Idx).getRawEncoding();
7742 break;
7743
7744 case DeclarationName::CXXLiteralOperatorName:
7745 DNLoc.CXXLiteralOperatorName.OpNameLoc
7746 = ReadSourceLocation(F, Record, Idx).getRawEncoding();
7747 break;
7748
7749 case DeclarationName::Identifier:
7750 case DeclarationName::ObjCZeroArgSelector:
7751 case DeclarationName::ObjCOneArgSelector:
7752 case DeclarationName::ObjCMultiArgSelector:
7753 case DeclarationName::CXXUsingDirective:
7754 break;
7755 }
7756}
7757
7758void ASTReader::ReadDeclarationNameInfo(ModuleFile &F,
7759 DeclarationNameInfo &NameInfo,
7760 const RecordData &Record, unsigned &Idx) {
7761 NameInfo.setName(ReadDeclarationName(F, Record, Idx));
7762 NameInfo.setLoc(ReadSourceLocation(F, Record, Idx));
7763 DeclarationNameLoc DNLoc;
7764 ReadDeclarationNameLoc(F, DNLoc, NameInfo.getName(), Record, Idx);
7765 NameInfo.setInfo(DNLoc);
7766}
7767
7768void ASTReader::ReadQualifierInfo(ModuleFile &F, QualifierInfo &Info,
7769 const RecordData &Record, unsigned &Idx) {
7770 Info.QualifierLoc = ReadNestedNameSpecifierLoc(F, Record, Idx);
7771 unsigned NumTPLists = Record[Idx++];
7772 Info.NumTemplParamLists = NumTPLists;
7773 if (NumTPLists) {
7774 Info.TemplParamLists = new (Context) TemplateParameterList*[NumTPLists];
7775 for (unsigned i=0; i != NumTPLists; ++i)
7776 Info.TemplParamLists[i] = ReadTemplateParameterList(F, Record, Idx);
7777 }
7778}
7779
7780TemplateName
7781ASTReader::ReadTemplateName(ModuleFile &F, const RecordData &Record,
7782 unsigned &Idx) {
7783 TemplateName::NameKind Kind = (TemplateName::NameKind)Record[Idx++];
7784 switch (Kind) {
7785 case TemplateName::Template:
7786 return TemplateName(ReadDeclAs<TemplateDecl>(F, Record, Idx));
7787
7788 case TemplateName::OverloadedTemplate: {
7789 unsigned size = Record[Idx++];
7790 UnresolvedSet<8> Decls;
7791 while (size--)
7792 Decls.addDecl(ReadDeclAs<NamedDecl>(F, Record, Idx));
7793
7794 return Context.getOverloadedTemplateName(Decls.begin(), Decls.end());
7795 }
7796
7797 case TemplateName::QualifiedTemplate: {
7798 NestedNameSpecifier *NNS = ReadNestedNameSpecifier(F, Record, Idx);
7799 bool hasTemplKeyword = Record[Idx++];
7800 TemplateDecl *Template = ReadDeclAs<TemplateDecl>(F, Record, Idx);
7801 return Context.getQualifiedTemplateName(NNS, hasTemplKeyword, Template);
7802 }
7803
7804 case TemplateName::DependentTemplate: {
7805 NestedNameSpecifier *NNS = ReadNestedNameSpecifier(F, Record, Idx);
7806 if (Record[Idx++]) // isIdentifier
7807 return Context.getDependentTemplateName(NNS,
7808 GetIdentifierInfo(F, Record,
7809 Idx));
7810 return Context.getDependentTemplateName(NNS,
7811 (OverloadedOperatorKind)Record[Idx++]);
7812 }
7813
7814 case TemplateName::SubstTemplateTemplateParm: {
7815 TemplateTemplateParmDecl *param
7816 = ReadDeclAs<TemplateTemplateParmDecl>(F, Record, Idx);
7817 if (!param) return TemplateName();
7818 TemplateName replacement = ReadTemplateName(F, Record, Idx);
7819 return Context.getSubstTemplateTemplateParm(param, replacement);
7820 }
7821
7822 case TemplateName::SubstTemplateTemplateParmPack: {
7823 TemplateTemplateParmDecl *Param
7824 = ReadDeclAs<TemplateTemplateParmDecl>(F, Record, Idx);
7825 if (!Param)
7826 return TemplateName();
7827
7828 TemplateArgument ArgPack = ReadTemplateArgument(F, Record, Idx);
7829 if (ArgPack.getKind() != TemplateArgument::Pack)
7830 return TemplateName();
7831
7832 return Context.getSubstTemplateTemplateParmPack(Param, ArgPack);
7833 }
7834 }
7835
7836 llvm_unreachable("Unhandled template name kind!");
7837}
7838
7839TemplateArgument
7840ASTReader::ReadTemplateArgument(ModuleFile &F,
7841 const RecordData &Record, unsigned &Idx) {
7842 TemplateArgument::ArgKind Kind = (TemplateArgument::ArgKind)Record[Idx++];
7843 switch (Kind) {
7844 case TemplateArgument::Null:
7845 return TemplateArgument();
7846 case TemplateArgument::Type:
7847 return TemplateArgument(readType(F, Record, Idx));
7848 case TemplateArgument::Declaration: {
7849 ValueDecl *D = ReadDeclAs<ValueDecl>(F, Record, Idx);
David Blaikie0f62c8d2014-10-16 04:21:25 +00007850 return TemplateArgument(D, readType(F, Record, Idx));
Guy Benyei11169dd2012-12-18 14:30:41 +00007851 }
7852 case TemplateArgument::NullPtr:
7853 return TemplateArgument(readType(F, Record, Idx), /*isNullPtr*/true);
7854 case TemplateArgument::Integral: {
7855 llvm::APSInt Value = ReadAPSInt(Record, Idx);
7856 QualType T = readType(F, Record, Idx);
7857 return TemplateArgument(Context, Value, T);
7858 }
7859 case TemplateArgument::Template:
7860 return TemplateArgument(ReadTemplateName(F, Record, Idx));
7861 case TemplateArgument::TemplateExpansion: {
7862 TemplateName Name = ReadTemplateName(F, Record, Idx);
David Blaikie05785d12013-02-20 22:23:23 +00007863 Optional<unsigned> NumTemplateExpansions;
Guy Benyei11169dd2012-12-18 14:30:41 +00007864 if (unsigned NumExpansions = Record[Idx++])
7865 NumTemplateExpansions = NumExpansions - 1;
7866 return TemplateArgument(Name, NumTemplateExpansions);
7867 }
7868 case TemplateArgument::Expression:
7869 return TemplateArgument(ReadExpr(F));
7870 case TemplateArgument::Pack: {
7871 unsigned NumArgs = Record[Idx++];
7872 TemplateArgument *Args = new (Context) TemplateArgument[NumArgs];
7873 for (unsigned I = 0; I != NumArgs; ++I)
7874 Args[I] = ReadTemplateArgument(F, Record, Idx);
7875 return TemplateArgument(Args, NumArgs);
7876 }
7877 }
7878
7879 llvm_unreachable("Unhandled template argument kind!");
7880}
7881
7882TemplateParameterList *
7883ASTReader::ReadTemplateParameterList(ModuleFile &F,
7884 const RecordData &Record, unsigned &Idx) {
7885 SourceLocation TemplateLoc = ReadSourceLocation(F, Record, Idx);
7886 SourceLocation LAngleLoc = ReadSourceLocation(F, Record, Idx);
7887 SourceLocation RAngleLoc = ReadSourceLocation(F, Record, Idx);
7888
7889 unsigned NumParams = Record[Idx++];
7890 SmallVector<NamedDecl *, 16> Params;
7891 Params.reserve(NumParams);
7892 while (NumParams--)
7893 Params.push_back(ReadDeclAs<NamedDecl>(F, Record, Idx));
7894
7895 TemplateParameterList* TemplateParams =
7896 TemplateParameterList::Create(Context, TemplateLoc, LAngleLoc,
7897 Params.data(), Params.size(), RAngleLoc);
7898 return TemplateParams;
7899}
7900
7901void
7902ASTReader::
Craig Topper5603df42013-07-05 19:34:19 +00007903ReadTemplateArgumentList(SmallVectorImpl<TemplateArgument> &TemplArgs,
Guy Benyei11169dd2012-12-18 14:30:41 +00007904 ModuleFile &F, const RecordData &Record,
7905 unsigned &Idx) {
7906 unsigned NumTemplateArgs = Record[Idx++];
7907 TemplArgs.reserve(NumTemplateArgs);
7908 while (NumTemplateArgs--)
7909 TemplArgs.push_back(ReadTemplateArgument(F, Record, Idx));
7910}
7911
7912/// \brief Read a UnresolvedSet structure.
Richard Smitha4ba74c2013-08-30 04:46:40 +00007913void ASTReader::ReadUnresolvedSet(ModuleFile &F, LazyASTUnresolvedSet &Set,
Guy Benyei11169dd2012-12-18 14:30:41 +00007914 const RecordData &Record, unsigned &Idx) {
7915 unsigned NumDecls = Record[Idx++];
7916 Set.reserve(Context, NumDecls);
7917 while (NumDecls--) {
Richard Smitha4ba74c2013-08-30 04:46:40 +00007918 DeclID ID = ReadDeclID(F, Record, Idx);
Guy Benyei11169dd2012-12-18 14:30:41 +00007919 AccessSpecifier AS = (AccessSpecifier)Record[Idx++];
Richard Smitha4ba74c2013-08-30 04:46:40 +00007920 Set.addLazyDecl(Context, ID, AS);
Guy Benyei11169dd2012-12-18 14:30:41 +00007921 }
7922}
7923
7924CXXBaseSpecifier
7925ASTReader::ReadCXXBaseSpecifier(ModuleFile &F,
7926 const RecordData &Record, unsigned &Idx) {
7927 bool isVirtual = static_cast<bool>(Record[Idx++]);
7928 bool isBaseOfClass = static_cast<bool>(Record[Idx++]);
7929 AccessSpecifier AS = static_cast<AccessSpecifier>(Record[Idx++]);
7930 bool inheritConstructors = static_cast<bool>(Record[Idx++]);
7931 TypeSourceInfo *TInfo = GetTypeSourceInfo(F, Record, Idx);
7932 SourceRange Range = ReadSourceRange(F, Record, Idx);
7933 SourceLocation EllipsisLoc = ReadSourceLocation(F, Record, Idx);
7934 CXXBaseSpecifier Result(Range, isVirtual, isBaseOfClass, AS, TInfo,
7935 EllipsisLoc);
7936 Result.setInheritConstructors(inheritConstructors);
7937 return Result;
7938}
7939
7940std::pair<CXXCtorInitializer **, unsigned>
7941ASTReader::ReadCXXCtorInitializers(ModuleFile &F, const RecordData &Record,
7942 unsigned &Idx) {
Craig Toppera13603a2014-05-22 05:54:18 +00007943 CXXCtorInitializer **CtorInitializers = nullptr;
Guy Benyei11169dd2012-12-18 14:30:41 +00007944 unsigned NumInitializers = Record[Idx++];
7945 if (NumInitializers) {
7946 CtorInitializers
7947 = new (Context) CXXCtorInitializer*[NumInitializers];
7948 for (unsigned i=0; i != NumInitializers; ++i) {
Craig Toppera13603a2014-05-22 05:54:18 +00007949 TypeSourceInfo *TInfo = nullptr;
Guy Benyei11169dd2012-12-18 14:30:41 +00007950 bool IsBaseVirtual = false;
Craig Toppera13603a2014-05-22 05:54:18 +00007951 FieldDecl *Member = nullptr;
7952 IndirectFieldDecl *IndirectMember = nullptr;
Guy Benyei11169dd2012-12-18 14:30:41 +00007953
7954 CtorInitializerType Type = (CtorInitializerType)Record[Idx++];
7955 switch (Type) {
7956 case CTOR_INITIALIZER_BASE:
7957 TInfo = GetTypeSourceInfo(F, Record, Idx);
7958 IsBaseVirtual = Record[Idx++];
7959 break;
7960
7961 case CTOR_INITIALIZER_DELEGATING:
7962 TInfo = GetTypeSourceInfo(F, Record, Idx);
7963 break;
7964
7965 case CTOR_INITIALIZER_MEMBER:
7966 Member = ReadDeclAs<FieldDecl>(F, Record, Idx);
7967 break;
7968
7969 case CTOR_INITIALIZER_INDIRECT_MEMBER:
7970 IndirectMember = ReadDeclAs<IndirectFieldDecl>(F, Record, Idx);
7971 break;
7972 }
7973
7974 SourceLocation MemberOrEllipsisLoc = ReadSourceLocation(F, Record, Idx);
7975 Expr *Init = ReadExpr(F);
7976 SourceLocation LParenLoc = ReadSourceLocation(F, Record, Idx);
7977 SourceLocation RParenLoc = ReadSourceLocation(F, Record, Idx);
7978 bool IsWritten = Record[Idx++];
7979 unsigned SourceOrderOrNumArrayIndices;
7980 SmallVector<VarDecl *, 8> Indices;
7981 if (IsWritten) {
7982 SourceOrderOrNumArrayIndices = Record[Idx++];
7983 } else {
7984 SourceOrderOrNumArrayIndices = Record[Idx++];
7985 Indices.reserve(SourceOrderOrNumArrayIndices);
7986 for (unsigned i=0; i != SourceOrderOrNumArrayIndices; ++i)
7987 Indices.push_back(ReadDeclAs<VarDecl>(F, Record, Idx));
7988 }
7989
7990 CXXCtorInitializer *BOMInit;
7991 if (Type == CTOR_INITIALIZER_BASE) {
7992 BOMInit = new (Context) CXXCtorInitializer(Context, TInfo, IsBaseVirtual,
7993 LParenLoc, Init, RParenLoc,
7994 MemberOrEllipsisLoc);
7995 } else if (Type == CTOR_INITIALIZER_DELEGATING) {
7996 BOMInit = new (Context) CXXCtorInitializer(Context, TInfo, LParenLoc,
7997 Init, RParenLoc);
7998 } else if (IsWritten) {
7999 if (Member)
8000 BOMInit = new (Context) CXXCtorInitializer(Context, Member, MemberOrEllipsisLoc,
8001 LParenLoc, Init, RParenLoc);
8002 else
8003 BOMInit = new (Context) CXXCtorInitializer(Context, IndirectMember,
8004 MemberOrEllipsisLoc, LParenLoc,
8005 Init, RParenLoc);
8006 } else {
Argyrios Kyrtzidis794671d2013-05-30 23:59:46 +00008007 if (IndirectMember) {
8008 assert(Indices.empty() && "Indirect field improperly initialized");
8009 BOMInit = new (Context) CXXCtorInitializer(Context, IndirectMember,
8010 MemberOrEllipsisLoc, LParenLoc,
8011 Init, RParenLoc);
8012 } else {
8013 BOMInit = CXXCtorInitializer::Create(Context, Member, MemberOrEllipsisLoc,
8014 LParenLoc, Init, RParenLoc,
8015 Indices.data(), Indices.size());
8016 }
Guy Benyei11169dd2012-12-18 14:30:41 +00008017 }
8018
8019 if (IsWritten)
8020 BOMInit->setSourceOrder(SourceOrderOrNumArrayIndices);
8021 CtorInitializers[i] = BOMInit;
8022 }
8023 }
8024
8025 return std::make_pair(CtorInitializers, NumInitializers);
8026}
8027
8028NestedNameSpecifier *
8029ASTReader::ReadNestedNameSpecifier(ModuleFile &F,
8030 const RecordData &Record, unsigned &Idx) {
8031 unsigned N = Record[Idx++];
Craig Toppera13603a2014-05-22 05:54:18 +00008032 NestedNameSpecifier *NNS = nullptr, *Prev = nullptr;
Guy Benyei11169dd2012-12-18 14:30:41 +00008033 for (unsigned I = 0; I != N; ++I) {
8034 NestedNameSpecifier::SpecifierKind Kind
8035 = (NestedNameSpecifier::SpecifierKind)Record[Idx++];
8036 switch (Kind) {
8037 case NestedNameSpecifier::Identifier: {
8038 IdentifierInfo *II = GetIdentifierInfo(F, Record, Idx);
8039 NNS = NestedNameSpecifier::Create(Context, Prev, II);
8040 break;
8041 }
8042
8043 case NestedNameSpecifier::Namespace: {
8044 NamespaceDecl *NS = ReadDeclAs<NamespaceDecl>(F, Record, Idx);
8045 NNS = NestedNameSpecifier::Create(Context, Prev, NS);
8046 break;
8047 }
8048
8049 case NestedNameSpecifier::NamespaceAlias: {
8050 NamespaceAliasDecl *Alias =ReadDeclAs<NamespaceAliasDecl>(F, Record, Idx);
8051 NNS = NestedNameSpecifier::Create(Context, Prev, Alias);
8052 break;
8053 }
8054
8055 case NestedNameSpecifier::TypeSpec:
8056 case NestedNameSpecifier::TypeSpecWithTemplate: {
8057 const Type *T = readType(F, Record, Idx).getTypePtrOrNull();
8058 if (!T)
Craig Toppera13603a2014-05-22 05:54:18 +00008059 return nullptr;
8060
Guy Benyei11169dd2012-12-18 14:30:41 +00008061 bool Template = Record[Idx++];
8062 NNS = NestedNameSpecifier::Create(Context, Prev, Template, T);
8063 break;
8064 }
8065
8066 case NestedNameSpecifier::Global: {
8067 NNS = NestedNameSpecifier::GlobalSpecifier(Context);
8068 // No associated value, and there can't be a prefix.
8069 break;
8070 }
Nikola Smiljanic67860242014-09-26 00:28:20 +00008071
8072 case NestedNameSpecifier::Super: {
8073 CXXRecordDecl *RD = ReadDeclAs<CXXRecordDecl>(F, Record, Idx);
8074 NNS = NestedNameSpecifier::SuperSpecifier(Context, RD);
8075 break;
8076 }
Guy Benyei11169dd2012-12-18 14:30:41 +00008077 }
8078 Prev = NNS;
8079 }
8080 return NNS;
8081}
8082
8083NestedNameSpecifierLoc
8084ASTReader::ReadNestedNameSpecifierLoc(ModuleFile &F, const RecordData &Record,
8085 unsigned &Idx) {
8086 unsigned N = Record[Idx++];
8087 NestedNameSpecifierLocBuilder Builder;
8088 for (unsigned I = 0; I != N; ++I) {
8089 NestedNameSpecifier::SpecifierKind Kind
8090 = (NestedNameSpecifier::SpecifierKind)Record[Idx++];
8091 switch (Kind) {
8092 case NestedNameSpecifier::Identifier: {
8093 IdentifierInfo *II = GetIdentifierInfo(F, Record, Idx);
8094 SourceRange Range = ReadSourceRange(F, Record, Idx);
8095 Builder.Extend(Context, II, Range.getBegin(), Range.getEnd());
8096 break;
8097 }
8098
8099 case NestedNameSpecifier::Namespace: {
8100 NamespaceDecl *NS = ReadDeclAs<NamespaceDecl>(F, Record, Idx);
8101 SourceRange Range = ReadSourceRange(F, Record, Idx);
8102 Builder.Extend(Context, NS, Range.getBegin(), Range.getEnd());
8103 break;
8104 }
8105
8106 case NestedNameSpecifier::NamespaceAlias: {
8107 NamespaceAliasDecl *Alias =ReadDeclAs<NamespaceAliasDecl>(F, Record, Idx);
8108 SourceRange Range = ReadSourceRange(F, Record, Idx);
8109 Builder.Extend(Context, Alias, Range.getBegin(), Range.getEnd());
8110 break;
8111 }
8112
8113 case NestedNameSpecifier::TypeSpec:
8114 case NestedNameSpecifier::TypeSpecWithTemplate: {
8115 bool Template = Record[Idx++];
8116 TypeSourceInfo *T = GetTypeSourceInfo(F, Record, Idx);
8117 if (!T)
8118 return NestedNameSpecifierLoc();
8119 SourceLocation ColonColonLoc = ReadSourceLocation(F, Record, Idx);
8120
8121 // FIXME: 'template' keyword location not saved anywhere, so we fake it.
8122 Builder.Extend(Context,
8123 Template? T->getTypeLoc().getBeginLoc() : SourceLocation(),
8124 T->getTypeLoc(), ColonColonLoc);
8125 break;
8126 }
8127
8128 case NestedNameSpecifier::Global: {
8129 SourceLocation ColonColonLoc = ReadSourceLocation(F, Record, Idx);
8130 Builder.MakeGlobal(Context, ColonColonLoc);
8131 break;
8132 }
Nikola Smiljanic67860242014-09-26 00:28:20 +00008133
8134 case NestedNameSpecifier::Super: {
8135 CXXRecordDecl *RD = ReadDeclAs<CXXRecordDecl>(F, Record, Idx);
8136 SourceRange Range = ReadSourceRange(F, Record, Idx);
8137 Builder.MakeSuper(Context, RD, Range.getBegin(), Range.getEnd());
8138 break;
8139 }
Guy Benyei11169dd2012-12-18 14:30:41 +00008140 }
8141 }
Nikola Smiljanic67860242014-09-26 00:28:20 +00008142
Guy Benyei11169dd2012-12-18 14:30:41 +00008143 return Builder.getWithLocInContext(Context);
8144}
8145
8146SourceRange
8147ASTReader::ReadSourceRange(ModuleFile &F, const RecordData &Record,
8148 unsigned &Idx) {
8149 SourceLocation beg = ReadSourceLocation(F, Record, Idx);
8150 SourceLocation end = ReadSourceLocation(F, Record, Idx);
8151 return SourceRange(beg, end);
8152}
8153
8154/// \brief Read an integral value
8155llvm::APInt ASTReader::ReadAPInt(const RecordData &Record, unsigned &Idx) {
8156 unsigned BitWidth = Record[Idx++];
8157 unsigned NumWords = llvm::APInt::getNumWords(BitWidth);
8158 llvm::APInt Result(BitWidth, NumWords, &Record[Idx]);
8159 Idx += NumWords;
8160 return Result;
8161}
8162
8163/// \brief Read a signed integral value
8164llvm::APSInt ASTReader::ReadAPSInt(const RecordData &Record, unsigned &Idx) {
8165 bool isUnsigned = Record[Idx++];
8166 return llvm::APSInt(ReadAPInt(Record, Idx), isUnsigned);
8167}
8168
8169/// \brief Read a floating-point value
Tim Northover178723a2013-01-22 09:46:51 +00008170llvm::APFloat ASTReader::ReadAPFloat(const RecordData &Record,
8171 const llvm::fltSemantics &Sem,
8172 unsigned &Idx) {
8173 return llvm::APFloat(Sem, ReadAPInt(Record, Idx));
Guy Benyei11169dd2012-12-18 14:30:41 +00008174}
8175
8176// \brief Read a string
8177std::string ASTReader::ReadString(const RecordData &Record, unsigned &Idx) {
8178 unsigned Len = Record[Idx++];
8179 std::string Result(Record.data() + Idx, Record.data() + Idx + Len);
8180 Idx += Len;
8181 return Result;
8182}
8183
Richard Smith7ed1bc92014-12-05 22:42:13 +00008184std::string ASTReader::ReadPath(ModuleFile &F, const RecordData &Record,
8185 unsigned &Idx) {
8186 std::string Filename = ReadString(Record, Idx);
8187 ResolveImportedPath(F, Filename);
8188 return Filename;
8189}
8190
Guy Benyei11169dd2012-12-18 14:30:41 +00008191VersionTuple ASTReader::ReadVersionTuple(const RecordData &Record,
8192 unsigned &Idx) {
8193 unsigned Major = Record[Idx++];
8194 unsigned Minor = Record[Idx++];
8195 unsigned Subminor = Record[Idx++];
8196 if (Minor == 0)
8197 return VersionTuple(Major);
8198 if (Subminor == 0)
8199 return VersionTuple(Major, Minor - 1);
8200 return VersionTuple(Major, Minor - 1, Subminor - 1);
8201}
8202
8203CXXTemporary *ASTReader::ReadCXXTemporary(ModuleFile &F,
8204 const RecordData &Record,
8205 unsigned &Idx) {
8206 CXXDestructorDecl *Decl = ReadDeclAs<CXXDestructorDecl>(F, Record, Idx);
8207 return CXXTemporary::Create(Context, Decl);
8208}
8209
8210DiagnosticBuilder ASTReader::Diag(unsigned DiagID) {
Argyrios Kyrtzidisdc9fdaf2013-05-24 05:44:08 +00008211 return Diag(CurrentImportLoc, DiagID);
Guy Benyei11169dd2012-12-18 14:30:41 +00008212}
8213
8214DiagnosticBuilder ASTReader::Diag(SourceLocation Loc, unsigned DiagID) {
8215 return Diags.Report(Loc, DiagID);
8216}
8217
8218/// \brief Retrieve the identifier table associated with the
8219/// preprocessor.
8220IdentifierTable &ASTReader::getIdentifierTable() {
8221 return PP.getIdentifierTable();
8222}
8223
8224/// \brief Record that the given ID maps to the given switch-case
8225/// statement.
8226void ASTReader::RecordSwitchCaseID(SwitchCase *SC, unsigned ID) {
Craig Toppera13603a2014-05-22 05:54:18 +00008227 assert((*CurrSwitchCaseStmts)[ID] == nullptr &&
Guy Benyei11169dd2012-12-18 14:30:41 +00008228 "Already have a SwitchCase with this ID");
8229 (*CurrSwitchCaseStmts)[ID] = SC;
8230}
8231
8232/// \brief Retrieve the switch-case statement with the given ID.
8233SwitchCase *ASTReader::getSwitchCaseWithID(unsigned ID) {
Craig Toppera13603a2014-05-22 05:54:18 +00008234 assert((*CurrSwitchCaseStmts)[ID] != nullptr && "No SwitchCase with this ID");
Guy Benyei11169dd2012-12-18 14:30:41 +00008235 return (*CurrSwitchCaseStmts)[ID];
8236}
8237
8238void ASTReader::ClearSwitchCaseIDs() {
8239 CurrSwitchCaseStmts->clear();
8240}
8241
8242void ASTReader::ReadComments() {
8243 std::vector<RawComment *> Comments;
Chris Lattner7fb3bef2013-01-20 00:56:42 +00008244 for (SmallVectorImpl<std::pair<BitstreamCursor,
Guy Benyei11169dd2012-12-18 14:30:41 +00008245 serialization::ModuleFile *> >::iterator
8246 I = CommentsCursors.begin(),
8247 E = CommentsCursors.end();
8248 I != E; ++I) {
Dmitri Gribenko9ee0e302014-03-27 15:40:39 +00008249 Comments.clear();
Chris Lattner7fb3bef2013-01-20 00:56:42 +00008250 BitstreamCursor &Cursor = I->first;
Guy Benyei11169dd2012-12-18 14:30:41 +00008251 serialization::ModuleFile &F = *I->second;
8252 SavedStreamPosition SavedPosition(Cursor);
8253
8254 RecordData Record;
8255 while (true) {
Chris Lattner7fb3bef2013-01-20 00:56:42 +00008256 llvm::BitstreamEntry Entry =
8257 Cursor.advanceSkippingSubblocks(BitstreamCursor::AF_DontPopBlockAtEnd);
Dmitri Gribenko9ee0e302014-03-27 15:40:39 +00008258
Chris Lattner7fb3bef2013-01-20 00:56:42 +00008259 switch (Entry.Kind) {
8260 case llvm::BitstreamEntry::SubBlock: // Handled for us already.
8261 case llvm::BitstreamEntry::Error:
8262 Error("malformed block record in AST file");
8263 return;
8264 case llvm::BitstreamEntry::EndBlock:
8265 goto NextCursor;
8266 case llvm::BitstreamEntry::Record:
8267 // The interesting case.
Guy Benyei11169dd2012-12-18 14:30:41 +00008268 break;
Guy Benyei11169dd2012-12-18 14:30:41 +00008269 }
8270
8271 // Read a record.
8272 Record.clear();
Chris Lattner0e6c9402013-01-20 02:38:54 +00008273 switch ((CommentRecordTypes)Cursor.readRecord(Entry.ID, Record)) {
Guy Benyei11169dd2012-12-18 14:30:41 +00008274 case COMMENTS_RAW_COMMENT: {
8275 unsigned Idx = 0;
8276 SourceRange SR = ReadSourceRange(F, Record, Idx);
8277 RawComment::CommentKind Kind =
8278 (RawComment::CommentKind) Record[Idx++];
8279 bool IsTrailingComment = Record[Idx++];
8280 bool IsAlmostTrailingComment = Record[Idx++];
Dmitri Gribenkoa7d16ce2013-04-10 15:35:17 +00008281 Comments.push_back(new (Context) RawComment(
8282 SR, Kind, IsTrailingComment, IsAlmostTrailingComment,
8283 Context.getLangOpts().CommentOpts.ParseAllComments));
Guy Benyei11169dd2012-12-18 14:30:41 +00008284 break;
8285 }
8286 }
8287 }
Dmitri Gribenko9ee0e302014-03-27 15:40:39 +00008288 NextCursor:
8289 Context.Comments.addDeserializedComments(Comments);
Guy Benyei11169dd2012-12-18 14:30:41 +00008290 }
Guy Benyei11169dd2012-12-18 14:30:41 +00008291}
8292
Argyrios Kyrtzidis1bde1172014-11-18 05:24:18 +00008293void ASTReader::getInputFiles(ModuleFile &F,
8294 SmallVectorImpl<serialization::InputFile> &Files) {
8295 for (unsigned I = 0, E = F.InputFilesLoaded.size(); I != E; ++I) {
8296 unsigned ID = I+1;
8297 Files.push_back(getInputFile(F, ID));
8298 }
8299}
8300
Richard Smithcd45dbc2014-04-19 03:48:30 +00008301std::string ASTReader::getOwningModuleNameForDiagnostic(const Decl *D) {
8302 // If we know the owning module, use it.
8303 if (Module *M = D->getOwningModule())
8304 return M->getFullModuleName();
8305
8306 // Otherwise, use the name of the top-level module the decl is within.
8307 if (ModuleFile *M = getOwningModuleFile(D))
8308 return M->ModuleName;
8309
8310 // Not from a module.
8311 return "";
8312}
8313
Guy Benyei11169dd2012-12-18 14:30:41 +00008314void ASTReader::finishPendingActions() {
Richard Smith851072e2014-05-19 20:59:20 +00008315 while (!PendingIdentifierInfos.empty() ||
8316 !PendingIncompleteDeclChains.empty() || !PendingDeclChains.empty() ||
Richard Smith2b9e3e32013-10-18 06:05:18 +00008317 !PendingMacroIDs.empty() || !PendingDeclContextInfos.empty() ||
Richard Smitha0ce9c42014-07-29 23:23:27 +00008318 !PendingUpdateRecords.empty()) {
Guy Benyei11169dd2012-12-18 14:30:41 +00008319 // If any identifiers with corresponding top-level declarations have
8320 // been loaded, load those declarations now.
Craig Topper79be4cd2013-07-05 04:33:53 +00008321 typedef llvm::DenseMap<IdentifierInfo *, SmallVector<Decl *, 2> >
8322 TopLevelDeclsMap;
8323 TopLevelDeclsMap TopLevelDecls;
8324
Guy Benyei11169dd2012-12-18 14:30:41 +00008325 while (!PendingIdentifierInfos.empty()) {
Douglas Gregor6168bd22013-02-18 15:53:43 +00008326 IdentifierInfo *II = PendingIdentifierInfos.back().first;
Richard Smithf0ae3c2d2014-03-28 17:31:23 +00008327 SmallVector<uint32_t, 4> DeclIDs =
8328 std::move(PendingIdentifierInfos.back().second);
Douglas Gregorcb15f082013-02-19 18:26:28 +00008329 PendingIdentifierInfos.pop_back();
Douglas Gregor6168bd22013-02-18 15:53:43 +00008330
8331 SetGloballyVisibleDecls(II, DeclIDs, &TopLevelDecls[II]);
Guy Benyei11169dd2012-12-18 14:30:41 +00008332 }
Richard Smithf0ae3c2d2014-03-28 17:31:23 +00008333
Richard Smith851072e2014-05-19 20:59:20 +00008334 // For each decl chain that we wanted to complete while deserializing, mark
8335 // it as "still needs to be completed".
8336 for (unsigned I = 0; I != PendingIncompleteDeclChains.size(); ++I) {
8337 markIncompleteDeclChain(PendingIncompleteDeclChains[I]);
8338 }
8339 PendingIncompleteDeclChains.clear();
8340
Guy Benyei11169dd2012-12-18 14:30:41 +00008341 // Load pending declaration chains.
8342 for (unsigned I = 0; I != PendingDeclChains.size(); ++I) {
8343 loadPendingDeclChain(PendingDeclChains[I]);
8344 PendingDeclChainsKnown.erase(PendingDeclChains[I]);
8345 }
8346 PendingDeclChains.clear();
8347
Douglas Gregor6168bd22013-02-18 15:53:43 +00008348 // Make the most recent of the top-level declarations visible.
Craig Topper79be4cd2013-07-05 04:33:53 +00008349 for (TopLevelDeclsMap::iterator TLD = TopLevelDecls.begin(),
8350 TLDEnd = TopLevelDecls.end(); TLD != TLDEnd; ++TLD) {
Douglas Gregor6168bd22013-02-18 15:53:43 +00008351 IdentifierInfo *II = TLD->first;
8352 for (unsigned I = 0, N = TLD->second.size(); I != N; ++I) {
Argyrios Kyrtzidise5edbf92013-04-26 21:33:35 +00008353 pushExternalDeclIntoScope(cast<NamedDecl>(TLD->second[I]), II);
Douglas Gregor6168bd22013-02-18 15:53:43 +00008354 }
8355 }
8356
Guy Benyei11169dd2012-12-18 14:30:41 +00008357 // Load any pending macro definitions.
8358 for (unsigned I = 0; I != PendingMacroIDs.size(); ++I) {
Argyrios Kyrtzidiseb663da2013-03-22 21:12:57 +00008359 IdentifierInfo *II = PendingMacroIDs.begin()[I].first;
8360 SmallVector<PendingMacroInfo, 2> GlobalIDs;
8361 GlobalIDs.swap(PendingMacroIDs.begin()[I].second);
8362 // Initialize the macro history from chained-PCHs ahead of module imports.
Richard Smith49f906a2014-03-01 00:08:04 +00008363 for (unsigned IDIdx = 0, NumIDs = GlobalIDs.size(); IDIdx != NumIDs;
Argyrios Kyrtzidis719736c2013-01-19 03:14:56 +00008364 ++IDIdx) {
Argyrios Kyrtzidiseb663da2013-03-22 21:12:57 +00008365 const PendingMacroInfo &Info = GlobalIDs[IDIdx];
Richard Smithe842a472014-10-22 02:05:46 +00008366 if (Info.M->Kind != MK_ImplicitModule &&
8367 Info.M->Kind != MK_ExplicitModule)
Argyrios Kyrtzidiseb663da2013-03-22 21:12:57 +00008368 resolvePendingMacro(II, Info);
8369 }
8370 // Handle module imports.
Richard Smith49f906a2014-03-01 00:08:04 +00008371 for (unsigned IDIdx = 0, NumIDs = GlobalIDs.size(); IDIdx != NumIDs;
Argyrios Kyrtzidiseb663da2013-03-22 21:12:57 +00008372 ++IDIdx) {
8373 const PendingMacroInfo &Info = GlobalIDs[IDIdx];
Richard Smithe842a472014-10-22 02:05:46 +00008374 if (Info.M->Kind == MK_ImplicitModule ||
8375 Info.M->Kind == MK_ExplicitModule)
Argyrios Kyrtzidiseb663da2013-03-22 21:12:57 +00008376 resolvePendingMacro(II, Info);
Guy Benyei11169dd2012-12-18 14:30:41 +00008377 }
8378 }
8379 PendingMacroIDs.clear();
Argyrios Kyrtzidis83a6e3b2013-02-16 00:48:59 +00008380
8381 // Wire up the DeclContexts for Decls that we delayed setting until
8382 // recursive loading is completed.
8383 while (!PendingDeclContextInfos.empty()) {
8384 PendingDeclContextInfo Info = PendingDeclContextInfos.front();
8385 PendingDeclContextInfos.pop_front();
8386 DeclContext *SemaDC = cast<DeclContext>(GetDecl(Info.SemaDC));
8387 DeclContext *LexicalDC = cast<DeclContext>(GetDecl(Info.LexicalDC));
8388 Info.D->setDeclContextsImpl(SemaDC, LexicalDC, getContext());
8389 }
Richard Smith2b9e3e32013-10-18 06:05:18 +00008390
Richard Smithd1c46742014-04-30 02:24:17 +00008391 // Perform any pending declaration updates.
Richard Smithd6db68c2014-08-07 20:58:41 +00008392 while (!PendingUpdateRecords.empty()) {
Richard Smithd1c46742014-04-30 02:24:17 +00008393 auto Update = PendingUpdateRecords.pop_back_val();
8394 ReadingKindTracker ReadingKind(Read_Decl, *this);
8395 loadDeclUpdateRecords(Update.first, Update.second);
8396 }
Guy Benyei11169dd2012-12-18 14:30:41 +00008397 }
Richard Smith8a639892015-01-24 01:07:20 +00008398
8399 // At this point, all update records for loaded decls are in place, so any
8400 // fake class definitions should have become real.
8401 assert(PendingFakeDefinitionData.empty() &&
8402 "faked up a class definition but never saw the real one");
8403
Guy Benyei11169dd2012-12-18 14:30:41 +00008404 // If we deserialized any C++ or Objective-C class definitions, any
8405 // Objective-C protocol definitions, or any redeclarable templates, make sure
8406 // that all redeclarations point to the definitions. Note that this can only
8407 // happen now, after the redeclaration chains have been fully wired.
Craig Topperc6914d02014-08-25 04:15:02 +00008408 for (Decl *D : PendingDefinitions) {
8409 if (TagDecl *TD = dyn_cast<TagDecl>(D)) {
Richard Smith5b21db82014-04-23 18:20:42 +00008410 if (const TagType *TagT = dyn_cast<TagType>(TD->getTypeForDecl())) {
Guy Benyei11169dd2012-12-18 14:30:41 +00008411 // Make sure that the TagType points at the definition.
8412 const_cast<TagType*>(TagT)->decl = TD;
8413 }
8414
Craig Topperc6914d02014-08-25 04:15:02 +00008415 if (auto RD = dyn_cast<CXXRecordDecl>(D)) {
Richard Smith2c381642014-08-27 23:11:59 +00008416 for (auto R : RD->redecls()) {
8417 assert((R == D) == R->isThisDeclarationADefinition() &&
8418 "declaration thinks it's the definition but it isn't");
Aaron Ballman86c93902014-03-06 23:45:36 +00008419 cast<CXXRecordDecl>(R)->DefinitionData = RD->DefinitionData;
Richard Smith2c381642014-08-27 23:11:59 +00008420 }
Guy Benyei11169dd2012-12-18 14:30:41 +00008421 }
8422
8423 continue;
8424 }
8425
Craig Topperc6914d02014-08-25 04:15:02 +00008426 if (auto ID = dyn_cast<ObjCInterfaceDecl>(D)) {
Guy Benyei11169dd2012-12-18 14:30:41 +00008427 // Make sure that the ObjCInterfaceType points at the definition.
8428 const_cast<ObjCInterfaceType *>(cast<ObjCInterfaceType>(ID->TypeForDecl))
8429 ->Decl = ID;
8430
Aaron Ballman86c93902014-03-06 23:45:36 +00008431 for (auto R : ID->redecls())
Guy Benyei11169dd2012-12-18 14:30:41 +00008432 R->Data = ID->Data;
8433
8434 continue;
8435 }
8436
Craig Topperc6914d02014-08-25 04:15:02 +00008437 if (auto PD = dyn_cast<ObjCProtocolDecl>(D)) {
Aaron Ballman86c93902014-03-06 23:45:36 +00008438 for (auto R : PD->redecls())
Guy Benyei11169dd2012-12-18 14:30:41 +00008439 R->Data = PD->Data;
8440
8441 continue;
8442 }
8443
Craig Topperc6914d02014-08-25 04:15:02 +00008444 auto RTD = cast<RedeclarableTemplateDecl>(D)->getCanonicalDecl();
Aaron Ballman86c93902014-03-06 23:45:36 +00008445 for (auto R : RTD->redecls())
Guy Benyei11169dd2012-12-18 14:30:41 +00008446 R->Common = RTD->Common;
8447 }
8448 PendingDefinitions.clear();
8449
8450 // Load the bodies of any functions or methods we've encountered. We do
8451 // this now (delayed) so that we can be sure that the declaration chains
8452 // have been fully wired up.
8453 for (PendingBodiesMap::iterator PB = PendingBodies.begin(),
8454 PBEnd = PendingBodies.end();
8455 PB != PBEnd; ++PB) {
8456 if (FunctionDecl *FD = dyn_cast<FunctionDecl>(PB->first)) {
8457 // FIXME: Check for =delete/=default?
8458 // FIXME: Complain about ODR violations here?
8459 if (!getContext().getLangOpts().Modules || !FD->hasBody())
8460 FD->setLazyBody(PB->second);
8461 continue;
8462 }
8463
8464 ObjCMethodDecl *MD = cast<ObjCMethodDecl>(PB->first);
8465 if (!getContext().getLangOpts().Modules || !MD->hasBody())
8466 MD->setLazyBody(PB->second);
8467 }
8468 PendingBodies.clear();
Richard Smitha0ce9c42014-07-29 23:23:27 +00008469}
8470
8471void ASTReader::diagnoseOdrViolations() {
Richard Smithbb853c72014-08-13 01:23:33 +00008472 if (PendingOdrMergeFailures.empty() && PendingOdrMergeChecks.empty())
8473 return;
8474
Richard Smitha0ce9c42014-07-29 23:23:27 +00008475 // Trigger the import of the full definition of each class that had any
8476 // odr-merging problems, so we can produce better diagnostics for them.
Richard Smithbb853c72014-08-13 01:23:33 +00008477 // These updates may in turn find and diagnose some ODR failures, so take
8478 // ownership of the set first.
8479 auto OdrMergeFailures = std::move(PendingOdrMergeFailures);
8480 PendingOdrMergeFailures.clear();
8481 for (auto &Merge : OdrMergeFailures) {
Richard Smitha0ce9c42014-07-29 23:23:27 +00008482 Merge.first->buildLookup();
8483 Merge.first->decls_begin();
8484 Merge.first->bases_begin();
8485 Merge.first->vbases_begin();
8486 for (auto *RD : Merge.second) {
8487 RD->decls_begin();
8488 RD->bases_begin();
8489 RD->vbases_begin();
8490 }
8491 }
8492
8493 // For each declaration from a merged context, check that the canonical
8494 // definition of that context also contains a declaration of the same
8495 // entity.
8496 //
8497 // Caution: this loop does things that might invalidate iterators into
8498 // PendingOdrMergeChecks. Don't turn this into a range-based for loop!
8499 while (!PendingOdrMergeChecks.empty()) {
8500 NamedDecl *D = PendingOdrMergeChecks.pop_back_val();
8501
8502 // FIXME: Skip over implicit declarations for now. This matters for things
8503 // like implicitly-declared special member functions. This isn't entirely
8504 // correct; we can end up with multiple unmerged declarations of the same
8505 // implicit entity.
8506 if (D->isImplicit())
8507 continue;
8508
8509 DeclContext *CanonDef = D->getDeclContext();
Richard Smitha0ce9c42014-07-29 23:23:27 +00008510
8511 bool Found = false;
8512 const Decl *DCanon = D->getCanonicalDecl();
8513
Richard Smith01bdb7a2014-08-28 05:44:07 +00008514 for (auto RI : D->redecls()) {
8515 if (RI->getLexicalDeclContext() == CanonDef) {
8516 Found = true;
8517 break;
8518 }
8519 }
8520 if (Found)
8521 continue;
8522
Richard Smitha0ce9c42014-07-29 23:23:27 +00008523 llvm::SmallVector<const NamedDecl*, 4> Candidates;
Richard Smith01bdb7a2014-08-28 05:44:07 +00008524 DeclContext::lookup_result R = CanonDef->lookup(D->getDeclName());
Richard Smitha0ce9c42014-07-29 23:23:27 +00008525 for (DeclContext::lookup_iterator I = R.begin(), E = R.end();
8526 !Found && I != E; ++I) {
8527 for (auto RI : (*I)->redecls()) {
8528 if (RI->getLexicalDeclContext() == CanonDef) {
8529 // This declaration is present in the canonical definition. If it's
8530 // in the same redecl chain, it's the one we're looking for.
8531 if (RI->getCanonicalDecl() == DCanon)
8532 Found = true;
8533 else
8534 Candidates.push_back(cast<NamedDecl>(RI));
8535 break;
8536 }
8537 }
8538 }
8539
8540 if (!Found) {
Richard Smithd08aeb62014-08-28 01:33:39 +00008541 // The AST doesn't like TagDecls becoming invalid after they've been
8542 // completed. We only really need to mark FieldDecls as invalid here.
8543 if (!isa<TagDecl>(D))
8544 D->setInvalidDecl();
Richard Smith4ab3dbd2015-02-13 22:43:51 +00008545
8546 // Ensure we don't accidentally recursively enter deserialization while
8547 // we're producing our diagnostic.
8548 Deserializing RecursionGuard(this);
Richard Smitha0ce9c42014-07-29 23:23:27 +00008549
8550 std::string CanonDefModule =
8551 getOwningModuleNameForDiagnostic(cast<Decl>(CanonDef));
8552 Diag(D->getLocation(), diag::err_module_odr_violation_missing_decl)
8553 << D << getOwningModuleNameForDiagnostic(D)
8554 << CanonDef << CanonDefModule.empty() << CanonDefModule;
8555
8556 if (Candidates.empty())
8557 Diag(cast<Decl>(CanonDef)->getLocation(),
8558 diag::note_module_odr_violation_no_possible_decls) << D;
8559 else {
8560 for (unsigned I = 0, N = Candidates.size(); I != N; ++I)
8561 Diag(Candidates[I]->getLocation(),
8562 diag::note_module_odr_violation_possible_decl)
8563 << Candidates[I];
8564 }
8565
8566 DiagnosedOdrMergeFailures.insert(CanonDef);
8567 }
8568 }
Richard Smithcd45dbc2014-04-19 03:48:30 +00008569
Richard Smith4ab3dbd2015-02-13 22:43:51 +00008570 if (OdrMergeFailures.empty())
8571 return;
8572
8573 // Ensure we don't accidentally recursively enter deserialization while
8574 // we're producing our diagnostics.
8575 Deserializing RecursionGuard(this);
8576
Richard Smithcd45dbc2014-04-19 03:48:30 +00008577 // Issue any pending ODR-failure diagnostics.
Richard Smithbb853c72014-08-13 01:23:33 +00008578 for (auto &Merge : OdrMergeFailures) {
Richard Smitha0ce9c42014-07-29 23:23:27 +00008579 // If we've already pointed out a specific problem with this class, don't
8580 // bother issuing a general "something's different" diagnostic.
David Blaikie82e95a32014-11-19 07:49:47 +00008581 if (!DiagnosedOdrMergeFailures.insert(Merge.first).second)
Richard Smithcd45dbc2014-04-19 03:48:30 +00008582 continue;
8583
8584 bool Diagnosed = false;
8585 for (auto *RD : Merge.second) {
8586 // Multiple different declarations got merged together; tell the user
8587 // where they came from.
8588 if (Merge.first != RD) {
8589 // FIXME: Walk the definition, figure out what's different,
8590 // and diagnose that.
8591 if (!Diagnosed) {
8592 std::string Module = getOwningModuleNameForDiagnostic(Merge.first);
8593 Diag(Merge.first->getLocation(),
8594 diag::err_module_odr_violation_different_definitions)
8595 << Merge.first << Module.empty() << Module;
8596 Diagnosed = true;
8597 }
8598
8599 Diag(RD->getLocation(),
8600 diag::note_module_odr_violation_different_definitions)
8601 << getOwningModuleNameForDiagnostic(RD);
8602 }
8603 }
8604
8605 if (!Diagnosed) {
8606 // All definitions are updates to the same declaration. This happens if a
8607 // module instantiates the declaration of a class template specialization
8608 // and two or more other modules instantiate its definition.
8609 //
8610 // FIXME: Indicate which modules had instantiations of this definition.
8611 // FIXME: How can this even happen?
8612 Diag(Merge.first->getLocation(),
8613 diag::err_module_odr_violation_different_instantiations)
8614 << Merge.first;
8615 }
8616 }
Guy Benyei11169dd2012-12-18 14:30:41 +00008617}
8618
8619void ASTReader::FinishedDeserializing() {
8620 assert(NumCurrentElementsDeserializing &&
8621 "FinishedDeserializing not paired with StartedDeserializing");
8622 if (NumCurrentElementsDeserializing == 1) {
8623 // We decrease NumCurrentElementsDeserializing only after pending actions
8624 // are finished, to avoid recursively re-calling finishPendingActions().
8625 finishPendingActions();
8626 }
8627 --NumCurrentElementsDeserializing;
8628
Richard Smitha0ce9c42014-07-29 23:23:27 +00008629 if (NumCurrentElementsDeserializing == 0) {
8630 diagnoseOdrViolations();
8631
Richard Smith04d05b52014-03-23 00:27:18 +00008632 // We are not in recursive loading, so it's safe to pass the "interesting"
8633 // decls to the consumer.
Richard Smitha0ce9c42014-07-29 23:23:27 +00008634 if (Consumer)
8635 PassInterestingDeclsToConsumer();
Guy Benyei11169dd2012-12-18 14:30:41 +00008636 }
8637}
8638
Argyrios Kyrtzidise5edbf92013-04-26 21:33:35 +00008639void ASTReader::pushExternalDeclIntoScope(NamedDecl *D, DeclarationName Name) {
Rafael Espindola7b56f6c2013-10-19 16:55:03 +00008640 D = D->getMostRecentDecl();
Argyrios Kyrtzidise5edbf92013-04-26 21:33:35 +00008641
8642 if (SemaObj->IdResolver.tryAddTopLevelDecl(D, Name) && SemaObj->TUScope) {
8643 SemaObj->TUScope->AddDecl(D);
8644 } else if (SemaObj->TUScope) {
8645 // Adding the decl to IdResolver may have failed because it was already in
8646 // (even though it was not added in scope). If it is already in, make sure
8647 // it gets in the scope as well.
8648 if (std::find(SemaObj->IdResolver.begin(Name),
8649 SemaObj->IdResolver.end(), D) != SemaObj->IdResolver.end())
8650 SemaObj->TUScope->AddDecl(D);
8651 }
8652}
8653
Nico Weber824285e2014-05-08 04:26:47 +00008654ASTReader::ASTReader(Preprocessor &PP, ASTContext &Context, StringRef isysroot,
8655 bool DisableValidation, bool AllowASTWithCompilerErrors,
8656 bool AllowConfigurationMismatch, bool ValidateSystemInputs,
Ben Langmuir2cb4a782014-02-05 22:21:15 +00008657 bool UseGlobalIndex)
Craig Toppera13603a2014-05-22 05:54:18 +00008658 : Listener(new PCHValidator(PP, *this)), DeserializationListener(nullptr),
Nico Weber824285e2014-05-08 04:26:47 +00008659 OwnsDeserializationListener(false), SourceMgr(PP.getSourceManager()),
Craig Toppera13603a2014-05-22 05:54:18 +00008660 FileMgr(PP.getFileManager()), Diags(PP.getDiagnostics()),
8661 SemaObj(nullptr), PP(PP), Context(Context), Consumer(nullptr),
8662 ModuleMgr(PP.getFileManager()), isysroot(isysroot),
8663 DisableValidation(DisableValidation),
Nico Weber824285e2014-05-08 04:26:47 +00008664 AllowASTWithCompilerErrors(AllowASTWithCompilerErrors),
8665 AllowConfigurationMismatch(AllowConfigurationMismatch),
8666 ValidateSystemInputs(ValidateSystemInputs),
8667 UseGlobalIndex(UseGlobalIndex), TriedLoadingGlobalIndex(false),
Richard Smith053f6c62014-05-16 23:01:30 +00008668 CurrSwitchCaseStmts(&SwitchCaseStmts),
Nico Weber824285e2014-05-08 04:26:47 +00008669 NumSLocEntriesRead(0), TotalNumSLocEntries(0), NumStatementsRead(0),
8670 TotalNumStatements(0), NumMacrosRead(0), TotalNumMacros(0),
8671 NumIdentifierLookups(0), NumIdentifierLookupHits(0), NumSelectorsRead(0),
8672 NumMethodPoolEntriesRead(0), NumMethodPoolLookups(0),
8673 NumMethodPoolHits(0), NumMethodPoolTableLookups(0),
8674 NumMethodPoolTableHits(0), TotalNumMethodPoolEntries(0),
8675 NumLexicalDeclContextsRead(0), TotalLexicalDeclContexts(0),
8676 NumVisibleDeclContextsRead(0), TotalVisibleDeclContexts(0),
8677 TotalModulesSizeInBits(0), NumCurrentElementsDeserializing(0),
8678 PassingDeclsToConsumer(false), NumCXXBaseSpecifiersLoaded(0),
8679 ReadingKind(Read_None) {
Guy Benyei11169dd2012-12-18 14:30:41 +00008680 SourceMgr.setExternalSLocEntrySource(this);
8681}
8682
8683ASTReader::~ASTReader() {
Nico Weber824285e2014-05-08 04:26:47 +00008684 if (OwnsDeserializationListener)
8685 delete DeserializationListener;
8686
Guy Benyei11169dd2012-12-18 14:30:41 +00008687 for (DeclContextVisibleUpdatesPending::iterator
8688 I = PendingVisibleUpdates.begin(),
8689 E = PendingVisibleUpdates.end();
8690 I != E; ++I) {
8691 for (DeclContextVisibleUpdates::iterator J = I->second.begin(),
8692 F = I->second.end();
8693 J != F; ++J)
8694 delete J->first;
8695 }
8696}