blob: 80b1c2b6bcc8ffd9a9d343533ed139a73ac28e2b [file] [log] [blame]
Nick Lewyckyf0f56162013-01-31 03:23:57 +00001//===--- ASTReader.cpp - AST File Reader ----------------------------------===//
Guy Benyei11169dd2012-12-18 14:30:41 +00002//
3// The LLVM Compiler Infrastructure
4//
5// This file is distributed under the University of Illinois Open Source
6// License. See LICENSE.TXT for details.
7//
8//===----------------------------------------------------------------------===//
9//
10// This file defines the ASTReader class, which reads AST files.
11//
12//===----------------------------------------------------------------------===//
13
14#include "clang/Serialization/ASTReader.h"
15#include "ASTCommon.h"
16#include "ASTReaderInternals.h"
17#include "clang/AST/ASTConsumer.h"
18#include "clang/AST/ASTContext.h"
19#include "clang/AST/DeclTemplate.h"
20#include "clang/AST/Expr.h"
21#include "clang/AST/ExprCXX.h"
22#include "clang/AST/NestedNameSpecifier.h"
23#include "clang/AST/Type.h"
24#include "clang/AST/TypeLocVisitor.h"
Benjamin Kramerf3ca26982014-05-10 16:31:55 +000025#include "clang/Basic/DiagnosticOptions.h"
Guy Benyei11169dd2012-12-18 14:30:41 +000026#include "clang/Basic/FileManager.h"
Guy Benyei11169dd2012-12-18 14:30:41 +000027#include "clang/Basic/SourceManager.h"
28#include "clang/Basic/SourceManagerInternals.h"
29#include "clang/Basic/TargetInfo.h"
30#include "clang/Basic/TargetOptions.h"
31#include "clang/Basic/Version.h"
32#include "clang/Basic/VersionTuple.h"
Ben Langmuirb92de022014-04-29 16:25:26 +000033#include "clang/Frontend/Utils.h"
Guy Benyei11169dd2012-12-18 14:30:41 +000034#include "clang/Lex/HeaderSearch.h"
35#include "clang/Lex/HeaderSearchOptions.h"
36#include "clang/Lex/MacroInfo.h"
37#include "clang/Lex/PreprocessingRecord.h"
38#include "clang/Lex/Preprocessor.h"
39#include "clang/Lex/PreprocessorOptions.h"
40#include "clang/Sema/Scope.h"
41#include "clang/Sema/Sema.h"
42#include "clang/Serialization/ASTDeserializationListener.h"
Douglas Gregore060e572013-01-25 01:03:03 +000043#include "clang/Serialization/GlobalModuleIndex.h"
Guy Benyei11169dd2012-12-18 14:30:41 +000044#include "clang/Serialization/ModuleManager.h"
45#include "clang/Serialization/SerializationDiagnostic.h"
Argyrios Kyrtzidis5c2a3452013-03-06 18:12:47 +000046#include "llvm/ADT/Hashing.h"
Guy Benyei11169dd2012-12-18 14:30:41 +000047#include "llvm/ADT/StringExtras.h"
48#include "llvm/Bitcode/BitstreamReader.h"
49#include "llvm/Support/ErrorHandling.h"
50#include "llvm/Support/FileSystem.h"
51#include "llvm/Support/MemoryBuffer.h"
52#include "llvm/Support/Path.h"
53#include "llvm/Support/SaveAndRestore.h"
Dmitri Gribenkof430da42014-02-12 10:33:14 +000054#include "llvm/Support/raw_ostream.h"
Guy Benyei11169dd2012-12-18 14:30:41 +000055#include <algorithm>
Chris Lattner91f373e2013-01-20 00:57:52 +000056#include <cstdio>
Guy Benyei11169dd2012-12-18 14:30:41 +000057#include <iterator>
Rafael Espindola8a8e5542014-06-12 17:19:42 +000058#include <system_error>
Guy Benyei11169dd2012-12-18 14:30:41 +000059
60using namespace clang;
61using namespace clang::serialization;
62using namespace clang::serialization::reader;
Chris Lattner7fb3bef2013-01-20 00:56:42 +000063using llvm::BitstreamCursor;
Guy Benyei11169dd2012-12-18 14:30:41 +000064
Ben Langmuircb69b572014-03-07 06:40:32 +000065
66//===----------------------------------------------------------------------===//
67// ChainedASTReaderListener implementation
68//===----------------------------------------------------------------------===//
69
70bool
71ChainedASTReaderListener::ReadFullVersionInformation(StringRef FullVersion) {
72 return First->ReadFullVersionInformation(FullVersion) ||
73 Second->ReadFullVersionInformation(FullVersion);
74}
Ben Langmuir4f5212a2014-04-14 22:12:44 +000075void ChainedASTReaderListener::ReadModuleName(StringRef ModuleName) {
76 First->ReadModuleName(ModuleName);
77 Second->ReadModuleName(ModuleName);
78}
79void ChainedASTReaderListener::ReadModuleMapFile(StringRef ModuleMapPath) {
80 First->ReadModuleMapFile(ModuleMapPath);
81 Second->ReadModuleMapFile(ModuleMapPath);
82}
Ben Langmuircb69b572014-03-07 06:40:32 +000083bool ChainedASTReaderListener::ReadLanguageOptions(const LangOptions &LangOpts,
84 bool Complain) {
85 return First->ReadLanguageOptions(LangOpts, Complain) ||
86 Second->ReadLanguageOptions(LangOpts, Complain);
87}
88bool
89ChainedASTReaderListener::ReadTargetOptions(const TargetOptions &TargetOpts,
90 bool Complain) {
91 return First->ReadTargetOptions(TargetOpts, Complain) ||
92 Second->ReadTargetOptions(TargetOpts, Complain);
93}
94bool ChainedASTReaderListener::ReadDiagnosticOptions(
Ben Langmuirb92de022014-04-29 16:25:26 +000095 IntrusiveRefCntPtr<DiagnosticOptions> DiagOpts, bool Complain) {
Ben Langmuircb69b572014-03-07 06:40:32 +000096 return First->ReadDiagnosticOptions(DiagOpts, Complain) ||
97 Second->ReadDiagnosticOptions(DiagOpts, Complain);
98}
99bool
100ChainedASTReaderListener::ReadFileSystemOptions(const FileSystemOptions &FSOpts,
101 bool Complain) {
102 return First->ReadFileSystemOptions(FSOpts, Complain) ||
103 Second->ReadFileSystemOptions(FSOpts, Complain);
104}
105
106bool ChainedASTReaderListener::ReadHeaderSearchOptions(
107 const HeaderSearchOptions &HSOpts, bool Complain) {
108 return First->ReadHeaderSearchOptions(HSOpts, Complain) ||
109 Second->ReadHeaderSearchOptions(HSOpts, Complain);
110}
111bool ChainedASTReaderListener::ReadPreprocessorOptions(
112 const PreprocessorOptions &PPOpts, bool Complain,
113 std::string &SuggestedPredefines) {
114 return First->ReadPreprocessorOptions(PPOpts, Complain,
115 SuggestedPredefines) ||
116 Second->ReadPreprocessorOptions(PPOpts, Complain, SuggestedPredefines);
117}
118void ChainedASTReaderListener::ReadCounter(const serialization::ModuleFile &M,
119 unsigned Value) {
120 First->ReadCounter(M, Value);
121 Second->ReadCounter(M, Value);
122}
123bool ChainedASTReaderListener::needsInputFileVisitation() {
124 return First->needsInputFileVisitation() ||
125 Second->needsInputFileVisitation();
126}
127bool ChainedASTReaderListener::needsSystemInputFileVisitation() {
128 return First->needsSystemInputFileVisitation() ||
129 Second->needsSystemInputFileVisitation();
130}
Argyrios Kyrtzidis6d0753d2014-03-14 03:07:38 +0000131void ChainedASTReaderListener::visitModuleFile(StringRef Filename) {
132 First->visitModuleFile(Filename);
133 Second->visitModuleFile(Filename);
134}
Ben Langmuircb69b572014-03-07 06:40:32 +0000135bool ChainedASTReaderListener::visitInputFile(StringRef Filename,
Argyrios Kyrtzidis68ccbe02014-03-14 02:26:31 +0000136 bool isSystem,
137 bool isOverridden) {
Justin Bognerc65a66d2014-05-22 06:04:59 +0000138 bool Continue = false;
139 if (First->needsInputFileVisitation() &&
140 (!isSystem || First->needsSystemInputFileVisitation()))
141 Continue |= First->visitInputFile(Filename, isSystem, isOverridden);
142 if (Second->needsInputFileVisitation() &&
143 (!isSystem || Second->needsSystemInputFileVisitation()))
144 Continue |= Second->visitInputFile(Filename, isSystem, isOverridden);
145 return Continue;
Ben Langmuircb69b572014-03-07 06:40:32 +0000146}
147
Guy Benyei11169dd2012-12-18 14:30:41 +0000148//===----------------------------------------------------------------------===//
149// PCH validator implementation
150//===----------------------------------------------------------------------===//
151
152ASTReaderListener::~ASTReaderListener() {}
153
154/// \brief Compare the given set of language options against an existing set of
155/// language options.
156///
157/// \param Diags If non-NULL, diagnostics will be emitted via this engine.
158///
159/// \returns true if the languagae options mis-match, false otherwise.
160static bool checkLanguageOptions(const LangOptions &LangOpts,
161 const LangOptions &ExistingLangOpts,
162 DiagnosticsEngine *Diags) {
163#define LANGOPT(Name, Bits, Default, Description) \
164 if (ExistingLangOpts.Name != LangOpts.Name) { \
165 if (Diags) \
166 Diags->Report(diag::err_pch_langopt_mismatch) \
167 << Description << LangOpts.Name << ExistingLangOpts.Name; \
168 return true; \
169 }
170
171#define VALUE_LANGOPT(Name, Bits, Default, Description) \
172 if (ExistingLangOpts.Name != LangOpts.Name) { \
173 if (Diags) \
174 Diags->Report(diag::err_pch_langopt_value_mismatch) \
175 << Description; \
176 return true; \
177 }
178
179#define ENUM_LANGOPT(Name, Type, Bits, Default, Description) \
180 if (ExistingLangOpts.get##Name() != LangOpts.get##Name()) { \
181 if (Diags) \
182 Diags->Report(diag::err_pch_langopt_value_mismatch) \
183 << Description; \
184 return true; \
185 }
186
187#define BENIGN_LANGOPT(Name, Bits, Default, Description)
188#define BENIGN_ENUM_LANGOPT(Name, Type, Bits, Default, Description)
189#include "clang/Basic/LangOptions.def"
190
191 if (ExistingLangOpts.ObjCRuntime != LangOpts.ObjCRuntime) {
192 if (Diags)
193 Diags->Report(diag::err_pch_langopt_value_mismatch)
194 << "target Objective-C runtime";
195 return true;
196 }
197
Dmitri Gribenkoacf2e782013-02-22 14:21:27 +0000198 if (ExistingLangOpts.CommentOpts.BlockCommandNames !=
199 LangOpts.CommentOpts.BlockCommandNames) {
200 if (Diags)
201 Diags->Report(diag::err_pch_langopt_value_mismatch)
202 << "block command names";
203 return true;
204 }
205
Guy Benyei11169dd2012-12-18 14:30:41 +0000206 return false;
207}
208
209/// \brief Compare the given set of target options against an existing set of
210/// target options.
211///
212/// \param Diags If non-NULL, diagnostics will be emitted via this engine.
213///
214/// \returns true if the target options mis-match, false otherwise.
215static bool checkTargetOptions(const TargetOptions &TargetOpts,
216 const TargetOptions &ExistingTargetOpts,
217 DiagnosticsEngine *Diags) {
218#define CHECK_TARGET_OPT(Field, Name) \
219 if (TargetOpts.Field != ExistingTargetOpts.Field) { \
220 if (Diags) \
221 Diags->Report(diag::err_pch_targetopt_mismatch) \
222 << Name << TargetOpts.Field << ExistingTargetOpts.Field; \
223 return true; \
224 }
225
226 CHECK_TARGET_OPT(Triple, "target");
227 CHECK_TARGET_OPT(CPU, "target CPU");
228 CHECK_TARGET_OPT(ABI, "target ABI");
Guy Benyei11169dd2012-12-18 14:30:41 +0000229#undef CHECK_TARGET_OPT
230
231 // Compare feature sets.
232 SmallVector<StringRef, 4> ExistingFeatures(
233 ExistingTargetOpts.FeaturesAsWritten.begin(),
234 ExistingTargetOpts.FeaturesAsWritten.end());
235 SmallVector<StringRef, 4> ReadFeatures(TargetOpts.FeaturesAsWritten.begin(),
236 TargetOpts.FeaturesAsWritten.end());
237 std::sort(ExistingFeatures.begin(), ExistingFeatures.end());
238 std::sort(ReadFeatures.begin(), ReadFeatures.end());
239
240 unsigned ExistingIdx = 0, ExistingN = ExistingFeatures.size();
241 unsigned ReadIdx = 0, ReadN = ReadFeatures.size();
242 while (ExistingIdx < ExistingN && ReadIdx < ReadN) {
243 if (ExistingFeatures[ExistingIdx] == ReadFeatures[ReadIdx]) {
244 ++ExistingIdx;
245 ++ReadIdx;
246 continue;
247 }
248
249 if (ReadFeatures[ReadIdx] < ExistingFeatures[ExistingIdx]) {
250 if (Diags)
251 Diags->Report(diag::err_pch_targetopt_feature_mismatch)
252 << false << ReadFeatures[ReadIdx];
253 return true;
254 }
255
256 if (Diags)
257 Diags->Report(diag::err_pch_targetopt_feature_mismatch)
258 << true << ExistingFeatures[ExistingIdx];
259 return true;
260 }
261
262 if (ExistingIdx < ExistingN) {
263 if (Diags)
264 Diags->Report(diag::err_pch_targetopt_feature_mismatch)
265 << true << ExistingFeatures[ExistingIdx];
266 return true;
267 }
268
269 if (ReadIdx < ReadN) {
270 if (Diags)
271 Diags->Report(diag::err_pch_targetopt_feature_mismatch)
272 << false << ReadFeatures[ReadIdx];
273 return true;
274 }
275
276 return false;
277}
278
279bool
280PCHValidator::ReadLanguageOptions(const LangOptions &LangOpts,
281 bool Complain) {
282 const LangOptions &ExistingLangOpts = PP.getLangOpts();
283 return checkLanguageOptions(LangOpts, ExistingLangOpts,
Craig Toppera13603a2014-05-22 05:54:18 +0000284 Complain? &Reader.Diags : nullptr);
Guy Benyei11169dd2012-12-18 14:30:41 +0000285}
286
287bool PCHValidator::ReadTargetOptions(const TargetOptions &TargetOpts,
288 bool Complain) {
289 const TargetOptions &ExistingTargetOpts = PP.getTargetInfo().getTargetOpts();
290 return checkTargetOptions(TargetOpts, ExistingTargetOpts,
Craig Toppera13603a2014-05-22 05:54:18 +0000291 Complain? &Reader.Diags : nullptr);
Guy Benyei11169dd2012-12-18 14:30:41 +0000292}
293
294namespace {
295 typedef llvm::StringMap<std::pair<StringRef, bool /*IsUndef*/> >
296 MacroDefinitionsMap;
Craig Topper3598eb72013-07-05 04:43:31 +0000297 typedef llvm::DenseMap<DeclarationName, SmallVector<NamedDecl *, 8> >
298 DeclsMap;
Guy Benyei11169dd2012-12-18 14:30:41 +0000299}
300
Ben Langmuirb92de022014-04-29 16:25:26 +0000301static bool checkDiagnosticGroupMappings(DiagnosticsEngine &StoredDiags,
302 DiagnosticsEngine &Diags,
303 bool Complain) {
304 typedef DiagnosticsEngine::Level Level;
305
306 // Check current mappings for new -Werror mappings, and the stored mappings
307 // for cases that were explicitly mapped to *not* be errors that are now
308 // errors because of options like -Werror.
309 DiagnosticsEngine *MappingSources[] = { &Diags, &StoredDiags };
310
311 for (DiagnosticsEngine *MappingSource : MappingSources) {
312 for (auto DiagIDMappingPair : MappingSource->getDiagnosticMappings()) {
313 diag::kind DiagID = DiagIDMappingPair.first;
314 Level CurLevel = Diags.getDiagnosticLevel(DiagID, SourceLocation());
315 if (CurLevel < DiagnosticsEngine::Error)
316 continue; // not significant
317 Level StoredLevel =
318 StoredDiags.getDiagnosticLevel(DiagID, SourceLocation());
319 if (StoredLevel < DiagnosticsEngine::Error) {
320 if (Complain)
321 Diags.Report(diag::err_pch_diagopt_mismatch) << "-Werror=" +
322 Diags.getDiagnosticIDs()->getWarningOptionForDiag(DiagID).str();
323 return true;
324 }
325 }
326 }
327
328 return false;
329}
330
Alp Tokerac4e8e52014-06-22 21:58:33 +0000331static bool isExtHandlingFromDiagsError(DiagnosticsEngine &Diags) {
332 diag::Severity Ext = Diags.getExtensionHandlingBehavior();
333 if (Ext == diag::Severity::Warning && Diags.getWarningsAsErrors())
334 return true;
335 return Ext >= diag::Severity::Error;
Ben Langmuirb92de022014-04-29 16:25:26 +0000336}
337
338static bool checkDiagnosticMappings(DiagnosticsEngine &StoredDiags,
339 DiagnosticsEngine &Diags,
340 bool IsSystem, bool Complain) {
341 // Top-level options
342 if (IsSystem) {
343 if (Diags.getSuppressSystemWarnings())
344 return false;
345 // If -Wsystem-headers was not enabled before, be conservative
346 if (StoredDiags.getSuppressSystemWarnings()) {
347 if (Complain)
348 Diags.Report(diag::err_pch_diagopt_mismatch) << "-Wsystem-headers";
349 return true;
350 }
351 }
352
353 if (Diags.getWarningsAsErrors() && !StoredDiags.getWarningsAsErrors()) {
354 if (Complain)
355 Diags.Report(diag::err_pch_diagopt_mismatch) << "-Werror";
356 return true;
357 }
358
359 if (Diags.getWarningsAsErrors() && Diags.getEnableAllWarnings() &&
360 !StoredDiags.getEnableAllWarnings()) {
361 if (Complain)
362 Diags.Report(diag::err_pch_diagopt_mismatch) << "-Weverything -Werror";
363 return true;
364 }
365
366 if (isExtHandlingFromDiagsError(Diags) &&
367 !isExtHandlingFromDiagsError(StoredDiags)) {
368 if (Complain)
369 Diags.Report(diag::err_pch_diagopt_mismatch) << "-pedantic-errors";
370 return true;
371 }
372
373 return checkDiagnosticGroupMappings(StoredDiags, Diags, Complain);
374}
375
376bool PCHValidator::ReadDiagnosticOptions(
377 IntrusiveRefCntPtr<DiagnosticOptions> DiagOpts, bool Complain) {
378 DiagnosticsEngine &ExistingDiags = PP.getDiagnostics();
379 IntrusiveRefCntPtr<DiagnosticIDs> DiagIDs(ExistingDiags.getDiagnosticIDs());
380 IntrusiveRefCntPtr<DiagnosticsEngine> Diags(
Alp Tokerf994cef2014-07-05 03:08:06 +0000381 new DiagnosticsEngine(DiagIDs, DiagOpts.get()));
Ben Langmuirb92de022014-04-29 16:25:26 +0000382 // This should never fail, because we would have processed these options
383 // before writing them to an ASTFile.
384 ProcessWarningOptions(*Diags, *DiagOpts, /*Report*/false);
385
386 ModuleManager &ModuleMgr = Reader.getModuleManager();
387 assert(ModuleMgr.size() >= 1 && "what ASTFile is this then");
388
389 // If the original import came from a file explicitly generated by the user,
390 // don't check the diagnostic mappings.
391 // FIXME: currently this is approximated by checking whether this is not a
Richard Smithe842a472014-10-22 02:05:46 +0000392 // module import of an implicitly-loaded module file.
Ben Langmuirb92de022014-04-29 16:25:26 +0000393 // Note: ModuleMgr.rbegin() may not be the current module, but it must be in
394 // the transitive closure of its imports, since unrelated modules cannot be
395 // imported until after this module finishes validation.
396 ModuleFile *TopImport = *ModuleMgr.rbegin();
397 while (!TopImport->ImportedBy.empty())
398 TopImport = TopImport->ImportedBy[0];
Richard Smithe842a472014-10-22 02:05:46 +0000399 if (TopImport->Kind != MK_ImplicitModule)
Ben Langmuirb92de022014-04-29 16:25:26 +0000400 return false;
401
402 StringRef ModuleName = TopImport->ModuleName;
403 assert(!ModuleName.empty() && "diagnostic options read before module name");
404
405 Module *M = PP.getHeaderSearchInfo().lookupModule(ModuleName);
406 assert(M && "missing module");
407
408 // FIXME: if the diagnostics are incompatible, save a DiagnosticOptions that
409 // contains the union of their flags.
410 return checkDiagnosticMappings(*Diags, ExistingDiags, M->IsSystem, Complain);
411}
412
Guy Benyei11169dd2012-12-18 14:30:41 +0000413/// \brief Collect the macro definitions provided by the given preprocessor
414/// options.
Craig Toppera13603a2014-05-22 05:54:18 +0000415static void
416collectMacroDefinitions(const PreprocessorOptions &PPOpts,
417 MacroDefinitionsMap &Macros,
418 SmallVectorImpl<StringRef> *MacroNames = nullptr) {
Guy Benyei11169dd2012-12-18 14:30:41 +0000419 for (unsigned I = 0, N = PPOpts.Macros.size(); I != N; ++I) {
420 StringRef Macro = PPOpts.Macros[I].first;
421 bool IsUndef = PPOpts.Macros[I].second;
422
423 std::pair<StringRef, StringRef> MacroPair = Macro.split('=');
424 StringRef MacroName = MacroPair.first;
425 StringRef MacroBody = MacroPair.second;
426
427 // For an #undef'd macro, we only care about the name.
428 if (IsUndef) {
429 if (MacroNames && !Macros.count(MacroName))
430 MacroNames->push_back(MacroName);
431
432 Macros[MacroName] = std::make_pair("", true);
433 continue;
434 }
435
436 // For a #define'd macro, figure out the actual definition.
437 if (MacroName.size() == Macro.size())
438 MacroBody = "1";
439 else {
440 // Note: GCC drops anything following an end-of-line character.
441 StringRef::size_type End = MacroBody.find_first_of("\n\r");
442 MacroBody = MacroBody.substr(0, End);
443 }
444
445 if (MacroNames && !Macros.count(MacroName))
446 MacroNames->push_back(MacroName);
447 Macros[MacroName] = std::make_pair(MacroBody, false);
448 }
449}
450
451/// \brief Check the preprocessor options deserialized from the control block
452/// against the preprocessor options in an existing preprocessor.
453///
454/// \param Diags If non-null, produce diagnostics for any mismatches incurred.
455static bool checkPreprocessorOptions(const PreprocessorOptions &PPOpts,
456 const PreprocessorOptions &ExistingPPOpts,
457 DiagnosticsEngine *Diags,
458 FileManager &FileMgr,
Argyrios Kyrtzidisd3afa0c2013-04-26 21:33:40 +0000459 std::string &SuggestedPredefines,
460 const LangOptions &LangOpts) {
Guy Benyei11169dd2012-12-18 14:30:41 +0000461 // Check macro definitions.
462 MacroDefinitionsMap ASTFileMacros;
463 collectMacroDefinitions(PPOpts, ASTFileMacros);
464 MacroDefinitionsMap ExistingMacros;
465 SmallVector<StringRef, 4> ExistingMacroNames;
466 collectMacroDefinitions(ExistingPPOpts, ExistingMacros, &ExistingMacroNames);
467
468 for (unsigned I = 0, N = ExistingMacroNames.size(); I != N; ++I) {
469 // Dig out the macro definition in the existing preprocessor options.
470 StringRef MacroName = ExistingMacroNames[I];
471 std::pair<StringRef, bool> Existing = ExistingMacros[MacroName];
472
473 // Check whether we know anything about this macro name or not.
474 llvm::StringMap<std::pair<StringRef, bool /*IsUndef*/> >::iterator Known
475 = ASTFileMacros.find(MacroName);
476 if (Known == ASTFileMacros.end()) {
477 // FIXME: Check whether this identifier was referenced anywhere in the
478 // AST file. If so, we should reject the AST file. Unfortunately, this
479 // information isn't in the control block. What shall we do about it?
480
481 if (Existing.second) {
482 SuggestedPredefines += "#undef ";
483 SuggestedPredefines += MacroName.str();
484 SuggestedPredefines += '\n';
485 } else {
486 SuggestedPredefines += "#define ";
487 SuggestedPredefines += MacroName.str();
488 SuggestedPredefines += ' ';
489 SuggestedPredefines += Existing.first.str();
490 SuggestedPredefines += '\n';
491 }
492 continue;
493 }
494
495 // If the macro was defined in one but undef'd in the other, we have a
496 // conflict.
497 if (Existing.second != Known->second.second) {
498 if (Diags) {
499 Diags->Report(diag::err_pch_macro_def_undef)
500 << MacroName << Known->second.second;
501 }
502 return true;
503 }
504
505 // If the macro was #undef'd in both, or if the macro bodies are identical,
506 // it's fine.
507 if (Existing.second || Existing.first == Known->second.first)
508 continue;
509
510 // The macro bodies differ; complain.
511 if (Diags) {
512 Diags->Report(diag::err_pch_macro_def_conflict)
513 << MacroName << Known->second.first << Existing.first;
514 }
515 return true;
516 }
517
518 // Check whether we're using predefines.
519 if (PPOpts.UsePredefines != ExistingPPOpts.UsePredefines) {
520 if (Diags) {
521 Diags->Report(diag::err_pch_undef) << ExistingPPOpts.UsePredefines;
522 }
523 return true;
524 }
525
Argyrios Kyrtzidisd3afa0c2013-04-26 21:33:40 +0000526 // Detailed record is important since it is used for the module cache hash.
527 if (LangOpts.Modules &&
528 PPOpts.DetailedRecord != ExistingPPOpts.DetailedRecord) {
529 if (Diags) {
530 Diags->Report(diag::err_pch_pp_detailed_record) << PPOpts.DetailedRecord;
531 }
532 return true;
533 }
534
Guy Benyei11169dd2012-12-18 14:30:41 +0000535 // Compute the #include and #include_macros lines we need.
536 for (unsigned I = 0, N = ExistingPPOpts.Includes.size(); I != N; ++I) {
537 StringRef File = ExistingPPOpts.Includes[I];
538 if (File == ExistingPPOpts.ImplicitPCHInclude)
539 continue;
540
541 if (std::find(PPOpts.Includes.begin(), PPOpts.Includes.end(), File)
542 != PPOpts.Includes.end())
543 continue;
544
545 SuggestedPredefines += "#include \"";
Manuel Klimek9af34ae2014-08-12 08:25:57 +0000546 SuggestedPredefines += File;
Guy Benyei11169dd2012-12-18 14:30:41 +0000547 SuggestedPredefines += "\"\n";
548 }
549
550 for (unsigned I = 0, N = ExistingPPOpts.MacroIncludes.size(); I != N; ++I) {
551 StringRef File = ExistingPPOpts.MacroIncludes[I];
552 if (std::find(PPOpts.MacroIncludes.begin(), PPOpts.MacroIncludes.end(),
553 File)
554 != PPOpts.MacroIncludes.end())
555 continue;
556
557 SuggestedPredefines += "#__include_macros \"";
Manuel Klimek9af34ae2014-08-12 08:25:57 +0000558 SuggestedPredefines += File;
Guy Benyei11169dd2012-12-18 14:30:41 +0000559 SuggestedPredefines += "\"\n##\n";
560 }
561
562 return false;
563}
564
565bool PCHValidator::ReadPreprocessorOptions(const PreprocessorOptions &PPOpts,
566 bool Complain,
567 std::string &SuggestedPredefines) {
568 const PreprocessorOptions &ExistingPPOpts = PP.getPreprocessorOpts();
569
570 return checkPreprocessorOptions(PPOpts, ExistingPPOpts,
Craig Toppera13603a2014-05-22 05:54:18 +0000571 Complain? &Reader.Diags : nullptr,
Guy Benyei11169dd2012-12-18 14:30:41 +0000572 PP.getFileManager(),
Argyrios Kyrtzidisd3afa0c2013-04-26 21:33:40 +0000573 SuggestedPredefines,
574 PP.getLangOpts());
Guy Benyei11169dd2012-12-18 14:30:41 +0000575}
576
Guy Benyei11169dd2012-12-18 14:30:41 +0000577void PCHValidator::ReadCounter(const ModuleFile &M, unsigned Value) {
578 PP.setCounterValue(Value);
579}
580
581//===----------------------------------------------------------------------===//
582// AST reader implementation
583//===----------------------------------------------------------------------===//
584
Nico Weber824285e2014-05-08 04:26:47 +0000585void ASTReader::setDeserializationListener(ASTDeserializationListener *Listener,
586 bool TakeOwnership) {
Guy Benyei11169dd2012-12-18 14:30:41 +0000587 DeserializationListener = Listener;
Nico Weber824285e2014-05-08 04:26:47 +0000588 OwnsDeserializationListener = TakeOwnership;
Guy Benyei11169dd2012-12-18 14:30:41 +0000589}
590
591
592
593unsigned ASTSelectorLookupTrait::ComputeHash(Selector Sel) {
594 return serialization::ComputeHash(Sel);
595}
596
597
598std::pair<unsigned, unsigned>
599ASTSelectorLookupTrait::ReadKeyDataLength(const unsigned char*& d) {
Justin Bogner57ba0b22014-03-28 22:03:24 +0000600 using namespace llvm::support;
601 unsigned KeyLen = endian::readNext<uint16_t, little, unaligned>(d);
602 unsigned DataLen = endian::readNext<uint16_t, little, unaligned>(d);
Guy Benyei11169dd2012-12-18 14:30:41 +0000603 return std::make_pair(KeyLen, DataLen);
604}
605
606ASTSelectorLookupTrait::internal_key_type
607ASTSelectorLookupTrait::ReadKey(const unsigned char* d, unsigned) {
Justin Bogner57ba0b22014-03-28 22:03:24 +0000608 using namespace llvm::support;
Guy Benyei11169dd2012-12-18 14:30:41 +0000609 SelectorTable &SelTable = Reader.getContext().Selectors;
Justin Bogner57ba0b22014-03-28 22:03:24 +0000610 unsigned N = endian::readNext<uint16_t, little, unaligned>(d);
611 IdentifierInfo *FirstII = Reader.getLocalIdentifier(
612 F, endian::readNext<uint32_t, little, unaligned>(d));
Guy Benyei11169dd2012-12-18 14:30:41 +0000613 if (N == 0)
614 return SelTable.getNullarySelector(FirstII);
615 else if (N == 1)
616 return SelTable.getUnarySelector(FirstII);
617
618 SmallVector<IdentifierInfo *, 16> Args;
619 Args.push_back(FirstII);
620 for (unsigned I = 1; I != N; ++I)
Justin Bogner57ba0b22014-03-28 22:03:24 +0000621 Args.push_back(Reader.getLocalIdentifier(
622 F, endian::readNext<uint32_t, little, unaligned>(d)));
Guy Benyei11169dd2012-12-18 14:30:41 +0000623
624 return SelTable.getSelector(N, Args.data());
625}
626
627ASTSelectorLookupTrait::data_type
628ASTSelectorLookupTrait::ReadData(Selector, const unsigned char* d,
629 unsigned DataLen) {
Justin Bogner57ba0b22014-03-28 22:03:24 +0000630 using namespace llvm::support;
Guy Benyei11169dd2012-12-18 14:30:41 +0000631
632 data_type Result;
633
Justin Bogner57ba0b22014-03-28 22:03:24 +0000634 Result.ID = Reader.getGlobalSelectorID(
635 F, endian::readNext<uint32_t, little, unaligned>(d));
636 unsigned NumInstanceMethodsAndBits =
637 endian::readNext<uint16_t, little, unaligned>(d);
638 unsigned NumFactoryMethodsAndBits =
639 endian::readNext<uint16_t, little, unaligned>(d);
Argyrios Kyrtzidisd3da6e02013-04-17 00:08:58 +0000640 Result.InstanceBits = NumInstanceMethodsAndBits & 0x3;
641 Result.FactoryBits = NumFactoryMethodsAndBits & 0x3;
642 unsigned NumInstanceMethods = NumInstanceMethodsAndBits >> 2;
643 unsigned NumFactoryMethods = NumFactoryMethodsAndBits >> 2;
Guy Benyei11169dd2012-12-18 14:30:41 +0000644
645 // Load instance methods
646 for (unsigned I = 0; I != NumInstanceMethods; ++I) {
Justin Bogner57ba0b22014-03-28 22:03:24 +0000647 if (ObjCMethodDecl *Method = Reader.GetLocalDeclAs<ObjCMethodDecl>(
648 F, endian::readNext<uint32_t, little, unaligned>(d)))
Guy Benyei11169dd2012-12-18 14:30:41 +0000649 Result.Instance.push_back(Method);
650 }
651
652 // Load factory methods
653 for (unsigned I = 0; I != NumFactoryMethods; ++I) {
Justin Bogner57ba0b22014-03-28 22:03:24 +0000654 if (ObjCMethodDecl *Method = Reader.GetLocalDeclAs<ObjCMethodDecl>(
655 F, endian::readNext<uint32_t, little, unaligned>(d)))
Guy Benyei11169dd2012-12-18 14:30:41 +0000656 Result.Factory.push_back(Method);
657 }
658
659 return Result;
660}
661
Douglas Gregorbfd73d72013-01-23 18:53:14 +0000662unsigned ASTIdentifierLookupTraitBase::ComputeHash(const internal_key_type& a) {
663 return llvm::HashString(a);
Guy Benyei11169dd2012-12-18 14:30:41 +0000664}
665
666std::pair<unsigned, unsigned>
Douglas Gregorbfd73d72013-01-23 18:53:14 +0000667ASTIdentifierLookupTraitBase::ReadKeyDataLength(const unsigned char*& d) {
Justin Bogner57ba0b22014-03-28 22:03:24 +0000668 using namespace llvm::support;
669 unsigned DataLen = endian::readNext<uint16_t, little, unaligned>(d);
670 unsigned KeyLen = endian::readNext<uint16_t, little, unaligned>(d);
Guy Benyei11169dd2012-12-18 14:30:41 +0000671 return std::make_pair(KeyLen, DataLen);
672}
673
Douglas Gregorbfd73d72013-01-23 18:53:14 +0000674ASTIdentifierLookupTraitBase::internal_key_type
675ASTIdentifierLookupTraitBase::ReadKey(const unsigned char* d, unsigned n) {
Guy Benyei11169dd2012-12-18 14:30:41 +0000676 assert(n >= 2 && d[n-1] == '\0');
Douglas Gregorbfd73d72013-01-23 18:53:14 +0000677 return StringRef((const char*) d, n-1);
Guy Benyei11169dd2012-12-18 14:30:41 +0000678}
679
Douglas Gregordcf25082013-02-11 18:16:18 +0000680/// \brief Whether the given identifier is "interesting".
681static bool isInterestingIdentifier(IdentifierInfo &II) {
682 return II.isPoisoned() ||
683 II.isExtensionToken() ||
684 II.getObjCOrBuiltinID() ||
685 II.hasRevertedTokenIDToIdentifier() ||
686 II.hadMacroDefinition() ||
687 II.getFETokenInfo<void>();
688}
689
Guy Benyei11169dd2012-12-18 14:30:41 +0000690IdentifierInfo *ASTIdentifierLookupTrait::ReadData(const internal_key_type& k,
691 const unsigned char* d,
692 unsigned DataLen) {
Justin Bogner57ba0b22014-03-28 22:03:24 +0000693 using namespace llvm::support;
694 unsigned RawID = endian::readNext<uint32_t, little, unaligned>(d);
Guy Benyei11169dd2012-12-18 14:30:41 +0000695 bool IsInteresting = RawID & 0x01;
696
697 // Wipe out the "is interesting" bit.
698 RawID = RawID >> 1;
699
700 IdentID ID = Reader.getGlobalIdentifierID(F, RawID);
701 if (!IsInteresting) {
702 // For uninteresting identifiers, just build the IdentifierInfo
703 // and associate it with the persistent ID.
704 IdentifierInfo *II = KnownII;
705 if (!II) {
Douglas Gregorbfd73d72013-01-23 18:53:14 +0000706 II = &Reader.getIdentifierTable().getOwn(k);
Guy Benyei11169dd2012-12-18 14:30:41 +0000707 KnownII = II;
708 }
709 Reader.SetIdentifierInfo(ID, II);
Douglas Gregordcf25082013-02-11 18:16:18 +0000710 if (!II->isFromAST()) {
711 bool WasInteresting = isInterestingIdentifier(*II);
712 II->setIsFromAST();
713 if (WasInteresting)
714 II->setChangedSinceDeserialization();
715 }
716 Reader.markIdentifierUpToDate(II);
Guy Benyei11169dd2012-12-18 14:30:41 +0000717 return II;
718 }
719
Justin Bogner57ba0b22014-03-28 22:03:24 +0000720 unsigned ObjCOrBuiltinID = endian::readNext<uint16_t, little, unaligned>(d);
721 unsigned Bits = endian::readNext<uint16_t, little, unaligned>(d);
Guy Benyei11169dd2012-12-18 14:30:41 +0000722 bool CPlusPlusOperatorKeyword = Bits & 0x01;
723 Bits >>= 1;
724 bool HasRevertedTokenIDToIdentifier = Bits & 0x01;
725 Bits >>= 1;
726 bool Poisoned = Bits & 0x01;
727 Bits >>= 1;
728 bool ExtensionToken = Bits & 0x01;
729 Bits >>= 1;
Argyrios Kyrtzidiseb663da2013-03-22 21:12:57 +0000730 bool hasSubmoduleMacros = Bits & 0x01;
731 Bits >>= 1;
Guy Benyei11169dd2012-12-18 14:30:41 +0000732 bool hadMacroDefinition = Bits & 0x01;
733 Bits >>= 1;
734
735 assert(Bits == 0 && "Extra bits in the identifier?");
736 DataLen -= 8;
737
738 // Build the IdentifierInfo itself and link the identifier ID with
739 // the new IdentifierInfo.
740 IdentifierInfo *II = KnownII;
741 if (!II) {
Douglas Gregorbfd73d72013-01-23 18:53:14 +0000742 II = &Reader.getIdentifierTable().getOwn(StringRef(k));
Guy Benyei11169dd2012-12-18 14:30:41 +0000743 KnownII = II;
744 }
745 Reader.markIdentifierUpToDate(II);
Douglas Gregordcf25082013-02-11 18:16:18 +0000746 if (!II->isFromAST()) {
747 bool WasInteresting = isInterestingIdentifier(*II);
748 II->setIsFromAST();
749 if (WasInteresting)
750 II->setChangedSinceDeserialization();
751 }
Guy Benyei11169dd2012-12-18 14:30:41 +0000752
753 // Set or check the various bits in the IdentifierInfo structure.
754 // Token IDs are read-only.
Argyrios Kyrtzidisddee8c92013-02-27 01:13:51 +0000755 if (HasRevertedTokenIDToIdentifier && II->getTokenID() != tok::identifier)
Guy Benyei11169dd2012-12-18 14:30:41 +0000756 II->RevertTokenIDToIdentifier();
757 II->setObjCOrBuiltinID(ObjCOrBuiltinID);
758 assert(II->isExtensionToken() == ExtensionToken &&
759 "Incorrect extension token flag");
760 (void)ExtensionToken;
761 if (Poisoned)
762 II->setIsPoisoned(true);
763 assert(II->isCPlusPlusOperatorKeyword() == CPlusPlusOperatorKeyword &&
764 "Incorrect C++ operator keyword flag");
765 (void)CPlusPlusOperatorKeyword;
766
767 // If this identifier is a macro, deserialize the macro
768 // definition.
769 if (hadMacroDefinition) {
Justin Bogner57ba0b22014-03-28 22:03:24 +0000770 uint32_t MacroDirectivesOffset =
771 endian::readNext<uint32_t, little, unaligned>(d);
Argyrios Kyrtzidiseb663da2013-03-22 21:12:57 +0000772 DataLen -= 4;
773 SmallVector<uint32_t, 8> LocalMacroIDs;
774 if (hasSubmoduleMacros) {
Richard Smithdaa69e02014-07-25 04:40:03 +0000775 while (true) {
776 uint32_t LocalMacroID =
777 endian::readNext<uint32_t, little, unaligned>(d);
Argyrios Kyrtzidiseb663da2013-03-22 21:12:57 +0000778 DataLen -= 4;
Richard Smithdaa69e02014-07-25 04:40:03 +0000779 if (LocalMacroID == 0xdeadbeef) break;
Argyrios Kyrtzidiseb663da2013-03-22 21:12:57 +0000780 LocalMacroIDs.push_back(LocalMacroID);
781 }
Argyrios Kyrtzidis719736c2013-01-19 03:14:56 +0000782 }
Argyrios Kyrtzidiseb663da2013-03-22 21:12:57 +0000783
Richard Smithe842a472014-10-22 02:05:46 +0000784 if (F.Kind == MK_ImplicitModule || F.Kind == MK_ExplicitModule) {
Richard Smith49f906a2014-03-01 00:08:04 +0000785 // Macro definitions are stored from newest to oldest, so reverse them
786 // before registering them.
787 llvm::SmallVector<unsigned, 8> MacroSizes;
Argyrios Kyrtzidiseb663da2013-03-22 21:12:57 +0000788 for (SmallVectorImpl<uint32_t>::iterator
Richard Smith49f906a2014-03-01 00:08:04 +0000789 I = LocalMacroIDs.begin(), E = LocalMacroIDs.end(); I != E; /**/) {
790 unsigned Size = 1;
791
792 static const uint32_t HasOverridesFlag = 0x80000000U;
793 if (I + 1 != E && (I[1] & HasOverridesFlag))
794 Size += 1 + (I[1] & ~HasOverridesFlag);
795
796 MacroSizes.push_back(Size);
797 I += Size;
Argyrios Kyrtzidiseb663da2013-03-22 21:12:57 +0000798 }
Richard Smith49f906a2014-03-01 00:08:04 +0000799
800 SmallVectorImpl<uint32_t>::iterator I = LocalMacroIDs.end();
801 for (SmallVectorImpl<unsigned>::reverse_iterator SI = MacroSizes.rbegin(),
802 SE = MacroSizes.rend();
803 SI != SE; ++SI) {
804 I -= *SI;
805
806 uint32_t LocalMacroID = *I;
Craig Topper00bbdcf2014-06-28 23:22:23 +0000807 ArrayRef<uint32_t> Overrides;
Richard Smith49f906a2014-03-01 00:08:04 +0000808 if (*SI != 1)
809 Overrides = llvm::makeArrayRef(&I[2], *SI - 2);
810 Reader.addPendingMacroFromModule(II, &F, LocalMacroID, Overrides);
811 }
812 assert(I == LocalMacroIDs.begin());
Argyrios Kyrtzidiseb663da2013-03-22 21:12:57 +0000813 } else {
814 Reader.addPendingMacroFromPCH(II, &F, MacroDirectivesOffset);
815 }
Guy Benyei11169dd2012-12-18 14:30:41 +0000816 }
817
818 Reader.SetIdentifierInfo(ID, II);
819
820 // Read all of the declarations visible at global scope with this
821 // name.
822 if (DataLen > 0) {
823 SmallVector<uint32_t, 4> DeclIDs;
824 for (; DataLen > 0; DataLen -= 4)
Justin Bogner57ba0b22014-03-28 22:03:24 +0000825 DeclIDs.push_back(Reader.getGlobalDeclID(
826 F, endian::readNext<uint32_t, little, unaligned>(d)));
Guy Benyei11169dd2012-12-18 14:30:41 +0000827 Reader.SetGloballyVisibleDecls(II, DeclIDs);
828 }
829
830 return II;
831}
832
833unsigned
834ASTDeclContextNameLookupTrait::ComputeHash(const DeclNameKey &Key) const {
835 llvm::FoldingSetNodeID ID;
836 ID.AddInteger(Key.Kind);
837
838 switch (Key.Kind) {
839 case DeclarationName::Identifier:
840 case DeclarationName::CXXLiteralOperatorName:
841 ID.AddString(((IdentifierInfo*)Key.Data)->getName());
842 break;
843 case DeclarationName::ObjCZeroArgSelector:
844 case DeclarationName::ObjCOneArgSelector:
845 case DeclarationName::ObjCMultiArgSelector:
846 ID.AddInteger(serialization::ComputeHash(Selector(Key.Data)));
847 break;
848 case DeclarationName::CXXOperatorName:
849 ID.AddInteger((OverloadedOperatorKind)Key.Data);
850 break;
851 case DeclarationName::CXXConstructorName:
852 case DeclarationName::CXXDestructorName:
853 case DeclarationName::CXXConversionFunctionName:
854 case DeclarationName::CXXUsingDirective:
855 break;
856 }
857
858 return ID.ComputeHash();
859}
860
861ASTDeclContextNameLookupTrait::internal_key_type
862ASTDeclContextNameLookupTrait::GetInternalKey(
863 const external_key_type& Name) const {
864 DeclNameKey Key;
865 Key.Kind = Name.getNameKind();
866 switch (Name.getNameKind()) {
867 case DeclarationName::Identifier:
868 Key.Data = (uint64_t)Name.getAsIdentifierInfo();
869 break;
870 case DeclarationName::ObjCZeroArgSelector:
871 case DeclarationName::ObjCOneArgSelector:
872 case DeclarationName::ObjCMultiArgSelector:
873 Key.Data = (uint64_t)Name.getObjCSelector().getAsOpaquePtr();
874 break;
875 case DeclarationName::CXXOperatorName:
876 Key.Data = Name.getCXXOverloadedOperator();
877 break;
878 case DeclarationName::CXXLiteralOperatorName:
879 Key.Data = (uint64_t)Name.getCXXLiteralIdentifier();
880 break;
881 case DeclarationName::CXXConstructorName:
882 case DeclarationName::CXXDestructorName:
883 case DeclarationName::CXXConversionFunctionName:
884 case DeclarationName::CXXUsingDirective:
885 Key.Data = 0;
886 break;
887 }
888
889 return Key;
890}
891
892std::pair<unsigned, unsigned>
893ASTDeclContextNameLookupTrait::ReadKeyDataLength(const unsigned char*& d) {
Justin Bogner57ba0b22014-03-28 22:03:24 +0000894 using namespace llvm::support;
895 unsigned KeyLen = endian::readNext<uint16_t, little, unaligned>(d);
896 unsigned DataLen = endian::readNext<uint16_t, little, unaligned>(d);
Guy Benyei11169dd2012-12-18 14:30:41 +0000897 return std::make_pair(KeyLen, DataLen);
898}
899
900ASTDeclContextNameLookupTrait::internal_key_type
901ASTDeclContextNameLookupTrait::ReadKey(const unsigned char* d, unsigned) {
Justin Bogner57ba0b22014-03-28 22:03:24 +0000902 using namespace llvm::support;
Guy Benyei11169dd2012-12-18 14:30:41 +0000903
904 DeclNameKey Key;
905 Key.Kind = (DeclarationName::NameKind)*d++;
906 switch (Key.Kind) {
907 case DeclarationName::Identifier:
Justin Bogner57ba0b22014-03-28 22:03:24 +0000908 Key.Data = (uint64_t)Reader.getLocalIdentifier(
909 F, endian::readNext<uint32_t, little, unaligned>(d));
Guy Benyei11169dd2012-12-18 14:30:41 +0000910 break;
911 case DeclarationName::ObjCZeroArgSelector:
912 case DeclarationName::ObjCOneArgSelector:
913 case DeclarationName::ObjCMultiArgSelector:
914 Key.Data =
Justin Bogner57ba0b22014-03-28 22:03:24 +0000915 (uint64_t)Reader.getLocalSelector(
916 F, endian::readNext<uint32_t, little, unaligned>(
917 d)).getAsOpaquePtr();
Guy Benyei11169dd2012-12-18 14:30:41 +0000918 break;
919 case DeclarationName::CXXOperatorName:
920 Key.Data = *d++; // OverloadedOperatorKind
921 break;
922 case DeclarationName::CXXLiteralOperatorName:
Justin Bogner57ba0b22014-03-28 22:03:24 +0000923 Key.Data = (uint64_t)Reader.getLocalIdentifier(
924 F, endian::readNext<uint32_t, little, unaligned>(d));
Guy Benyei11169dd2012-12-18 14:30:41 +0000925 break;
926 case DeclarationName::CXXConstructorName:
927 case DeclarationName::CXXDestructorName:
928 case DeclarationName::CXXConversionFunctionName:
929 case DeclarationName::CXXUsingDirective:
930 Key.Data = 0;
931 break;
932 }
933
934 return Key;
935}
936
937ASTDeclContextNameLookupTrait::data_type
938ASTDeclContextNameLookupTrait::ReadData(internal_key_type,
939 const unsigned char* d,
940 unsigned DataLen) {
Justin Bogner57ba0b22014-03-28 22:03:24 +0000941 using namespace llvm::support;
942 unsigned NumDecls = endian::readNext<uint16_t, little, unaligned>(d);
Argyrios Kyrtzidisc57e5032013-01-11 22:29:49 +0000943 LE32DeclID *Start = reinterpret_cast<LE32DeclID *>(
944 const_cast<unsigned char *>(d));
Guy Benyei11169dd2012-12-18 14:30:41 +0000945 return std::make_pair(Start, Start + NumDecls);
946}
947
948bool ASTReader::ReadDeclContextStorage(ModuleFile &M,
Chris Lattner7fb3bef2013-01-20 00:56:42 +0000949 BitstreamCursor &Cursor,
Guy Benyei11169dd2012-12-18 14:30:41 +0000950 const std::pair<uint64_t, uint64_t> &Offsets,
951 DeclContextInfo &Info) {
952 SavedStreamPosition SavedPosition(Cursor);
953 // First the lexical decls.
954 if (Offsets.first != 0) {
955 Cursor.JumpToBit(Offsets.first);
956
957 RecordData Record;
Chris Lattner0e6c9402013-01-20 02:38:54 +0000958 StringRef Blob;
Guy Benyei11169dd2012-12-18 14:30:41 +0000959 unsigned Code = Cursor.ReadCode();
Chris Lattner0e6c9402013-01-20 02:38:54 +0000960 unsigned RecCode = Cursor.readRecord(Code, Record, &Blob);
Guy Benyei11169dd2012-12-18 14:30:41 +0000961 if (RecCode != DECL_CONTEXT_LEXICAL) {
962 Error("Expected lexical block");
963 return true;
964 }
965
Chris Lattner0e6c9402013-01-20 02:38:54 +0000966 Info.LexicalDecls = reinterpret_cast<const KindDeclIDPair*>(Blob.data());
967 Info.NumLexicalDecls = Blob.size() / sizeof(KindDeclIDPair);
Guy Benyei11169dd2012-12-18 14:30:41 +0000968 }
969
970 // Now the lookup table.
971 if (Offsets.second != 0) {
972 Cursor.JumpToBit(Offsets.second);
973
974 RecordData Record;
Chris Lattner0e6c9402013-01-20 02:38:54 +0000975 StringRef Blob;
Guy Benyei11169dd2012-12-18 14:30:41 +0000976 unsigned Code = Cursor.ReadCode();
Chris Lattner0e6c9402013-01-20 02:38:54 +0000977 unsigned RecCode = Cursor.readRecord(Code, Record, &Blob);
Guy Benyei11169dd2012-12-18 14:30:41 +0000978 if (RecCode != DECL_CONTEXT_VISIBLE) {
979 Error("Expected visible lookup table block");
980 return true;
981 }
Justin Bognerda4e6502014-04-14 16:34:29 +0000982 Info.NameLookupTableData = ASTDeclContextNameLookupTable::Create(
983 (const unsigned char *)Blob.data() + Record[0],
984 (const unsigned char *)Blob.data() + sizeof(uint32_t),
985 (const unsigned char *)Blob.data(),
986 ASTDeclContextNameLookupTrait(*this, M));
Guy Benyei11169dd2012-12-18 14:30:41 +0000987 }
988
989 return false;
990}
991
992void ASTReader::Error(StringRef Msg) {
993 Error(diag::err_fe_pch_malformed, Msg);
Douglas Gregor940e8052013-05-10 22:15:13 +0000994 if (Context.getLangOpts().Modules && !Diags.isDiagnosticInFlight()) {
995 Diag(diag::note_module_cache_path)
996 << PP.getHeaderSearchInfo().getModuleCachePath();
997 }
Guy Benyei11169dd2012-12-18 14:30:41 +0000998}
999
1000void ASTReader::Error(unsigned DiagID,
1001 StringRef Arg1, StringRef Arg2) {
1002 if (Diags.isDiagnosticInFlight())
1003 Diags.SetDelayedDiagnostic(DiagID, Arg1, Arg2);
1004 else
1005 Diag(DiagID) << Arg1 << Arg2;
1006}
1007
1008//===----------------------------------------------------------------------===//
1009// Source Manager Deserialization
1010//===----------------------------------------------------------------------===//
1011
1012/// \brief Read the line table in the source manager block.
1013/// \returns true if there was an error.
1014bool ASTReader::ParseLineTable(ModuleFile &F,
1015 SmallVectorImpl<uint64_t> &Record) {
1016 unsigned Idx = 0;
1017 LineTableInfo &LineTable = SourceMgr.getLineTable();
1018
1019 // Parse the file names
1020 std::map<int, int> FileIDs;
1021 for (int I = 0, N = Record[Idx++]; I != N; ++I) {
1022 // Extract the file name
1023 unsigned FilenameLen = Record[Idx++];
1024 std::string Filename(&Record[Idx], &Record[Idx] + FilenameLen);
1025 Idx += FilenameLen;
1026 MaybeAddSystemRootToFilename(F, Filename);
1027 FileIDs[I] = LineTable.getLineTableFilenameID(Filename);
1028 }
1029
1030 // Parse the line entries
1031 std::vector<LineEntry> Entries;
1032 while (Idx < Record.size()) {
1033 int FID = Record[Idx++];
1034 assert(FID >= 0 && "Serialized line entries for non-local file.");
1035 // Remap FileID from 1-based old view.
1036 FID += F.SLocEntryBaseID - 1;
1037
1038 // Extract the line entries
1039 unsigned NumEntries = Record[Idx++];
1040 assert(NumEntries && "Numentries is 00000");
1041 Entries.clear();
1042 Entries.reserve(NumEntries);
1043 for (unsigned I = 0; I != NumEntries; ++I) {
1044 unsigned FileOffset = Record[Idx++];
1045 unsigned LineNo = Record[Idx++];
1046 int FilenameID = FileIDs[Record[Idx++]];
1047 SrcMgr::CharacteristicKind FileKind
1048 = (SrcMgr::CharacteristicKind)Record[Idx++];
1049 unsigned IncludeOffset = Record[Idx++];
1050 Entries.push_back(LineEntry::get(FileOffset, LineNo, FilenameID,
1051 FileKind, IncludeOffset));
1052 }
1053 LineTable.AddEntry(FileID::get(FID), Entries);
1054 }
1055
1056 return false;
1057}
1058
1059/// \brief Read a source manager block
1060bool ASTReader::ReadSourceManagerBlock(ModuleFile &F) {
1061 using namespace SrcMgr;
1062
Chris Lattner7fb3bef2013-01-20 00:56:42 +00001063 BitstreamCursor &SLocEntryCursor = F.SLocEntryCursor;
Guy Benyei11169dd2012-12-18 14:30:41 +00001064
1065 // Set the source-location entry cursor to the current position in
1066 // the stream. This cursor will be used to read the contents of the
1067 // source manager block initially, and then lazily read
1068 // source-location entries as needed.
1069 SLocEntryCursor = F.Stream;
1070
1071 // The stream itself is going to skip over the source manager block.
1072 if (F.Stream.SkipBlock()) {
1073 Error("malformed block record in AST file");
1074 return true;
1075 }
1076
1077 // Enter the source manager block.
1078 if (SLocEntryCursor.EnterSubBlock(SOURCE_MANAGER_BLOCK_ID)) {
1079 Error("malformed source manager block record in AST file");
1080 return true;
1081 }
1082
1083 RecordData Record;
1084 while (true) {
Chris Lattnere7b154b2013-01-19 21:39:22 +00001085 llvm::BitstreamEntry E = SLocEntryCursor.advanceSkippingSubblocks();
1086
1087 switch (E.Kind) {
1088 case llvm::BitstreamEntry::SubBlock: // Handled for us already.
1089 case llvm::BitstreamEntry::Error:
1090 Error("malformed block record in AST file");
1091 return true;
1092 case llvm::BitstreamEntry::EndBlock:
Guy Benyei11169dd2012-12-18 14:30:41 +00001093 return false;
Chris Lattnere7b154b2013-01-19 21:39:22 +00001094 case llvm::BitstreamEntry::Record:
1095 // The interesting case.
1096 break;
Guy Benyei11169dd2012-12-18 14:30:41 +00001097 }
Chris Lattnere7b154b2013-01-19 21:39:22 +00001098
Guy Benyei11169dd2012-12-18 14:30:41 +00001099 // Read a record.
Guy Benyei11169dd2012-12-18 14:30:41 +00001100 Record.clear();
Chris Lattner15c3e7d2013-01-21 18:28:26 +00001101 StringRef Blob;
1102 switch (SLocEntryCursor.readRecord(E.ID, Record, &Blob)) {
Guy Benyei11169dd2012-12-18 14:30:41 +00001103 default: // Default behavior: ignore.
1104 break;
1105
1106 case SM_SLOC_FILE_ENTRY:
1107 case SM_SLOC_BUFFER_ENTRY:
1108 case SM_SLOC_EXPANSION_ENTRY:
1109 // Once we hit one of the source location entries, we're done.
1110 return false;
1111 }
1112 }
1113}
1114
1115/// \brief If a header file is not found at the path that we expect it to be
1116/// and the PCH file was moved from its original location, try to resolve the
1117/// file by assuming that header+PCH were moved together and the header is in
1118/// the same place relative to the PCH.
1119static std::string
1120resolveFileRelativeToOriginalDir(const std::string &Filename,
1121 const std::string &OriginalDir,
1122 const std::string &CurrDir) {
1123 assert(OriginalDir != CurrDir &&
1124 "No point trying to resolve the file if the PCH dir didn't change");
1125 using namespace llvm::sys;
1126 SmallString<128> filePath(Filename);
1127 fs::make_absolute(filePath);
1128 assert(path::is_absolute(OriginalDir));
1129 SmallString<128> currPCHPath(CurrDir);
1130
1131 path::const_iterator fileDirI = path::begin(path::parent_path(filePath)),
1132 fileDirE = path::end(path::parent_path(filePath));
1133 path::const_iterator origDirI = path::begin(OriginalDir),
1134 origDirE = path::end(OriginalDir);
1135 // Skip the common path components from filePath and OriginalDir.
1136 while (fileDirI != fileDirE && origDirI != origDirE &&
1137 *fileDirI == *origDirI) {
1138 ++fileDirI;
1139 ++origDirI;
1140 }
1141 for (; origDirI != origDirE; ++origDirI)
1142 path::append(currPCHPath, "..");
1143 path::append(currPCHPath, fileDirI, fileDirE);
1144 path::append(currPCHPath, path::filename(Filename));
1145 return currPCHPath.str();
1146}
1147
1148bool ASTReader::ReadSLocEntry(int ID) {
1149 if (ID == 0)
1150 return false;
1151
1152 if (unsigned(-ID) - 2 >= getTotalNumSLocs() || ID > 0) {
1153 Error("source location entry ID out-of-range for AST file");
1154 return true;
1155 }
1156
1157 ModuleFile *F = GlobalSLocEntryMap.find(-ID)->second;
1158 F->SLocEntryCursor.JumpToBit(F->SLocEntryOffsets[ID - F->SLocEntryBaseID]);
Chris Lattner7fb3bef2013-01-20 00:56:42 +00001159 BitstreamCursor &SLocEntryCursor = F->SLocEntryCursor;
Guy Benyei11169dd2012-12-18 14:30:41 +00001160 unsigned BaseOffset = F->SLocEntryBaseOffset;
1161
1162 ++NumSLocEntriesRead;
Chris Lattnere7b154b2013-01-19 21:39:22 +00001163 llvm::BitstreamEntry Entry = SLocEntryCursor.advance();
1164 if (Entry.Kind != llvm::BitstreamEntry::Record) {
Guy Benyei11169dd2012-12-18 14:30:41 +00001165 Error("incorrectly-formatted source location entry in AST file");
1166 return true;
1167 }
Chris Lattnere7b154b2013-01-19 21:39:22 +00001168
Guy Benyei11169dd2012-12-18 14:30:41 +00001169 RecordData Record;
Chris Lattner0e6c9402013-01-20 02:38:54 +00001170 StringRef Blob;
1171 switch (SLocEntryCursor.readRecord(Entry.ID, Record, &Blob)) {
Guy Benyei11169dd2012-12-18 14:30:41 +00001172 default:
1173 Error("incorrectly-formatted source location entry in AST file");
1174 return true;
1175
1176 case SM_SLOC_FILE_ENTRY: {
1177 // We will detect whether a file changed and return 'Failure' for it, but
1178 // we will also try to fail gracefully by setting up the SLocEntry.
1179 unsigned InputID = Record[4];
1180 InputFile IF = getInputFile(*F, InputID);
Argyrios Kyrtzidis61c3d872013-03-01 03:26:04 +00001181 const FileEntry *File = IF.getFile();
1182 bool OverriddenBuffer = IF.isOverridden();
Guy Benyei11169dd2012-12-18 14:30:41 +00001183
Argyrios Kyrtzidis61c3d872013-03-01 03:26:04 +00001184 // Note that we only check if a File was returned. If it was out-of-date
1185 // we have complained but we will continue creating a FileID to recover
1186 // gracefully.
1187 if (!File)
Guy Benyei11169dd2012-12-18 14:30:41 +00001188 return true;
1189
1190 SourceLocation IncludeLoc = ReadSourceLocation(*F, Record[1]);
1191 if (IncludeLoc.isInvalid() && F->Kind != MK_MainFile) {
1192 // This is the module's main file.
1193 IncludeLoc = getImportLocation(F);
1194 }
1195 SrcMgr::CharacteristicKind
1196 FileCharacter = (SrcMgr::CharacteristicKind)Record[2];
1197 FileID FID = SourceMgr.createFileID(File, IncludeLoc, FileCharacter,
1198 ID, BaseOffset + Record[0]);
1199 SrcMgr::FileInfo &FileInfo =
1200 const_cast<SrcMgr::FileInfo&>(SourceMgr.getSLocEntry(FID).getFile());
1201 FileInfo.NumCreatedFIDs = Record[5];
1202 if (Record[3])
1203 FileInfo.setHasLineDirectives();
1204
1205 const DeclID *FirstDecl = F->FileSortedDecls + Record[6];
1206 unsigned NumFileDecls = Record[7];
1207 if (NumFileDecls) {
1208 assert(F->FileSortedDecls && "FILE_SORTED_DECLS not encountered yet ?");
1209 FileDeclIDs[FID] = FileDeclsInfo(F, llvm::makeArrayRef(FirstDecl,
1210 NumFileDecls));
1211 }
1212
1213 const SrcMgr::ContentCache *ContentCache
1214 = SourceMgr.getOrCreateContentCache(File,
1215 /*isSystemFile=*/FileCharacter != SrcMgr::C_User);
1216 if (OverriddenBuffer && !ContentCache->BufferOverridden &&
1217 ContentCache->ContentsEntry == ContentCache->OrigEntry) {
1218 unsigned Code = SLocEntryCursor.ReadCode();
1219 Record.clear();
Chris Lattner0e6c9402013-01-20 02:38:54 +00001220 unsigned RecCode = SLocEntryCursor.readRecord(Code, Record, &Blob);
Guy Benyei11169dd2012-12-18 14:30:41 +00001221
1222 if (RecCode != SM_SLOC_BUFFER_BLOB) {
1223 Error("AST record has invalid code");
1224 return true;
1225 }
1226
Rafael Espindolad87f8d72014-08-27 20:03:29 +00001227 std::unique_ptr<llvm::MemoryBuffer> Buffer
Chris Lattner0e6c9402013-01-20 02:38:54 +00001228 = llvm::MemoryBuffer::getMemBuffer(Blob.drop_back(1), File->getName());
David Blaikie49cc3182014-08-27 20:54:45 +00001229 SourceMgr.overrideFileContents(File, std::move(Buffer));
Guy Benyei11169dd2012-12-18 14:30:41 +00001230 }
1231
1232 break;
1233 }
1234
1235 case SM_SLOC_BUFFER_ENTRY: {
Chris Lattner0e6c9402013-01-20 02:38:54 +00001236 const char *Name = Blob.data();
Guy Benyei11169dd2012-12-18 14:30:41 +00001237 unsigned Offset = Record[0];
1238 SrcMgr::CharacteristicKind
1239 FileCharacter = (SrcMgr::CharacteristicKind)Record[2];
1240 SourceLocation IncludeLoc = ReadSourceLocation(*F, Record[1]);
Richard Smithe842a472014-10-22 02:05:46 +00001241 if (IncludeLoc.isInvalid() &&
1242 (F->Kind == MK_ImplicitModule || F->Kind == MK_ExplicitModule)) {
Guy Benyei11169dd2012-12-18 14:30:41 +00001243 IncludeLoc = getImportLocation(F);
1244 }
1245 unsigned Code = SLocEntryCursor.ReadCode();
1246 Record.clear();
1247 unsigned RecCode
Chris Lattner0e6c9402013-01-20 02:38:54 +00001248 = SLocEntryCursor.readRecord(Code, Record, &Blob);
Guy Benyei11169dd2012-12-18 14:30:41 +00001249
1250 if (RecCode != SM_SLOC_BUFFER_BLOB) {
1251 Error("AST record has invalid code");
1252 return true;
1253 }
1254
Rafael Espindolad87f8d72014-08-27 20:03:29 +00001255 std::unique_ptr<llvm::MemoryBuffer> Buffer =
1256 llvm::MemoryBuffer::getMemBuffer(Blob.drop_back(1), Name);
David Blaikie50a5f972014-08-29 07:59:55 +00001257 SourceMgr.createFileID(std::move(Buffer), FileCharacter, ID,
Rafael Espindolad87f8d72014-08-27 20:03:29 +00001258 BaseOffset + Offset, IncludeLoc);
Guy Benyei11169dd2012-12-18 14:30:41 +00001259 break;
1260 }
1261
1262 case SM_SLOC_EXPANSION_ENTRY: {
1263 SourceLocation SpellingLoc = ReadSourceLocation(*F, Record[1]);
1264 SourceMgr.createExpansionLoc(SpellingLoc,
1265 ReadSourceLocation(*F, Record[2]),
1266 ReadSourceLocation(*F, Record[3]),
1267 Record[4],
1268 ID,
1269 BaseOffset + Record[0]);
1270 break;
1271 }
1272 }
1273
1274 return false;
1275}
1276
1277std::pair<SourceLocation, StringRef> ASTReader::getModuleImportLoc(int ID) {
1278 if (ID == 0)
1279 return std::make_pair(SourceLocation(), "");
1280
1281 if (unsigned(-ID) - 2 >= getTotalNumSLocs() || ID > 0) {
1282 Error("source location entry ID out-of-range for AST file");
1283 return std::make_pair(SourceLocation(), "");
1284 }
1285
1286 // Find which module file this entry lands in.
1287 ModuleFile *M = GlobalSLocEntryMap.find(-ID)->second;
Richard Smithe842a472014-10-22 02:05:46 +00001288 if (M->Kind != MK_ImplicitModule && M->Kind != MK_ExplicitModule)
Guy Benyei11169dd2012-12-18 14:30:41 +00001289 return std::make_pair(SourceLocation(), "");
1290
1291 // FIXME: Can we map this down to a particular submodule? That would be
1292 // ideal.
Ben Langmuirbeee15e2014-04-14 18:00:01 +00001293 return std::make_pair(M->ImportLoc, StringRef(M->ModuleName));
Guy Benyei11169dd2012-12-18 14:30:41 +00001294}
1295
1296/// \brief Find the location where the module F is imported.
1297SourceLocation ASTReader::getImportLocation(ModuleFile *F) {
1298 if (F->ImportLoc.isValid())
1299 return F->ImportLoc;
1300
1301 // Otherwise we have a PCH. It's considered to be "imported" at the first
1302 // location of its includer.
1303 if (F->ImportedBy.empty() || !F->ImportedBy[0]) {
Ben Langmuirbeee15e2014-04-14 18:00:01 +00001304 // Main file is the importer.
1305 assert(!SourceMgr.getMainFileID().isInvalid() && "missing main file");
1306 return SourceMgr.getLocForStartOfFile(SourceMgr.getMainFileID());
Guy Benyei11169dd2012-12-18 14:30:41 +00001307 }
Guy Benyei11169dd2012-12-18 14:30:41 +00001308 return F->ImportedBy[0]->FirstLoc;
1309}
1310
1311/// ReadBlockAbbrevs - Enter a subblock of the specified BlockID with the
1312/// specified cursor. Read the abbreviations that are at the top of the block
1313/// and then leave the cursor pointing into the block.
Chris Lattner7fb3bef2013-01-20 00:56:42 +00001314bool ASTReader::ReadBlockAbbrevs(BitstreamCursor &Cursor, unsigned BlockID) {
Guy Benyei11169dd2012-12-18 14:30:41 +00001315 if (Cursor.EnterSubBlock(BlockID)) {
1316 Error("malformed block record in AST file");
1317 return Failure;
1318 }
1319
1320 while (true) {
1321 uint64_t Offset = Cursor.GetCurrentBitNo();
1322 unsigned Code = Cursor.ReadCode();
1323
1324 // We expect all abbrevs to be at the start of the block.
1325 if (Code != llvm::bitc::DEFINE_ABBREV) {
1326 Cursor.JumpToBit(Offset);
1327 return false;
1328 }
1329 Cursor.ReadAbbrevRecord();
1330 }
1331}
1332
Richard Smithe40f2ba2013-08-07 21:41:30 +00001333Token ASTReader::ReadToken(ModuleFile &F, const RecordDataImpl &Record,
John McCallf413f5e2013-05-03 00:10:13 +00001334 unsigned &Idx) {
1335 Token Tok;
1336 Tok.startToken();
1337 Tok.setLocation(ReadSourceLocation(F, Record, Idx));
1338 Tok.setLength(Record[Idx++]);
1339 if (IdentifierInfo *II = getLocalIdentifier(F, Record[Idx++]))
1340 Tok.setIdentifierInfo(II);
1341 Tok.setKind((tok::TokenKind)Record[Idx++]);
1342 Tok.setFlag((Token::TokenFlags)Record[Idx++]);
1343 return Tok;
1344}
1345
Argyrios Kyrtzidiseb663da2013-03-22 21:12:57 +00001346MacroInfo *ASTReader::ReadMacroRecord(ModuleFile &F, uint64_t Offset) {
Chris Lattner7fb3bef2013-01-20 00:56:42 +00001347 BitstreamCursor &Stream = F.MacroCursor;
Guy Benyei11169dd2012-12-18 14:30:41 +00001348
1349 // Keep track of where we are in the stream, then jump back there
1350 // after reading this macro.
1351 SavedStreamPosition SavedPosition(Stream);
1352
1353 Stream.JumpToBit(Offset);
1354 RecordData Record;
1355 SmallVector<IdentifierInfo*, 16> MacroArgs;
Craig Toppera13603a2014-05-22 05:54:18 +00001356 MacroInfo *Macro = nullptr;
Guy Benyei11169dd2012-12-18 14:30:41 +00001357
Guy Benyei11169dd2012-12-18 14:30:41 +00001358 while (true) {
Chris Lattnerefa77172013-01-20 00:00:22 +00001359 // Advance to the next record, but if we get to the end of the block, don't
1360 // pop it (removing all the abbreviations from the cursor) since we want to
1361 // be able to reseek within the block and read entries.
Chris Lattner7fb3bef2013-01-20 00:56:42 +00001362 unsigned Flags = BitstreamCursor::AF_DontPopBlockAtEnd;
Chris Lattnerefa77172013-01-20 00:00:22 +00001363 llvm::BitstreamEntry Entry = Stream.advanceSkippingSubblocks(Flags);
1364
1365 switch (Entry.Kind) {
1366 case llvm::BitstreamEntry::SubBlock: // Handled for us already.
1367 case llvm::BitstreamEntry::Error:
1368 Error("malformed block record in AST file");
Argyrios Kyrtzidiseb663da2013-03-22 21:12:57 +00001369 return Macro;
Chris Lattnerefa77172013-01-20 00:00:22 +00001370 case llvm::BitstreamEntry::EndBlock:
Argyrios Kyrtzidiseb663da2013-03-22 21:12:57 +00001371 return Macro;
Chris Lattnerefa77172013-01-20 00:00:22 +00001372 case llvm::BitstreamEntry::Record:
1373 // The interesting case.
1374 break;
Guy Benyei11169dd2012-12-18 14:30:41 +00001375 }
1376
1377 // Read a record.
Guy Benyei11169dd2012-12-18 14:30:41 +00001378 Record.clear();
1379 PreprocessorRecordTypes RecType =
Chris Lattner0e6c9402013-01-20 02:38:54 +00001380 (PreprocessorRecordTypes)Stream.readRecord(Entry.ID, Record);
Guy Benyei11169dd2012-12-18 14:30:41 +00001381 switch (RecType) {
Argyrios Kyrtzidiseb663da2013-03-22 21:12:57 +00001382 case PP_MACRO_DIRECTIVE_HISTORY:
1383 return Macro;
1384
Guy Benyei11169dd2012-12-18 14:30:41 +00001385 case PP_MACRO_OBJECT_LIKE:
1386 case PP_MACRO_FUNCTION_LIKE: {
1387 // If we already have a macro, that means that we've hit the end
1388 // of the definition of the macro we were looking for. We're
1389 // done.
1390 if (Macro)
Argyrios Kyrtzidiseb663da2013-03-22 21:12:57 +00001391 return Macro;
Guy Benyei11169dd2012-12-18 14:30:41 +00001392
Argyrios Kyrtzidiseb663da2013-03-22 21:12:57 +00001393 unsigned NextIndex = 1; // Skip identifier ID.
1394 SubmoduleID SubModID = getGlobalSubmoduleID(F, Record[NextIndex++]);
Guy Benyei11169dd2012-12-18 14:30:41 +00001395 SourceLocation Loc = ReadSourceLocation(F, Record, NextIndex);
Argyrios Kyrtzidiseb663da2013-03-22 21:12:57 +00001396 MacroInfo *MI = PP.AllocateDeserializedMacroInfo(Loc, SubModID);
Argyrios Kyrtzidis7572be22013-01-07 19:16:23 +00001397 MI->setDefinitionEndLoc(ReadSourceLocation(F, Record, NextIndex));
Guy Benyei11169dd2012-12-18 14:30:41 +00001398 MI->setIsUsed(Record[NextIndex++]);
Argyrios Kyrtzidis9ef53ce2014-04-09 18:21:23 +00001399 MI->setUsedForHeaderGuard(Record[NextIndex++]);
Guy Benyei11169dd2012-12-18 14:30:41 +00001400
Guy Benyei11169dd2012-12-18 14:30:41 +00001401 if (RecType == PP_MACRO_FUNCTION_LIKE) {
1402 // Decode function-like macro info.
1403 bool isC99VarArgs = Record[NextIndex++];
1404 bool isGNUVarArgs = Record[NextIndex++];
1405 bool hasCommaPasting = Record[NextIndex++];
1406 MacroArgs.clear();
1407 unsigned NumArgs = Record[NextIndex++];
1408 for (unsigned i = 0; i != NumArgs; ++i)
1409 MacroArgs.push_back(getLocalIdentifier(F, Record[NextIndex++]));
1410
1411 // Install function-like macro info.
1412 MI->setIsFunctionLike();
1413 if (isC99VarArgs) MI->setIsC99Varargs();
1414 if (isGNUVarArgs) MI->setIsGNUVarargs();
1415 if (hasCommaPasting) MI->setHasCommaPasting();
1416 MI->setArgumentList(MacroArgs.data(), MacroArgs.size(),
1417 PP.getPreprocessorAllocator());
1418 }
1419
Guy Benyei11169dd2012-12-18 14:30:41 +00001420 // Remember that we saw this macro last so that we add the tokens that
1421 // form its body to it.
1422 Macro = MI;
1423
1424 if (NextIndex + 1 == Record.size() && PP.getPreprocessingRecord() &&
1425 Record[NextIndex]) {
1426 // We have a macro definition. Register the association
1427 PreprocessedEntityID
1428 GlobalID = getGlobalPreprocessedEntityID(F, Record[NextIndex]);
1429 PreprocessingRecord &PPRec = *PP.getPreprocessingRecord();
Argyrios Kyrtzidis832de9f2013-02-22 18:35:59 +00001430 PreprocessingRecord::PPEntityID
1431 PPID = PPRec.getPPEntityID(GlobalID-1, /*isLoaded=*/true);
1432 MacroDefinition *PPDef =
1433 cast_or_null<MacroDefinition>(PPRec.getPreprocessedEntity(PPID));
1434 if (PPDef)
1435 PPRec.RegisterMacroDefinition(Macro, PPDef);
Guy Benyei11169dd2012-12-18 14:30:41 +00001436 }
1437
1438 ++NumMacrosRead;
1439 break;
1440 }
1441
1442 case PP_TOKEN: {
1443 // If we see a TOKEN before a PP_MACRO_*, then the file is
1444 // erroneous, just pretend we didn't see this.
Craig Toppera13603a2014-05-22 05:54:18 +00001445 if (!Macro) break;
Guy Benyei11169dd2012-12-18 14:30:41 +00001446
John McCallf413f5e2013-05-03 00:10:13 +00001447 unsigned Idx = 0;
1448 Token Tok = ReadToken(F, Record, Idx);
Guy Benyei11169dd2012-12-18 14:30:41 +00001449 Macro->AddTokenToBody(Tok);
1450 break;
1451 }
1452 }
1453 }
1454}
1455
1456PreprocessedEntityID
1457ASTReader::getGlobalPreprocessedEntityID(ModuleFile &M, unsigned LocalID) const {
1458 ContinuousRangeMap<uint32_t, int, 2>::const_iterator
1459 I = M.PreprocessedEntityRemap.find(LocalID - NUM_PREDEF_PP_ENTITY_IDS);
1460 assert(I != M.PreprocessedEntityRemap.end()
1461 && "Invalid index into preprocessed entity index remap");
1462
1463 return LocalID + I->second;
1464}
1465
Argyrios Kyrtzidis5c2a3452013-03-06 18:12:47 +00001466unsigned HeaderFileInfoTrait::ComputeHash(internal_key_ref ikey) {
1467 return llvm::hash_combine(ikey.Size, ikey.ModTime);
Guy Benyei11169dd2012-12-18 14:30:41 +00001468}
1469
1470HeaderFileInfoTrait::internal_key_type
Argyrios Kyrtzidis5c2a3452013-03-06 18:12:47 +00001471HeaderFileInfoTrait::GetInternalKey(const FileEntry *FE) {
1472 internal_key_type ikey = { FE->getSize(), FE->getModificationTime(),
1473 FE->getName() };
1474 return ikey;
1475}
Guy Benyei11169dd2012-12-18 14:30:41 +00001476
Argyrios Kyrtzidis5c2a3452013-03-06 18:12:47 +00001477bool HeaderFileInfoTrait::EqualKey(internal_key_ref a, internal_key_ref b) {
1478 if (a.Size != b.Size || a.ModTime != b.ModTime)
Guy Benyei11169dd2012-12-18 14:30:41 +00001479 return false;
1480
Argyrios Kyrtzidis5c2a3452013-03-06 18:12:47 +00001481 if (strcmp(a.Filename, b.Filename) == 0)
1482 return true;
1483
Guy Benyei11169dd2012-12-18 14:30:41 +00001484 // Determine whether the actual files are equivalent.
Argyrios Kyrtzidis2a513e82013-03-04 20:33:40 +00001485 FileManager &FileMgr = Reader.getFileManager();
Argyrios Kyrtzidis5c2a3452013-03-06 18:12:47 +00001486 const FileEntry *FEA = FileMgr.getFile(a.Filename);
1487 const FileEntry *FEB = FileMgr.getFile(b.Filename);
Argyrios Kyrtzidis2a513e82013-03-04 20:33:40 +00001488 return (FEA && FEA == FEB);
Guy Benyei11169dd2012-12-18 14:30:41 +00001489}
1490
1491std::pair<unsigned, unsigned>
1492HeaderFileInfoTrait::ReadKeyDataLength(const unsigned char*& d) {
Justin Bogner57ba0b22014-03-28 22:03:24 +00001493 using namespace llvm::support;
1494 unsigned KeyLen = (unsigned) endian::readNext<uint16_t, little, unaligned>(d);
Guy Benyei11169dd2012-12-18 14:30:41 +00001495 unsigned DataLen = (unsigned) *d++;
Argyrios Kyrtzidis5c2a3452013-03-06 18:12:47 +00001496 return std::make_pair(KeyLen, DataLen);
Guy Benyei11169dd2012-12-18 14:30:41 +00001497}
Argyrios Kyrtzidis5c2a3452013-03-06 18:12:47 +00001498
1499HeaderFileInfoTrait::internal_key_type
1500HeaderFileInfoTrait::ReadKey(const unsigned char *d, unsigned) {
Justin Bogner57ba0b22014-03-28 22:03:24 +00001501 using namespace llvm::support;
Argyrios Kyrtzidis5c2a3452013-03-06 18:12:47 +00001502 internal_key_type ikey;
Justin Bogner57ba0b22014-03-28 22:03:24 +00001503 ikey.Size = off_t(endian::readNext<uint64_t, little, unaligned>(d));
1504 ikey.ModTime = time_t(endian::readNext<uint64_t, little, unaligned>(d));
Argyrios Kyrtzidis5c2a3452013-03-06 18:12:47 +00001505 ikey.Filename = (const char *)d;
1506 return ikey;
1507}
1508
Guy Benyei11169dd2012-12-18 14:30:41 +00001509HeaderFileInfoTrait::data_type
Argyrios Kyrtzidisb146baa2013-03-13 21:13:51 +00001510HeaderFileInfoTrait::ReadData(internal_key_ref key, const unsigned char *d,
Guy Benyei11169dd2012-12-18 14:30:41 +00001511 unsigned DataLen) {
1512 const unsigned char *End = d + DataLen;
Justin Bogner57ba0b22014-03-28 22:03:24 +00001513 using namespace llvm::support;
Guy Benyei11169dd2012-12-18 14:30:41 +00001514 HeaderFileInfo HFI;
1515 unsigned Flags = *d++;
Lawrence Crowlb53e5482013-06-20 21:14:14 +00001516 HFI.HeaderRole = static_cast<ModuleMap::ModuleHeaderRole>
1517 ((Flags >> 6) & 0x03);
Guy Benyei11169dd2012-12-18 14:30:41 +00001518 HFI.isImport = (Flags >> 5) & 0x01;
1519 HFI.isPragmaOnce = (Flags >> 4) & 0x01;
1520 HFI.DirInfo = (Flags >> 2) & 0x03;
1521 HFI.Resolved = (Flags >> 1) & 0x01;
1522 HFI.IndexHeaderMapHeader = Flags & 0x01;
Justin Bogner57ba0b22014-03-28 22:03:24 +00001523 HFI.NumIncludes = endian::readNext<uint16_t, little, unaligned>(d);
1524 HFI.ControllingMacroID = Reader.getGlobalIdentifierID(
1525 M, endian::readNext<uint32_t, little, unaligned>(d));
1526 if (unsigned FrameworkOffset =
1527 endian::readNext<uint32_t, little, unaligned>(d)) {
Guy Benyei11169dd2012-12-18 14:30:41 +00001528 // The framework offset is 1 greater than the actual offset,
1529 // since 0 is used as an indicator for "no framework name".
1530 StringRef FrameworkName(FrameworkStrings + FrameworkOffset - 1);
1531 HFI.Framework = HS->getUniqueFrameworkName(FrameworkName);
1532 }
1533
Argyrios Kyrtzidisb146baa2013-03-13 21:13:51 +00001534 if (d != End) {
Justin Bogner57ba0b22014-03-28 22:03:24 +00001535 uint32_t LocalSMID = endian::readNext<uint32_t, little, unaligned>(d);
Argyrios Kyrtzidisb146baa2013-03-13 21:13:51 +00001536 if (LocalSMID) {
1537 // This header is part of a module. Associate it with the module to enable
1538 // implicit module import.
1539 SubmoduleID GlobalSMID = Reader.getGlobalSubmoduleID(M, LocalSMID);
1540 Module *Mod = Reader.getSubmodule(GlobalSMID);
1541 HFI.isModuleHeader = true;
1542 FileManager &FileMgr = Reader.getFileManager();
1543 ModuleMap &ModMap =
1544 Reader.getPreprocessor().getHeaderSearchInfo().getModuleMap();
Lawrence Crowlb53e5482013-06-20 21:14:14 +00001545 ModMap.addHeader(Mod, FileMgr.getFile(key.Filename), HFI.getHeaderRole());
Argyrios Kyrtzidisb146baa2013-03-13 21:13:51 +00001546 }
1547 }
1548
Guy Benyei11169dd2012-12-18 14:30:41 +00001549 assert(End == d && "Wrong data length in HeaderFileInfo deserialization");
1550 (void)End;
1551
1552 // This HeaderFileInfo was externally loaded.
1553 HFI.External = true;
1554 return HFI;
1555}
1556
Richard Smith49f906a2014-03-01 00:08:04 +00001557void
1558ASTReader::addPendingMacroFromModule(IdentifierInfo *II, ModuleFile *M,
1559 GlobalMacroID GMacID,
Craig Topper00bbdcf2014-06-28 23:22:23 +00001560 ArrayRef<SubmoduleID> Overrides) {
Guy Benyei11169dd2012-12-18 14:30:41 +00001561 assert(NumCurrentElementsDeserializing > 0 &&"Missing deserialization guard");
Craig Toppera13603a2014-05-22 05:54:18 +00001562 SubmoduleID *OverrideData = nullptr;
Richard Smith49f906a2014-03-01 00:08:04 +00001563 if (!Overrides.empty()) {
1564 OverrideData = new (Context) SubmoduleID[Overrides.size() + 1];
1565 OverrideData[0] = Overrides.size();
1566 for (unsigned I = 0; I != Overrides.size(); ++I)
1567 OverrideData[I + 1] = getGlobalSubmoduleID(*M, Overrides[I]);
1568 }
1569 PendingMacroIDs[II].push_back(PendingMacroInfo(M, GMacID, OverrideData));
Argyrios Kyrtzidiseb663da2013-03-22 21:12:57 +00001570}
1571
1572void ASTReader::addPendingMacroFromPCH(IdentifierInfo *II,
1573 ModuleFile *M,
1574 uint64_t MacroDirectivesOffset) {
1575 assert(NumCurrentElementsDeserializing > 0 &&"Missing deserialization guard");
1576 PendingMacroIDs[II].push_back(PendingMacroInfo(M, MacroDirectivesOffset));
Guy Benyei11169dd2012-12-18 14:30:41 +00001577}
1578
1579void ASTReader::ReadDefinedMacros() {
1580 // Note that we are loading defined macros.
1581 Deserializing Macros(this);
1582
1583 for (ModuleReverseIterator I = ModuleMgr.rbegin(),
1584 E = ModuleMgr.rend(); I != E; ++I) {
Chris Lattner7fb3bef2013-01-20 00:56:42 +00001585 BitstreamCursor &MacroCursor = (*I)->MacroCursor;
Guy Benyei11169dd2012-12-18 14:30:41 +00001586
1587 // If there was no preprocessor block, skip this file.
1588 if (!MacroCursor.getBitStreamReader())
1589 continue;
1590
Chris Lattner7fb3bef2013-01-20 00:56:42 +00001591 BitstreamCursor Cursor = MacroCursor;
Guy Benyei11169dd2012-12-18 14:30:41 +00001592 Cursor.JumpToBit((*I)->MacroStartOffset);
1593
1594 RecordData Record;
1595 while (true) {
Chris Lattnere7b154b2013-01-19 21:39:22 +00001596 llvm::BitstreamEntry E = Cursor.advanceSkippingSubblocks();
1597
1598 switch (E.Kind) {
1599 case llvm::BitstreamEntry::SubBlock: // Handled for us already.
1600 case llvm::BitstreamEntry::Error:
1601 Error("malformed block record in AST file");
1602 return;
1603 case llvm::BitstreamEntry::EndBlock:
1604 goto NextCursor;
1605
1606 case llvm::BitstreamEntry::Record:
Chris Lattnere7b154b2013-01-19 21:39:22 +00001607 Record.clear();
Chris Lattner0e6c9402013-01-20 02:38:54 +00001608 switch (Cursor.readRecord(E.ID, Record)) {
Chris Lattnere7b154b2013-01-19 21:39:22 +00001609 default: // Default behavior: ignore.
1610 break;
1611
1612 case PP_MACRO_OBJECT_LIKE:
1613 case PP_MACRO_FUNCTION_LIKE:
1614 getLocalIdentifier(**I, Record[0]);
1615 break;
1616
1617 case PP_TOKEN:
1618 // Ignore tokens.
1619 break;
Guy Benyei11169dd2012-12-18 14:30:41 +00001620 }
Guy Benyei11169dd2012-12-18 14:30:41 +00001621 break;
1622 }
1623 }
Chris Lattnere7b154b2013-01-19 21:39:22 +00001624 NextCursor: ;
Guy Benyei11169dd2012-12-18 14:30:41 +00001625 }
1626}
1627
1628namespace {
1629 /// \brief Visitor class used to look up identifirs in an AST file.
1630 class IdentifierLookupVisitor {
1631 StringRef Name;
1632 unsigned PriorGeneration;
Douglas Gregor00a50f72013-01-25 00:38:33 +00001633 unsigned &NumIdentifierLookups;
1634 unsigned &NumIdentifierLookupHits;
Guy Benyei11169dd2012-12-18 14:30:41 +00001635 IdentifierInfo *Found;
Douglas Gregor00a50f72013-01-25 00:38:33 +00001636
Guy Benyei11169dd2012-12-18 14:30:41 +00001637 public:
Douglas Gregor00a50f72013-01-25 00:38:33 +00001638 IdentifierLookupVisitor(StringRef Name, unsigned PriorGeneration,
1639 unsigned &NumIdentifierLookups,
1640 unsigned &NumIdentifierLookupHits)
Douglas Gregor7211ac12013-01-25 23:32:03 +00001641 : Name(Name), PriorGeneration(PriorGeneration),
Douglas Gregor00a50f72013-01-25 00:38:33 +00001642 NumIdentifierLookups(NumIdentifierLookups),
1643 NumIdentifierLookupHits(NumIdentifierLookupHits),
1644 Found()
1645 {
1646 }
Guy Benyei11169dd2012-12-18 14:30:41 +00001647
1648 static bool visit(ModuleFile &M, void *UserData) {
1649 IdentifierLookupVisitor *This
1650 = static_cast<IdentifierLookupVisitor *>(UserData);
1651
1652 // If we've already searched this module file, skip it now.
1653 if (M.Generation <= This->PriorGeneration)
1654 return true;
Douglas Gregore060e572013-01-25 01:03:03 +00001655
Guy Benyei11169dd2012-12-18 14:30:41 +00001656 ASTIdentifierLookupTable *IdTable
1657 = (ASTIdentifierLookupTable *)M.IdentifierLookupTable;
1658 if (!IdTable)
1659 return false;
1660
1661 ASTIdentifierLookupTrait Trait(IdTable->getInfoObj().getReader(),
1662 M, This->Found);
Douglas Gregor00a50f72013-01-25 00:38:33 +00001663 ++This->NumIdentifierLookups;
1664 ASTIdentifierLookupTable::iterator Pos = IdTable->find(This->Name,&Trait);
Guy Benyei11169dd2012-12-18 14:30:41 +00001665 if (Pos == IdTable->end())
1666 return false;
1667
1668 // Dereferencing the iterator has the effect of building the
1669 // IdentifierInfo node and populating it with the various
1670 // declarations it needs.
Douglas Gregor00a50f72013-01-25 00:38:33 +00001671 ++This->NumIdentifierLookupHits;
Guy Benyei11169dd2012-12-18 14:30:41 +00001672 This->Found = *Pos;
1673 return true;
1674 }
1675
1676 // \brief Retrieve the identifier info found within the module
1677 // files.
1678 IdentifierInfo *getIdentifierInfo() const { return Found; }
1679 };
1680}
1681
1682void ASTReader::updateOutOfDateIdentifier(IdentifierInfo &II) {
1683 // Note that we are loading an identifier.
1684 Deserializing AnIdentifier(this);
1685
1686 unsigned PriorGeneration = 0;
1687 if (getContext().getLangOpts().Modules)
1688 PriorGeneration = IdentifierGeneration[&II];
Douglas Gregore060e572013-01-25 01:03:03 +00001689
1690 // If there is a global index, look there first to determine which modules
1691 // provably do not have any results for this identifier.
Douglas Gregor7211ac12013-01-25 23:32:03 +00001692 GlobalModuleIndex::HitSet Hits;
Craig Toppera13603a2014-05-22 05:54:18 +00001693 GlobalModuleIndex::HitSet *HitsPtr = nullptr;
Douglas Gregore060e572013-01-25 01:03:03 +00001694 if (!loadGlobalIndex()) {
Douglas Gregor7211ac12013-01-25 23:32:03 +00001695 if (GlobalIndex->lookupIdentifier(II.getName(), Hits)) {
1696 HitsPtr = &Hits;
Douglas Gregore060e572013-01-25 01:03:03 +00001697 }
1698 }
1699
Douglas Gregor7211ac12013-01-25 23:32:03 +00001700 IdentifierLookupVisitor Visitor(II.getName(), PriorGeneration,
Douglas Gregor00a50f72013-01-25 00:38:33 +00001701 NumIdentifierLookups,
1702 NumIdentifierLookupHits);
Douglas Gregor7211ac12013-01-25 23:32:03 +00001703 ModuleMgr.visit(IdentifierLookupVisitor::visit, &Visitor, HitsPtr);
Guy Benyei11169dd2012-12-18 14:30:41 +00001704 markIdentifierUpToDate(&II);
1705}
1706
1707void ASTReader::markIdentifierUpToDate(IdentifierInfo *II) {
1708 if (!II)
1709 return;
1710
1711 II->setOutOfDate(false);
1712
1713 // Update the generation for this identifier.
1714 if (getContext().getLangOpts().Modules)
Richard Smith053f6c62014-05-16 23:01:30 +00001715 IdentifierGeneration[II] = getGeneration();
Guy Benyei11169dd2012-12-18 14:30:41 +00001716}
1717
Richard Smith49f906a2014-03-01 00:08:04 +00001718struct ASTReader::ModuleMacroInfo {
1719 SubmoduleID SubModID;
1720 MacroInfo *MI;
1721 SubmoduleID *Overrides;
1722 // FIXME: Remove this.
1723 ModuleFile *F;
1724
1725 bool isDefine() const { return MI; }
1726
1727 SubmoduleID getSubmoduleID() const { return SubModID; }
1728
Craig Topper00bbdcf2014-06-28 23:22:23 +00001729 ArrayRef<SubmoduleID> getOverriddenSubmodules() const {
Richard Smith49f906a2014-03-01 00:08:04 +00001730 if (!Overrides)
Craig Topper00bbdcf2014-06-28 23:22:23 +00001731 return None;
Richard Smith49f906a2014-03-01 00:08:04 +00001732 return llvm::makeArrayRef(Overrides + 1, *Overrides);
1733 }
1734
Richard Smithdaa69e02014-07-25 04:40:03 +00001735 MacroDirective *import(Preprocessor &PP, SourceLocation ImportLoc) const {
Richard Smith49f906a2014-03-01 00:08:04 +00001736 if (!MI)
Richard Smithdaa69e02014-07-25 04:40:03 +00001737 return PP.AllocateUndefMacroDirective(ImportLoc, SubModID,
1738 getOverriddenSubmodules());
1739 return PP.AllocateDefMacroDirective(MI, ImportLoc, SubModID,
1740 getOverriddenSubmodules());
Richard Smith49f906a2014-03-01 00:08:04 +00001741 }
1742};
1743
1744ASTReader::ModuleMacroInfo *
1745ASTReader::getModuleMacro(const PendingMacroInfo &PMInfo) {
1746 ModuleMacroInfo Info;
1747
1748 uint32_t ID = PMInfo.ModuleMacroData.MacID;
1749 if (ID & 1) {
1750 // Macro undefinition.
1751 Info.SubModID = getGlobalSubmoduleID(*PMInfo.M, ID >> 1);
Craig Toppera13603a2014-05-22 05:54:18 +00001752 Info.MI = nullptr;
Richard Smith49f906a2014-03-01 00:08:04 +00001753 } else {
1754 // Macro definition.
1755 GlobalMacroID GMacID = getGlobalMacroID(*PMInfo.M, ID >> 1);
1756 assert(GMacID);
1757
1758 // If this macro has already been loaded, don't do so again.
1759 // FIXME: This is highly dubious. Multiple macro definitions can have the
1760 // same MacroInfo (and hence the same GMacID) due to #pragma push_macro etc.
1761 if (MacrosLoaded[GMacID - NUM_PREDEF_MACRO_IDS])
Craig Toppera13603a2014-05-22 05:54:18 +00001762 return nullptr;
Richard Smith49f906a2014-03-01 00:08:04 +00001763
1764 Info.MI = getMacro(GMacID);
1765 Info.SubModID = Info.MI->getOwningModuleID();
1766 }
1767 Info.Overrides = PMInfo.ModuleMacroData.Overrides;
1768 Info.F = PMInfo.M;
1769
1770 return new (Context) ModuleMacroInfo(Info);
1771}
1772
Argyrios Kyrtzidiseb663da2013-03-22 21:12:57 +00001773void ASTReader::resolvePendingMacro(IdentifierInfo *II,
1774 const PendingMacroInfo &PMInfo) {
1775 assert(II);
1776
Richard Smithe842a472014-10-22 02:05:46 +00001777 if (PMInfo.M->Kind != MK_ImplicitModule &&
1778 PMInfo.M->Kind != MK_ExplicitModule) {
Argyrios Kyrtzidiseb663da2013-03-22 21:12:57 +00001779 installPCHMacroDirectives(II, *PMInfo.M,
1780 PMInfo.PCHMacroData.MacroDirectivesOffset);
1781 return;
1782 }
Richard Smith49f906a2014-03-01 00:08:04 +00001783
Argyrios Kyrtzidiseb663da2013-03-22 21:12:57 +00001784 // Module Macro.
1785
Richard Smith49f906a2014-03-01 00:08:04 +00001786 ModuleMacroInfo *MMI = getModuleMacro(PMInfo);
1787 if (!MMI)
Argyrios Kyrtzidiseb663da2013-03-22 21:12:57 +00001788 return;
1789
Richard Smith49f906a2014-03-01 00:08:04 +00001790 Module *Owner = getSubmodule(MMI->getSubmoduleID());
1791 if (Owner && Owner->NameVisibility == Module::Hidden) {
1792 // Macros in the owning module are hidden. Just remember this macro to
1793 // install if we make this module visible.
1794 HiddenNamesMap[Owner].HiddenMacros.insert(std::make_pair(II, MMI));
1795 } else {
Richard Smithdaa69e02014-07-25 04:40:03 +00001796 installImportedMacro(II, MMI, Owner);
Argyrios Kyrtzidiseb663da2013-03-22 21:12:57 +00001797 }
Argyrios Kyrtzidiseb663da2013-03-22 21:12:57 +00001798}
1799
1800void ASTReader::installPCHMacroDirectives(IdentifierInfo *II,
1801 ModuleFile &M, uint64_t Offset) {
Richard Smithe842a472014-10-22 02:05:46 +00001802 assert(M.Kind != MK_ImplicitModule && M.Kind != MK_ExplicitModule);
Argyrios Kyrtzidiseb663da2013-03-22 21:12:57 +00001803
1804 BitstreamCursor &Cursor = M.MacroCursor;
1805 SavedStreamPosition SavedPosition(Cursor);
1806 Cursor.JumpToBit(Offset);
1807
1808 llvm::BitstreamEntry Entry =
1809 Cursor.advance(BitstreamCursor::AF_DontPopBlockAtEnd);
1810 if (Entry.Kind != llvm::BitstreamEntry::Record) {
1811 Error("malformed block record in AST file");
1812 return;
1813 }
1814
1815 RecordData Record;
1816 PreprocessorRecordTypes RecType =
1817 (PreprocessorRecordTypes)Cursor.readRecord(Entry.ID, Record);
1818 if (RecType != PP_MACRO_DIRECTIVE_HISTORY) {
1819 Error("malformed block record in AST file");
1820 return;
1821 }
1822
1823 // Deserialize the macro directives history in reverse source-order.
Craig Toppera13603a2014-05-22 05:54:18 +00001824 MacroDirective *Latest = nullptr, *Earliest = nullptr;
Argyrios Kyrtzidiseb663da2013-03-22 21:12:57 +00001825 unsigned Idx = 0, N = Record.size();
1826 while (Idx < N) {
Craig Toppera13603a2014-05-22 05:54:18 +00001827 MacroDirective *MD = nullptr;
Argyrios Kyrtzidiseb663da2013-03-22 21:12:57 +00001828 SourceLocation Loc = ReadSourceLocation(M, Record, Idx);
Argyrios Kyrtzidisb6210df2013-03-26 17:17:01 +00001829 MacroDirective::Kind K = (MacroDirective::Kind)Record[Idx++];
1830 switch (K) {
1831 case MacroDirective::MD_Define: {
1832 GlobalMacroID GMacID = getGlobalMacroID(M, Record[Idx++]);
1833 MacroInfo *MI = getMacro(GMacID);
Richard Smithdaa69e02014-07-25 04:40:03 +00001834 SubmoduleID ImportedFrom = Record[Idx++];
1835 bool IsAmbiguous = Record[Idx++];
1836 llvm::SmallVector<unsigned, 4> Overrides;
1837 if (ImportedFrom) {
1838 Overrides.insert(Overrides.end(),
1839 &Record[Idx] + 1, &Record[Idx] + 1 + Record[Idx]);
1840 Idx += Overrides.size() + 1;
1841 }
Argyrios Kyrtzidisb6210df2013-03-26 17:17:01 +00001842 DefMacroDirective *DefMD =
Richard Smithdaa69e02014-07-25 04:40:03 +00001843 PP.AllocateDefMacroDirective(MI, Loc, ImportedFrom, Overrides);
1844 DefMD->setAmbiguous(IsAmbiguous);
Argyrios Kyrtzidisb6210df2013-03-26 17:17:01 +00001845 MD = DefMD;
1846 break;
1847 }
Richard Smithdaa69e02014-07-25 04:40:03 +00001848 case MacroDirective::MD_Undefine: {
1849 SubmoduleID ImportedFrom = Record[Idx++];
1850 llvm::SmallVector<unsigned, 4> Overrides;
1851 if (ImportedFrom) {
1852 Overrides.insert(Overrides.end(),
1853 &Record[Idx] + 1, &Record[Idx] + 1 + Record[Idx]);
1854 Idx += Overrides.size() + 1;
1855 }
1856 MD = PP.AllocateUndefMacroDirective(Loc, ImportedFrom, Overrides);
Argyrios Kyrtzidisb6210df2013-03-26 17:17:01 +00001857 break;
Richard Smithdaa69e02014-07-25 04:40:03 +00001858 }
1859 case MacroDirective::MD_Visibility:
Argyrios Kyrtzidisb6210df2013-03-26 17:17:01 +00001860 bool isPublic = Record[Idx++];
1861 MD = PP.AllocateVisibilityMacroDirective(Loc, isPublic);
1862 break;
1863 }
Argyrios Kyrtzidiseb663da2013-03-22 21:12:57 +00001864
1865 if (!Latest)
1866 Latest = MD;
1867 if (Earliest)
1868 Earliest->setPrevious(MD);
1869 Earliest = MD;
1870 }
1871
1872 PP.setLoadedMacroDirective(II, Latest);
1873}
1874
Argyrios Kyrtzidis3a9c42c2013-03-27 01:25:34 +00001875/// \brief For the given macro definitions, check if they are both in system
Douglas Gregor0b202052013-04-12 21:00:54 +00001876/// modules.
1877static bool areDefinedInSystemModules(MacroInfo *PrevMI, MacroInfo *NewMI,
Douglas Gregor5e461192013-06-07 22:56:11 +00001878 Module *NewOwner, ASTReader &Reader) {
Argyrios Kyrtzidis3a9c42c2013-03-27 01:25:34 +00001879 assert(PrevMI && NewMI);
Craig Toppera13603a2014-05-22 05:54:18 +00001880 Module *PrevOwner = nullptr;
Argyrios Kyrtzidis3a9c42c2013-03-27 01:25:34 +00001881 if (SubmoduleID PrevModID = PrevMI->getOwningModuleID())
1882 PrevOwner = Reader.getSubmodule(PrevModID);
Douglas Gregor5e461192013-06-07 22:56:11 +00001883 SourceManager &SrcMgr = Reader.getSourceManager();
1884 bool PrevInSystem
1885 = PrevOwner? PrevOwner->IsSystem
1886 : SrcMgr.isInSystemHeader(PrevMI->getDefinitionLoc());
1887 bool NewInSystem
1888 = NewOwner? NewOwner->IsSystem
1889 : SrcMgr.isInSystemHeader(NewMI->getDefinitionLoc());
1890 if (PrevOwner && PrevOwner == NewOwner)
Argyrios Kyrtzidis3a9c42c2013-03-27 01:25:34 +00001891 return false;
Douglas Gregor5e461192013-06-07 22:56:11 +00001892 return PrevInSystem && NewInSystem;
Argyrios Kyrtzidis3a9c42c2013-03-27 01:25:34 +00001893}
1894
Richard Smith49f906a2014-03-01 00:08:04 +00001895void ASTReader::removeOverriddenMacros(IdentifierInfo *II,
Richard Smithdaa69e02014-07-25 04:40:03 +00001896 SourceLocation ImportLoc,
Richard Smith49f906a2014-03-01 00:08:04 +00001897 AmbiguousMacros &Ambig,
Craig Topper00bbdcf2014-06-28 23:22:23 +00001898 ArrayRef<SubmoduleID> Overrides) {
Richard Smith49f906a2014-03-01 00:08:04 +00001899 for (unsigned OI = 0, ON = Overrides.size(); OI != ON; ++OI) {
1900 SubmoduleID OwnerID = Overrides[OI];
Argyrios Kyrtzidiseb663da2013-03-22 21:12:57 +00001901
Richard Smith49f906a2014-03-01 00:08:04 +00001902 // If this macro is not yet visible, remove it from the hidden names list.
Richard Smithbb853c72014-08-13 01:23:33 +00001903 // It won't be there if we're in the middle of making the owner visible.
Richard Smith49f906a2014-03-01 00:08:04 +00001904 Module *Owner = getSubmodule(OwnerID);
Richard Smithbb853c72014-08-13 01:23:33 +00001905 auto HiddenIt = HiddenNamesMap.find(Owner);
1906 if (HiddenIt != HiddenNamesMap.end()) {
1907 HiddenNames &Hidden = HiddenIt->second;
1908 HiddenMacrosMap::iterator HI = Hidden.HiddenMacros.find(II);
1909 if (HI != Hidden.HiddenMacros.end()) {
1910 // Register the macro now so we don't lose it when we re-export.
1911 PP.appendMacroDirective(II, HI->second->import(PP, ImportLoc));
Richard Smithdaa69e02014-07-25 04:40:03 +00001912
Richard Smithbb853c72014-08-13 01:23:33 +00001913 auto SubOverrides = HI->second->getOverriddenSubmodules();
1914 Hidden.HiddenMacros.erase(HI);
1915 removeOverriddenMacros(II, ImportLoc, Ambig, SubOverrides);
1916 }
Richard Smith49f906a2014-03-01 00:08:04 +00001917 }
1918
1919 // If this macro is already in our list of conflicts, remove it from there.
Richard Smithbb29e512014-03-06 00:33:23 +00001920 Ambig.erase(
1921 std::remove_if(Ambig.begin(), Ambig.end(), [&](DefMacroDirective *MD) {
1922 return MD->getInfo()->getOwningModuleID() == OwnerID;
1923 }),
1924 Ambig.end());
Richard Smith49f906a2014-03-01 00:08:04 +00001925 }
1926}
1927
1928ASTReader::AmbiguousMacros *
1929ASTReader::removeOverriddenMacros(IdentifierInfo *II,
Richard Smithdaa69e02014-07-25 04:40:03 +00001930 SourceLocation ImportLoc,
Craig Topper00bbdcf2014-06-28 23:22:23 +00001931 ArrayRef<SubmoduleID> Overrides) {
Argyrios Kyrtzidiseb663da2013-03-22 21:12:57 +00001932 MacroDirective *Prev = PP.getMacroDirective(II);
Richard Smith49f906a2014-03-01 00:08:04 +00001933 if (!Prev && Overrides.empty())
Craig Toppera13603a2014-05-22 05:54:18 +00001934 return nullptr;
Richard Smith49f906a2014-03-01 00:08:04 +00001935
Craig Toppera13603a2014-05-22 05:54:18 +00001936 DefMacroDirective *PrevDef = Prev ? Prev->getDefinition().getDirective()
1937 : nullptr;
Richard Smith49f906a2014-03-01 00:08:04 +00001938 if (PrevDef && PrevDef->isAmbiguous()) {
1939 // We had a prior ambiguity. Check whether we resolve it (or make it worse).
1940 AmbiguousMacros &Ambig = AmbiguousMacroDefs[II];
1941 Ambig.push_back(PrevDef);
1942
Richard Smithdaa69e02014-07-25 04:40:03 +00001943 removeOverriddenMacros(II, ImportLoc, Ambig, Overrides);
Richard Smith49f906a2014-03-01 00:08:04 +00001944
1945 if (!Ambig.empty())
1946 return &Ambig;
1947
1948 AmbiguousMacroDefs.erase(II);
1949 } else {
1950 // There's no ambiguity yet. Maybe we're introducing one.
Benjamin Kramer834652a2014-05-03 18:44:26 +00001951 AmbiguousMacros Ambig;
Richard Smith49f906a2014-03-01 00:08:04 +00001952 if (PrevDef)
1953 Ambig.push_back(PrevDef);
1954
Richard Smithdaa69e02014-07-25 04:40:03 +00001955 removeOverriddenMacros(II, ImportLoc, Ambig, Overrides);
Richard Smith49f906a2014-03-01 00:08:04 +00001956
1957 if (!Ambig.empty()) {
1958 AmbiguousMacros &Result = AmbiguousMacroDefs[II];
Benjamin Kramer834652a2014-05-03 18:44:26 +00001959 std::swap(Result, Ambig);
Richard Smith49f906a2014-03-01 00:08:04 +00001960 return &Result;
Argyrios Kyrtzidisb6210df2013-03-26 17:17:01 +00001961 }
Argyrios Kyrtzidiseb663da2013-03-22 21:12:57 +00001962 }
Richard Smith49f906a2014-03-01 00:08:04 +00001963
1964 // We ended up with no ambiguity.
Craig Toppera13603a2014-05-22 05:54:18 +00001965 return nullptr;
Richard Smith49f906a2014-03-01 00:08:04 +00001966}
1967
1968void ASTReader::installImportedMacro(IdentifierInfo *II, ModuleMacroInfo *MMI,
Richard Smithdaa69e02014-07-25 04:40:03 +00001969 Module *Owner) {
Richard Smith49f906a2014-03-01 00:08:04 +00001970 assert(II && Owner);
1971
1972 SourceLocation ImportLoc = Owner->MacroVisibilityLoc;
Richard Smithdaa69e02014-07-25 04:40:03 +00001973 if (ImportLoc.isInvalid()) {
Richard Smith49f906a2014-03-01 00:08:04 +00001974 // FIXME: If we made macros from this module visible but didn't provide a
1975 // source location for the import, we don't have a location for the macro.
1976 // Use the location at which the containing module file was first imported
1977 // for now.
1978 ImportLoc = MMI->F->DirectImportLoc;
Richard Smith56be7542014-03-21 00:33:59 +00001979 assert(ImportLoc.isValid() && "no import location for a visible macro?");
Richard Smith49f906a2014-03-01 00:08:04 +00001980 }
1981
Benjamin Kramer834652a2014-05-03 18:44:26 +00001982 AmbiguousMacros *Prev =
Richard Smithdaa69e02014-07-25 04:40:03 +00001983 removeOverriddenMacros(II, ImportLoc, MMI->getOverriddenSubmodules());
Richard Smith49f906a2014-03-01 00:08:04 +00001984
Richard Smith49f906a2014-03-01 00:08:04 +00001985 // Create a synthetic macro definition corresponding to the import (or null
1986 // if this was an undefinition of the macro).
Richard Smithdaa69e02014-07-25 04:40:03 +00001987 MacroDirective *Imported = MMI->import(PP, ImportLoc);
1988 DefMacroDirective *MD = dyn_cast<DefMacroDirective>(Imported);
Richard Smith49f906a2014-03-01 00:08:04 +00001989
1990 // If there's no ambiguity, just install the macro.
1991 if (!Prev) {
Richard Smithdaa69e02014-07-25 04:40:03 +00001992 PP.appendMacroDirective(II, Imported);
Richard Smith49f906a2014-03-01 00:08:04 +00001993 return;
1994 }
1995 assert(!Prev->empty());
1996
1997 if (!MD) {
1998 // We imported a #undef that didn't remove all prior definitions. The most
1999 // recent prior definition remains, and we install it in the place of the
Richard Smithdaa69e02014-07-25 04:40:03 +00002000 // imported directive, as if by a local #pragma pop_macro.
Richard Smith49f906a2014-03-01 00:08:04 +00002001 MacroInfo *NewMI = Prev->back()->getInfo();
2002 Prev->pop_back();
Richard Smithdaa69e02014-07-25 04:40:03 +00002003 MD = PP.AllocateDefMacroDirective(NewMI, ImportLoc);
2004
2005 // Install our #undef first so that we don't lose track of it. We'll replace
2006 // this with whichever macro definition ends up winning.
2007 PP.appendMacroDirective(II, Imported);
Richard Smith49f906a2014-03-01 00:08:04 +00002008 }
2009
2010 // We're introducing a macro definition that creates or adds to an ambiguity.
2011 // We can resolve that ambiguity if this macro is token-for-token identical to
2012 // all of the existing definitions.
2013 MacroInfo *NewMI = MD->getInfo();
2014 assert(NewMI && "macro definition with no MacroInfo?");
2015 while (!Prev->empty()) {
2016 MacroInfo *PrevMI = Prev->back()->getInfo();
2017 assert(PrevMI && "macro definition with no MacroInfo?");
2018
2019 // Before marking the macros as ambiguous, check if this is a case where
2020 // both macros are in system headers. If so, we trust that the system
2021 // did not get it wrong. This also handles cases where Clang's own
2022 // headers have a different spelling of certain system macros:
2023 // #define LONG_MAX __LONG_MAX__ (clang's limits.h)
2024 // #define LONG_MAX 0x7fffffffffffffffL (system's limits.h)
2025 //
2026 // FIXME: Remove the defined-in-system-headers check. clang's limits.h
2027 // overrides the system limits.h's macros, so there's no conflict here.
2028 if (NewMI != PrevMI &&
2029 !PrevMI->isIdenticalTo(*NewMI, PP, /*Syntactically=*/true) &&
2030 !areDefinedInSystemModules(PrevMI, NewMI, Owner, *this))
2031 break;
2032
2033 // The previous definition is the same as this one (or both are defined in
2034 // system modules so we can assume they're equivalent); we don't need to
2035 // track it any more.
2036 Prev->pop_back();
2037 }
2038
2039 if (!Prev->empty())
2040 MD->setAmbiguous(true);
2041
Argyrios Kyrtzidisb6210df2013-03-26 17:17:01 +00002042 PP.appendMacroDirective(II, MD);
Argyrios Kyrtzidiseb663da2013-03-22 21:12:57 +00002043}
2044
Argyrios Kyrtzidisce9b49e2014-03-14 02:26:27 +00002045ASTReader::InputFileInfo
2046ASTReader::readInputFileInfo(ModuleFile &F, unsigned ID) {
Ben Langmuir198c1682014-03-07 07:27:49 +00002047 // Go find this input file.
2048 BitstreamCursor &Cursor = F.InputFilesCursor;
2049 SavedStreamPosition SavedPosition(Cursor);
2050 Cursor.JumpToBit(F.InputFileOffsets[ID-1]);
2051
2052 unsigned Code = Cursor.ReadCode();
2053 RecordData Record;
2054 StringRef Blob;
2055
2056 unsigned Result = Cursor.readRecord(Code, Record, &Blob);
2057 assert(static_cast<InputFileRecordTypes>(Result) == INPUT_FILE &&
2058 "invalid record type for input file");
2059 (void)Result;
2060
Argyrios Kyrtzidisce9b49e2014-03-14 02:26:27 +00002061 std::string Filename;
2062 off_t StoredSize;
2063 time_t StoredTime;
2064 bool Overridden;
2065
Ben Langmuir198c1682014-03-07 07:27:49 +00002066 assert(Record[0] == ID && "Bogus stored ID or offset");
2067 StoredSize = static_cast<off_t>(Record[1]);
2068 StoredTime = static_cast<time_t>(Record[2]);
2069 Overridden = static_cast<bool>(Record[3]);
2070 Filename = Blob;
2071 MaybeAddSystemRootToFilename(F, Filename);
Argyrios Kyrtzidisce9b49e2014-03-14 02:26:27 +00002072
Hans Wennborg73945142014-03-14 17:45:06 +00002073 InputFileInfo R = { std::move(Filename), StoredSize, StoredTime, Overridden };
2074 return R;
Ben Langmuir198c1682014-03-07 07:27:49 +00002075}
2076
2077std::string ASTReader::getInputFileName(ModuleFile &F, unsigned int ID) {
Argyrios Kyrtzidisce9b49e2014-03-14 02:26:27 +00002078 return readInputFileInfo(F, ID).Filename;
Ben Langmuir198c1682014-03-07 07:27:49 +00002079}
2080
Argyrios Kyrtzidis61c3d872013-03-01 03:26:04 +00002081InputFile ASTReader::getInputFile(ModuleFile &F, unsigned ID, bool Complain) {
Guy Benyei11169dd2012-12-18 14:30:41 +00002082 // If this ID is bogus, just return an empty input file.
2083 if (ID == 0 || ID > F.InputFilesLoaded.size())
2084 return InputFile();
2085
2086 // If we've already loaded this input file, return it.
Argyrios Kyrtzidis61c3d872013-03-01 03:26:04 +00002087 if (F.InputFilesLoaded[ID-1].getFile())
Guy Benyei11169dd2012-12-18 14:30:41 +00002088 return F.InputFilesLoaded[ID-1];
2089
Argyrios Kyrtzidis9308f0a2014-01-08 19:13:34 +00002090 if (F.InputFilesLoaded[ID-1].isNotFound())
2091 return InputFile();
2092
Guy Benyei11169dd2012-12-18 14:30:41 +00002093 // Go find this input file.
Chris Lattner7fb3bef2013-01-20 00:56:42 +00002094 BitstreamCursor &Cursor = F.InputFilesCursor;
Guy Benyei11169dd2012-12-18 14:30:41 +00002095 SavedStreamPosition SavedPosition(Cursor);
2096 Cursor.JumpToBit(F.InputFileOffsets[ID-1]);
2097
Argyrios Kyrtzidisce9b49e2014-03-14 02:26:27 +00002098 InputFileInfo FI = readInputFileInfo(F, ID);
2099 off_t StoredSize = FI.StoredSize;
2100 time_t StoredTime = FI.StoredTime;
2101 bool Overridden = FI.Overridden;
2102 StringRef Filename = FI.Filename;
Argyrios Kyrtzidis61c3d872013-03-01 03:26:04 +00002103
Ben Langmuir198c1682014-03-07 07:27:49 +00002104 const FileEntry *File
2105 = Overridden? FileMgr.getVirtualFile(Filename, StoredSize, StoredTime)
2106 : FileMgr.getFile(Filename, /*OpenFile=*/false);
2107
2108 // If we didn't find the file, resolve it relative to the
2109 // original directory from which this AST file was created.
Craig Toppera13603a2014-05-22 05:54:18 +00002110 if (File == nullptr && !F.OriginalDir.empty() && !CurrentDir.empty() &&
Ben Langmuir198c1682014-03-07 07:27:49 +00002111 F.OriginalDir != CurrentDir) {
2112 std::string Resolved = resolveFileRelativeToOriginalDir(Filename,
2113 F.OriginalDir,
2114 CurrentDir);
2115 if (!Resolved.empty())
2116 File = FileMgr.getFile(Resolved);
2117 }
2118
2119 // For an overridden file, create a virtual file with the stored
2120 // size/timestamp.
Craig Toppera13603a2014-05-22 05:54:18 +00002121 if (Overridden && File == nullptr) {
Ben Langmuir198c1682014-03-07 07:27:49 +00002122 File = FileMgr.getVirtualFile(Filename, StoredSize, StoredTime);
2123 }
2124
Craig Toppera13603a2014-05-22 05:54:18 +00002125 if (File == nullptr) {
Ben Langmuir198c1682014-03-07 07:27:49 +00002126 if (Complain) {
2127 std::string ErrorStr = "could not find file '";
2128 ErrorStr += Filename;
2129 ErrorStr += "' referenced by AST file";
2130 Error(ErrorStr.c_str());
Guy Benyei11169dd2012-12-18 14:30:41 +00002131 }
Ben Langmuir198c1682014-03-07 07:27:49 +00002132 // Record that we didn't find the file.
2133 F.InputFilesLoaded[ID-1] = InputFile::getNotFound();
2134 return InputFile();
2135 }
Guy Benyei11169dd2012-12-18 14:30:41 +00002136
Ben Langmuir198c1682014-03-07 07:27:49 +00002137 // Check if there was a request to override the contents of the file
2138 // that was part of the precompiled header. Overridding such a file
2139 // can lead to problems when lexing using the source locations from the
2140 // PCH.
2141 SourceManager &SM = getSourceManager();
2142 if (!Overridden && SM.isFileOverridden(File)) {
2143 if (Complain)
2144 Error(diag::err_fe_pch_file_overridden, Filename);
2145 // After emitting the diagnostic, recover by disabling the override so
2146 // that the original file will be used.
2147 SM.disableFileContentsOverride(File);
2148 // The FileEntry is a virtual file entry with the size of the contents
2149 // that would override the original contents. Set it to the original's
2150 // size/time.
2151 FileMgr.modifyFileEntry(const_cast<FileEntry*>(File),
2152 StoredSize, StoredTime);
2153 }
Guy Benyei11169dd2012-12-18 14:30:41 +00002154
Ben Langmuir198c1682014-03-07 07:27:49 +00002155 bool IsOutOfDate = false;
2156
2157 // For an overridden file, there is nothing to validate.
2158 if (!Overridden && (StoredSize != File->getSize()
Guy Benyei11169dd2012-12-18 14:30:41 +00002159#if !defined(LLVM_ON_WIN32)
Ben Langmuir198c1682014-03-07 07:27:49 +00002160 // In our regression testing, the Windows file system seems to
2161 // have inconsistent modification times that sometimes
2162 // erroneously trigger this error-handling path.
2163 || StoredTime != File->getModificationTime()
Guy Benyei11169dd2012-12-18 14:30:41 +00002164#endif
Ben Langmuir198c1682014-03-07 07:27:49 +00002165 )) {
2166 if (Complain) {
2167 // Build a list of the PCH imports that got us here (in reverse).
2168 SmallVector<ModuleFile *, 4> ImportStack(1, &F);
2169 while (ImportStack.back()->ImportedBy.size() > 0)
2170 ImportStack.push_back(ImportStack.back()->ImportedBy[0]);
Ben Langmuire82630d2014-01-17 00:19:09 +00002171
Ben Langmuir198c1682014-03-07 07:27:49 +00002172 // The top-level PCH is stale.
2173 StringRef TopLevelPCHName(ImportStack.back()->FileName);
2174 Error(diag::err_fe_pch_file_modified, Filename, TopLevelPCHName);
Ben Langmuire82630d2014-01-17 00:19:09 +00002175
Ben Langmuir198c1682014-03-07 07:27:49 +00002176 // Print the import stack.
2177 if (ImportStack.size() > 1 && !Diags.isDiagnosticInFlight()) {
2178 Diag(diag::note_pch_required_by)
2179 << Filename << ImportStack[0]->FileName;
2180 for (unsigned I = 1; I < ImportStack.size(); ++I)
Ben Langmuire82630d2014-01-17 00:19:09 +00002181 Diag(diag::note_pch_required_by)
Ben Langmuir198c1682014-03-07 07:27:49 +00002182 << ImportStack[I-1]->FileName << ImportStack[I]->FileName;
Douglas Gregor7029ce12013-03-19 00:28:20 +00002183 }
2184
Ben Langmuir198c1682014-03-07 07:27:49 +00002185 if (!Diags.isDiagnosticInFlight())
2186 Diag(diag::note_pch_rebuild_required) << TopLevelPCHName;
Guy Benyei11169dd2012-12-18 14:30:41 +00002187 }
2188
Ben Langmuir198c1682014-03-07 07:27:49 +00002189 IsOutOfDate = true;
Guy Benyei11169dd2012-12-18 14:30:41 +00002190 }
2191
Ben Langmuir198c1682014-03-07 07:27:49 +00002192 InputFile IF = InputFile(File, Overridden, IsOutOfDate);
2193
2194 // Note that we've loaded this input file.
2195 F.InputFilesLoaded[ID-1] = IF;
2196 return IF;
Guy Benyei11169dd2012-12-18 14:30:41 +00002197}
2198
2199const FileEntry *ASTReader::getFileEntry(StringRef filenameStrRef) {
2200 ModuleFile &M = ModuleMgr.getPrimaryModule();
2201 std::string Filename = filenameStrRef;
2202 MaybeAddSystemRootToFilename(M, Filename);
2203 const FileEntry *File = FileMgr.getFile(Filename);
Craig Toppera13603a2014-05-22 05:54:18 +00002204 if (File == nullptr && !M.OriginalDir.empty() && !CurrentDir.empty() &&
Guy Benyei11169dd2012-12-18 14:30:41 +00002205 M.OriginalDir != CurrentDir) {
2206 std::string resolved = resolveFileRelativeToOriginalDir(Filename,
2207 M.OriginalDir,
2208 CurrentDir);
2209 if (!resolved.empty())
2210 File = FileMgr.getFile(resolved);
2211 }
2212
2213 return File;
2214}
2215
2216/// \brief If we are loading a relocatable PCH file, and the filename is
2217/// not an absolute path, add the system root to the beginning of the file
2218/// name.
2219void ASTReader::MaybeAddSystemRootToFilename(ModuleFile &M,
2220 std::string &Filename) {
2221 // If this is not a relocatable PCH file, there's nothing to do.
2222 if (!M.RelocatablePCH)
2223 return;
2224
2225 if (Filename.empty() || llvm::sys::path::is_absolute(Filename))
2226 return;
2227
2228 if (isysroot.empty()) {
2229 // If no system root was given, default to '/'
2230 Filename.insert(Filename.begin(), '/');
2231 return;
2232 }
2233
2234 unsigned Length = isysroot.size();
2235 if (isysroot[Length - 1] != '/')
2236 Filename.insert(Filename.begin(), '/');
2237
2238 Filename.insert(Filename.begin(), isysroot.begin(), isysroot.end());
2239}
2240
2241ASTReader::ASTReadResult
2242ASTReader::ReadControlBlock(ModuleFile &F,
Dmitri Gribenkof8579502013-01-12 19:30:44 +00002243 SmallVectorImpl<ImportedModule> &Loaded,
Ben Langmuirbeee15e2014-04-14 18:00:01 +00002244 const ModuleFile *ImportedBy,
Guy Benyei11169dd2012-12-18 14:30:41 +00002245 unsigned ClientLoadCapabilities) {
Chris Lattner7fb3bef2013-01-20 00:56:42 +00002246 BitstreamCursor &Stream = F.Stream;
Guy Benyei11169dd2012-12-18 14:30:41 +00002247
2248 if (Stream.EnterSubBlock(CONTROL_BLOCK_ID)) {
2249 Error("malformed block record in AST file");
2250 return Failure;
2251 }
2252
2253 // Read all of the records and blocks in the control block.
2254 RecordData Record;
Chris Lattnere7b154b2013-01-19 21:39:22 +00002255 while (1) {
2256 llvm::BitstreamEntry Entry = Stream.advance();
2257
2258 switch (Entry.Kind) {
2259 case llvm::BitstreamEntry::Error:
2260 Error("malformed block record in AST file");
2261 return Failure;
Dmitri Gribenkof430da42014-02-12 10:33:14 +00002262 case llvm::BitstreamEntry::EndBlock: {
2263 // Validate input files.
2264 const HeaderSearchOptions &HSOpts =
2265 PP.getHeaderSearchInfo().getHeaderSearchOpts();
Ben Langmuircb69b572014-03-07 06:40:32 +00002266
2267 // All user input files reside at the index range [0, Record[1]), and
2268 // system input files reside at [Record[1], Record[0]).
2269 // Record is the one from INPUT_FILE_OFFSETS.
2270 unsigned NumInputs = Record[0];
2271 unsigned NumUserInputs = Record[1];
2272
Dmitri Gribenkof430da42014-02-12 10:33:14 +00002273 if (!DisableValidation &&
Ben Langmuir1e258222014-04-08 15:36:28 +00002274 (ValidateSystemInputs || !HSOpts.ModulesValidateOncePerBuildSession ||
Dmitri Gribenkof430da42014-02-12 10:33:14 +00002275 F.InputFilesValidationTimestamp <= HSOpts.BuildSessionTimestamp)) {
Guy Benyei11169dd2012-12-18 14:30:41 +00002276 bool Complain = (ClientLoadCapabilities & ARR_OutOfDate) == 0;
Ben Langmuircb69b572014-03-07 06:40:32 +00002277
Dmitri Gribenkof430da42014-02-12 10:33:14 +00002278 // If we are reading a module, we will create a verification timestamp,
2279 // so we verify all input files. Otherwise, verify only user input
2280 // files.
Ben Langmuircb69b572014-03-07 06:40:32 +00002281
2282 unsigned N = NumUserInputs;
2283 if (ValidateSystemInputs ||
Richard Smithe842a472014-10-22 02:05:46 +00002284 (HSOpts.ModulesValidateOncePerBuildSession &&
2285 F.Kind == MK_ImplicitModule))
Ben Langmuircb69b572014-03-07 06:40:32 +00002286 N = NumInputs;
2287
Ben Langmuir3d4417c2014-02-07 17:31:11 +00002288 for (unsigned I = 0; I < N; ++I) {
Argyrios Kyrtzidis61c3d872013-03-01 03:26:04 +00002289 InputFile IF = getInputFile(F, I+1, Complain);
2290 if (!IF.getFile() || IF.isOutOfDate())
Guy Benyei11169dd2012-12-18 14:30:41 +00002291 return OutOfDate;
Argyrios Kyrtzidis61c3d872013-03-01 03:26:04 +00002292 }
Guy Benyei11169dd2012-12-18 14:30:41 +00002293 }
Ben Langmuircb69b572014-03-07 06:40:32 +00002294
Argyrios Kyrtzidis6d0753d2014-03-14 03:07:38 +00002295 if (Listener)
2296 Listener->visitModuleFile(F.FileName);
2297
Ben Langmuircb69b572014-03-07 06:40:32 +00002298 if (Listener && Listener->needsInputFileVisitation()) {
2299 unsigned N = Listener->needsSystemInputFileVisitation() ? NumInputs
2300 : NumUserInputs;
Argyrios Kyrtzidis68ccbe02014-03-14 02:26:31 +00002301 for (unsigned I = 0; I < N; ++I) {
2302 bool IsSystem = I >= NumUserInputs;
2303 InputFileInfo FI = readInputFileInfo(F, I+1);
2304 Listener->visitInputFile(FI.Filename, IsSystem, FI.Overridden);
2305 }
Ben Langmuircb69b572014-03-07 06:40:32 +00002306 }
2307
Guy Benyei11169dd2012-12-18 14:30:41 +00002308 return Success;
Dmitri Gribenkof430da42014-02-12 10:33:14 +00002309 }
2310
Chris Lattnere7b154b2013-01-19 21:39:22 +00002311 case llvm::BitstreamEntry::SubBlock:
2312 switch (Entry.ID) {
Guy Benyei11169dd2012-12-18 14:30:41 +00002313 case INPUT_FILES_BLOCK_ID:
2314 F.InputFilesCursor = Stream;
2315 if (Stream.SkipBlock() || // Skip with the main cursor
2316 // Read the abbreviations
2317 ReadBlockAbbrevs(F.InputFilesCursor, INPUT_FILES_BLOCK_ID)) {
2318 Error("malformed block record in AST file");
2319 return Failure;
2320 }
2321 continue;
Chris Lattnere7b154b2013-01-19 21:39:22 +00002322
Guy Benyei11169dd2012-12-18 14:30:41 +00002323 default:
Chris Lattnere7b154b2013-01-19 21:39:22 +00002324 if (Stream.SkipBlock()) {
2325 Error("malformed block record in AST file");
2326 return Failure;
2327 }
2328 continue;
Guy Benyei11169dd2012-12-18 14:30:41 +00002329 }
Chris Lattnere7b154b2013-01-19 21:39:22 +00002330
2331 case llvm::BitstreamEntry::Record:
2332 // The interesting case.
2333 break;
Guy Benyei11169dd2012-12-18 14:30:41 +00002334 }
2335
2336 // Read and process a record.
2337 Record.clear();
Chris Lattner0e6c9402013-01-20 02:38:54 +00002338 StringRef Blob;
2339 switch ((ControlRecordTypes)Stream.readRecord(Entry.ID, Record, &Blob)) {
Guy Benyei11169dd2012-12-18 14:30:41 +00002340 case METADATA: {
2341 if (Record[0] != VERSION_MAJOR && !DisableValidation) {
2342 if ((ClientLoadCapabilities & ARR_VersionMismatch) == 0)
Dmitri Gribenko2228cd32014-02-11 15:40:09 +00002343 Diag(Record[0] < VERSION_MAJOR? diag::err_pch_version_too_old
2344 : diag::err_pch_version_too_new);
Guy Benyei11169dd2012-12-18 14:30:41 +00002345 return VersionMismatch;
2346 }
2347
2348 bool hasErrors = Record[5];
2349 if (hasErrors && !DisableValidation && !AllowASTWithCompilerErrors) {
2350 Diag(diag::err_pch_with_compiler_errors);
2351 return HadErrors;
2352 }
2353
2354 F.RelocatablePCH = Record[4];
2355
2356 const std::string &CurBranch = getClangFullRepositoryVersion();
Chris Lattner0e6c9402013-01-20 02:38:54 +00002357 StringRef ASTBranch = Blob;
Guy Benyei11169dd2012-12-18 14:30:41 +00002358 if (StringRef(CurBranch) != ASTBranch && !DisableValidation) {
2359 if ((ClientLoadCapabilities & ARR_VersionMismatch) == 0)
Dmitri Gribenko2228cd32014-02-11 15:40:09 +00002360 Diag(diag::err_pch_different_branch) << ASTBranch << CurBranch;
Guy Benyei11169dd2012-12-18 14:30:41 +00002361 return VersionMismatch;
2362 }
2363 break;
2364 }
2365
Ben Langmuir487ea142014-10-23 18:05:36 +00002366 case SIGNATURE:
2367 assert((!F.Signature || F.Signature == Record[0]) && "signature changed");
2368 F.Signature = Record[0];
2369 break;
2370
Guy Benyei11169dd2012-12-18 14:30:41 +00002371 case IMPORTS: {
2372 // Load each of the imported PCH files.
2373 unsigned Idx = 0, N = Record.size();
2374 while (Idx < N) {
2375 // Read information about the AST file.
2376 ModuleKind ImportedKind = (ModuleKind)Record[Idx++];
2377 // The import location will be the local one for now; we will adjust
2378 // all import locations of module imports after the global source
2379 // location info are setup.
2380 SourceLocation ImportLoc =
2381 SourceLocation::getFromRawEncoding(Record[Idx++]);
Douglas Gregor7029ce12013-03-19 00:28:20 +00002382 off_t StoredSize = (off_t)Record[Idx++];
2383 time_t StoredModTime = (time_t)Record[Idx++];
Ben Langmuir487ea142014-10-23 18:05:36 +00002384 ASTFileSignature StoredSignature = Record[Idx++];
Guy Benyei11169dd2012-12-18 14:30:41 +00002385 unsigned Length = Record[Idx++];
2386 SmallString<128> ImportedFile(Record.begin() + Idx,
2387 Record.begin() + Idx + Length);
2388 Idx += Length;
2389
2390 // Load the AST file.
2391 switch(ReadASTCore(ImportedFile, ImportedKind, ImportLoc, &F, Loaded,
Ben Langmuir487ea142014-10-23 18:05:36 +00002392 StoredSize, StoredModTime, StoredSignature,
Guy Benyei11169dd2012-12-18 14:30:41 +00002393 ClientLoadCapabilities)) {
2394 case Failure: return Failure;
2395 // If we have to ignore the dependency, we'll have to ignore this too.
Douglas Gregor2f1806e2013-03-19 00:38:50 +00002396 case Missing:
Guy Benyei11169dd2012-12-18 14:30:41 +00002397 case OutOfDate: return OutOfDate;
2398 case VersionMismatch: return VersionMismatch;
2399 case ConfigurationMismatch: return ConfigurationMismatch;
2400 case HadErrors: return HadErrors;
2401 case Success: break;
2402 }
2403 }
2404 break;
2405 }
2406
2407 case LANGUAGE_OPTIONS: {
2408 bool Complain = (ClientLoadCapabilities & ARR_ConfigurationMismatch) == 0;
2409 if (Listener && &F == *ModuleMgr.begin() &&
2410 ParseLanguageOptions(Record, Complain, *Listener) &&
Ben Langmuir2cb4a782014-02-05 22:21:15 +00002411 !DisableValidation && !AllowConfigurationMismatch)
Guy Benyei11169dd2012-12-18 14:30:41 +00002412 return ConfigurationMismatch;
2413 break;
2414 }
2415
2416 case TARGET_OPTIONS: {
2417 bool Complain = (ClientLoadCapabilities & ARR_ConfigurationMismatch)==0;
2418 if (Listener && &F == *ModuleMgr.begin() &&
2419 ParseTargetOptions(Record, Complain, *Listener) &&
Ben Langmuir2cb4a782014-02-05 22:21:15 +00002420 !DisableValidation && !AllowConfigurationMismatch)
Guy Benyei11169dd2012-12-18 14:30:41 +00002421 return ConfigurationMismatch;
2422 break;
2423 }
2424
2425 case DIAGNOSTIC_OPTIONS: {
Ben Langmuirb92de022014-04-29 16:25:26 +00002426 bool Complain = (ClientLoadCapabilities & ARR_OutOfDate)==0;
Guy Benyei11169dd2012-12-18 14:30:41 +00002427 if (Listener && &F == *ModuleMgr.begin() &&
2428 ParseDiagnosticOptions(Record, Complain, *Listener) &&
Ben Langmuirb92de022014-04-29 16:25:26 +00002429 !DisableValidation)
2430 return OutOfDate;
Guy Benyei11169dd2012-12-18 14:30:41 +00002431 break;
2432 }
2433
2434 case FILE_SYSTEM_OPTIONS: {
2435 bool Complain = (ClientLoadCapabilities & ARR_ConfigurationMismatch)==0;
2436 if (Listener && &F == *ModuleMgr.begin() &&
2437 ParseFileSystemOptions(Record, Complain, *Listener) &&
Ben Langmuir2cb4a782014-02-05 22:21:15 +00002438 !DisableValidation && !AllowConfigurationMismatch)
Guy Benyei11169dd2012-12-18 14:30:41 +00002439 return ConfigurationMismatch;
2440 break;
2441 }
2442
2443 case HEADER_SEARCH_OPTIONS: {
2444 bool Complain = (ClientLoadCapabilities & ARR_ConfigurationMismatch)==0;
2445 if (Listener && &F == *ModuleMgr.begin() &&
2446 ParseHeaderSearchOptions(Record, Complain, *Listener) &&
Ben Langmuir2cb4a782014-02-05 22:21:15 +00002447 !DisableValidation && !AllowConfigurationMismatch)
Guy Benyei11169dd2012-12-18 14:30:41 +00002448 return ConfigurationMismatch;
2449 break;
2450 }
2451
2452 case PREPROCESSOR_OPTIONS: {
2453 bool Complain = (ClientLoadCapabilities & ARR_ConfigurationMismatch)==0;
2454 if (Listener && &F == *ModuleMgr.begin() &&
2455 ParsePreprocessorOptions(Record, Complain, *Listener,
2456 SuggestedPredefines) &&
Ben Langmuir2cb4a782014-02-05 22:21:15 +00002457 !DisableValidation && !AllowConfigurationMismatch)
Guy Benyei11169dd2012-12-18 14:30:41 +00002458 return ConfigurationMismatch;
2459 break;
2460 }
2461
2462 case ORIGINAL_FILE:
2463 F.OriginalSourceFileID = FileID::get(Record[0]);
Chris Lattner0e6c9402013-01-20 02:38:54 +00002464 F.ActualOriginalSourceFileName = Blob;
Guy Benyei11169dd2012-12-18 14:30:41 +00002465 F.OriginalSourceFileName = F.ActualOriginalSourceFileName;
2466 MaybeAddSystemRootToFilename(F, F.OriginalSourceFileName);
2467 break;
2468
2469 case ORIGINAL_FILE_ID:
2470 F.OriginalSourceFileID = FileID::get(Record[0]);
2471 break;
2472
2473 case ORIGINAL_PCH_DIR:
Chris Lattner0e6c9402013-01-20 02:38:54 +00002474 F.OriginalDir = Blob;
Guy Benyei11169dd2012-12-18 14:30:41 +00002475 break;
2476
Ben Langmuirbeee15e2014-04-14 18:00:01 +00002477 case MODULE_NAME:
2478 F.ModuleName = Blob;
Ben Langmuir4f5212a2014-04-14 22:12:44 +00002479 if (Listener)
2480 Listener->ReadModuleName(F.ModuleName);
Ben Langmuirbeee15e2014-04-14 18:00:01 +00002481 break;
2482
2483 case MODULE_MAP_FILE:
Ben Langmuir4b8a9e92014-08-12 16:42:33 +00002484 if (ASTReadResult Result =
2485 ReadModuleMapFileBlock(Record, F, ImportedBy, ClientLoadCapabilities))
2486 return Result;
Guy Benyei11169dd2012-12-18 14:30:41 +00002487 case INPUT_FILE_OFFSETS:
Chris Lattner0e6c9402013-01-20 02:38:54 +00002488 F.InputFileOffsets = (const uint32_t *)Blob.data();
Guy Benyei11169dd2012-12-18 14:30:41 +00002489 F.InputFilesLoaded.resize(Record[0]);
2490 break;
2491 }
2492 }
Guy Benyei11169dd2012-12-18 14:30:41 +00002493}
2494
Ben Langmuir2c9af442014-04-10 17:57:43 +00002495ASTReader::ASTReadResult
2496ASTReader::ReadASTBlock(ModuleFile &F, unsigned ClientLoadCapabilities) {
Chris Lattner7fb3bef2013-01-20 00:56:42 +00002497 BitstreamCursor &Stream = F.Stream;
Guy Benyei11169dd2012-12-18 14:30:41 +00002498
2499 if (Stream.EnterSubBlock(AST_BLOCK_ID)) {
2500 Error("malformed block record in AST file");
Ben Langmuir2c9af442014-04-10 17:57:43 +00002501 return Failure;
Guy Benyei11169dd2012-12-18 14:30:41 +00002502 }
2503
2504 // Read all of the records and blocks for the AST file.
2505 RecordData Record;
Chris Lattnere7b154b2013-01-19 21:39:22 +00002506 while (1) {
2507 llvm::BitstreamEntry Entry = Stream.advance();
2508
2509 switch (Entry.Kind) {
2510 case llvm::BitstreamEntry::Error:
2511 Error("error at end of module block in AST file");
Ben Langmuir2c9af442014-04-10 17:57:43 +00002512 return Failure;
Chris Lattnere7b154b2013-01-19 21:39:22 +00002513 case llvm::BitstreamEntry::EndBlock: {
Richard Smithc0fbba72013-04-03 22:49:41 +00002514 // Outside of C++, we do not store a lookup map for the translation unit.
2515 // Instead, mark it as needing a lookup map to be built if this module
2516 // contains any declarations lexically within it (which it always does!).
2517 // This usually has no cost, since we very rarely need the lookup map for
2518 // the translation unit outside C++.
Guy Benyei11169dd2012-12-18 14:30:41 +00002519 DeclContext *DC = Context.getTranslationUnitDecl();
Richard Smithc0fbba72013-04-03 22:49:41 +00002520 if (DC->hasExternalLexicalStorage() &&
2521 !getContext().getLangOpts().CPlusPlus)
Guy Benyei11169dd2012-12-18 14:30:41 +00002522 DC->setMustBuildLookupTable();
Chris Lattnere7b154b2013-01-19 21:39:22 +00002523
Ben Langmuir2c9af442014-04-10 17:57:43 +00002524 return Success;
Guy Benyei11169dd2012-12-18 14:30:41 +00002525 }
Chris Lattnere7b154b2013-01-19 21:39:22 +00002526 case llvm::BitstreamEntry::SubBlock:
2527 switch (Entry.ID) {
Guy Benyei11169dd2012-12-18 14:30:41 +00002528 case DECLTYPES_BLOCK_ID:
2529 // We lazily load the decls block, but we want to set up the
2530 // DeclsCursor cursor to point into it. Clone our current bitcode
2531 // cursor to it, enter the block and read the abbrevs in that block.
2532 // With the main cursor, we just skip over it.
2533 F.DeclsCursor = Stream;
2534 if (Stream.SkipBlock() || // Skip with the main cursor.
2535 // Read the abbrevs.
2536 ReadBlockAbbrevs(F.DeclsCursor, DECLTYPES_BLOCK_ID)) {
2537 Error("malformed block record in AST file");
Ben Langmuir2c9af442014-04-10 17:57:43 +00002538 return Failure;
Guy Benyei11169dd2012-12-18 14:30:41 +00002539 }
2540 break;
Richard Smithb9eab6d2014-03-20 19:44:17 +00002541
Guy Benyei11169dd2012-12-18 14:30:41 +00002542 case PREPROCESSOR_BLOCK_ID:
2543 F.MacroCursor = Stream;
2544 if (!PP.getExternalSource())
2545 PP.setExternalSource(this);
Chris Lattnere7b154b2013-01-19 21:39:22 +00002546
Guy Benyei11169dd2012-12-18 14:30:41 +00002547 if (Stream.SkipBlock() ||
2548 ReadBlockAbbrevs(F.MacroCursor, PREPROCESSOR_BLOCK_ID)) {
2549 Error("malformed block record in AST file");
Ben Langmuir2c9af442014-04-10 17:57:43 +00002550 return Failure;
Guy Benyei11169dd2012-12-18 14:30:41 +00002551 }
2552 F.MacroStartOffset = F.MacroCursor.GetCurrentBitNo();
2553 break;
Chris Lattnere7b154b2013-01-19 21:39:22 +00002554
Guy Benyei11169dd2012-12-18 14:30:41 +00002555 case PREPROCESSOR_DETAIL_BLOCK_ID:
2556 F.PreprocessorDetailCursor = Stream;
2557 if (Stream.SkipBlock() ||
Chris Lattnere7b154b2013-01-19 21:39:22 +00002558 ReadBlockAbbrevs(F.PreprocessorDetailCursor,
Guy Benyei11169dd2012-12-18 14:30:41 +00002559 PREPROCESSOR_DETAIL_BLOCK_ID)) {
Chris Lattnere7b154b2013-01-19 21:39:22 +00002560 Error("malformed preprocessor detail record in AST file");
Ben Langmuir2c9af442014-04-10 17:57:43 +00002561 return Failure;
Chris Lattnere7b154b2013-01-19 21:39:22 +00002562 }
Guy Benyei11169dd2012-12-18 14:30:41 +00002563 F.PreprocessorDetailStartOffset
Chris Lattnere7b154b2013-01-19 21:39:22 +00002564 = F.PreprocessorDetailCursor.GetCurrentBitNo();
2565
Guy Benyei11169dd2012-12-18 14:30:41 +00002566 if (!PP.getPreprocessingRecord())
2567 PP.createPreprocessingRecord();
2568 if (!PP.getPreprocessingRecord()->getExternalSource())
2569 PP.getPreprocessingRecord()->SetExternalSource(*this);
2570 break;
2571
2572 case SOURCE_MANAGER_BLOCK_ID:
2573 if (ReadSourceManagerBlock(F))
Ben Langmuir2c9af442014-04-10 17:57:43 +00002574 return Failure;
Guy Benyei11169dd2012-12-18 14:30:41 +00002575 break;
Chris Lattnere7b154b2013-01-19 21:39:22 +00002576
Guy Benyei11169dd2012-12-18 14:30:41 +00002577 case SUBMODULE_BLOCK_ID:
Ben Langmuir2c9af442014-04-10 17:57:43 +00002578 if (ASTReadResult Result = ReadSubmoduleBlock(F, ClientLoadCapabilities))
2579 return Result;
Guy Benyei11169dd2012-12-18 14:30:41 +00002580 break;
Chris Lattnere7b154b2013-01-19 21:39:22 +00002581
Guy Benyei11169dd2012-12-18 14:30:41 +00002582 case COMMENTS_BLOCK_ID: {
Chris Lattner7fb3bef2013-01-20 00:56:42 +00002583 BitstreamCursor C = Stream;
Guy Benyei11169dd2012-12-18 14:30:41 +00002584 if (Stream.SkipBlock() ||
2585 ReadBlockAbbrevs(C, COMMENTS_BLOCK_ID)) {
2586 Error("malformed comments block in AST file");
Ben Langmuir2c9af442014-04-10 17:57:43 +00002587 return Failure;
Guy Benyei11169dd2012-12-18 14:30:41 +00002588 }
2589 CommentsCursors.push_back(std::make_pair(C, &F));
2590 break;
2591 }
Chris Lattnere7b154b2013-01-19 21:39:22 +00002592
Guy Benyei11169dd2012-12-18 14:30:41 +00002593 default:
Chris Lattnere7b154b2013-01-19 21:39:22 +00002594 if (Stream.SkipBlock()) {
2595 Error("malformed block record in AST file");
Ben Langmuir2c9af442014-04-10 17:57:43 +00002596 return Failure;
Chris Lattnere7b154b2013-01-19 21:39:22 +00002597 }
2598 break;
Guy Benyei11169dd2012-12-18 14:30:41 +00002599 }
2600 continue;
Chris Lattnere7b154b2013-01-19 21:39:22 +00002601
2602 case llvm::BitstreamEntry::Record:
2603 // The interesting case.
2604 break;
Guy Benyei11169dd2012-12-18 14:30:41 +00002605 }
2606
2607 // Read and process a record.
2608 Record.clear();
Chris Lattner0e6c9402013-01-20 02:38:54 +00002609 StringRef Blob;
2610 switch ((ASTRecordTypes)Stream.readRecord(Entry.ID, Record, &Blob)) {
Guy Benyei11169dd2012-12-18 14:30:41 +00002611 default: // Default behavior: ignore.
2612 break;
2613
2614 case TYPE_OFFSET: {
2615 if (F.LocalNumTypes != 0) {
2616 Error("duplicate TYPE_OFFSET record in AST file");
Ben Langmuir2c9af442014-04-10 17:57:43 +00002617 return Failure;
Guy Benyei11169dd2012-12-18 14:30:41 +00002618 }
Chris Lattner0e6c9402013-01-20 02:38:54 +00002619 F.TypeOffsets = (const uint32_t *)Blob.data();
Guy Benyei11169dd2012-12-18 14:30:41 +00002620 F.LocalNumTypes = Record[0];
2621 unsigned LocalBaseTypeIndex = Record[1];
2622 F.BaseTypeIndex = getTotalNumTypes();
2623
2624 if (F.LocalNumTypes > 0) {
2625 // Introduce the global -> local mapping for types within this module.
2626 GlobalTypeMap.insert(std::make_pair(getTotalNumTypes(), &F));
2627
2628 // Introduce the local -> global mapping for types within this module.
2629 F.TypeRemap.insertOrReplace(
2630 std::make_pair(LocalBaseTypeIndex,
2631 F.BaseTypeIndex - LocalBaseTypeIndex));
Ben Langmuir52ca6782014-10-20 16:27:32 +00002632
2633 TypesLoaded.resize(TypesLoaded.size() + F.LocalNumTypes);
Guy Benyei11169dd2012-12-18 14:30:41 +00002634 }
2635 break;
2636 }
2637
2638 case DECL_OFFSET: {
2639 if (F.LocalNumDecls != 0) {
2640 Error("duplicate DECL_OFFSET record in AST file");
Ben Langmuir2c9af442014-04-10 17:57:43 +00002641 return Failure;
Guy Benyei11169dd2012-12-18 14:30:41 +00002642 }
Chris Lattner0e6c9402013-01-20 02:38:54 +00002643 F.DeclOffsets = (const DeclOffset *)Blob.data();
Guy Benyei11169dd2012-12-18 14:30:41 +00002644 F.LocalNumDecls = Record[0];
2645 unsigned LocalBaseDeclID = Record[1];
2646 F.BaseDeclID = getTotalNumDecls();
2647
2648 if (F.LocalNumDecls > 0) {
2649 // Introduce the global -> local mapping for declarations within this
2650 // module.
2651 GlobalDeclMap.insert(
2652 std::make_pair(getTotalNumDecls() + NUM_PREDEF_DECL_IDS, &F));
2653
2654 // Introduce the local -> global mapping for declarations within this
2655 // module.
2656 F.DeclRemap.insertOrReplace(
2657 std::make_pair(LocalBaseDeclID, F.BaseDeclID - LocalBaseDeclID));
2658
2659 // Introduce the global -> local mapping for declarations within this
2660 // module.
2661 F.GlobalToLocalDeclIDs[&F] = LocalBaseDeclID;
Ben Langmuirfe971d92014-08-16 04:54:18 +00002662
Ben Langmuir52ca6782014-10-20 16:27:32 +00002663 DeclsLoaded.resize(DeclsLoaded.size() + F.LocalNumDecls);
2664 }
Guy Benyei11169dd2012-12-18 14:30:41 +00002665 break;
2666 }
2667
2668 case TU_UPDATE_LEXICAL: {
2669 DeclContext *TU = Context.getTranslationUnitDecl();
2670 DeclContextInfo &Info = F.DeclContextInfos[TU];
Chris Lattner0e6c9402013-01-20 02:38:54 +00002671 Info.LexicalDecls = reinterpret_cast<const KindDeclIDPair *>(Blob.data());
Guy Benyei11169dd2012-12-18 14:30:41 +00002672 Info.NumLexicalDecls
Chris Lattner0e6c9402013-01-20 02:38:54 +00002673 = static_cast<unsigned int>(Blob.size() / sizeof(KindDeclIDPair));
Guy Benyei11169dd2012-12-18 14:30:41 +00002674 TU->setHasExternalLexicalStorage(true);
2675 break;
2676 }
2677
2678 case UPDATE_VISIBLE: {
2679 unsigned Idx = 0;
2680 serialization::DeclID ID = ReadDeclID(F, Record, Idx);
2681 ASTDeclContextNameLookupTable *Table =
Justin Bognerda4e6502014-04-14 16:34:29 +00002682 ASTDeclContextNameLookupTable::Create(
2683 (const unsigned char *)Blob.data() + Record[Idx++],
2684 (const unsigned char *)Blob.data() + sizeof(uint32_t),
2685 (const unsigned char *)Blob.data(),
2686 ASTDeclContextNameLookupTrait(*this, F));
Richard Smithcd45dbc2014-04-19 03:48:30 +00002687 if (Decl *D = GetExistingDecl(ID)) {
Richard Smithd9174792014-03-11 03:10:46 +00002688 auto *DC = cast<DeclContext>(D);
2689 DC->getPrimaryContext()->setHasExternalVisibleStorage(true);
Richard Smith52e3fba2014-03-11 07:17:35 +00002690 auto *&LookupTable = F.DeclContextInfos[DC].NameLookupTableData;
2691 delete LookupTable;
2692 LookupTable = Table;
Guy Benyei11169dd2012-12-18 14:30:41 +00002693 } else
2694 PendingVisibleUpdates[ID].push_back(std::make_pair(Table, &F));
2695 break;
2696 }
2697
2698 case IDENTIFIER_TABLE:
Chris Lattner0e6c9402013-01-20 02:38:54 +00002699 F.IdentifierTableData = Blob.data();
Guy Benyei11169dd2012-12-18 14:30:41 +00002700 if (Record[0]) {
Justin Bognerda4e6502014-04-14 16:34:29 +00002701 F.IdentifierLookupTable = ASTIdentifierLookupTable::Create(
2702 (const unsigned char *)F.IdentifierTableData + Record[0],
2703 (const unsigned char *)F.IdentifierTableData + sizeof(uint32_t),
2704 (const unsigned char *)F.IdentifierTableData,
2705 ASTIdentifierLookupTrait(*this, F));
Guy Benyei11169dd2012-12-18 14:30:41 +00002706
2707 PP.getIdentifierTable().setExternalIdentifierLookup(this);
2708 }
2709 break;
2710
2711 case IDENTIFIER_OFFSET: {
2712 if (F.LocalNumIdentifiers != 0) {
2713 Error("duplicate IDENTIFIER_OFFSET record in AST file");
Ben Langmuir2c9af442014-04-10 17:57:43 +00002714 return Failure;
Guy Benyei11169dd2012-12-18 14:30:41 +00002715 }
Chris Lattner0e6c9402013-01-20 02:38:54 +00002716 F.IdentifierOffsets = (const uint32_t *)Blob.data();
Guy Benyei11169dd2012-12-18 14:30:41 +00002717 F.LocalNumIdentifiers = Record[0];
2718 unsigned LocalBaseIdentifierID = Record[1];
2719 F.BaseIdentifierID = getTotalNumIdentifiers();
2720
2721 if (F.LocalNumIdentifiers > 0) {
2722 // Introduce the global -> local mapping for identifiers within this
2723 // module.
2724 GlobalIdentifierMap.insert(std::make_pair(getTotalNumIdentifiers() + 1,
2725 &F));
2726
2727 // Introduce the local -> global mapping for identifiers within this
2728 // module.
2729 F.IdentifierRemap.insertOrReplace(
2730 std::make_pair(LocalBaseIdentifierID,
2731 F.BaseIdentifierID - LocalBaseIdentifierID));
Ben Langmuirfe971d92014-08-16 04:54:18 +00002732
Ben Langmuir52ca6782014-10-20 16:27:32 +00002733 IdentifiersLoaded.resize(IdentifiersLoaded.size()
2734 + F.LocalNumIdentifiers);
2735 }
Guy Benyei11169dd2012-12-18 14:30:41 +00002736 break;
2737 }
2738
Ben Langmuir332aafe2014-01-31 01:06:56 +00002739 case EAGERLY_DESERIALIZED_DECLS:
Guy Benyei11169dd2012-12-18 14:30:41 +00002740 for (unsigned I = 0, N = Record.size(); I != N; ++I)
Ben Langmuir332aafe2014-01-31 01:06:56 +00002741 EagerlyDeserializedDecls.push_back(getGlobalDeclID(F, Record[I]));
Guy Benyei11169dd2012-12-18 14:30:41 +00002742 break;
2743
2744 case SPECIAL_TYPES:
Douglas Gregor44180f82013-02-01 23:45:03 +00002745 if (SpecialTypes.empty()) {
2746 for (unsigned I = 0, N = Record.size(); I != N; ++I)
2747 SpecialTypes.push_back(getGlobalTypeID(F, Record[I]));
2748 break;
2749 }
2750
2751 if (SpecialTypes.size() != Record.size()) {
2752 Error("invalid special-types record");
Ben Langmuir2c9af442014-04-10 17:57:43 +00002753 return Failure;
Douglas Gregor44180f82013-02-01 23:45:03 +00002754 }
2755
2756 for (unsigned I = 0, N = Record.size(); I != N; ++I) {
2757 serialization::TypeID ID = getGlobalTypeID(F, Record[I]);
2758 if (!SpecialTypes[I])
2759 SpecialTypes[I] = ID;
2760 // FIXME: If ID && SpecialTypes[I] != ID, do we need a separate
2761 // merge step?
2762 }
Guy Benyei11169dd2012-12-18 14:30:41 +00002763 break;
2764
2765 case STATISTICS:
2766 TotalNumStatements += Record[0];
2767 TotalNumMacros += Record[1];
2768 TotalLexicalDeclContexts += Record[2];
2769 TotalVisibleDeclContexts += Record[3];
2770 break;
2771
2772 case UNUSED_FILESCOPED_DECLS:
2773 for (unsigned I = 0, N = Record.size(); I != N; ++I)
2774 UnusedFileScopedDecls.push_back(getGlobalDeclID(F, Record[I]));
2775 break;
2776
2777 case DELEGATING_CTORS:
2778 for (unsigned I = 0, N = Record.size(); I != N; ++I)
2779 DelegatingCtorDecls.push_back(getGlobalDeclID(F, Record[I]));
2780 break;
2781
2782 case WEAK_UNDECLARED_IDENTIFIERS:
2783 if (Record.size() % 4 != 0) {
2784 Error("invalid weak identifiers record");
Ben Langmuir2c9af442014-04-10 17:57:43 +00002785 return Failure;
Guy Benyei11169dd2012-12-18 14:30:41 +00002786 }
2787
2788 // FIXME: Ignore weak undeclared identifiers from non-original PCH
2789 // files. This isn't the way to do it :)
2790 WeakUndeclaredIdentifiers.clear();
2791
2792 // Translate the weak, undeclared identifiers into global IDs.
2793 for (unsigned I = 0, N = Record.size(); I < N; /* in loop */) {
2794 WeakUndeclaredIdentifiers.push_back(
2795 getGlobalIdentifierID(F, Record[I++]));
2796 WeakUndeclaredIdentifiers.push_back(
2797 getGlobalIdentifierID(F, Record[I++]));
2798 WeakUndeclaredIdentifiers.push_back(
2799 ReadSourceLocation(F, Record, I).getRawEncoding());
2800 WeakUndeclaredIdentifiers.push_back(Record[I++]);
2801 }
2802 break;
2803
Richard Smith78165b52013-01-10 23:43:47 +00002804 case LOCALLY_SCOPED_EXTERN_C_DECLS:
Guy Benyei11169dd2012-12-18 14:30:41 +00002805 for (unsigned I = 0, N = Record.size(); I != N; ++I)
Richard Smith78165b52013-01-10 23:43:47 +00002806 LocallyScopedExternCDecls.push_back(getGlobalDeclID(F, Record[I]));
Guy Benyei11169dd2012-12-18 14:30:41 +00002807 break;
2808
2809 case SELECTOR_OFFSETS: {
Chris Lattner0e6c9402013-01-20 02:38:54 +00002810 F.SelectorOffsets = (const uint32_t *)Blob.data();
Guy Benyei11169dd2012-12-18 14:30:41 +00002811 F.LocalNumSelectors = Record[0];
2812 unsigned LocalBaseSelectorID = Record[1];
2813 F.BaseSelectorID = getTotalNumSelectors();
2814
2815 if (F.LocalNumSelectors > 0) {
2816 // Introduce the global -> local mapping for selectors within this
2817 // module.
2818 GlobalSelectorMap.insert(std::make_pair(getTotalNumSelectors()+1, &F));
2819
2820 // Introduce the local -> global mapping for selectors within this
2821 // module.
2822 F.SelectorRemap.insertOrReplace(
2823 std::make_pair(LocalBaseSelectorID,
2824 F.BaseSelectorID - LocalBaseSelectorID));
Ben Langmuir52ca6782014-10-20 16:27:32 +00002825
2826 SelectorsLoaded.resize(SelectorsLoaded.size() + F.LocalNumSelectors);
Guy Benyei11169dd2012-12-18 14:30:41 +00002827 }
2828 break;
2829 }
2830
2831 case METHOD_POOL:
Chris Lattner0e6c9402013-01-20 02:38:54 +00002832 F.SelectorLookupTableData = (const unsigned char *)Blob.data();
Guy Benyei11169dd2012-12-18 14:30:41 +00002833 if (Record[0])
2834 F.SelectorLookupTable
2835 = ASTSelectorLookupTable::Create(
2836 F.SelectorLookupTableData + Record[0],
2837 F.SelectorLookupTableData,
2838 ASTSelectorLookupTrait(*this, F));
2839 TotalNumMethodPoolEntries += Record[1];
2840 break;
2841
2842 case REFERENCED_SELECTOR_POOL:
2843 if (!Record.empty()) {
2844 for (unsigned Idx = 0, N = Record.size() - 1; Idx < N; /* in loop */) {
2845 ReferencedSelectorsData.push_back(getGlobalSelectorID(F,
2846 Record[Idx++]));
2847 ReferencedSelectorsData.push_back(ReadSourceLocation(F, Record, Idx).
2848 getRawEncoding());
2849 }
2850 }
2851 break;
2852
2853 case PP_COUNTER_VALUE:
2854 if (!Record.empty() && Listener)
2855 Listener->ReadCounter(F, Record[0]);
2856 break;
2857
2858 case FILE_SORTED_DECLS:
Chris Lattner0e6c9402013-01-20 02:38:54 +00002859 F.FileSortedDecls = (const DeclID *)Blob.data();
Guy Benyei11169dd2012-12-18 14:30:41 +00002860 F.NumFileSortedDecls = Record[0];
2861 break;
2862
2863 case SOURCE_LOCATION_OFFSETS: {
Chris Lattner0e6c9402013-01-20 02:38:54 +00002864 F.SLocEntryOffsets = (const uint32_t *)Blob.data();
Guy Benyei11169dd2012-12-18 14:30:41 +00002865 F.LocalNumSLocEntries = Record[0];
2866 unsigned SLocSpaceSize = Record[1];
Benjamin Kramer867ea1d2014-03-02 13:01:17 +00002867 std::tie(F.SLocEntryBaseID, F.SLocEntryBaseOffset) =
Ben Langmuir52ca6782014-10-20 16:27:32 +00002868 SourceMgr.AllocateLoadedSLocEntries(F.LocalNumSLocEntries,
Guy Benyei11169dd2012-12-18 14:30:41 +00002869 SLocSpaceSize);
2870 // Make our entry in the range map. BaseID is negative and growing, so
2871 // we invert it. Because we invert it, though, we need the other end of
2872 // the range.
2873 unsigned RangeStart =
2874 unsigned(-F.SLocEntryBaseID) - F.LocalNumSLocEntries + 1;
2875 GlobalSLocEntryMap.insert(std::make_pair(RangeStart, &F));
2876 F.FirstLoc = SourceLocation::getFromRawEncoding(F.SLocEntryBaseOffset);
2877
2878 // SLocEntryBaseOffset is lower than MaxLoadedOffset and decreasing.
2879 assert((F.SLocEntryBaseOffset & (1U << 31U)) == 0);
2880 GlobalSLocOffsetMap.insert(
2881 std::make_pair(SourceManager::MaxLoadedOffset - F.SLocEntryBaseOffset
2882 - SLocSpaceSize,&F));
2883
2884 // Initialize the remapping table.
2885 // Invalid stays invalid.
Richard Smithb9eab6d2014-03-20 19:44:17 +00002886 F.SLocRemap.insertOrReplace(std::make_pair(0U, 0));
Guy Benyei11169dd2012-12-18 14:30:41 +00002887 // This module. Base was 2 when being compiled.
Richard Smithb9eab6d2014-03-20 19:44:17 +00002888 F.SLocRemap.insertOrReplace(std::make_pair(2U,
Guy Benyei11169dd2012-12-18 14:30:41 +00002889 static_cast<int>(F.SLocEntryBaseOffset - 2)));
2890
2891 TotalNumSLocEntries += F.LocalNumSLocEntries;
2892 break;
2893 }
2894
2895 case MODULE_OFFSET_MAP: {
2896 // Additional remapping information.
Chris Lattner0e6c9402013-01-20 02:38:54 +00002897 const unsigned char *Data = (const unsigned char*)Blob.data();
2898 const unsigned char *DataEnd = Data + Blob.size();
Richard Smithb9eab6d2014-03-20 19:44:17 +00002899
2900 // If we see this entry before SOURCE_LOCATION_OFFSETS, add placeholders.
2901 if (F.SLocRemap.find(0) == F.SLocRemap.end()) {
2902 F.SLocRemap.insert(std::make_pair(0U, 0));
2903 F.SLocRemap.insert(std::make_pair(2U, 1));
2904 }
2905
Guy Benyei11169dd2012-12-18 14:30:41 +00002906 // Continuous range maps we may be updating in our module.
Ben Langmuir785180e2014-10-20 16:27:30 +00002907 typedef ContinuousRangeMap<uint32_t, int, 2>::Builder
2908 RemapBuilder;
2909 RemapBuilder SLocRemap(F.SLocRemap);
2910 RemapBuilder IdentifierRemap(F.IdentifierRemap);
2911 RemapBuilder MacroRemap(F.MacroRemap);
2912 RemapBuilder PreprocessedEntityRemap(F.PreprocessedEntityRemap);
2913 RemapBuilder SubmoduleRemap(F.SubmoduleRemap);
2914 RemapBuilder SelectorRemap(F.SelectorRemap);
2915 RemapBuilder DeclRemap(F.DeclRemap);
2916 RemapBuilder TypeRemap(F.TypeRemap);
Guy Benyei11169dd2012-12-18 14:30:41 +00002917
2918 while(Data < DataEnd) {
Justin Bogner57ba0b22014-03-28 22:03:24 +00002919 using namespace llvm::support;
2920 uint16_t Len = endian::readNext<uint16_t, little, unaligned>(Data);
Guy Benyei11169dd2012-12-18 14:30:41 +00002921 StringRef Name = StringRef((const char*)Data, Len);
2922 Data += Len;
2923 ModuleFile *OM = ModuleMgr.lookup(Name);
2924 if (!OM) {
2925 Error("SourceLocation remap refers to unknown module");
Ben Langmuir2c9af442014-04-10 17:57:43 +00002926 return Failure;
Guy Benyei11169dd2012-12-18 14:30:41 +00002927 }
2928
Justin Bogner57ba0b22014-03-28 22:03:24 +00002929 uint32_t SLocOffset =
2930 endian::readNext<uint32_t, little, unaligned>(Data);
2931 uint32_t IdentifierIDOffset =
2932 endian::readNext<uint32_t, little, unaligned>(Data);
2933 uint32_t MacroIDOffset =
2934 endian::readNext<uint32_t, little, unaligned>(Data);
2935 uint32_t PreprocessedEntityIDOffset =
2936 endian::readNext<uint32_t, little, unaligned>(Data);
2937 uint32_t SubmoduleIDOffset =
2938 endian::readNext<uint32_t, little, unaligned>(Data);
2939 uint32_t SelectorIDOffset =
2940 endian::readNext<uint32_t, little, unaligned>(Data);
2941 uint32_t DeclIDOffset =
2942 endian::readNext<uint32_t, little, unaligned>(Data);
2943 uint32_t TypeIndexOffset =
2944 endian::readNext<uint32_t, little, unaligned>(Data);
2945
Ben Langmuir785180e2014-10-20 16:27:30 +00002946 uint32_t None = std::numeric_limits<uint32_t>::max();
2947
2948 auto mapOffset = [&](uint32_t Offset, uint32_t BaseOffset,
2949 RemapBuilder &Remap) {
2950 if (Offset != None)
2951 Remap.insert(std::make_pair(Offset,
2952 static_cast<int>(BaseOffset - Offset)));
2953 };
2954 mapOffset(SLocOffset, OM->SLocEntryBaseOffset, SLocRemap);
2955 mapOffset(IdentifierIDOffset, OM->BaseIdentifierID, IdentifierRemap);
2956 mapOffset(MacroIDOffset, OM->BaseMacroID, MacroRemap);
2957 mapOffset(PreprocessedEntityIDOffset, OM->BasePreprocessedEntityID,
2958 PreprocessedEntityRemap);
2959 mapOffset(SubmoduleIDOffset, OM->BaseSubmoduleID, SubmoduleRemap);
2960 mapOffset(SelectorIDOffset, OM->BaseSelectorID, SelectorRemap);
2961 mapOffset(DeclIDOffset, OM->BaseDeclID, DeclRemap);
2962 mapOffset(TypeIndexOffset, OM->BaseTypeIndex, TypeRemap);
Guy Benyei11169dd2012-12-18 14:30:41 +00002963
2964 // Global -> local mappings.
2965 F.GlobalToLocalDeclIDs[OM] = DeclIDOffset;
2966 }
2967 break;
2968 }
2969
2970 case SOURCE_MANAGER_LINE_TABLE:
2971 if (ParseLineTable(F, Record))
Ben Langmuir2c9af442014-04-10 17:57:43 +00002972 return Failure;
Guy Benyei11169dd2012-12-18 14:30:41 +00002973 break;
2974
2975 case SOURCE_LOCATION_PRELOADS: {
2976 // Need to transform from the local view (1-based IDs) to the global view,
2977 // which is based off F.SLocEntryBaseID.
2978 if (!F.PreloadSLocEntries.empty()) {
2979 Error("Multiple SOURCE_LOCATION_PRELOADS records in AST file");
Ben Langmuir2c9af442014-04-10 17:57:43 +00002980 return Failure;
Guy Benyei11169dd2012-12-18 14:30:41 +00002981 }
2982
2983 F.PreloadSLocEntries.swap(Record);
2984 break;
2985 }
2986
2987 case EXT_VECTOR_DECLS:
2988 for (unsigned I = 0, N = Record.size(); I != N; ++I)
2989 ExtVectorDecls.push_back(getGlobalDeclID(F, Record[I]));
2990 break;
2991
2992 case VTABLE_USES:
2993 if (Record.size() % 3 != 0) {
2994 Error("Invalid VTABLE_USES record");
Ben Langmuir2c9af442014-04-10 17:57:43 +00002995 return Failure;
Guy Benyei11169dd2012-12-18 14:30:41 +00002996 }
2997
2998 // Later tables overwrite earlier ones.
2999 // FIXME: Modules will have some trouble with this. This is clearly not
3000 // the right way to do this.
3001 VTableUses.clear();
3002
3003 for (unsigned Idx = 0, N = Record.size(); Idx != N; /* In loop */) {
3004 VTableUses.push_back(getGlobalDeclID(F, Record[Idx++]));
3005 VTableUses.push_back(
3006 ReadSourceLocation(F, Record, Idx).getRawEncoding());
3007 VTableUses.push_back(Record[Idx++]);
3008 }
3009 break;
3010
3011 case DYNAMIC_CLASSES:
3012 for (unsigned I = 0, N = Record.size(); I != N; ++I)
3013 DynamicClasses.push_back(getGlobalDeclID(F, Record[I]));
3014 break;
3015
3016 case PENDING_IMPLICIT_INSTANTIATIONS:
3017 if (PendingInstantiations.size() % 2 != 0) {
3018 Error("Invalid existing PendingInstantiations");
Ben Langmuir2c9af442014-04-10 17:57:43 +00003019 return Failure;
Guy Benyei11169dd2012-12-18 14:30:41 +00003020 }
3021
3022 if (Record.size() % 2 != 0) {
3023 Error("Invalid PENDING_IMPLICIT_INSTANTIATIONS block");
Ben Langmuir2c9af442014-04-10 17:57:43 +00003024 return Failure;
Guy Benyei11169dd2012-12-18 14:30:41 +00003025 }
3026
3027 for (unsigned I = 0, N = Record.size(); I != N; /* in loop */) {
3028 PendingInstantiations.push_back(getGlobalDeclID(F, Record[I++]));
3029 PendingInstantiations.push_back(
3030 ReadSourceLocation(F, Record, I).getRawEncoding());
3031 }
3032 break;
3033
3034 case SEMA_DECL_REFS:
Richard Smith3d8e97e2013-10-18 06:54:39 +00003035 if (Record.size() != 2) {
3036 Error("Invalid SEMA_DECL_REFS block");
Ben Langmuir2c9af442014-04-10 17:57:43 +00003037 return Failure;
Richard Smith3d8e97e2013-10-18 06:54:39 +00003038 }
Guy Benyei11169dd2012-12-18 14:30:41 +00003039 for (unsigned I = 0, N = Record.size(); I != N; ++I)
3040 SemaDeclRefs.push_back(getGlobalDeclID(F, Record[I]));
3041 break;
3042
3043 case PPD_ENTITIES_OFFSETS: {
Chris Lattner0e6c9402013-01-20 02:38:54 +00003044 F.PreprocessedEntityOffsets = (const PPEntityOffset *)Blob.data();
3045 assert(Blob.size() % sizeof(PPEntityOffset) == 0);
3046 F.NumPreprocessedEntities = Blob.size() / sizeof(PPEntityOffset);
Guy Benyei11169dd2012-12-18 14:30:41 +00003047
3048 unsigned LocalBasePreprocessedEntityID = Record[0];
3049
3050 unsigned StartingID;
3051 if (!PP.getPreprocessingRecord())
3052 PP.createPreprocessingRecord();
3053 if (!PP.getPreprocessingRecord()->getExternalSource())
3054 PP.getPreprocessingRecord()->SetExternalSource(*this);
3055 StartingID
3056 = PP.getPreprocessingRecord()
Ben Langmuir52ca6782014-10-20 16:27:32 +00003057 ->allocateLoadedEntities(F.NumPreprocessedEntities);
Guy Benyei11169dd2012-12-18 14:30:41 +00003058 F.BasePreprocessedEntityID = StartingID;
3059
3060 if (F.NumPreprocessedEntities > 0) {
3061 // Introduce the global -> local mapping for preprocessed entities in
3062 // this module.
3063 GlobalPreprocessedEntityMap.insert(std::make_pair(StartingID, &F));
3064
3065 // Introduce the local -> global mapping for preprocessed entities in
3066 // this module.
3067 F.PreprocessedEntityRemap.insertOrReplace(
3068 std::make_pair(LocalBasePreprocessedEntityID,
3069 F.BasePreprocessedEntityID - LocalBasePreprocessedEntityID));
3070 }
3071
3072 break;
3073 }
3074
3075 case DECL_UPDATE_OFFSETS: {
3076 if (Record.size() % 2 != 0) {
3077 Error("invalid DECL_UPDATE_OFFSETS block in AST file");
Ben Langmuir2c9af442014-04-10 17:57:43 +00003078 return Failure;
Guy Benyei11169dd2012-12-18 14:30:41 +00003079 }
Richard Smithcd45dbc2014-04-19 03:48:30 +00003080 for (unsigned I = 0, N = Record.size(); I != N; I += 2) {
3081 GlobalDeclID ID = getGlobalDeclID(F, Record[I]);
3082 DeclUpdateOffsets[ID].push_back(std::make_pair(&F, Record[I + 1]));
3083
3084 // If we've already loaded the decl, perform the updates when we finish
3085 // loading this block.
3086 if (Decl *D = GetExistingDecl(ID))
3087 PendingUpdateRecords.push_back(std::make_pair(ID, D));
3088 }
Guy Benyei11169dd2012-12-18 14:30:41 +00003089 break;
3090 }
3091
3092 case DECL_REPLACEMENTS: {
3093 if (Record.size() % 3 != 0) {
3094 Error("invalid DECL_REPLACEMENTS block in AST file");
Ben Langmuir2c9af442014-04-10 17:57:43 +00003095 return Failure;
Guy Benyei11169dd2012-12-18 14:30:41 +00003096 }
3097 for (unsigned I = 0, N = Record.size(); I != N; I += 3)
3098 ReplacedDecls[getGlobalDeclID(F, Record[I])]
3099 = ReplacedDeclInfo(&F, Record[I+1], Record[I+2]);
3100 break;
3101 }
3102
3103 case OBJC_CATEGORIES_MAP: {
3104 if (F.LocalNumObjCCategoriesInMap != 0) {
3105 Error("duplicate OBJC_CATEGORIES_MAP record in AST file");
Ben Langmuir2c9af442014-04-10 17:57:43 +00003106 return Failure;
Guy Benyei11169dd2012-12-18 14:30:41 +00003107 }
3108
3109 F.LocalNumObjCCategoriesInMap = Record[0];
Chris Lattner0e6c9402013-01-20 02:38:54 +00003110 F.ObjCCategoriesMap = (const ObjCCategoriesInfo *)Blob.data();
Guy Benyei11169dd2012-12-18 14:30:41 +00003111 break;
3112 }
3113
3114 case OBJC_CATEGORIES:
3115 F.ObjCCategories.swap(Record);
3116 break;
3117
3118 case CXX_BASE_SPECIFIER_OFFSETS: {
3119 if (F.LocalNumCXXBaseSpecifiers != 0) {
3120 Error("duplicate CXX_BASE_SPECIFIER_OFFSETS record in AST file");
Ben Langmuir2c9af442014-04-10 17:57:43 +00003121 return Failure;
Guy Benyei11169dd2012-12-18 14:30:41 +00003122 }
3123
3124 F.LocalNumCXXBaseSpecifiers = Record[0];
Chris Lattner0e6c9402013-01-20 02:38:54 +00003125 F.CXXBaseSpecifiersOffsets = (const uint32_t *)Blob.data();
Guy Benyei11169dd2012-12-18 14:30:41 +00003126 NumCXXBaseSpecifiersLoaded += F.LocalNumCXXBaseSpecifiers;
3127 break;
3128 }
3129
3130 case DIAG_PRAGMA_MAPPINGS:
3131 if (F.PragmaDiagMappings.empty())
3132 F.PragmaDiagMappings.swap(Record);
3133 else
3134 F.PragmaDiagMappings.insert(F.PragmaDiagMappings.end(),
3135 Record.begin(), Record.end());
3136 break;
3137
3138 case CUDA_SPECIAL_DECL_REFS:
3139 // Later tables overwrite earlier ones.
3140 // FIXME: Modules will have trouble with this.
3141 CUDASpecialDeclRefs.clear();
3142 for (unsigned I = 0, N = Record.size(); I != N; ++I)
3143 CUDASpecialDeclRefs.push_back(getGlobalDeclID(F, Record[I]));
3144 break;
3145
3146 case HEADER_SEARCH_TABLE: {
Chris Lattner0e6c9402013-01-20 02:38:54 +00003147 F.HeaderFileInfoTableData = Blob.data();
Guy Benyei11169dd2012-12-18 14:30:41 +00003148 F.LocalNumHeaderFileInfos = Record[1];
Guy Benyei11169dd2012-12-18 14:30:41 +00003149 if (Record[0]) {
3150 F.HeaderFileInfoTable
3151 = HeaderFileInfoLookupTable::Create(
3152 (const unsigned char *)F.HeaderFileInfoTableData + Record[0],
3153 (const unsigned char *)F.HeaderFileInfoTableData,
3154 HeaderFileInfoTrait(*this, F,
3155 &PP.getHeaderSearchInfo(),
Chris Lattner0e6c9402013-01-20 02:38:54 +00003156 Blob.data() + Record[2]));
Guy Benyei11169dd2012-12-18 14:30:41 +00003157
3158 PP.getHeaderSearchInfo().SetExternalSource(this);
3159 if (!PP.getHeaderSearchInfo().getExternalLookup())
3160 PP.getHeaderSearchInfo().SetExternalLookup(this);
3161 }
3162 break;
3163 }
3164
3165 case FP_PRAGMA_OPTIONS:
3166 // Later tables overwrite earlier ones.
3167 FPPragmaOptions.swap(Record);
3168 break;
3169
3170 case OPENCL_EXTENSIONS:
3171 // Later tables overwrite earlier ones.
3172 OpenCLExtensions.swap(Record);
3173 break;
3174
3175 case TENTATIVE_DEFINITIONS:
3176 for (unsigned I = 0, N = Record.size(); I != N; ++I)
3177 TentativeDefinitions.push_back(getGlobalDeclID(F, Record[I]));
3178 break;
3179
3180 case KNOWN_NAMESPACES:
3181 for (unsigned I = 0, N = Record.size(); I != N; ++I)
3182 KnownNamespaces.push_back(getGlobalDeclID(F, Record[I]));
3183 break;
Nick Lewycky8334af82013-01-26 00:35:08 +00003184
Nick Lewycky9c7eb1d2013-02-01 08:13:20 +00003185 case UNDEFINED_BUT_USED:
3186 if (UndefinedButUsed.size() % 2 != 0) {
3187 Error("Invalid existing UndefinedButUsed");
Ben Langmuir2c9af442014-04-10 17:57:43 +00003188 return Failure;
Nick Lewycky8334af82013-01-26 00:35:08 +00003189 }
3190
3191 if (Record.size() % 2 != 0) {
Nick Lewycky9c7eb1d2013-02-01 08:13:20 +00003192 Error("invalid undefined-but-used record");
Ben Langmuir2c9af442014-04-10 17:57:43 +00003193 return Failure;
Nick Lewycky8334af82013-01-26 00:35:08 +00003194 }
3195 for (unsigned I = 0, N = Record.size(); I != N; /* in loop */) {
Nick Lewycky9c7eb1d2013-02-01 08:13:20 +00003196 UndefinedButUsed.push_back(getGlobalDeclID(F, Record[I++]));
3197 UndefinedButUsed.push_back(
Nick Lewycky8334af82013-01-26 00:35:08 +00003198 ReadSourceLocation(F, Record, I).getRawEncoding());
3199 }
3200 break;
3201
Guy Benyei11169dd2012-12-18 14:30:41 +00003202 case IMPORTED_MODULES: {
Richard Smithe842a472014-10-22 02:05:46 +00003203 if (F.Kind != MK_ImplicitModule && F.Kind != MK_ExplicitModule) {
Guy Benyei11169dd2012-12-18 14:30:41 +00003204 // If we aren't loading a module (which has its own exports), make
3205 // all of the imported modules visible.
3206 // FIXME: Deal with macros-only imports.
Richard Smith56be7542014-03-21 00:33:59 +00003207 for (unsigned I = 0, N = Record.size(); I != N; /**/) {
3208 unsigned GlobalID = getGlobalSubmoduleID(F, Record[I++]);
3209 SourceLocation Loc = ReadSourceLocation(F, Record, I);
3210 if (GlobalID)
Aaron Ballman4f45b712014-03-21 15:22:56 +00003211 ImportedModules.push_back(ImportedSubmodule(GlobalID, Loc));
Guy Benyei11169dd2012-12-18 14:30:41 +00003212 }
3213 }
3214 break;
3215 }
3216
3217 case LOCAL_REDECLARATIONS: {
3218 F.RedeclarationChains.swap(Record);
3219 break;
3220 }
3221
3222 case LOCAL_REDECLARATIONS_MAP: {
3223 if (F.LocalNumRedeclarationsInMap != 0) {
3224 Error("duplicate LOCAL_REDECLARATIONS_MAP record in AST file");
Ben Langmuir2c9af442014-04-10 17:57:43 +00003225 return Failure;
Guy Benyei11169dd2012-12-18 14:30:41 +00003226 }
3227
3228 F.LocalNumRedeclarationsInMap = Record[0];
Chris Lattner0e6c9402013-01-20 02:38:54 +00003229 F.RedeclarationsMap = (const LocalRedeclarationsInfo *)Blob.data();
Guy Benyei11169dd2012-12-18 14:30:41 +00003230 break;
3231 }
3232
3233 case MERGED_DECLARATIONS: {
3234 for (unsigned Idx = 0; Idx < Record.size(); /* increment in loop */) {
3235 GlobalDeclID CanonID = getGlobalDeclID(F, Record[Idx++]);
3236 SmallVectorImpl<GlobalDeclID> &Decls = StoredMergedDecls[CanonID];
3237 for (unsigned N = Record[Idx++]; N > 0; --N)
3238 Decls.push_back(getGlobalDeclID(F, Record[Idx++]));
3239 }
3240 break;
3241 }
3242
3243 case MACRO_OFFSET: {
3244 if (F.LocalNumMacros != 0) {
3245 Error("duplicate MACRO_OFFSET record in AST file");
Ben Langmuir2c9af442014-04-10 17:57:43 +00003246 return Failure;
Guy Benyei11169dd2012-12-18 14:30:41 +00003247 }
Chris Lattner0e6c9402013-01-20 02:38:54 +00003248 F.MacroOffsets = (const uint32_t *)Blob.data();
Guy Benyei11169dd2012-12-18 14:30:41 +00003249 F.LocalNumMacros = Record[0];
3250 unsigned LocalBaseMacroID = Record[1];
3251 F.BaseMacroID = getTotalNumMacros();
3252
3253 if (F.LocalNumMacros > 0) {
3254 // Introduce the global -> local mapping for macros within this module.
3255 GlobalMacroMap.insert(std::make_pair(getTotalNumMacros() + 1, &F));
3256
3257 // Introduce the local -> global mapping for macros within this module.
3258 F.MacroRemap.insertOrReplace(
3259 std::make_pair(LocalBaseMacroID,
3260 F.BaseMacroID - LocalBaseMacroID));
Ben Langmuir52ca6782014-10-20 16:27:32 +00003261
3262 MacrosLoaded.resize(MacrosLoaded.size() + F.LocalNumMacros);
Guy Benyei11169dd2012-12-18 14:30:41 +00003263 }
3264 break;
3265 }
3266
Argyrios Kyrtzidiseb663da2013-03-22 21:12:57 +00003267 case MACRO_TABLE: {
3268 // FIXME: Not used yet.
Guy Benyei11169dd2012-12-18 14:30:41 +00003269 break;
3270 }
Richard Smithe40f2ba2013-08-07 21:41:30 +00003271
3272 case LATE_PARSED_TEMPLATE: {
3273 LateParsedTemplates.append(Record.begin(), Record.end());
3274 break;
3275 }
Dario Domizioli13a0a382014-05-23 12:13:25 +00003276
3277 case OPTIMIZE_PRAGMA_OPTIONS:
3278 if (Record.size() != 1) {
3279 Error("invalid pragma optimize record");
3280 return Failure;
3281 }
3282 OptimizeOffPragmaLocation = ReadSourceLocation(F, Record[0]);
3283 break;
Nico Weber72889432014-09-06 01:25:55 +00003284
3285 case UNUSED_LOCAL_TYPEDEF_NAME_CANDIDATES:
3286 for (unsigned I = 0, N = Record.size(); I != N; ++I)
3287 UnusedLocalTypedefNameCandidates.push_back(
3288 getGlobalDeclID(F, Record[I]));
3289 break;
Guy Benyei11169dd2012-12-18 14:30:41 +00003290 }
3291 }
Guy Benyei11169dd2012-12-18 14:30:41 +00003292}
3293
Ben Langmuir4b8a9e92014-08-12 16:42:33 +00003294ASTReader::ASTReadResult
3295ASTReader::ReadModuleMapFileBlock(RecordData &Record, ModuleFile &F,
3296 const ModuleFile *ImportedBy,
3297 unsigned ClientLoadCapabilities) {
3298 unsigned Idx = 0;
3299 F.ModuleMapPath = ReadString(Record, Idx);
3300
Richard Smithe842a472014-10-22 02:05:46 +00003301 if (F.Kind == MK_ExplicitModule) {
3302 // For an explicitly-loaded module, we don't care whether the original
3303 // module map file exists or matches.
3304 return Success;
3305 }
3306
Ben Langmuir4b8a9e92014-08-12 16:42:33 +00003307 // Try to resolve ModuleName in the current header search context and
3308 // verify that it is found in the same module map file as we saved. If the
3309 // top-level AST file is a main file, skip this check because there is no
3310 // usable header search context.
3311 assert(!F.ModuleName.empty() &&
Richard Smithe842a472014-10-22 02:05:46 +00003312 "MODULE_NAME should come before MODULE_MAP_FILE");
3313 if (F.Kind == MK_ImplicitModule &&
3314 (*ModuleMgr.begin())->Kind != MK_MainFile) {
3315 // An implicitly-loaded module file should have its module listed in some
3316 // module map file that we've already loaded.
Ben Langmuir4b8a9e92014-08-12 16:42:33 +00003317 Module *M = PP.getHeaderSearchInfo().lookupModule(F.ModuleName);
Richard Smithe842a472014-10-22 02:05:46 +00003318 auto &Map = PP.getHeaderSearchInfo().getModuleMap();
3319 const FileEntry *ModMap = M ? Map.getModuleMapFileForUniquing(M) : nullptr;
3320 if (!ModMap) {
Ben Langmuir4b8a9e92014-08-12 16:42:33 +00003321 assert(ImportedBy && "top-level import should be verified");
3322 if ((ClientLoadCapabilities & ARR_Missing) == 0)
Richard Smithe842a472014-10-22 02:05:46 +00003323 Diag(diag::err_imported_module_not_found) << F.ModuleName << F.FileName
3324 << ImportedBy->FileName
3325 << F.ModuleMapPath;
Ben Langmuir4b8a9e92014-08-12 16:42:33 +00003326 return Missing;
3327 }
3328
Richard Smithe842a472014-10-22 02:05:46 +00003329 assert(M->Name == F.ModuleName && "found module with different name");
3330
Ben Langmuir4b8a9e92014-08-12 16:42:33 +00003331 // Check the primary module map file.
Ben Langmuir4b8a9e92014-08-12 16:42:33 +00003332 const FileEntry *StoredModMap = FileMgr.getFile(F.ModuleMapPath);
Ben Langmuir4b8a9e92014-08-12 16:42:33 +00003333 if (StoredModMap == nullptr || StoredModMap != ModMap) {
3334 assert(ModMap && "found module is missing module map file");
Ben Langmuir4b8a9e92014-08-12 16:42:33 +00003335 assert(ImportedBy && "top-level import should be verified");
3336 if ((ClientLoadCapabilities & ARR_OutOfDate) == 0)
3337 Diag(diag::err_imported_module_modmap_changed)
3338 << F.ModuleName << ImportedBy->FileName
3339 << ModMap->getName() << F.ModuleMapPath;
3340 return OutOfDate;
3341 }
3342
3343 llvm::SmallPtrSet<const FileEntry *, 1> AdditionalStoredMaps;
3344 for (unsigned I = 0, N = Record[Idx++]; I < N; ++I) {
3345 // FIXME: we should use input files rather than storing names.
3346 std::string Filename = ReadString(Record, Idx);
3347 const FileEntry *F =
3348 FileMgr.getFile(Filename, false, false);
3349 if (F == nullptr) {
3350 if ((ClientLoadCapabilities & ARR_OutOfDate) == 0)
3351 Error("could not find file '" + Filename +"' referenced by AST file");
3352 return OutOfDate;
3353 }
3354 AdditionalStoredMaps.insert(F);
3355 }
3356
3357 // Check any additional module map files (e.g. module.private.modulemap)
3358 // that are not in the pcm.
3359 if (auto *AdditionalModuleMaps = Map.getAdditionalModuleMapFiles(M)) {
3360 for (const FileEntry *ModMap : *AdditionalModuleMaps) {
3361 // Remove files that match
3362 // Note: SmallPtrSet::erase is really remove
3363 if (!AdditionalStoredMaps.erase(ModMap)) {
3364 if ((ClientLoadCapabilities & ARR_OutOfDate) == 0)
3365 Diag(diag::err_module_different_modmap)
3366 << F.ModuleName << /*new*/0 << ModMap->getName();
3367 return OutOfDate;
3368 }
3369 }
3370 }
3371
3372 // Check any additional module map files that are in the pcm, but not
3373 // found in header search. Cases that match are already removed.
3374 for (const FileEntry *ModMap : AdditionalStoredMaps) {
3375 if ((ClientLoadCapabilities & ARR_OutOfDate) == 0)
3376 Diag(diag::err_module_different_modmap)
3377 << F.ModuleName << /*not new*/1 << ModMap->getName();
3378 return OutOfDate;
3379 }
3380 }
3381
3382 if (Listener)
3383 Listener->ReadModuleMapFile(F.ModuleMapPath);
3384 return Success;
3385}
3386
3387
Douglas Gregorc1489562013-02-12 23:36:21 +00003388/// \brief Move the given method to the back of the global list of methods.
3389static void moveMethodToBackOfGlobalList(Sema &S, ObjCMethodDecl *Method) {
3390 // Find the entry for this selector in the method pool.
3391 Sema::GlobalMethodPool::iterator Known
3392 = S.MethodPool.find(Method->getSelector());
3393 if (Known == S.MethodPool.end())
3394 return;
3395
3396 // Retrieve the appropriate method list.
3397 ObjCMethodList &Start = Method->isInstanceMethod()? Known->second.first
3398 : Known->second.second;
3399 bool Found = false;
Argyrios Kyrtzidisd3da6e02013-04-17 00:08:58 +00003400 for (ObjCMethodList *List = &Start; List; List = List->getNext()) {
Douglas Gregorc1489562013-02-12 23:36:21 +00003401 if (!Found) {
3402 if (List->Method == Method) {
3403 Found = true;
3404 } else {
3405 // Keep searching.
3406 continue;
3407 }
3408 }
3409
Argyrios Kyrtzidisd3da6e02013-04-17 00:08:58 +00003410 if (List->getNext())
3411 List->Method = List->getNext()->Method;
Douglas Gregorc1489562013-02-12 23:36:21 +00003412 else
3413 List->Method = Method;
3414 }
3415}
3416
Richard Smithe657bbd2014-07-18 22:13:40 +00003417void ASTReader::makeNamesVisible(const HiddenNames &Names, Module *Owner,
3418 bool FromFinalization) {
3419 // FIXME: Only do this if Owner->NameVisibility == AllVisible.
Richard Smith57721ac2014-07-21 04:10:40 +00003420 for (Decl *D : Names.HiddenDecls) {
Richard Smith49f906a2014-03-01 00:08:04 +00003421 bool wasHidden = D->Hidden;
3422 D->Hidden = false;
Guy Benyei11169dd2012-12-18 14:30:41 +00003423
Richard Smith49f906a2014-03-01 00:08:04 +00003424 if (wasHidden && SemaObj) {
3425 if (ObjCMethodDecl *Method = dyn_cast<ObjCMethodDecl>(D)) {
3426 moveMethodToBackOfGlobalList(*SemaObj, Method);
Douglas Gregorc1489562013-02-12 23:36:21 +00003427 }
Guy Benyei11169dd2012-12-18 14:30:41 +00003428 }
3429 }
Richard Smith49f906a2014-03-01 00:08:04 +00003430
Richard Smithe657bbd2014-07-18 22:13:40 +00003431 assert((FromFinalization || Owner->NameVisibility >= Module::MacrosVisible) &&
3432 "nothing to make visible?");
Richard Smithdaa69e02014-07-25 04:40:03 +00003433 for (const auto &Macro : Names.HiddenMacros) {
3434 if (FromFinalization)
3435 PP.appendMacroDirective(Macro.first,
3436 Macro.second->import(PP, SourceLocation()));
3437 else
3438 installImportedMacro(Macro.first, Macro.second, Owner);
3439 }
Guy Benyei11169dd2012-12-18 14:30:41 +00003440}
3441
Richard Smith49f906a2014-03-01 00:08:04 +00003442void ASTReader::makeModuleVisible(Module *Mod,
Argyrios Kyrtzidis125df052013-02-01 16:36:12 +00003443 Module::NameVisibilityKind NameVisibility,
Douglas Gregorfb912652013-03-20 21:10:35 +00003444 SourceLocation ImportLoc,
3445 bool Complain) {
Guy Benyei11169dd2012-12-18 14:30:41 +00003446 llvm::SmallPtrSet<Module *, 4> Visited;
Dmitri Gribenkof8579502013-01-12 19:30:44 +00003447 SmallVector<Module *, 4> Stack;
Robert Wilhelm25284cc2013-08-23 16:11:15 +00003448 Stack.push_back(Mod);
Guy Benyei11169dd2012-12-18 14:30:41 +00003449 while (!Stack.empty()) {
Robert Wilhelm25284cc2013-08-23 16:11:15 +00003450 Mod = Stack.pop_back_val();
Guy Benyei11169dd2012-12-18 14:30:41 +00003451
3452 if (NameVisibility <= Mod->NameVisibility) {
Robert Wilhelm25284cc2013-08-23 16:11:15 +00003453 // This module already has this level of visibility (or greater), so
Guy Benyei11169dd2012-12-18 14:30:41 +00003454 // there is nothing more to do.
3455 continue;
3456 }
Richard Smith49f906a2014-03-01 00:08:04 +00003457
Guy Benyei11169dd2012-12-18 14:30:41 +00003458 if (!Mod->isAvailable()) {
3459 // Modules that aren't available cannot be made visible.
3460 continue;
3461 }
3462
3463 // Update the module's name visibility.
Richard Smith49f906a2014-03-01 00:08:04 +00003464 if (NameVisibility >= Module::MacrosVisible &&
3465 Mod->NameVisibility < Module::MacrosVisible)
3466 Mod->MacroVisibilityLoc = ImportLoc;
Guy Benyei11169dd2012-12-18 14:30:41 +00003467 Mod->NameVisibility = NameVisibility;
Richard Smith49f906a2014-03-01 00:08:04 +00003468
Guy Benyei11169dd2012-12-18 14:30:41 +00003469 // If we've already deserialized any names from this module,
3470 // mark them as visible.
3471 HiddenNamesMapType::iterator Hidden = HiddenNamesMap.find(Mod);
3472 if (Hidden != HiddenNamesMap.end()) {
Richard Smith57721ac2014-07-21 04:10:40 +00003473 auto HiddenNames = std::move(*Hidden);
Guy Benyei11169dd2012-12-18 14:30:41 +00003474 HiddenNamesMap.erase(Hidden);
Richard Smith57721ac2014-07-21 04:10:40 +00003475 makeNamesVisible(HiddenNames.second, HiddenNames.first,
3476 /*FromFinalization*/false);
3477 assert(HiddenNamesMap.find(Mod) == HiddenNamesMap.end() &&
3478 "making names visible added hidden names");
Guy Benyei11169dd2012-12-18 14:30:41 +00003479 }
Dmitri Gribenkoe9bcf5b2013-11-04 21:51:33 +00003480
Guy Benyei11169dd2012-12-18 14:30:41 +00003481 // Push any exported modules onto the stack to be marked as visible.
Argyrios Kyrtzidis8739f7b2013-02-19 19:34:40 +00003482 SmallVector<Module *, 16> Exports;
3483 Mod->getExportedModules(Exports);
3484 for (SmallVectorImpl<Module *>::iterator
3485 I = Exports.begin(), E = Exports.end(); I != E; ++I) {
3486 Module *Exported = *I;
3487 if (Visited.insert(Exported))
3488 Stack.push_back(Exported);
Guy Benyei11169dd2012-12-18 14:30:41 +00003489 }
Douglas Gregorfb912652013-03-20 21:10:35 +00003490
3491 // Detect any conflicts.
3492 if (Complain) {
3493 assert(ImportLoc.isValid() && "Missing import location");
3494 for (unsigned I = 0, N = Mod->Conflicts.size(); I != N; ++I) {
3495 if (Mod->Conflicts[I].Other->NameVisibility >= NameVisibility) {
3496 Diag(ImportLoc, diag::warn_module_conflict)
3497 << Mod->getFullModuleName()
3498 << Mod->Conflicts[I].Other->getFullModuleName()
3499 << Mod->Conflicts[I].Message;
3500 // FIXME: Need note where the other module was imported.
3501 }
3502 }
3503 }
Guy Benyei11169dd2012-12-18 14:30:41 +00003504 }
3505}
3506
Douglas Gregore060e572013-01-25 01:03:03 +00003507bool ASTReader::loadGlobalIndex() {
3508 if (GlobalIndex)
3509 return false;
3510
3511 if (TriedLoadingGlobalIndex || !UseGlobalIndex ||
3512 !Context.getLangOpts().Modules)
3513 return true;
3514
3515 // Try to load the global index.
3516 TriedLoadingGlobalIndex = true;
3517 StringRef ModuleCachePath
3518 = getPreprocessor().getHeaderSearchInfo().getModuleCachePath();
3519 std::pair<GlobalModuleIndex *, GlobalModuleIndex::ErrorCode> Result
Douglas Gregor7029ce12013-03-19 00:28:20 +00003520 = GlobalModuleIndex::readIndex(ModuleCachePath);
Douglas Gregore060e572013-01-25 01:03:03 +00003521 if (!Result.first)
3522 return true;
3523
3524 GlobalIndex.reset(Result.first);
Douglas Gregor7211ac12013-01-25 23:32:03 +00003525 ModuleMgr.setGlobalIndex(GlobalIndex.get());
Douglas Gregore060e572013-01-25 01:03:03 +00003526 return false;
3527}
3528
3529bool ASTReader::isGlobalIndexUnavailable() const {
3530 return Context.getLangOpts().Modules && UseGlobalIndex &&
3531 !hasGlobalIndex() && TriedLoadingGlobalIndex;
3532}
3533
Dmitri Gribenkof430da42014-02-12 10:33:14 +00003534static void updateModuleTimestamp(ModuleFile &MF) {
3535 // Overwrite the timestamp file contents so that file's mtime changes.
3536 std::string TimestampFilename = MF.getTimestampFilename();
Rafael Espindoladae941a2014-08-25 18:17:04 +00003537 std::error_code EC;
3538 llvm::raw_fd_ostream OS(TimestampFilename, EC, llvm::sys::fs::F_Text);
3539 if (EC)
Dmitri Gribenkof430da42014-02-12 10:33:14 +00003540 return;
3541 OS << "Timestamp file\n";
3542}
3543
Guy Benyei11169dd2012-12-18 14:30:41 +00003544ASTReader::ASTReadResult ASTReader::ReadAST(const std::string &FileName,
3545 ModuleKind Type,
3546 SourceLocation ImportLoc,
3547 unsigned ClientLoadCapabilities) {
Argyrios Kyrtzidisdc9fdaf2013-05-24 05:44:08 +00003548 llvm::SaveAndRestore<SourceLocation>
3549 SetCurImportLocRAII(CurrentImportLoc, ImportLoc);
3550
Richard Smithd1c46742014-04-30 02:24:17 +00003551 // Defer any pending actions until we get to the end of reading the AST file.
3552 Deserializing AnASTFile(this);
3553
Guy Benyei11169dd2012-12-18 14:30:41 +00003554 // Bump the generation number.
Richard Smith053f6c62014-05-16 23:01:30 +00003555 unsigned PreviousGeneration = incrementGeneration(Context);
Guy Benyei11169dd2012-12-18 14:30:41 +00003556
3557 unsigned NumModules = ModuleMgr.size();
Dmitri Gribenkof8579502013-01-12 19:30:44 +00003558 SmallVector<ImportedModule, 4> Loaded;
Guy Benyei11169dd2012-12-18 14:30:41 +00003559 switch(ASTReadResult ReadResult = ReadASTCore(FileName, Type, ImportLoc,
Craig Toppera13603a2014-05-22 05:54:18 +00003560 /*ImportedBy=*/nullptr, Loaded,
Ben Langmuir487ea142014-10-23 18:05:36 +00003561 0, 0, 0,
Guy Benyei11169dd2012-12-18 14:30:41 +00003562 ClientLoadCapabilities)) {
3563 case Failure:
Douglas Gregor7029ce12013-03-19 00:28:20 +00003564 case Missing:
Guy Benyei11169dd2012-12-18 14:30:41 +00003565 case OutOfDate:
3566 case VersionMismatch:
3567 case ConfigurationMismatch:
Ben Langmuir9801b252014-06-20 00:24:56 +00003568 case HadErrors: {
3569 llvm::SmallPtrSet<ModuleFile *, 4> LoadedSet;
3570 for (const ImportedModule &IM : Loaded)
3571 LoadedSet.insert(IM.Mod);
3572
Douglas Gregor7029ce12013-03-19 00:28:20 +00003573 ModuleMgr.removeModules(ModuleMgr.begin() + NumModules, ModuleMgr.end(),
Ben Langmuir9801b252014-06-20 00:24:56 +00003574 LoadedSet,
Douglas Gregor7029ce12013-03-19 00:28:20 +00003575 Context.getLangOpts().Modules
3576 ? &PP.getHeaderSearchInfo().getModuleMap()
Craig Toppera13603a2014-05-22 05:54:18 +00003577 : nullptr);
Douglas Gregore060e572013-01-25 01:03:03 +00003578
3579 // If we find that any modules are unusable, the global index is going
3580 // to be out-of-date. Just remove it.
3581 GlobalIndex.reset();
Craig Toppera13603a2014-05-22 05:54:18 +00003582 ModuleMgr.setGlobalIndex(nullptr);
Guy Benyei11169dd2012-12-18 14:30:41 +00003583 return ReadResult;
Ben Langmuir9801b252014-06-20 00:24:56 +00003584 }
Guy Benyei11169dd2012-12-18 14:30:41 +00003585 case Success:
3586 break;
3587 }
3588
3589 // Here comes stuff that we only do once the entire chain is loaded.
3590
3591 // Load the AST blocks of all of the modules that we loaded.
Dmitri Gribenkof8579502013-01-12 19:30:44 +00003592 for (SmallVectorImpl<ImportedModule>::iterator M = Loaded.begin(),
3593 MEnd = Loaded.end();
Guy Benyei11169dd2012-12-18 14:30:41 +00003594 M != MEnd; ++M) {
3595 ModuleFile &F = *M->Mod;
3596
3597 // Read the AST block.
Ben Langmuir2c9af442014-04-10 17:57:43 +00003598 if (ASTReadResult Result = ReadASTBlock(F, ClientLoadCapabilities))
3599 return Result;
Guy Benyei11169dd2012-12-18 14:30:41 +00003600
3601 // Once read, set the ModuleFile bit base offset and update the size in
3602 // bits of all files we've seen.
3603 F.GlobalBitOffset = TotalModulesSizeInBits;
3604 TotalModulesSizeInBits += F.SizeInBits;
3605 GlobalBitOffsetsMap.insert(std::make_pair(F.GlobalBitOffset, &F));
3606
3607 // Preload SLocEntries.
3608 for (unsigned I = 0, N = F.PreloadSLocEntries.size(); I != N; ++I) {
3609 int Index = int(F.PreloadSLocEntries[I] - 1) + F.SLocEntryBaseID;
3610 // Load it through the SourceManager and don't call ReadSLocEntry()
3611 // directly because the entry may have already been loaded in which case
3612 // calling ReadSLocEntry() directly would trigger an assertion in
3613 // SourceManager.
3614 SourceMgr.getLoadedSLocEntryByID(Index);
3615 }
3616 }
3617
Douglas Gregor603cd862013-03-22 18:50:14 +00003618 // Setup the import locations and notify the module manager that we've
3619 // committed to these module files.
Dmitri Gribenkof8579502013-01-12 19:30:44 +00003620 for (SmallVectorImpl<ImportedModule>::iterator M = Loaded.begin(),
3621 MEnd = Loaded.end();
Guy Benyei11169dd2012-12-18 14:30:41 +00003622 M != MEnd; ++M) {
3623 ModuleFile &F = *M->Mod;
Douglas Gregor603cd862013-03-22 18:50:14 +00003624
3625 ModuleMgr.moduleFileAccepted(&F);
3626
3627 // Set the import location.
Argyrios Kyrtzidis71c1af82013-02-01 16:36:14 +00003628 F.DirectImportLoc = ImportLoc;
Guy Benyei11169dd2012-12-18 14:30:41 +00003629 if (!M->ImportedBy)
3630 F.ImportLoc = M->ImportLoc;
3631 else
3632 F.ImportLoc = ReadSourceLocation(*M->ImportedBy,
3633 M->ImportLoc.getRawEncoding());
3634 }
3635
3636 // Mark all of the identifiers in the identifier table as being out of date,
3637 // so that various accessors know to check the loaded modules when the
3638 // identifier is used.
3639 for (IdentifierTable::iterator Id = PP.getIdentifierTable().begin(),
3640 IdEnd = PP.getIdentifierTable().end();
3641 Id != IdEnd; ++Id)
3642 Id->second->setOutOfDate(true);
3643
3644 // Resolve any unresolved module exports.
Douglas Gregorfb912652013-03-20 21:10:35 +00003645 for (unsigned I = 0, N = UnresolvedModuleRefs.size(); I != N; ++I) {
3646 UnresolvedModuleRef &Unresolved = UnresolvedModuleRefs[I];
Guy Benyei11169dd2012-12-18 14:30:41 +00003647 SubmoduleID GlobalID = getGlobalSubmoduleID(*Unresolved.File,Unresolved.ID);
3648 Module *ResolvedMod = getSubmodule(GlobalID);
Douglas Gregorfb912652013-03-20 21:10:35 +00003649
3650 switch (Unresolved.Kind) {
3651 case UnresolvedModuleRef::Conflict:
3652 if (ResolvedMod) {
3653 Module::Conflict Conflict;
3654 Conflict.Other = ResolvedMod;
3655 Conflict.Message = Unresolved.String.str();
3656 Unresolved.Mod->Conflicts.push_back(Conflict);
3657 }
3658 continue;
3659
3660 case UnresolvedModuleRef::Import:
Guy Benyei11169dd2012-12-18 14:30:41 +00003661 if (ResolvedMod)
3662 Unresolved.Mod->Imports.push_back(ResolvedMod);
3663 continue;
Guy Benyei11169dd2012-12-18 14:30:41 +00003664
Douglas Gregorfb912652013-03-20 21:10:35 +00003665 case UnresolvedModuleRef::Export:
3666 if (ResolvedMod || Unresolved.IsWildcard)
3667 Unresolved.Mod->Exports.push_back(
3668 Module::ExportDecl(ResolvedMod, Unresolved.IsWildcard));
3669 continue;
3670 }
Guy Benyei11169dd2012-12-18 14:30:41 +00003671 }
Douglas Gregorfb912652013-03-20 21:10:35 +00003672 UnresolvedModuleRefs.clear();
Daniel Jasperba7f2f72013-09-24 09:14:14 +00003673
3674 // FIXME: How do we load the 'use'd modules? They may not be submodules.
3675 // Might be unnecessary as use declarations are only used to build the
3676 // module itself.
Guy Benyei11169dd2012-12-18 14:30:41 +00003677
3678 InitializeContext();
3679
Richard Smith3d8e97e2013-10-18 06:54:39 +00003680 if (SemaObj)
3681 UpdateSema();
3682
Guy Benyei11169dd2012-12-18 14:30:41 +00003683 if (DeserializationListener)
3684 DeserializationListener->ReaderInitialized(this);
3685
3686 ModuleFile &PrimaryModule = ModuleMgr.getPrimaryModule();
3687 if (!PrimaryModule.OriginalSourceFileID.isInvalid()) {
3688 PrimaryModule.OriginalSourceFileID
3689 = FileID::get(PrimaryModule.SLocEntryBaseID
3690 + PrimaryModule.OriginalSourceFileID.getOpaqueValue() - 1);
3691
3692 // If this AST file is a precompiled preamble, then set the
3693 // preamble file ID of the source manager to the file source file
3694 // from which the preamble was built.
3695 if (Type == MK_Preamble) {
3696 SourceMgr.setPreambleFileID(PrimaryModule.OriginalSourceFileID);
3697 } else if (Type == MK_MainFile) {
3698 SourceMgr.setMainFileID(PrimaryModule.OriginalSourceFileID);
3699 }
3700 }
3701
3702 // For any Objective-C class definitions we have already loaded, make sure
3703 // that we load any additional categories.
3704 for (unsigned I = 0, N = ObjCClassesLoaded.size(); I != N; ++I) {
3705 loadObjCCategories(ObjCClassesLoaded[I]->getGlobalID(),
3706 ObjCClassesLoaded[I],
3707 PreviousGeneration);
3708 }
Douglas Gregore060e572013-01-25 01:03:03 +00003709
Dmitri Gribenkof430da42014-02-12 10:33:14 +00003710 if (PP.getHeaderSearchInfo()
3711 .getHeaderSearchOpts()
3712 .ModulesValidateOncePerBuildSession) {
3713 // Now we are certain that the module and all modules it depends on are
3714 // up to date. Create or update timestamp files for modules that are
3715 // located in the module cache (not for PCH files that could be anywhere
3716 // in the filesystem).
3717 for (unsigned I = 0, N = Loaded.size(); I != N; ++I) {
3718 ImportedModule &M = Loaded[I];
Richard Smithe842a472014-10-22 02:05:46 +00003719 if (M.Mod->Kind == MK_ImplicitModule) {
Dmitri Gribenkof430da42014-02-12 10:33:14 +00003720 updateModuleTimestamp(*M.Mod);
3721 }
3722 }
3723 }
3724
Guy Benyei11169dd2012-12-18 14:30:41 +00003725 return Success;
3726}
3727
Ben Langmuir487ea142014-10-23 18:05:36 +00003728static ASTFileSignature readASTFileSignature(llvm::BitstreamReader &StreamFile);
3729
Guy Benyei11169dd2012-12-18 14:30:41 +00003730ASTReader::ASTReadResult
3731ASTReader::ReadASTCore(StringRef FileName,
3732 ModuleKind Type,
3733 SourceLocation ImportLoc,
3734 ModuleFile *ImportedBy,
Dmitri Gribenkof8579502013-01-12 19:30:44 +00003735 SmallVectorImpl<ImportedModule> &Loaded,
Douglas Gregor7029ce12013-03-19 00:28:20 +00003736 off_t ExpectedSize, time_t ExpectedModTime,
Ben Langmuir487ea142014-10-23 18:05:36 +00003737 ASTFileSignature ExpectedSignature,
Guy Benyei11169dd2012-12-18 14:30:41 +00003738 unsigned ClientLoadCapabilities) {
3739 ModuleFile *M;
Guy Benyei11169dd2012-12-18 14:30:41 +00003740 std::string ErrorStr;
Douglas Gregor7029ce12013-03-19 00:28:20 +00003741 ModuleManager::AddModuleResult AddResult
3742 = ModuleMgr.addModule(FileName, Type, ImportLoc, ImportedBy,
Richard Smith053f6c62014-05-16 23:01:30 +00003743 getGeneration(), ExpectedSize, ExpectedModTime,
Ben Langmuir487ea142014-10-23 18:05:36 +00003744 ExpectedSignature, readASTFileSignature,
Douglas Gregor7029ce12013-03-19 00:28:20 +00003745 M, ErrorStr);
Guy Benyei11169dd2012-12-18 14:30:41 +00003746
Douglas Gregor7029ce12013-03-19 00:28:20 +00003747 switch (AddResult) {
3748 case ModuleManager::AlreadyLoaded:
3749 return Success;
3750
3751 case ModuleManager::NewlyLoaded:
3752 // Load module file below.
3753 break;
3754
3755 case ModuleManager::Missing:
Richard Smithe842a472014-10-22 02:05:46 +00003756 // The module file was missing; if the client can handle that, return
Douglas Gregor7029ce12013-03-19 00:28:20 +00003757 // it.
3758 if (ClientLoadCapabilities & ARR_Missing)
3759 return Missing;
3760
3761 // Otherwise, return an error.
3762 {
3763 std::string Msg = "Unable to load module \"" + FileName.str() + "\": "
3764 + ErrorStr;
3765 Error(Msg);
3766 }
3767 return Failure;
3768
3769 case ModuleManager::OutOfDate:
3770 // We couldn't load the module file because it is out-of-date. If the
3771 // client can handle out-of-date, return it.
3772 if (ClientLoadCapabilities & ARR_OutOfDate)
3773 return OutOfDate;
3774
3775 // Otherwise, return an error.
3776 {
3777 std::string Msg = "Unable to load module \"" + FileName.str() + "\": "
3778 + ErrorStr;
3779 Error(Msg);
3780 }
Guy Benyei11169dd2012-12-18 14:30:41 +00003781 return Failure;
3782 }
3783
Douglas Gregor7029ce12013-03-19 00:28:20 +00003784 assert(M && "Missing module file");
Guy Benyei11169dd2012-12-18 14:30:41 +00003785
3786 // FIXME: This seems rather a hack. Should CurrentDir be part of the
3787 // module?
3788 if (FileName != "-") {
3789 CurrentDir = llvm::sys::path::parent_path(FileName);
3790 if (CurrentDir.empty()) CurrentDir = ".";
3791 }
3792
3793 ModuleFile &F = *M;
Chris Lattner7fb3bef2013-01-20 00:56:42 +00003794 BitstreamCursor &Stream = F.Stream;
Guy Benyei11169dd2012-12-18 14:30:41 +00003795 Stream.init(F.StreamFile);
3796 F.SizeInBits = F.Buffer->getBufferSize() * 8;
3797
3798 // Sniff for the signature.
3799 if (Stream.Read(8) != 'C' ||
3800 Stream.Read(8) != 'P' ||
3801 Stream.Read(8) != 'C' ||
3802 Stream.Read(8) != 'H') {
3803 Diag(diag::err_not_a_pch_file) << FileName;
3804 return Failure;
3805 }
3806
3807 // This is used for compatibility with older PCH formats.
3808 bool HaveReadControlBlock = false;
3809
Chris Lattnerefa77172013-01-20 00:00:22 +00003810 while (1) {
3811 llvm::BitstreamEntry Entry = Stream.advance();
3812
3813 switch (Entry.Kind) {
3814 case llvm::BitstreamEntry::Error:
3815 case llvm::BitstreamEntry::EndBlock:
3816 case llvm::BitstreamEntry::Record:
Guy Benyei11169dd2012-12-18 14:30:41 +00003817 Error("invalid record at top-level of AST file");
3818 return Failure;
Chris Lattnerefa77172013-01-20 00:00:22 +00003819
3820 case llvm::BitstreamEntry::SubBlock:
3821 break;
Guy Benyei11169dd2012-12-18 14:30:41 +00003822 }
3823
Guy Benyei11169dd2012-12-18 14:30:41 +00003824 // We only know the control subblock ID.
Chris Lattnerefa77172013-01-20 00:00:22 +00003825 switch (Entry.ID) {
Guy Benyei11169dd2012-12-18 14:30:41 +00003826 case llvm::bitc::BLOCKINFO_BLOCK_ID:
3827 if (Stream.ReadBlockInfoBlock()) {
3828 Error("malformed BlockInfoBlock in AST file");
3829 return Failure;
3830 }
3831 break;
3832 case CONTROL_BLOCK_ID:
3833 HaveReadControlBlock = true;
Ben Langmuirbeee15e2014-04-14 18:00:01 +00003834 switch (ReadControlBlock(F, Loaded, ImportedBy, ClientLoadCapabilities)) {
Guy Benyei11169dd2012-12-18 14:30:41 +00003835 case Success:
3836 break;
3837
3838 case Failure: return Failure;
Douglas Gregor7029ce12013-03-19 00:28:20 +00003839 case Missing: return Missing;
Guy Benyei11169dd2012-12-18 14:30:41 +00003840 case OutOfDate: return OutOfDate;
3841 case VersionMismatch: return VersionMismatch;
3842 case ConfigurationMismatch: return ConfigurationMismatch;
3843 case HadErrors: return HadErrors;
3844 }
3845 break;
3846 case AST_BLOCK_ID:
3847 if (!HaveReadControlBlock) {
3848 if ((ClientLoadCapabilities & ARR_VersionMismatch) == 0)
Dmitri Gribenko2228cd32014-02-11 15:40:09 +00003849 Diag(diag::err_pch_version_too_old);
Guy Benyei11169dd2012-12-18 14:30:41 +00003850 return VersionMismatch;
3851 }
3852
3853 // Record that we've loaded this module.
3854 Loaded.push_back(ImportedModule(M, ImportedBy, ImportLoc));
3855 return Success;
3856
3857 default:
3858 if (Stream.SkipBlock()) {
3859 Error("malformed block record in AST file");
3860 return Failure;
3861 }
3862 break;
3863 }
3864 }
3865
3866 return Success;
3867}
3868
3869void ASTReader::InitializeContext() {
3870 // If there's a listener, notify them that we "read" the translation unit.
3871 if (DeserializationListener)
3872 DeserializationListener->DeclRead(PREDEF_DECL_TRANSLATION_UNIT_ID,
3873 Context.getTranslationUnitDecl());
3874
Guy Benyei11169dd2012-12-18 14:30:41 +00003875 // FIXME: Find a better way to deal with collisions between these
3876 // built-in types. Right now, we just ignore the problem.
3877
3878 // Load the special types.
3879 if (SpecialTypes.size() >= NumSpecialTypeIDs) {
3880 if (unsigned String = SpecialTypes[SPECIAL_TYPE_CF_CONSTANT_STRING]) {
3881 if (!Context.CFConstantStringTypeDecl)
3882 Context.setCFConstantStringType(GetType(String));
3883 }
3884
3885 if (unsigned File = SpecialTypes[SPECIAL_TYPE_FILE]) {
3886 QualType FileType = GetType(File);
3887 if (FileType.isNull()) {
3888 Error("FILE type is NULL");
3889 return;
3890 }
3891
3892 if (!Context.FILEDecl) {
3893 if (const TypedefType *Typedef = FileType->getAs<TypedefType>())
3894 Context.setFILEDecl(Typedef->getDecl());
3895 else {
3896 const TagType *Tag = FileType->getAs<TagType>();
3897 if (!Tag) {
3898 Error("Invalid FILE type in AST file");
3899 return;
3900 }
3901 Context.setFILEDecl(Tag->getDecl());
3902 }
3903 }
3904 }
3905
3906 if (unsigned Jmp_buf = SpecialTypes[SPECIAL_TYPE_JMP_BUF]) {
3907 QualType Jmp_bufType = GetType(Jmp_buf);
3908 if (Jmp_bufType.isNull()) {
3909 Error("jmp_buf type is NULL");
3910 return;
3911 }
3912
3913 if (!Context.jmp_bufDecl) {
3914 if (const TypedefType *Typedef = Jmp_bufType->getAs<TypedefType>())
3915 Context.setjmp_bufDecl(Typedef->getDecl());
3916 else {
3917 const TagType *Tag = Jmp_bufType->getAs<TagType>();
3918 if (!Tag) {
3919 Error("Invalid jmp_buf type in AST file");
3920 return;
3921 }
3922 Context.setjmp_bufDecl(Tag->getDecl());
3923 }
3924 }
3925 }
3926
3927 if (unsigned Sigjmp_buf = SpecialTypes[SPECIAL_TYPE_SIGJMP_BUF]) {
3928 QualType Sigjmp_bufType = GetType(Sigjmp_buf);
3929 if (Sigjmp_bufType.isNull()) {
3930 Error("sigjmp_buf type is NULL");
3931 return;
3932 }
3933
3934 if (!Context.sigjmp_bufDecl) {
3935 if (const TypedefType *Typedef = Sigjmp_bufType->getAs<TypedefType>())
3936 Context.setsigjmp_bufDecl(Typedef->getDecl());
3937 else {
3938 const TagType *Tag = Sigjmp_bufType->getAs<TagType>();
3939 assert(Tag && "Invalid sigjmp_buf type in AST file");
3940 Context.setsigjmp_bufDecl(Tag->getDecl());
3941 }
3942 }
3943 }
3944
3945 if (unsigned ObjCIdRedef
3946 = SpecialTypes[SPECIAL_TYPE_OBJC_ID_REDEFINITION]) {
3947 if (Context.ObjCIdRedefinitionType.isNull())
3948 Context.ObjCIdRedefinitionType = GetType(ObjCIdRedef);
3949 }
3950
3951 if (unsigned ObjCClassRedef
3952 = SpecialTypes[SPECIAL_TYPE_OBJC_CLASS_REDEFINITION]) {
3953 if (Context.ObjCClassRedefinitionType.isNull())
3954 Context.ObjCClassRedefinitionType = GetType(ObjCClassRedef);
3955 }
3956
3957 if (unsigned ObjCSelRedef
3958 = SpecialTypes[SPECIAL_TYPE_OBJC_SEL_REDEFINITION]) {
3959 if (Context.ObjCSelRedefinitionType.isNull())
3960 Context.ObjCSelRedefinitionType = GetType(ObjCSelRedef);
3961 }
3962
3963 if (unsigned Ucontext_t = SpecialTypes[SPECIAL_TYPE_UCONTEXT_T]) {
3964 QualType Ucontext_tType = GetType(Ucontext_t);
3965 if (Ucontext_tType.isNull()) {
3966 Error("ucontext_t type is NULL");
3967 return;
3968 }
3969
3970 if (!Context.ucontext_tDecl) {
3971 if (const TypedefType *Typedef = Ucontext_tType->getAs<TypedefType>())
3972 Context.setucontext_tDecl(Typedef->getDecl());
3973 else {
3974 const TagType *Tag = Ucontext_tType->getAs<TagType>();
3975 assert(Tag && "Invalid ucontext_t type in AST file");
3976 Context.setucontext_tDecl(Tag->getDecl());
3977 }
3978 }
3979 }
3980 }
3981
3982 ReadPragmaDiagnosticMappings(Context.getDiagnostics());
3983
3984 // If there were any CUDA special declarations, deserialize them.
3985 if (!CUDASpecialDeclRefs.empty()) {
3986 assert(CUDASpecialDeclRefs.size() == 1 && "More decl refs than expected!");
3987 Context.setcudaConfigureCallDecl(
3988 cast<FunctionDecl>(GetDecl(CUDASpecialDeclRefs[0])));
3989 }
Richard Smith56be7542014-03-21 00:33:59 +00003990
Guy Benyei11169dd2012-12-18 14:30:41 +00003991 // Re-export any modules that were imported by a non-module AST file.
Richard Smith56be7542014-03-21 00:33:59 +00003992 // FIXME: This does not make macro-only imports visible again. It also doesn't
3993 // make #includes mapped to module imports visible.
3994 for (auto &Import : ImportedModules) {
3995 if (Module *Imported = getSubmodule(Import.ID))
Argyrios Kyrtzidis125df052013-02-01 16:36:12 +00003996 makeModuleVisible(Imported, Module::AllVisible,
Richard Smith56be7542014-03-21 00:33:59 +00003997 /*ImportLoc=*/Import.ImportLoc,
Douglas Gregorfb912652013-03-20 21:10:35 +00003998 /*Complain=*/false);
Guy Benyei11169dd2012-12-18 14:30:41 +00003999 }
4000 ImportedModules.clear();
4001}
4002
4003void ASTReader::finalizeForWriting() {
Richard Smith57721ac2014-07-21 04:10:40 +00004004 while (!HiddenNamesMap.empty()) {
4005 auto HiddenNames = std::move(*HiddenNamesMap.begin());
4006 HiddenNamesMap.erase(HiddenNamesMap.begin());
4007 makeNamesVisible(HiddenNames.second, HiddenNames.first,
4008 /*FromFinalization*/true);
Guy Benyei11169dd2012-12-18 14:30:41 +00004009 }
Guy Benyei11169dd2012-12-18 14:30:41 +00004010}
4011
Argyrios Kyrtzidisc4cd2c42013-05-06 19:23:40 +00004012/// \brief Given a cursor at the start of an AST file, scan ahead and drop the
4013/// cursor into the start of the given block ID, returning false on success and
4014/// true on failure.
4015static bool SkipCursorToBlock(BitstreamCursor &Cursor, unsigned BlockID) {
Chris Lattner7fb3bef2013-01-20 00:56:42 +00004016 while (1) {
4017 llvm::BitstreamEntry Entry = Cursor.advance();
4018 switch (Entry.Kind) {
4019 case llvm::BitstreamEntry::Error:
4020 case llvm::BitstreamEntry::EndBlock:
4021 return true;
4022
4023 case llvm::BitstreamEntry::Record:
4024 // Ignore top-level records.
4025 Cursor.skipRecord(Entry.ID);
4026 break;
4027
4028 case llvm::BitstreamEntry::SubBlock:
Argyrios Kyrtzidisc4cd2c42013-05-06 19:23:40 +00004029 if (Entry.ID == BlockID) {
4030 if (Cursor.EnterSubBlock(BlockID))
Chris Lattner7fb3bef2013-01-20 00:56:42 +00004031 return true;
4032 // Found it!
4033 return false;
4034 }
4035
4036 if (Cursor.SkipBlock())
4037 return true;
4038 }
4039 }
4040}
4041
Ben Langmuir487ea142014-10-23 18:05:36 +00004042static ASTFileSignature readASTFileSignature(llvm::BitstreamReader &StreamFile){
4043 BitstreamCursor Stream(StreamFile);
4044 if (Stream.Read(8) != 'C' ||
4045 Stream.Read(8) != 'P' ||
4046 Stream.Read(8) != 'C' ||
4047 Stream.Read(8) != 'H') {
4048 return 0;
4049 }
4050
4051 // Scan for the CONTROL_BLOCK_ID block.
4052 if (SkipCursorToBlock(Stream, CONTROL_BLOCK_ID))
4053 return 0;
4054
4055 // Scan for SIGNATURE inside the control block.
4056 ASTReader::RecordData Record;
4057 while (1) {
4058 llvm::BitstreamEntry Entry = Stream.advanceSkippingSubblocks();
4059 if (Entry.Kind == llvm::BitstreamEntry::EndBlock ||
4060 Entry.Kind != llvm::BitstreamEntry::Record)
4061 return 0;
4062
4063 Record.clear();
4064 StringRef Blob;
4065 if (SIGNATURE == Stream.readRecord(Entry.ID, Record, &Blob))
4066 return Record[0];
4067 }
4068}
4069
Guy Benyei11169dd2012-12-18 14:30:41 +00004070/// \brief Retrieve the name of the original source file name
4071/// directly from the AST file, without actually loading the AST
4072/// file.
4073std::string ASTReader::getOriginalSourceFile(const std::string &ASTFileName,
4074 FileManager &FileMgr,
4075 DiagnosticsEngine &Diags) {
4076 // Open the AST file.
4077 std::string ErrStr;
Rafael Espindola6406f7b2014-08-26 19:54:40 +00004078 std::unique_ptr<llvm::MemoryBuffer> Buffer =
4079 FileMgr.getBufferForFile(ASTFileName, &ErrStr);
Guy Benyei11169dd2012-12-18 14:30:41 +00004080 if (!Buffer) {
4081 Diags.Report(diag::err_fe_unable_to_read_pch_file) << ASTFileName << ErrStr;
4082 return std::string();
4083 }
4084
4085 // Initialize the stream
4086 llvm::BitstreamReader StreamFile;
Chris Lattner7fb3bef2013-01-20 00:56:42 +00004087 BitstreamCursor Stream;
Guy Benyei11169dd2012-12-18 14:30:41 +00004088 StreamFile.init((const unsigned char *)Buffer->getBufferStart(),
4089 (const unsigned char *)Buffer->getBufferEnd());
4090 Stream.init(StreamFile);
4091
4092 // Sniff for the signature.
4093 if (Stream.Read(8) != 'C' ||
4094 Stream.Read(8) != 'P' ||
4095 Stream.Read(8) != 'C' ||
4096 Stream.Read(8) != 'H') {
4097 Diags.Report(diag::err_fe_not_a_pch_file) << ASTFileName;
4098 return std::string();
4099 }
Chris Lattner7fb3bef2013-01-20 00:56:42 +00004100
Chris Lattnere7b154b2013-01-19 21:39:22 +00004101 // Scan for the CONTROL_BLOCK_ID block.
Argyrios Kyrtzidisc4cd2c42013-05-06 19:23:40 +00004102 if (SkipCursorToBlock(Stream, CONTROL_BLOCK_ID)) {
Chris Lattner7fb3bef2013-01-20 00:56:42 +00004103 Diags.Report(diag::err_fe_pch_malformed_block) << ASTFileName;
4104 return std::string();
Chris Lattnere7b154b2013-01-19 21:39:22 +00004105 }
Guy Benyei11169dd2012-12-18 14:30:41 +00004106
Chris Lattner7fb3bef2013-01-20 00:56:42 +00004107 // Scan for ORIGINAL_FILE inside the control block.
4108 RecordData Record;
Chris Lattnere7b154b2013-01-19 21:39:22 +00004109 while (1) {
Chris Lattner7fb3bef2013-01-20 00:56:42 +00004110 llvm::BitstreamEntry Entry = Stream.advanceSkippingSubblocks();
Chris Lattnere7b154b2013-01-19 21:39:22 +00004111 if (Entry.Kind == llvm::BitstreamEntry::EndBlock)
4112 return std::string();
4113
4114 if (Entry.Kind != llvm::BitstreamEntry::Record) {
4115 Diags.Report(diag::err_fe_pch_malformed_block) << ASTFileName;
4116 return std::string();
Guy Benyei11169dd2012-12-18 14:30:41 +00004117 }
Chris Lattnere7b154b2013-01-19 21:39:22 +00004118
Guy Benyei11169dd2012-12-18 14:30:41 +00004119 Record.clear();
Chris Lattner0e6c9402013-01-20 02:38:54 +00004120 StringRef Blob;
4121 if (Stream.readRecord(Entry.ID, Record, &Blob) == ORIGINAL_FILE)
4122 return Blob.str();
Guy Benyei11169dd2012-12-18 14:30:41 +00004123 }
Guy Benyei11169dd2012-12-18 14:30:41 +00004124}
4125
4126namespace {
4127 class SimplePCHValidator : public ASTReaderListener {
4128 const LangOptions &ExistingLangOpts;
4129 const TargetOptions &ExistingTargetOpts;
4130 const PreprocessorOptions &ExistingPPOpts;
4131 FileManager &FileMgr;
4132
4133 public:
4134 SimplePCHValidator(const LangOptions &ExistingLangOpts,
4135 const TargetOptions &ExistingTargetOpts,
4136 const PreprocessorOptions &ExistingPPOpts,
4137 FileManager &FileMgr)
4138 : ExistingLangOpts(ExistingLangOpts),
4139 ExistingTargetOpts(ExistingTargetOpts),
4140 ExistingPPOpts(ExistingPPOpts),
4141 FileMgr(FileMgr)
4142 {
4143 }
4144
Craig Topper3e89dfe2014-03-13 02:13:41 +00004145 bool ReadLanguageOptions(const LangOptions &LangOpts,
4146 bool Complain) override {
Craig Toppera13603a2014-05-22 05:54:18 +00004147 return checkLanguageOptions(ExistingLangOpts, LangOpts, nullptr);
Guy Benyei11169dd2012-12-18 14:30:41 +00004148 }
Craig Topper3e89dfe2014-03-13 02:13:41 +00004149 bool ReadTargetOptions(const TargetOptions &TargetOpts,
4150 bool Complain) override {
Craig Toppera13603a2014-05-22 05:54:18 +00004151 return checkTargetOptions(ExistingTargetOpts, TargetOpts, nullptr);
Guy Benyei11169dd2012-12-18 14:30:41 +00004152 }
Craig Topper3e89dfe2014-03-13 02:13:41 +00004153 bool ReadPreprocessorOptions(const PreprocessorOptions &PPOpts,
4154 bool Complain,
4155 std::string &SuggestedPredefines) override {
Craig Toppera13603a2014-05-22 05:54:18 +00004156 return checkPreprocessorOptions(ExistingPPOpts, PPOpts, nullptr, FileMgr,
Argyrios Kyrtzidisd3afa0c2013-04-26 21:33:40 +00004157 SuggestedPredefines, ExistingLangOpts);
Guy Benyei11169dd2012-12-18 14:30:41 +00004158 }
4159 };
4160}
4161
4162bool ASTReader::readASTFileControlBlock(StringRef Filename,
4163 FileManager &FileMgr,
4164 ASTReaderListener &Listener) {
4165 // Open the AST file.
4166 std::string ErrStr;
Rafael Espindola6406f7b2014-08-26 19:54:40 +00004167 std::unique_ptr<llvm::MemoryBuffer> Buffer =
4168 FileMgr.getBufferForFile(Filename, &ErrStr);
Guy Benyei11169dd2012-12-18 14:30:41 +00004169 if (!Buffer) {
4170 return true;
4171 }
4172
4173 // Initialize the stream
4174 llvm::BitstreamReader StreamFile;
Chris Lattner7fb3bef2013-01-20 00:56:42 +00004175 BitstreamCursor Stream;
Guy Benyei11169dd2012-12-18 14:30:41 +00004176 StreamFile.init((const unsigned char *)Buffer->getBufferStart(),
4177 (const unsigned char *)Buffer->getBufferEnd());
4178 Stream.init(StreamFile);
4179
4180 // Sniff for the signature.
4181 if (Stream.Read(8) != 'C' ||
4182 Stream.Read(8) != 'P' ||
4183 Stream.Read(8) != 'C' ||
4184 Stream.Read(8) != 'H') {
4185 return true;
4186 }
4187
Chris Lattner7fb3bef2013-01-20 00:56:42 +00004188 // Scan for the CONTROL_BLOCK_ID block.
Argyrios Kyrtzidisc4cd2c42013-05-06 19:23:40 +00004189 if (SkipCursorToBlock(Stream, CONTROL_BLOCK_ID))
Chris Lattner7fb3bef2013-01-20 00:56:42 +00004190 return true;
Argyrios Kyrtzidisc4cd2c42013-05-06 19:23:40 +00004191
4192 bool NeedsInputFiles = Listener.needsInputFileVisitation();
Ben Langmuircb69b572014-03-07 06:40:32 +00004193 bool NeedsSystemInputFiles = Listener.needsSystemInputFileVisitation();
Argyrios Kyrtzidisc4cd2c42013-05-06 19:23:40 +00004194 BitstreamCursor InputFilesCursor;
4195 if (NeedsInputFiles) {
4196 InputFilesCursor = Stream;
4197 if (SkipCursorToBlock(InputFilesCursor, INPUT_FILES_BLOCK_ID))
4198 return true;
4199
4200 // Read the abbreviations
4201 while (true) {
4202 uint64_t Offset = InputFilesCursor.GetCurrentBitNo();
4203 unsigned Code = InputFilesCursor.ReadCode();
4204
4205 // We expect all abbrevs to be at the start of the block.
4206 if (Code != llvm::bitc::DEFINE_ABBREV) {
4207 InputFilesCursor.JumpToBit(Offset);
4208 break;
4209 }
4210 InputFilesCursor.ReadAbbrevRecord();
4211 }
4212 }
Chris Lattner7fb3bef2013-01-20 00:56:42 +00004213
4214 // Scan for ORIGINAL_FILE inside the control block.
Guy Benyei11169dd2012-12-18 14:30:41 +00004215 RecordData Record;
Chris Lattner7fb3bef2013-01-20 00:56:42 +00004216 while (1) {
4217 llvm::BitstreamEntry Entry = Stream.advanceSkippingSubblocks();
4218 if (Entry.Kind == llvm::BitstreamEntry::EndBlock)
4219 return false;
4220
4221 if (Entry.Kind != llvm::BitstreamEntry::Record)
4222 return true;
4223
Guy Benyei11169dd2012-12-18 14:30:41 +00004224 Record.clear();
Chris Lattner0e6c9402013-01-20 02:38:54 +00004225 StringRef Blob;
4226 unsigned RecCode = Stream.readRecord(Entry.ID, Record, &Blob);
Chris Lattner7fb3bef2013-01-20 00:56:42 +00004227 switch ((ControlRecordTypes)RecCode) {
4228 case METADATA: {
4229 if (Record[0] != VERSION_MAJOR)
4230 return true;
Guy Benyei11169dd2012-12-18 14:30:41 +00004231
Douglas Gregorbf7fc9c2013-03-27 16:47:18 +00004232 if (Listener.ReadFullVersionInformation(Blob))
Chris Lattner7fb3bef2013-01-20 00:56:42 +00004233 return true;
Douglas Gregorbf7fc9c2013-03-27 16:47:18 +00004234
Chris Lattner7fb3bef2013-01-20 00:56:42 +00004235 break;
4236 }
Ben Langmuir4f5212a2014-04-14 22:12:44 +00004237 case MODULE_NAME:
4238 Listener.ReadModuleName(Blob);
4239 break;
Ben Langmuir4b8a9e92014-08-12 16:42:33 +00004240 case MODULE_MAP_FILE: {
4241 unsigned Idx = 0;
4242 Listener.ReadModuleMapFile(ReadString(Record, Idx));
Ben Langmuir4f5212a2014-04-14 22:12:44 +00004243 break;
Ben Langmuir4b8a9e92014-08-12 16:42:33 +00004244 }
Chris Lattner7fb3bef2013-01-20 00:56:42 +00004245 case LANGUAGE_OPTIONS:
4246 if (ParseLanguageOptions(Record, false, Listener))
4247 return true;
4248 break;
Guy Benyei11169dd2012-12-18 14:30:41 +00004249
Chris Lattner7fb3bef2013-01-20 00:56:42 +00004250 case TARGET_OPTIONS:
4251 if (ParseTargetOptions(Record, false, Listener))
4252 return true;
4253 break;
Guy Benyei11169dd2012-12-18 14:30:41 +00004254
Chris Lattner7fb3bef2013-01-20 00:56:42 +00004255 case DIAGNOSTIC_OPTIONS:
4256 if (ParseDiagnosticOptions(Record, false, Listener))
4257 return true;
4258 break;
Guy Benyei11169dd2012-12-18 14:30:41 +00004259
Chris Lattner7fb3bef2013-01-20 00:56:42 +00004260 case FILE_SYSTEM_OPTIONS:
4261 if (ParseFileSystemOptions(Record, false, Listener))
4262 return true;
4263 break;
Guy Benyei11169dd2012-12-18 14:30:41 +00004264
Chris Lattner7fb3bef2013-01-20 00:56:42 +00004265 case HEADER_SEARCH_OPTIONS:
4266 if (ParseHeaderSearchOptions(Record, false, Listener))
4267 return true;
4268 break;
Guy Benyei11169dd2012-12-18 14:30:41 +00004269
Chris Lattner7fb3bef2013-01-20 00:56:42 +00004270 case PREPROCESSOR_OPTIONS: {
4271 std::string IgnoredSuggestedPredefines;
4272 if (ParsePreprocessorOptions(Record, false, Listener,
4273 IgnoredSuggestedPredefines))
4274 return true;
4275 break;
4276 }
Guy Benyei11169dd2012-12-18 14:30:41 +00004277
Argyrios Kyrtzidisc4cd2c42013-05-06 19:23:40 +00004278 case INPUT_FILE_OFFSETS: {
4279 if (!NeedsInputFiles)
4280 break;
4281
4282 unsigned NumInputFiles = Record[0];
4283 unsigned NumUserFiles = Record[1];
4284 const uint32_t *InputFileOffs = (const uint32_t *)Blob.data();
4285 for (unsigned I = 0; I != NumInputFiles; ++I) {
4286 // Go find this input file.
4287 bool isSystemFile = I >= NumUserFiles;
Ben Langmuircb69b572014-03-07 06:40:32 +00004288
4289 if (isSystemFile && !NeedsSystemInputFiles)
4290 break; // the rest are system input files
4291
Argyrios Kyrtzidisc4cd2c42013-05-06 19:23:40 +00004292 BitstreamCursor &Cursor = InputFilesCursor;
4293 SavedStreamPosition SavedPosition(Cursor);
4294 Cursor.JumpToBit(InputFileOffs[I]);
4295
4296 unsigned Code = Cursor.ReadCode();
4297 RecordData Record;
4298 StringRef Blob;
4299 bool shouldContinue = false;
4300 switch ((InputFileRecordTypes)Cursor.readRecord(Code, Record, &Blob)) {
4301 case INPUT_FILE:
Argyrios Kyrtzidis68ccbe02014-03-14 02:26:31 +00004302 bool Overridden = static_cast<bool>(Record[3]);
4303 shouldContinue = Listener.visitInputFile(Blob, isSystemFile, Overridden);
Argyrios Kyrtzidisc4cd2c42013-05-06 19:23:40 +00004304 break;
4305 }
4306 if (!shouldContinue)
4307 break;
4308 }
4309 break;
4310 }
4311
Chris Lattner7fb3bef2013-01-20 00:56:42 +00004312 default:
4313 // No other validation to perform.
4314 break;
Guy Benyei11169dd2012-12-18 14:30:41 +00004315 }
4316 }
Guy Benyei11169dd2012-12-18 14:30:41 +00004317}
4318
4319
4320bool ASTReader::isAcceptableASTFile(StringRef Filename,
4321 FileManager &FileMgr,
4322 const LangOptions &LangOpts,
4323 const TargetOptions &TargetOpts,
4324 const PreprocessorOptions &PPOpts) {
4325 SimplePCHValidator validator(LangOpts, TargetOpts, PPOpts, FileMgr);
4326 return !readASTFileControlBlock(Filename, FileMgr, validator);
4327}
4328
Ben Langmuir2c9af442014-04-10 17:57:43 +00004329ASTReader::ASTReadResult
4330ASTReader::ReadSubmoduleBlock(ModuleFile &F, unsigned ClientLoadCapabilities) {
Guy Benyei11169dd2012-12-18 14:30:41 +00004331 // Enter the submodule block.
4332 if (F.Stream.EnterSubBlock(SUBMODULE_BLOCK_ID)) {
4333 Error("malformed submodule block record in AST file");
Ben Langmuir2c9af442014-04-10 17:57:43 +00004334 return Failure;
Guy Benyei11169dd2012-12-18 14:30:41 +00004335 }
4336
4337 ModuleMap &ModMap = PP.getHeaderSearchInfo().getModuleMap();
4338 bool First = true;
Craig Toppera13603a2014-05-22 05:54:18 +00004339 Module *CurrentModule = nullptr;
Guy Benyei11169dd2012-12-18 14:30:41 +00004340 RecordData Record;
4341 while (true) {
Chris Lattner7fb3bef2013-01-20 00:56:42 +00004342 llvm::BitstreamEntry Entry = F.Stream.advanceSkippingSubblocks();
4343
4344 switch (Entry.Kind) {
4345 case llvm::BitstreamEntry::SubBlock: // Handled for us already.
4346 case llvm::BitstreamEntry::Error:
4347 Error("malformed block record in AST file");
Ben Langmuir2c9af442014-04-10 17:57:43 +00004348 return Failure;
Chris Lattner7fb3bef2013-01-20 00:56:42 +00004349 case llvm::BitstreamEntry::EndBlock:
Ben Langmuir2c9af442014-04-10 17:57:43 +00004350 return Success;
Chris Lattner7fb3bef2013-01-20 00:56:42 +00004351 case llvm::BitstreamEntry::Record:
4352 // The interesting case.
4353 break;
Guy Benyei11169dd2012-12-18 14:30:41 +00004354 }
Chris Lattner7fb3bef2013-01-20 00:56:42 +00004355
Guy Benyei11169dd2012-12-18 14:30:41 +00004356 // Read a record.
Chris Lattner0e6c9402013-01-20 02:38:54 +00004357 StringRef Blob;
Guy Benyei11169dd2012-12-18 14:30:41 +00004358 Record.clear();
Chris Lattner0e6c9402013-01-20 02:38:54 +00004359 switch (F.Stream.readRecord(Entry.ID, Record, &Blob)) {
Guy Benyei11169dd2012-12-18 14:30:41 +00004360 default: // Default behavior: ignore.
4361 break;
4362
4363 case SUBMODULE_DEFINITION: {
4364 if (First) {
4365 Error("missing submodule metadata record at beginning of block");
Ben Langmuir2c9af442014-04-10 17:57:43 +00004366 return Failure;
Guy Benyei11169dd2012-12-18 14:30:41 +00004367 }
4368
Douglas Gregor8d932422013-03-20 03:59:18 +00004369 if (Record.size() < 8) {
Guy Benyei11169dd2012-12-18 14:30:41 +00004370 Error("malformed module definition");
Ben Langmuir2c9af442014-04-10 17:57:43 +00004371 return Failure;
Guy Benyei11169dd2012-12-18 14:30:41 +00004372 }
4373
Chris Lattner0e6c9402013-01-20 02:38:54 +00004374 StringRef Name = Blob;
Richard Smith9bca2982014-03-08 00:03:56 +00004375 unsigned Idx = 0;
4376 SubmoduleID GlobalID = getGlobalSubmoduleID(F, Record[Idx++]);
4377 SubmoduleID Parent = getGlobalSubmoduleID(F, Record[Idx++]);
4378 bool IsFramework = Record[Idx++];
4379 bool IsExplicit = Record[Idx++];
4380 bool IsSystem = Record[Idx++];
4381 bool IsExternC = Record[Idx++];
4382 bool InferSubmodules = Record[Idx++];
4383 bool InferExplicitSubmodules = Record[Idx++];
4384 bool InferExportWildcard = Record[Idx++];
4385 bool ConfigMacrosExhaustive = Record[Idx++];
Douglas Gregor8d932422013-03-20 03:59:18 +00004386
Ben Langmuirbeee15e2014-04-14 18:00:01 +00004387 Module *ParentModule = nullptr;
Ben Langmuir9d6448b2014-08-09 00:57:23 +00004388 if (Parent)
Guy Benyei11169dd2012-12-18 14:30:41 +00004389 ParentModule = getSubmodule(Parent);
Ben Langmuirbeee15e2014-04-14 18:00:01 +00004390
Guy Benyei11169dd2012-12-18 14:30:41 +00004391 // Retrieve this (sub)module from the module map, creating it if
4392 // necessary.
Ben Langmuir9d6448b2014-08-09 00:57:23 +00004393 CurrentModule = ModMap.findOrCreateModule(Name, ParentModule, IsFramework,
Guy Benyei11169dd2012-12-18 14:30:41 +00004394 IsExplicit).first;
Ben Langmuir9d6448b2014-08-09 00:57:23 +00004395
4396 // FIXME: set the definition loc for CurrentModule, or call
4397 // ModMap.setInferredModuleAllowedBy()
4398
Guy Benyei11169dd2012-12-18 14:30:41 +00004399 SubmoduleID GlobalIndex = GlobalID - NUM_PREDEF_SUBMODULE_IDS;
4400 if (GlobalIndex >= SubmodulesLoaded.size() ||
4401 SubmodulesLoaded[GlobalIndex]) {
4402 Error("too many submodules");
Ben Langmuir2c9af442014-04-10 17:57:43 +00004403 return Failure;
Guy Benyei11169dd2012-12-18 14:30:41 +00004404 }
Douglas Gregor8a114ab2013-02-06 22:40:31 +00004405
Douglas Gregor7029ce12013-03-19 00:28:20 +00004406 if (!ParentModule) {
4407 if (const FileEntry *CurFile = CurrentModule->getASTFile()) {
4408 if (CurFile != F.File) {
4409 if (!Diags.isDiagnosticInFlight()) {
4410 Diag(diag::err_module_file_conflict)
4411 << CurrentModule->getTopLevelModuleName()
4412 << CurFile->getName()
4413 << F.File->getName();
4414 }
Ben Langmuir2c9af442014-04-10 17:57:43 +00004415 return Failure;
Douglas Gregor8a114ab2013-02-06 22:40:31 +00004416 }
Douglas Gregor8a114ab2013-02-06 22:40:31 +00004417 }
Douglas Gregor7029ce12013-03-19 00:28:20 +00004418
4419 CurrentModule->setASTFile(F.File);
Douglas Gregor8a114ab2013-02-06 22:40:31 +00004420 }
Ben Langmuirbeee15e2014-04-14 18:00:01 +00004421
Guy Benyei11169dd2012-12-18 14:30:41 +00004422 CurrentModule->IsFromModuleFile = true;
4423 CurrentModule->IsSystem = IsSystem || CurrentModule->IsSystem;
Richard Smith9bca2982014-03-08 00:03:56 +00004424 CurrentModule->IsExternC = IsExternC;
Guy Benyei11169dd2012-12-18 14:30:41 +00004425 CurrentModule->InferSubmodules = InferSubmodules;
4426 CurrentModule->InferExplicitSubmodules = InferExplicitSubmodules;
4427 CurrentModule->InferExportWildcard = InferExportWildcard;
Douglas Gregor8d932422013-03-20 03:59:18 +00004428 CurrentModule->ConfigMacrosExhaustive = ConfigMacrosExhaustive;
Guy Benyei11169dd2012-12-18 14:30:41 +00004429 if (DeserializationListener)
4430 DeserializationListener->ModuleRead(GlobalID, CurrentModule);
4431
4432 SubmodulesLoaded[GlobalIndex] = CurrentModule;
Douglas Gregor6ddfca92013-01-14 17:21:00 +00004433
Douglas Gregorfb912652013-03-20 21:10:35 +00004434 // Clear out data that will be replaced by what is the module file.
Douglas Gregor6ddfca92013-01-14 17:21:00 +00004435 CurrentModule->LinkLibraries.clear();
Douglas Gregor8d932422013-03-20 03:59:18 +00004436 CurrentModule->ConfigMacros.clear();
Douglas Gregorfb912652013-03-20 21:10:35 +00004437 CurrentModule->UnresolvedConflicts.clear();
4438 CurrentModule->Conflicts.clear();
Guy Benyei11169dd2012-12-18 14:30:41 +00004439 break;
4440 }
4441
4442 case SUBMODULE_UMBRELLA_HEADER: {
4443 if (First) {
4444 Error("missing submodule metadata record at beginning of block");
Ben Langmuir2c9af442014-04-10 17:57:43 +00004445 return Failure;
Guy Benyei11169dd2012-12-18 14:30:41 +00004446 }
4447
4448 if (!CurrentModule)
4449 break;
4450
Chris Lattner0e6c9402013-01-20 02:38:54 +00004451 if (const FileEntry *Umbrella = PP.getFileManager().getFile(Blob)) {
Guy Benyei11169dd2012-12-18 14:30:41 +00004452 if (!CurrentModule->getUmbrellaHeader())
4453 ModMap.setUmbrellaHeader(CurrentModule, Umbrella);
4454 else if (CurrentModule->getUmbrellaHeader() != Umbrella) {
Ben Langmuir2c9af442014-04-10 17:57:43 +00004455 if ((ClientLoadCapabilities & ARR_OutOfDate) == 0)
4456 Error("mismatched umbrella headers in submodule");
4457 return OutOfDate;
Guy Benyei11169dd2012-12-18 14:30:41 +00004458 }
4459 }
4460 break;
4461 }
4462
4463 case SUBMODULE_HEADER: {
4464 if (First) {
4465 Error("missing submodule metadata record at beginning of block");
Ben Langmuir2c9af442014-04-10 17:57:43 +00004466 return Failure;
Guy Benyei11169dd2012-12-18 14:30:41 +00004467 }
4468
4469 if (!CurrentModule)
4470 break;
4471
Argyrios Kyrtzidisb146baa2013-03-13 21:13:51 +00004472 // We lazily associate headers with their modules via the HeaderInfoTable.
4473 // FIXME: Re-evaluate this section; maybe only store InputFile IDs instead
4474 // of complete filenames or remove it entirely.
Guy Benyei11169dd2012-12-18 14:30:41 +00004475 break;
4476 }
4477
4478 case SUBMODULE_EXCLUDED_HEADER: {
4479 if (First) {
4480 Error("missing submodule metadata record at beginning of block");
Ben Langmuir2c9af442014-04-10 17:57:43 +00004481 return Failure;
Guy Benyei11169dd2012-12-18 14:30:41 +00004482 }
4483
4484 if (!CurrentModule)
4485 break;
4486
Argyrios Kyrtzidisb146baa2013-03-13 21:13:51 +00004487 // We lazily associate headers with their modules via the HeaderInfoTable.
4488 // FIXME: Re-evaluate this section; maybe only store InputFile IDs instead
4489 // of complete filenames or remove it entirely.
Guy Benyei11169dd2012-12-18 14:30:41 +00004490 break;
4491 }
4492
Lawrence Crowlb53e5482013-06-20 21:14:14 +00004493 case SUBMODULE_PRIVATE_HEADER: {
4494 if (First) {
4495 Error("missing submodule metadata record at beginning of block");
Ben Langmuir2c9af442014-04-10 17:57:43 +00004496 return Failure;
Lawrence Crowlb53e5482013-06-20 21:14:14 +00004497 }
4498
4499 if (!CurrentModule)
4500 break;
4501
4502 // We lazily associate headers with their modules via the HeaderInfoTable.
4503 // FIXME: Re-evaluate this section; maybe only store InputFile IDs instead
4504 // of complete filenames or remove it entirely.
4505 break;
4506 }
4507
Guy Benyei11169dd2012-12-18 14:30:41 +00004508 case SUBMODULE_TOPHEADER: {
4509 if (First) {
4510 Error("missing submodule metadata record at beginning of block");
Ben Langmuir2c9af442014-04-10 17:57:43 +00004511 return Failure;
Guy Benyei11169dd2012-12-18 14:30:41 +00004512 }
4513
4514 if (!CurrentModule)
4515 break;
4516
Argyrios Kyrtzidis3c5305c2013-03-13 21:13:43 +00004517 CurrentModule->addTopHeaderFilename(Blob);
Guy Benyei11169dd2012-12-18 14:30:41 +00004518 break;
4519 }
4520
4521 case SUBMODULE_UMBRELLA_DIR: {
4522 if (First) {
4523 Error("missing submodule metadata record at beginning of block");
Ben Langmuir2c9af442014-04-10 17:57:43 +00004524 return Failure;
Guy Benyei11169dd2012-12-18 14:30:41 +00004525 }
4526
4527 if (!CurrentModule)
4528 break;
4529
Guy Benyei11169dd2012-12-18 14:30:41 +00004530 if (const DirectoryEntry *Umbrella
Chris Lattner0e6c9402013-01-20 02:38:54 +00004531 = PP.getFileManager().getDirectory(Blob)) {
Guy Benyei11169dd2012-12-18 14:30:41 +00004532 if (!CurrentModule->getUmbrellaDir())
4533 ModMap.setUmbrellaDir(CurrentModule, Umbrella);
4534 else if (CurrentModule->getUmbrellaDir() != Umbrella) {
Ben Langmuir2c9af442014-04-10 17:57:43 +00004535 if ((ClientLoadCapabilities & ARR_OutOfDate) == 0)
4536 Error("mismatched umbrella directories in submodule");
4537 return OutOfDate;
Guy Benyei11169dd2012-12-18 14:30:41 +00004538 }
4539 }
4540 break;
4541 }
4542
4543 case SUBMODULE_METADATA: {
4544 if (!First) {
4545 Error("submodule metadata record not at beginning of block");
Ben Langmuir2c9af442014-04-10 17:57:43 +00004546 return Failure;
Guy Benyei11169dd2012-12-18 14:30:41 +00004547 }
4548 First = false;
4549
4550 F.BaseSubmoduleID = getTotalNumSubmodules();
4551 F.LocalNumSubmodules = Record[0];
4552 unsigned LocalBaseSubmoduleID = Record[1];
4553 if (F.LocalNumSubmodules > 0) {
4554 // Introduce the global -> local mapping for submodules within this
4555 // module.
4556 GlobalSubmoduleMap.insert(std::make_pair(getTotalNumSubmodules()+1,&F));
4557
4558 // Introduce the local -> global mapping for submodules within this
4559 // module.
4560 F.SubmoduleRemap.insertOrReplace(
4561 std::make_pair(LocalBaseSubmoduleID,
4562 F.BaseSubmoduleID - LocalBaseSubmoduleID));
Ben Langmuirfe971d92014-08-16 04:54:18 +00004563
Ben Langmuir52ca6782014-10-20 16:27:32 +00004564 SubmodulesLoaded.resize(SubmodulesLoaded.size() + F.LocalNumSubmodules);
4565 }
Guy Benyei11169dd2012-12-18 14:30:41 +00004566 break;
4567 }
4568
4569 case SUBMODULE_IMPORTS: {
4570 if (First) {
4571 Error("missing submodule metadata record at beginning of block");
Ben Langmuir2c9af442014-04-10 17:57:43 +00004572 return Failure;
Guy Benyei11169dd2012-12-18 14:30:41 +00004573 }
4574
4575 if (!CurrentModule)
4576 break;
4577
4578 for (unsigned Idx = 0; Idx != Record.size(); ++Idx) {
Douglas Gregorfb912652013-03-20 21:10:35 +00004579 UnresolvedModuleRef Unresolved;
Guy Benyei11169dd2012-12-18 14:30:41 +00004580 Unresolved.File = &F;
4581 Unresolved.Mod = CurrentModule;
4582 Unresolved.ID = Record[Idx];
Douglas Gregorfb912652013-03-20 21:10:35 +00004583 Unresolved.Kind = UnresolvedModuleRef::Import;
Guy Benyei11169dd2012-12-18 14:30:41 +00004584 Unresolved.IsWildcard = false;
Douglas Gregorfb912652013-03-20 21:10:35 +00004585 UnresolvedModuleRefs.push_back(Unresolved);
Guy Benyei11169dd2012-12-18 14:30:41 +00004586 }
4587 break;
4588 }
4589
4590 case SUBMODULE_EXPORTS: {
4591 if (First) {
4592 Error("missing submodule metadata record at beginning of block");
Ben Langmuir2c9af442014-04-10 17:57:43 +00004593 return Failure;
Guy Benyei11169dd2012-12-18 14:30:41 +00004594 }
4595
4596 if (!CurrentModule)
4597 break;
4598
4599 for (unsigned Idx = 0; Idx + 1 < Record.size(); Idx += 2) {
Douglas Gregorfb912652013-03-20 21:10:35 +00004600 UnresolvedModuleRef Unresolved;
Guy Benyei11169dd2012-12-18 14:30:41 +00004601 Unresolved.File = &F;
4602 Unresolved.Mod = CurrentModule;
4603 Unresolved.ID = Record[Idx];
Douglas Gregorfb912652013-03-20 21:10:35 +00004604 Unresolved.Kind = UnresolvedModuleRef::Export;
Guy Benyei11169dd2012-12-18 14:30:41 +00004605 Unresolved.IsWildcard = Record[Idx + 1];
Douglas Gregorfb912652013-03-20 21:10:35 +00004606 UnresolvedModuleRefs.push_back(Unresolved);
Guy Benyei11169dd2012-12-18 14:30:41 +00004607 }
4608
4609 // Once we've loaded the set of exports, there's no reason to keep
4610 // the parsed, unresolved exports around.
4611 CurrentModule->UnresolvedExports.clear();
4612 break;
4613 }
4614 case SUBMODULE_REQUIRES: {
4615 if (First) {
4616 Error("missing submodule metadata record at beginning of block");
Ben Langmuir2c9af442014-04-10 17:57:43 +00004617 return Failure;
Guy Benyei11169dd2012-12-18 14:30:41 +00004618 }
4619
4620 if (!CurrentModule)
4621 break;
4622
Richard Smitha3feee22013-10-28 22:18:19 +00004623 CurrentModule->addRequirement(Blob, Record[0], Context.getLangOpts(),
Guy Benyei11169dd2012-12-18 14:30:41 +00004624 Context.getTargetInfo());
4625 break;
4626 }
Douglas Gregor6ddfca92013-01-14 17:21:00 +00004627
4628 case SUBMODULE_LINK_LIBRARY:
4629 if (First) {
4630 Error("missing submodule metadata record at beginning of block");
Ben Langmuir2c9af442014-04-10 17:57:43 +00004631 return Failure;
Douglas Gregor6ddfca92013-01-14 17:21:00 +00004632 }
4633
4634 if (!CurrentModule)
4635 break;
4636
4637 CurrentModule->LinkLibraries.push_back(
Chris Lattner0e6c9402013-01-20 02:38:54 +00004638 Module::LinkLibrary(Blob, Record[0]));
Douglas Gregor6ddfca92013-01-14 17:21:00 +00004639 break;
Douglas Gregor35b13ec2013-03-20 00:22:05 +00004640
4641 case SUBMODULE_CONFIG_MACRO:
4642 if (First) {
4643 Error("missing submodule metadata record at beginning of block");
Ben Langmuir2c9af442014-04-10 17:57:43 +00004644 return Failure;
Douglas Gregor35b13ec2013-03-20 00:22:05 +00004645 }
4646
4647 if (!CurrentModule)
4648 break;
4649
4650 CurrentModule->ConfigMacros.push_back(Blob.str());
4651 break;
Douglas Gregorfb912652013-03-20 21:10:35 +00004652
4653 case SUBMODULE_CONFLICT: {
4654 if (First) {
4655 Error("missing submodule metadata record at beginning of block");
Ben Langmuir2c9af442014-04-10 17:57:43 +00004656 return Failure;
Douglas Gregorfb912652013-03-20 21:10:35 +00004657 }
4658
4659 if (!CurrentModule)
4660 break;
4661
4662 UnresolvedModuleRef Unresolved;
4663 Unresolved.File = &F;
4664 Unresolved.Mod = CurrentModule;
4665 Unresolved.ID = Record[0];
4666 Unresolved.Kind = UnresolvedModuleRef::Conflict;
4667 Unresolved.IsWildcard = false;
4668 Unresolved.String = Blob;
4669 UnresolvedModuleRefs.push_back(Unresolved);
4670 break;
4671 }
Guy Benyei11169dd2012-12-18 14:30:41 +00004672 }
4673 }
4674}
4675
4676/// \brief Parse the record that corresponds to a LangOptions data
4677/// structure.
4678///
4679/// This routine parses the language options from the AST file and then gives
4680/// them to the AST listener if one is set.
4681///
4682/// \returns true if the listener deems the file unacceptable, false otherwise.
4683bool ASTReader::ParseLanguageOptions(const RecordData &Record,
4684 bool Complain,
4685 ASTReaderListener &Listener) {
4686 LangOptions LangOpts;
4687 unsigned Idx = 0;
4688#define LANGOPT(Name, Bits, Default, Description) \
4689 LangOpts.Name = Record[Idx++];
4690#define ENUM_LANGOPT(Name, Type, Bits, Default, Description) \
4691 LangOpts.set##Name(static_cast<LangOptions::Type>(Record[Idx++]));
4692#include "clang/Basic/LangOptions.def"
Will Dietzf54319c2013-01-18 11:30:38 +00004693#define SANITIZER(NAME, ID) LangOpts.Sanitize.ID = Record[Idx++];
4694#include "clang/Basic/Sanitizers.def"
Guy Benyei11169dd2012-12-18 14:30:41 +00004695
4696 ObjCRuntime::Kind runtimeKind = (ObjCRuntime::Kind) Record[Idx++];
4697 VersionTuple runtimeVersion = ReadVersionTuple(Record, Idx);
4698 LangOpts.ObjCRuntime = ObjCRuntime(runtimeKind, runtimeVersion);
4699
4700 unsigned Length = Record[Idx++];
4701 LangOpts.CurrentModule.assign(Record.begin() + Idx,
4702 Record.begin() + Idx + Length);
Dmitri Gribenkoacf2e782013-02-22 14:21:27 +00004703
4704 Idx += Length;
4705
4706 // Comment options.
4707 for (unsigned N = Record[Idx++]; N; --N) {
4708 LangOpts.CommentOpts.BlockCommandNames.push_back(
4709 ReadString(Record, Idx));
4710 }
Dmitri Gribenkoa7d16ce2013-04-10 15:35:17 +00004711 LangOpts.CommentOpts.ParseAllComments = Record[Idx++];
Dmitri Gribenkoacf2e782013-02-22 14:21:27 +00004712
Guy Benyei11169dd2012-12-18 14:30:41 +00004713 return Listener.ReadLanguageOptions(LangOpts, Complain);
4714}
4715
4716bool ASTReader::ParseTargetOptions(const RecordData &Record,
4717 bool Complain,
4718 ASTReaderListener &Listener) {
4719 unsigned Idx = 0;
4720 TargetOptions TargetOpts;
4721 TargetOpts.Triple = ReadString(Record, Idx);
4722 TargetOpts.CPU = ReadString(Record, Idx);
4723 TargetOpts.ABI = ReadString(Record, Idx);
Guy Benyei11169dd2012-12-18 14:30:41 +00004724 for (unsigned N = Record[Idx++]; N; --N) {
4725 TargetOpts.FeaturesAsWritten.push_back(ReadString(Record, Idx));
4726 }
4727 for (unsigned N = Record[Idx++]; N; --N) {
4728 TargetOpts.Features.push_back(ReadString(Record, Idx));
4729 }
4730
4731 return Listener.ReadTargetOptions(TargetOpts, Complain);
4732}
4733
4734bool ASTReader::ParseDiagnosticOptions(const RecordData &Record, bool Complain,
4735 ASTReaderListener &Listener) {
Ben Langmuirb92de022014-04-29 16:25:26 +00004736 IntrusiveRefCntPtr<DiagnosticOptions> DiagOpts(new DiagnosticOptions);
Guy Benyei11169dd2012-12-18 14:30:41 +00004737 unsigned Idx = 0;
Ben Langmuirb92de022014-04-29 16:25:26 +00004738#define DIAGOPT(Name, Bits, Default) DiagOpts->Name = Record[Idx++];
Guy Benyei11169dd2012-12-18 14:30:41 +00004739#define ENUM_DIAGOPT(Name, Type, Bits, Default) \
Ben Langmuirb92de022014-04-29 16:25:26 +00004740 DiagOpts->set##Name(static_cast<Type>(Record[Idx++]));
Guy Benyei11169dd2012-12-18 14:30:41 +00004741#include "clang/Basic/DiagnosticOptions.def"
4742
Richard Smith3be1cb22014-08-07 00:24:21 +00004743 for (unsigned N = Record[Idx++]; N; --N)
Ben Langmuirb92de022014-04-29 16:25:26 +00004744 DiagOpts->Warnings.push_back(ReadString(Record, Idx));
Richard Smith3be1cb22014-08-07 00:24:21 +00004745 for (unsigned N = Record[Idx++]; N; --N)
4746 DiagOpts->Remarks.push_back(ReadString(Record, Idx));
Guy Benyei11169dd2012-12-18 14:30:41 +00004747
4748 return Listener.ReadDiagnosticOptions(DiagOpts, Complain);
4749}
4750
4751bool ASTReader::ParseFileSystemOptions(const RecordData &Record, bool Complain,
4752 ASTReaderListener &Listener) {
4753 FileSystemOptions FSOpts;
4754 unsigned Idx = 0;
4755 FSOpts.WorkingDir = ReadString(Record, Idx);
4756 return Listener.ReadFileSystemOptions(FSOpts, Complain);
4757}
4758
4759bool ASTReader::ParseHeaderSearchOptions(const RecordData &Record,
4760 bool Complain,
4761 ASTReaderListener &Listener) {
4762 HeaderSearchOptions HSOpts;
4763 unsigned Idx = 0;
4764 HSOpts.Sysroot = ReadString(Record, Idx);
4765
4766 // Include entries.
4767 for (unsigned N = Record[Idx++]; N; --N) {
4768 std::string Path = ReadString(Record, Idx);
4769 frontend::IncludeDirGroup Group
4770 = static_cast<frontend::IncludeDirGroup>(Record[Idx++]);
Guy Benyei11169dd2012-12-18 14:30:41 +00004771 bool IsFramework = Record[Idx++];
4772 bool IgnoreSysRoot = Record[Idx++];
Guy Benyei11169dd2012-12-18 14:30:41 +00004773 HSOpts.UserEntries.push_back(
Daniel Dunbar53681732013-01-30 00:34:26 +00004774 HeaderSearchOptions::Entry(Path, Group, IsFramework, IgnoreSysRoot));
Guy Benyei11169dd2012-12-18 14:30:41 +00004775 }
4776
4777 // System header prefixes.
4778 for (unsigned N = Record[Idx++]; N; --N) {
4779 std::string Prefix = ReadString(Record, Idx);
4780 bool IsSystemHeader = Record[Idx++];
4781 HSOpts.SystemHeaderPrefixes.push_back(
4782 HeaderSearchOptions::SystemHeaderPrefix(Prefix, IsSystemHeader));
4783 }
4784
4785 HSOpts.ResourceDir = ReadString(Record, Idx);
4786 HSOpts.ModuleCachePath = ReadString(Record, Idx);
Argyrios Kyrtzidis1594c152014-03-03 08:12:05 +00004787 HSOpts.ModuleUserBuildPath = ReadString(Record, Idx);
Guy Benyei11169dd2012-12-18 14:30:41 +00004788 HSOpts.DisableModuleHash = Record[Idx++];
4789 HSOpts.UseBuiltinIncludes = Record[Idx++];
4790 HSOpts.UseStandardSystemIncludes = Record[Idx++];
4791 HSOpts.UseStandardCXXIncludes = Record[Idx++];
4792 HSOpts.UseLibcxx = Record[Idx++];
4793
4794 return Listener.ReadHeaderSearchOptions(HSOpts, Complain);
4795}
4796
4797bool ASTReader::ParsePreprocessorOptions(const RecordData &Record,
4798 bool Complain,
4799 ASTReaderListener &Listener,
4800 std::string &SuggestedPredefines) {
4801 PreprocessorOptions PPOpts;
4802 unsigned Idx = 0;
4803
4804 // Macro definitions/undefs
4805 for (unsigned N = Record[Idx++]; N; --N) {
4806 std::string Macro = ReadString(Record, Idx);
4807 bool IsUndef = Record[Idx++];
4808 PPOpts.Macros.push_back(std::make_pair(Macro, IsUndef));
4809 }
4810
4811 // Includes
4812 for (unsigned N = Record[Idx++]; N; --N) {
4813 PPOpts.Includes.push_back(ReadString(Record, Idx));
4814 }
4815
4816 // Macro Includes
4817 for (unsigned N = Record[Idx++]; N; --N) {
4818 PPOpts.MacroIncludes.push_back(ReadString(Record, Idx));
4819 }
4820
4821 PPOpts.UsePredefines = Record[Idx++];
Argyrios Kyrtzidisd3afa0c2013-04-26 21:33:40 +00004822 PPOpts.DetailedRecord = Record[Idx++];
Guy Benyei11169dd2012-12-18 14:30:41 +00004823 PPOpts.ImplicitPCHInclude = ReadString(Record, Idx);
4824 PPOpts.ImplicitPTHInclude = ReadString(Record, Idx);
4825 PPOpts.ObjCXXARCStandardLibrary =
4826 static_cast<ObjCXXARCStandardLibraryKind>(Record[Idx++]);
4827 SuggestedPredefines.clear();
4828 return Listener.ReadPreprocessorOptions(PPOpts, Complain,
4829 SuggestedPredefines);
4830}
4831
4832std::pair<ModuleFile *, unsigned>
4833ASTReader::getModulePreprocessedEntity(unsigned GlobalIndex) {
4834 GlobalPreprocessedEntityMapType::iterator
4835 I = GlobalPreprocessedEntityMap.find(GlobalIndex);
4836 assert(I != GlobalPreprocessedEntityMap.end() &&
4837 "Corrupted global preprocessed entity map");
4838 ModuleFile *M = I->second;
4839 unsigned LocalIndex = GlobalIndex - M->BasePreprocessedEntityID;
4840 return std::make_pair(M, LocalIndex);
4841}
4842
4843std::pair<PreprocessingRecord::iterator, PreprocessingRecord::iterator>
4844ASTReader::getModulePreprocessedEntities(ModuleFile &Mod) const {
4845 if (PreprocessingRecord *PPRec = PP.getPreprocessingRecord())
4846 return PPRec->getIteratorsForLoadedRange(Mod.BasePreprocessedEntityID,
4847 Mod.NumPreprocessedEntities);
4848
4849 return std::make_pair(PreprocessingRecord::iterator(),
4850 PreprocessingRecord::iterator());
4851}
4852
4853std::pair<ASTReader::ModuleDeclIterator, ASTReader::ModuleDeclIterator>
4854ASTReader::getModuleFileLevelDecls(ModuleFile &Mod) {
4855 return std::make_pair(ModuleDeclIterator(this, &Mod, Mod.FileSortedDecls),
4856 ModuleDeclIterator(this, &Mod,
4857 Mod.FileSortedDecls + Mod.NumFileSortedDecls));
4858}
4859
4860PreprocessedEntity *ASTReader::ReadPreprocessedEntity(unsigned Index) {
4861 PreprocessedEntityID PPID = Index+1;
4862 std::pair<ModuleFile *, unsigned> PPInfo = getModulePreprocessedEntity(Index);
4863 ModuleFile &M = *PPInfo.first;
4864 unsigned LocalIndex = PPInfo.second;
4865 const PPEntityOffset &PPOffs = M.PreprocessedEntityOffsets[LocalIndex];
4866
Guy Benyei11169dd2012-12-18 14:30:41 +00004867 if (!PP.getPreprocessingRecord()) {
4868 Error("no preprocessing record");
Craig Toppera13603a2014-05-22 05:54:18 +00004869 return nullptr;
Guy Benyei11169dd2012-12-18 14:30:41 +00004870 }
4871
Chris Lattner7fb3bef2013-01-20 00:56:42 +00004872 SavedStreamPosition SavedPosition(M.PreprocessorDetailCursor);
4873 M.PreprocessorDetailCursor.JumpToBit(PPOffs.BitOffset);
4874
4875 llvm::BitstreamEntry Entry =
4876 M.PreprocessorDetailCursor.advance(BitstreamCursor::AF_DontPopBlockAtEnd);
4877 if (Entry.Kind != llvm::BitstreamEntry::Record)
Craig Toppera13603a2014-05-22 05:54:18 +00004878 return nullptr;
Chris Lattner7fb3bef2013-01-20 00:56:42 +00004879
Guy Benyei11169dd2012-12-18 14:30:41 +00004880 // Read the record.
4881 SourceRange Range(ReadSourceLocation(M, PPOffs.Begin),
4882 ReadSourceLocation(M, PPOffs.End));
4883 PreprocessingRecord &PPRec = *PP.getPreprocessingRecord();
Chris Lattner0e6c9402013-01-20 02:38:54 +00004884 StringRef Blob;
Guy Benyei11169dd2012-12-18 14:30:41 +00004885 RecordData Record;
4886 PreprocessorDetailRecordTypes RecType =
Chris Lattner0e6c9402013-01-20 02:38:54 +00004887 (PreprocessorDetailRecordTypes)M.PreprocessorDetailCursor.readRecord(
4888 Entry.ID, Record, &Blob);
Guy Benyei11169dd2012-12-18 14:30:41 +00004889 switch (RecType) {
4890 case PPD_MACRO_EXPANSION: {
4891 bool isBuiltin = Record[0];
Craig Toppera13603a2014-05-22 05:54:18 +00004892 IdentifierInfo *Name = nullptr;
4893 MacroDefinition *Def = nullptr;
Guy Benyei11169dd2012-12-18 14:30:41 +00004894 if (isBuiltin)
4895 Name = getLocalIdentifier(M, Record[1]);
4896 else {
4897 PreprocessedEntityID
4898 GlobalID = getGlobalPreprocessedEntityID(M, Record[1]);
4899 Def =cast<MacroDefinition>(PPRec.getLoadedPreprocessedEntity(GlobalID-1));
4900 }
4901
4902 MacroExpansion *ME;
4903 if (isBuiltin)
4904 ME = new (PPRec) MacroExpansion(Name, Range);
4905 else
4906 ME = new (PPRec) MacroExpansion(Def, Range);
4907
4908 return ME;
4909 }
4910
4911 case PPD_MACRO_DEFINITION: {
4912 // Decode the identifier info and then check again; if the macro is
4913 // still defined and associated with the identifier,
4914 IdentifierInfo *II = getLocalIdentifier(M, Record[0]);
4915 MacroDefinition *MD
4916 = new (PPRec) MacroDefinition(II, Range);
4917
4918 if (DeserializationListener)
4919 DeserializationListener->MacroDefinitionRead(PPID, MD);
4920
4921 return MD;
4922 }
4923
4924 case PPD_INCLUSION_DIRECTIVE: {
Chris Lattner0e6c9402013-01-20 02:38:54 +00004925 const char *FullFileNameStart = Blob.data() + Record[0];
4926 StringRef FullFileName(FullFileNameStart, Blob.size() - Record[0]);
Craig Toppera13603a2014-05-22 05:54:18 +00004927 const FileEntry *File = nullptr;
Guy Benyei11169dd2012-12-18 14:30:41 +00004928 if (!FullFileName.empty())
4929 File = PP.getFileManager().getFile(FullFileName);
4930
4931 // FIXME: Stable encoding
4932 InclusionDirective::InclusionKind Kind
4933 = static_cast<InclusionDirective::InclusionKind>(Record[2]);
4934 InclusionDirective *ID
4935 = new (PPRec) InclusionDirective(PPRec, Kind,
Chris Lattner0e6c9402013-01-20 02:38:54 +00004936 StringRef(Blob.data(), Record[0]),
Guy Benyei11169dd2012-12-18 14:30:41 +00004937 Record[1], Record[3],
4938 File,
4939 Range);
4940 return ID;
4941 }
4942 }
4943
4944 llvm_unreachable("Invalid PreprocessorDetailRecordTypes");
4945}
4946
4947/// \brief \arg SLocMapI points at a chunk of a module that contains no
4948/// preprocessed entities or the entities it contains are not the ones we are
4949/// looking for. Find the next module that contains entities and return the ID
4950/// of the first entry.
4951PreprocessedEntityID ASTReader::findNextPreprocessedEntity(
4952 GlobalSLocOffsetMapType::const_iterator SLocMapI) const {
4953 ++SLocMapI;
4954 for (GlobalSLocOffsetMapType::const_iterator
4955 EndI = GlobalSLocOffsetMap.end(); SLocMapI != EndI; ++SLocMapI) {
4956 ModuleFile &M = *SLocMapI->second;
4957 if (M.NumPreprocessedEntities)
4958 return M.BasePreprocessedEntityID;
4959 }
4960
4961 return getTotalNumPreprocessedEntities();
4962}
4963
4964namespace {
4965
4966template <unsigned PPEntityOffset::*PPLoc>
4967struct PPEntityComp {
4968 const ASTReader &Reader;
4969 ModuleFile &M;
4970
4971 PPEntityComp(const ASTReader &Reader, ModuleFile &M) : Reader(Reader), M(M) { }
4972
4973 bool operator()(const PPEntityOffset &L, const PPEntityOffset &R) const {
4974 SourceLocation LHS = getLoc(L);
4975 SourceLocation RHS = getLoc(R);
4976 return Reader.getSourceManager().isBeforeInTranslationUnit(LHS, RHS);
4977 }
4978
4979 bool operator()(const PPEntityOffset &L, SourceLocation RHS) const {
4980 SourceLocation LHS = getLoc(L);
4981 return Reader.getSourceManager().isBeforeInTranslationUnit(LHS, RHS);
4982 }
4983
4984 bool operator()(SourceLocation LHS, const PPEntityOffset &R) const {
4985 SourceLocation RHS = getLoc(R);
4986 return Reader.getSourceManager().isBeforeInTranslationUnit(LHS, RHS);
4987 }
4988
4989 SourceLocation getLoc(const PPEntityOffset &PPE) const {
4990 return Reader.ReadSourceLocation(M, PPE.*PPLoc);
4991 }
4992};
4993
4994}
4995
Alp Toker2e9ce4c2014-05-16 18:59:21 +00004996PreprocessedEntityID ASTReader::findPreprocessedEntity(SourceLocation Loc,
4997 bool EndsAfter) const {
4998 if (SourceMgr.isLocalSourceLocation(Loc))
Guy Benyei11169dd2012-12-18 14:30:41 +00004999 return getTotalNumPreprocessedEntities();
5000
Alp Toker2e9ce4c2014-05-16 18:59:21 +00005001 GlobalSLocOffsetMapType::const_iterator SLocMapI = GlobalSLocOffsetMap.find(
5002 SourceManager::MaxLoadedOffset - Loc.getOffset() - 1);
Guy Benyei11169dd2012-12-18 14:30:41 +00005003 assert(SLocMapI != GlobalSLocOffsetMap.end() &&
5004 "Corrupted global sloc offset map");
5005
5006 if (SLocMapI->second->NumPreprocessedEntities == 0)
5007 return findNextPreprocessedEntity(SLocMapI);
5008
5009 ModuleFile &M = *SLocMapI->second;
5010 typedef const PPEntityOffset *pp_iterator;
5011 pp_iterator pp_begin = M.PreprocessedEntityOffsets;
5012 pp_iterator pp_end = pp_begin + M.NumPreprocessedEntities;
5013
5014 size_t Count = M.NumPreprocessedEntities;
5015 size_t Half;
5016 pp_iterator First = pp_begin;
5017 pp_iterator PPI;
5018
Alp Toker2e9ce4c2014-05-16 18:59:21 +00005019 if (EndsAfter) {
5020 PPI = std::upper_bound(pp_begin, pp_end, Loc,
5021 PPEntityComp<&PPEntityOffset::Begin>(*this, M));
5022 } else {
5023 // Do a binary search manually instead of using std::lower_bound because
5024 // The end locations of entities may be unordered (when a macro expansion
5025 // is inside another macro argument), but for this case it is not important
5026 // whether we get the first macro expansion or its containing macro.
5027 while (Count > 0) {
5028 Half = Count / 2;
5029 PPI = First;
5030 std::advance(PPI, Half);
5031 if (SourceMgr.isBeforeInTranslationUnit(ReadSourceLocation(M, PPI->End),
5032 Loc)) {
5033 First = PPI;
5034 ++First;
5035 Count = Count - Half - 1;
5036 } else
5037 Count = Half;
5038 }
Guy Benyei11169dd2012-12-18 14:30:41 +00005039 }
5040
5041 if (PPI == pp_end)
5042 return findNextPreprocessedEntity(SLocMapI);
5043
5044 return M.BasePreprocessedEntityID + (PPI - pp_begin);
5045}
5046
Guy Benyei11169dd2012-12-18 14:30:41 +00005047/// \brief Returns a pair of [Begin, End) indices of preallocated
5048/// preprocessed entities that \arg Range encompasses.
5049std::pair<unsigned, unsigned>
5050 ASTReader::findPreprocessedEntitiesInRange(SourceRange Range) {
5051 if (Range.isInvalid())
5052 return std::make_pair(0,0);
5053 assert(!SourceMgr.isBeforeInTranslationUnit(Range.getEnd(),Range.getBegin()));
5054
Alp Toker2e9ce4c2014-05-16 18:59:21 +00005055 PreprocessedEntityID BeginID =
5056 findPreprocessedEntity(Range.getBegin(), false);
5057 PreprocessedEntityID EndID = findPreprocessedEntity(Range.getEnd(), true);
Guy Benyei11169dd2012-12-18 14:30:41 +00005058 return std::make_pair(BeginID, EndID);
5059}
5060
5061/// \brief Optionally returns true or false if the preallocated preprocessed
5062/// entity with index \arg Index came from file \arg FID.
David Blaikie05785d12013-02-20 22:23:23 +00005063Optional<bool> ASTReader::isPreprocessedEntityInFileID(unsigned Index,
Guy Benyei11169dd2012-12-18 14:30:41 +00005064 FileID FID) {
5065 if (FID.isInvalid())
5066 return false;
5067
5068 std::pair<ModuleFile *, unsigned> PPInfo = getModulePreprocessedEntity(Index);
5069 ModuleFile &M = *PPInfo.first;
5070 unsigned LocalIndex = PPInfo.second;
5071 const PPEntityOffset &PPOffs = M.PreprocessedEntityOffsets[LocalIndex];
5072
5073 SourceLocation Loc = ReadSourceLocation(M, PPOffs.Begin);
5074 if (Loc.isInvalid())
5075 return false;
5076
5077 if (SourceMgr.isInFileID(SourceMgr.getFileLoc(Loc), FID))
5078 return true;
5079 else
5080 return false;
5081}
5082
5083namespace {
5084 /// \brief Visitor used to search for information about a header file.
5085 class HeaderFileInfoVisitor {
Guy Benyei11169dd2012-12-18 14:30:41 +00005086 const FileEntry *FE;
5087
David Blaikie05785d12013-02-20 22:23:23 +00005088 Optional<HeaderFileInfo> HFI;
Guy Benyei11169dd2012-12-18 14:30:41 +00005089
5090 public:
Argyrios Kyrtzidis61a38962013-03-06 18:12:44 +00005091 explicit HeaderFileInfoVisitor(const FileEntry *FE)
5092 : FE(FE) { }
Guy Benyei11169dd2012-12-18 14:30:41 +00005093
5094 static bool visit(ModuleFile &M, void *UserData) {
5095 HeaderFileInfoVisitor *This
5096 = static_cast<HeaderFileInfoVisitor *>(UserData);
5097
Guy Benyei11169dd2012-12-18 14:30:41 +00005098 HeaderFileInfoLookupTable *Table
5099 = static_cast<HeaderFileInfoLookupTable *>(M.HeaderFileInfoTable);
5100 if (!Table)
5101 return false;
5102
5103 // Look in the on-disk hash table for an entry for this file name.
Argyrios Kyrtzidis5c2a3452013-03-06 18:12:47 +00005104 HeaderFileInfoLookupTable::iterator Pos = Table->find(This->FE);
Guy Benyei11169dd2012-12-18 14:30:41 +00005105 if (Pos == Table->end())
5106 return false;
5107
5108 This->HFI = *Pos;
5109 return true;
5110 }
5111
David Blaikie05785d12013-02-20 22:23:23 +00005112 Optional<HeaderFileInfo> getHeaderFileInfo() const { return HFI; }
Guy Benyei11169dd2012-12-18 14:30:41 +00005113 };
5114}
5115
5116HeaderFileInfo ASTReader::GetHeaderFileInfo(const FileEntry *FE) {
Argyrios Kyrtzidis61a38962013-03-06 18:12:44 +00005117 HeaderFileInfoVisitor Visitor(FE);
Guy Benyei11169dd2012-12-18 14:30:41 +00005118 ModuleMgr.visit(&HeaderFileInfoVisitor::visit, &Visitor);
Argyrios Kyrtzidis1054bbf2013-05-08 23:46:55 +00005119 if (Optional<HeaderFileInfo> HFI = Visitor.getHeaderFileInfo())
Guy Benyei11169dd2012-12-18 14:30:41 +00005120 return *HFI;
Guy Benyei11169dd2012-12-18 14:30:41 +00005121
5122 return HeaderFileInfo();
5123}
5124
5125void ASTReader::ReadPragmaDiagnosticMappings(DiagnosticsEngine &Diag) {
5126 // FIXME: Make it work properly with modules.
Dmitri Gribenkof8579502013-01-12 19:30:44 +00005127 SmallVector<DiagnosticsEngine::DiagState *, 32> DiagStates;
Guy Benyei11169dd2012-12-18 14:30:41 +00005128 for (ModuleIterator I = ModuleMgr.begin(), E = ModuleMgr.end(); I != E; ++I) {
5129 ModuleFile &F = *(*I);
5130 unsigned Idx = 0;
5131 DiagStates.clear();
5132 assert(!Diag.DiagStates.empty());
5133 DiagStates.push_back(&Diag.DiagStates.front()); // the command-line one.
5134 while (Idx < F.PragmaDiagMappings.size()) {
5135 SourceLocation Loc = ReadSourceLocation(F, F.PragmaDiagMappings[Idx++]);
5136 unsigned DiagStateID = F.PragmaDiagMappings[Idx++];
5137 if (DiagStateID != 0) {
5138 Diag.DiagStatePoints.push_back(
5139 DiagnosticsEngine::DiagStatePoint(DiagStates[DiagStateID-1],
5140 FullSourceLoc(Loc, SourceMgr)));
5141 continue;
5142 }
5143
5144 assert(DiagStateID == 0);
5145 // A new DiagState was created here.
5146 Diag.DiagStates.push_back(*Diag.GetCurDiagState());
5147 DiagnosticsEngine::DiagState *NewState = &Diag.DiagStates.back();
5148 DiagStates.push_back(NewState);
5149 Diag.DiagStatePoints.push_back(
5150 DiagnosticsEngine::DiagStatePoint(NewState,
5151 FullSourceLoc(Loc, SourceMgr)));
5152 while (1) {
5153 assert(Idx < F.PragmaDiagMappings.size() &&
5154 "Invalid data, didn't find '-1' marking end of diag/map pairs");
5155 if (Idx >= F.PragmaDiagMappings.size()) {
5156 break; // Something is messed up but at least avoid infinite loop in
5157 // release build.
5158 }
5159 unsigned DiagID = F.PragmaDiagMappings[Idx++];
5160 if (DiagID == (unsigned)-1) {
5161 break; // no more diag/map pairs for this location.
5162 }
Alp Tokerc726c362014-06-10 09:31:37 +00005163 diag::Severity Map = (diag::Severity)F.PragmaDiagMappings[Idx++];
5164 DiagnosticMapping Mapping = Diag.makeUserMapping(Map, Loc);
5165 Diag.GetCurDiagState()->setMapping(DiagID, Mapping);
Guy Benyei11169dd2012-12-18 14:30:41 +00005166 }
5167 }
5168 }
5169}
5170
5171/// \brief Get the correct cursor and offset for loading a type.
5172ASTReader::RecordLocation ASTReader::TypeCursorForIndex(unsigned Index) {
5173 GlobalTypeMapType::iterator I = GlobalTypeMap.find(Index);
5174 assert(I != GlobalTypeMap.end() && "Corrupted global type map");
5175 ModuleFile *M = I->second;
5176 return RecordLocation(M, M->TypeOffsets[Index - M->BaseTypeIndex]);
5177}
5178
5179/// \brief Read and return the type with the given index..
5180///
5181/// The index is the type ID, shifted and minus the number of predefs. This
5182/// routine actually reads the record corresponding to the type at the given
5183/// location. It is a helper routine for GetType, which deals with reading type
5184/// IDs.
5185QualType ASTReader::readTypeRecord(unsigned Index) {
5186 RecordLocation Loc = TypeCursorForIndex(Index);
Chris Lattner7fb3bef2013-01-20 00:56:42 +00005187 BitstreamCursor &DeclsCursor = Loc.F->DeclsCursor;
Guy Benyei11169dd2012-12-18 14:30:41 +00005188
5189 // Keep track of where we are in the stream, then jump back there
5190 // after reading this type.
5191 SavedStreamPosition SavedPosition(DeclsCursor);
5192
5193 ReadingKindTracker ReadingKind(Read_Type, *this);
5194
5195 // Note that we are loading a type record.
5196 Deserializing AType(this);
5197
5198 unsigned Idx = 0;
5199 DeclsCursor.JumpToBit(Loc.Offset);
5200 RecordData Record;
5201 unsigned Code = DeclsCursor.ReadCode();
Chris Lattner0e6c9402013-01-20 02:38:54 +00005202 switch ((TypeCode)DeclsCursor.readRecord(Code, Record)) {
Guy Benyei11169dd2012-12-18 14:30:41 +00005203 case TYPE_EXT_QUAL: {
5204 if (Record.size() != 2) {
5205 Error("Incorrect encoding of extended qualifier type");
5206 return QualType();
5207 }
5208 QualType Base = readType(*Loc.F, Record, Idx);
5209 Qualifiers Quals = Qualifiers::fromOpaqueValue(Record[Idx++]);
5210 return Context.getQualifiedType(Base, Quals);
5211 }
5212
5213 case TYPE_COMPLEX: {
5214 if (Record.size() != 1) {
5215 Error("Incorrect encoding of complex type");
5216 return QualType();
5217 }
5218 QualType ElemType = readType(*Loc.F, Record, Idx);
5219 return Context.getComplexType(ElemType);
5220 }
5221
5222 case TYPE_POINTER: {
5223 if (Record.size() != 1) {
5224 Error("Incorrect encoding of pointer type");
5225 return QualType();
5226 }
5227 QualType PointeeType = readType(*Loc.F, Record, Idx);
5228 return Context.getPointerType(PointeeType);
5229 }
5230
Reid Kleckner8a365022013-06-24 17:51:48 +00005231 case TYPE_DECAYED: {
5232 if (Record.size() != 1) {
5233 Error("Incorrect encoding of decayed type");
5234 return QualType();
5235 }
5236 QualType OriginalType = readType(*Loc.F, Record, Idx);
5237 QualType DT = Context.getAdjustedParameterType(OriginalType);
5238 if (!isa<DecayedType>(DT))
5239 Error("Decayed type does not decay");
5240 return DT;
5241 }
5242
Reid Kleckner0503a872013-12-05 01:23:43 +00005243 case TYPE_ADJUSTED: {
5244 if (Record.size() != 2) {
5245 Error("Incorrect encoding of adjusted type");
5246 return QualType();
5247 }
5248 QualType OriginalTy = readType(*Loc.F, Record, Idx);
5249 QualType AdjustedTy = readType(*Loc.F, Record, Idx);
5250 return Context.getAdjustedType(OriginalTy, AdjustedTy);
5251 }
5252
Guy Benyei11169dd2012-12-18 14:30:41 +00005253 case TYPE_BLOCK_POINTER: {
5254 if (Record.size() != 1) {
5255 Error("Incorrect encoding of block pointer type");
5256 return QualType();
5257 }
5258 QualType PointeeType = readType(*Loc.F, Record, Idx);
5259 return Context.getBlockPointerType(PointeeType);
5260 }
5261
5262 case TYPE_LVALUE_REFERENCE: {
5263 if (Record.size() != 2) {
5264 Error("Incorrect encoding of lvalue reference type");
5265 return QualType();
5266 }
5267 QualType PointeeType = readType(*Loc.F, Record, Idx);
5268 return Context.getLValueReferenceType(PointeeType, Record[1]);
5269 }
5270
5271 case TYPE_RVALUE_REFERENCE: {
5272 if (Record.size() != 1) {
5273 Error("Incorrect encoding of rvalue reference type");
5274 return QualType();
5275 }
5276 QualType PointeeType = readType(*Loc.F, Record, Idx);
5277 return Context.getRValueReferenceType(PointeeType);
5278 }
5279
5280 case TYPE_MEMBER_POINTER: {
5281 if (Record.size() != 2) {
5282 Error("Incorrect encoding of member pointer type");
5283 return QualType();
5284 }
5285 QualType PointeeType = readType(*Loc.F, Record, Idx);
5286 QualType ClassType = readType(*Loc.F, Record, Idx);
5287 if (PointeeType.isNull() || ClassType.isNull())
5288 return QualType();
5289
5290 return Context.getMemberPointerType(PointeeType, ClassType.getTypePtr());
5291 }
5292
5293 case TYPE_CONSTANT_ARRAY: {
5294 QualType ElementType = readType(*Loc.F, Record, Idx);
5295 ArrayType::ArraySizeModifier ASM = (ArrayType::ArraySizeModifier)Record[1];
5296 unsigned IndexTypeQuals = Record[2];
5297 unsigned Idx = 3;
5298 llvm::APInt Size = ReadAPInt(Record, Idx);
5299 return Context.getConstantArrayType(ElementType, Size,
5300 ASM, IndexTypeQuals);
5301 }
5302
5303 case TYPE_INCOMPLETE_ARRAY: {
5304 QualType ElementType = readType(*Loc.F, Record, Idx);
5305 ArrayType::ArraySizeModifier ASM = (ArrayType::ArraySizeModifier)Record[1];
5306 unsigned IndexTypeQuals = Record[2];
5307 return Context.getIncompleteArrayType(ElementType, ASM, IndexTypeQuals);
5308 }
5309
5310 case TYPE_VARIABLE_ARRAY: {
5311 QualType ElementType = readType(*Loc.F, Record, Idx);
5312 ArrayType::ArraySizeModifier ASM = (ArrayType::ArraySizeModifier)Record[1];
5313 unsigned IndexTypeQuals = Record[2];
5314 SourceLocation LBLoc = ReadSourceLocation(*Loc.F, Record[3]);
5315 SourceLocation RBLoc = ReadSourceLocation(*Loc.F, Record[4]);
5316 return Context.getVariableArrayType(ElementType, ReadExpr(*Loc.F),
5317 ASM, IndexTypeQuals,
5318 SourceRange(LBLoc, RBLoc));
5319 }
5320
5321 case TYPE_VECTOR: {
5322 if (Record.size() != 3) {
5323 Error("incorrect encoding of vector type in AST file");
5324 return QualType();
5325 }
5326
5327 QualType ElementType = readType(*Loc.F, Record, Idx);
5328 unsigned NumElements = Record[1];
5329 unsigned VecKind = Record[2];
5330 return Context.getVectorType(ElementType, NumElements,
5331 (VectorType::VectorKind)VecKind);
5332 }
5333
5334 case TYPE_EXT_VECTOR: {
5335 if (Record.size() != 3) {
5336 Error("incorrect encoding of extended vector type in AST file");
5337 return QualType();
5338 }
5339
5340 QualType ElementType = readType(*Loc.F, Record, Idx);
5341 unsigned NumElements = Record[1];
5342 return Context.getExtVectorType(ElementType, NumElements);
5343 }
5344
5345 case TYPE_FUNCTION_NO_PROTO: {
5346 if (Record.size() != 6) {
5347 Error("incorrect encoding of no-proto function type");
5348 return QualType();
5349 }
5350 QualType ResultType = readType(*Loc.F, Record, Idx);
5351 FunctionType::ExtInfo Info(Record[1], Record[2], Record[3],
5352 (CallingConv)Record[4], Record[5]);
5353 return Context.getFunctionNoProtoType(ResultType, Info);
5354 }
5355
5356 case TYPE_FUNCTION_PROTO: {
5357 QualType ResultType = readType(*Loc.F, Record, Idx);
5358
5359 FunctionProtoType::ExtProtoInfo EPI;
5360 EPI.ExtInfo = FunctionType::ExtInfo(/*noreturn*/ Record[1],
5361 /*hasregparm*/ Record[2],
5362 /*regparm*/ Record[3],
5363 static_cast<CallingConv>(Record[4]),
5364 /*produces*/ Record[5]);
5365
5366 unsigned Idx = 6;
Guy Benyei11169dd2012-12-18 14:30:41 +00005367
5368 EPI.Variadic = Record[Idx++];
5369 EPI.HasTrailingReturn = Record[Idx++];
5370 EPI.TypeQuals = Record[Idx++];
5371 EPI.RefQualifier = static_cast<RefQualifierKind>(Record[Idx++]);
Richard Smith564417a2014-03-20 21:47:22 +00005372 SmallVector<QualType, 8> ExceptionStorage;
Richard Smith8acb4282014-07-31 21:57:55 +00005373 readExceptionSpec(*Loc.F, ExceptionStorage, EPI.ExceptionSpec, Record, Idx);
Richard Smith01b2cb42014-07-26 06:37:51 +00005374
5375 unsigned NumParams = Record[Idx++];
5376 SmallVector<QualType, 16> ParamTypes;
5377 for (unsigned I = 0; I != NumParams; ++I)
5378 ParamTypes.push_back(readType(*Loc.F, Record, Idx));
5379
Jordan Rose5c382722013-03-08 21:51:21 +00005380 return Context.getFunctionType(ResultType, ParamTypes, EPI);
Guy Benyei11169dd2012-12-18 14:30:41 +00005381 }
5382
5383 case TYPE_UNRESOLVED_USING: {
5384 unsigned Idx = 0;
5385 return Context.getTypeDeclType(
5386 ReadDeclAs<UnresolvedUsingTypenameDecl>(*Loc.F, Record, Idx));
5387 }
5388
5389 case TYPE_TYPEDEF: {
5390 if (Record.size() != 2) {
5391 Error("incorrect encoding of typedef type");
5392 return QualType();
5393 }
5394 unsigned Idx = 0;
5395 TypedefNameDecl *Decl = ReadDeclAs<TypedefNameDecl>(*Loc.F, Record, Idx);
5396 QualType Canonical = readType(*Loc.F, Record, Idx);
5397 if (!Canonical.isNull())
5398 Canonical = Context.getCanonicalType(Canonical);
5399 return Context.getTypedefType(Decl, Canonical);
5400 }
5401
5402 case TYPE_TYPEOF_EXPR:
5403 return Context.getTypeOfExprType(ReadExpr(*Loc.F));
5404
5405 case TYPE_TYPEOF: {
5406 if (Record.size() != 1) {
5407 Error("incorrect encoding of typeof(type) in AST file");
5408 return QualType();
5409 }
5410 QualType UnderlyingType = readType(*Loc.F, Record, Idx);
5411 return Context.getTypeOfType(UnderlyingType);
5412 }
5413
5414 case TYPE_DECLTYPE: {
5415 QualType UnderlyingType = readType(*Loc.F, Record, Idx);
5416 return Context.getDecltypeType(ReadExpr(*Loc.F), UnderlyingType);
5417 }
5418
5419 case TYPE_UNARY_TRANSFORM: {
5420 QualType BaseType = readType(*Loc.F, Record, Idx);
5421 QualType UnderlyingType = readType(*Loc.F, Record, Idx);
5422 UnaryTransformType::UTTKind UKind = (UnaryTransformType::UTTKind)Record[2];
5423 return Context.getUnaryTransformType(BaseType, UnderlyingType, UKind);
5424 }
5425
Richard Smith74aeef52013-04-26 16:15:35 +00005426 case TYPE_AUTO: {
5427 QualType Deduced = readType(*Loc.F, Record, Idx);
5428 bool IsDecltypeAuto = Record[Idx++];
Richard Smith27d807c2013-04-30 13:56:41 +00005429 bool IsDependent = Deduced.isNull() ? Record[Idx++] : false;
Manuel Klimek2fdbea22013-08-22 12:12:24 +00005430 return Context.getAutoType(Deduced, IsDecltypeAuto, IsDependent);
Richard Smith74aeef52013-04-26 16:15:35 +00005431 }
Guy Benyei11169dd2012-12-18 14:30:41 +00005432
5433 case TYPE_RECORD: {
5434 if (Record.size() != 2) {
5435 Error("incorrect encoding of record type");
5436 return QualType();
5437 }
5438 unsigned Idx = 0;
5439 bool IsDependent = Record[Idx++];
5440 RecordDecl *RD = ReadDeclAs<RecordDecl>(*Loc.F, Record, Idx);
5441 RD = cast_or_null<RecordDecl>(RD->getCanonicalDecl());
5442 QualType T = Context.getRecordType(RD);
5443 const_cast<Type*>(T.getTypePtr())->setDependent(IsDependent);
5444 return T;
5445 }
5446
5447 case TYPE_ENUM: {
5448 if (Record.size() != 2) {
5449 Error("incorrect encoding of enum type");
5450 return QualType();
5451 }
5452 unsigned Idx = 0;
5453 bool IsDependent = Record[Idx++];
5454 QualType T
5455 = Context.getEnumType(ReadDeclAs<EnumDecl>(*Loc.F, Record, Idx));
5456 const_cast<Type*>(T.getTypePtr())->setDependent(IsDependent);
5457 return T;
5458 }
5459
5460 case TYPE_ATTRIBUTED: {
5461 if (Record.size() != 3) {
5462 Error("incorrect encoding of attributed type");
5463 return QualType();
5464 }
5465 QualType modifiedType = readType(*Loc.F, Record, Idx);
5466 QualType equivalentType = readType(*Loc.F, Record, Idx);
5467 AttributedType::Kind kind = static_cast<AttributedType::Kind>(Record[2]);
5468 return Context.getAttributedType(kind, modifiedType, equivalentType);
5469 }
5470
5471 case TYPE_PAREN: {
5472 if (Record.size() != 1) {
5473 Error("incorrect encoding of paren type");
5474 return QualType();
5475 }
5476 QualType InnerType = readType(*Loc.F, Record, Idx);
5477 return Context.getParenType(InnerType);
5478 }
5479
5480 case TYPE_PACK_EXPANSION: {
5481 if (Record.size() != 2) {
5482 Error("incorrect encoding of pack expansion type");
5483 return QualType();
5484 }
5485 QualType Pattern = readType(*Loc.F, Record, Idx);
5486 if (Pattern.isNull())
5487 return QualType();
David Blaikie05785d12013-02-20 22:23:23 +00005488 Optional<unsigned> NumExpansions;
Guy Benyei11169dd2012-12-18 14:30:41 +00005489 if (Record[1])
5490 NumExpansions = Record[1] - 1;
5491 return Context.getPackExpansionType(Pattern, NumExpansions);
5492 }
5493
5494 case TYPE_ELABORATED: {
5495 unsigned Idx = 0;
5496 ElaboratedTypeKeyword Keyword = (ElaboratedTypeKeyword)Record[Idx++];
5497 NestedNameSpecifier *NNS = ReadNestedNameSpecifier(*Loc.F, Record, Idx);
5498 QualType NamedType = readType(*Loc.F, Record, Idx);
5499 return Context.getElaboratedType(Keyword, NNS, NamedType);
5500 }
5501
5502 case TYPE_OBJC_INTERFACE: {
5503 unsigned Idx = 0;
5504 ObjCInterfaceDecl *ItfD
5505 = ReadDeclAs<ObjCInterfaceDecl>(*Loc.F, Record, Idx);
5506 return Context.getObjCInterfaceType(ItfD->getCanonicalDecl());
5507 }
5508
5509 case TYPE_OBJC_OBJECT: {
5510 unsigned Idx = 0;
5511 QualType Base = readType(*Loc.F, Record, Idx);
5512 unsigned NumProtos = Record[Idx++];
5513 SmallVector<ObjCProtocolDecl*, 4> Protos;
5514 for (unsigned I = 0; I != NumProtos; ++I)
5515 Protos.push_back(ReadDeclAs<ObjCProtocolDecl>(*Loc.F, Record, Idx));
5516 return Context.getObjCObjectType(Base, Protos.data(), NumProtos);
5517 }
5518
5519 case TYPE_OBJC_OBJECT_POINTER: {
5520 unsigned Idx = 0;
5521 QualType Pointee = readType(*Loc.F, Record, Idx);
5522 return Context.getObjCObjectPointerType(Pointee);
5523 }
5524
5525 case TYPE_SUBST_TEMPLATE_TYPE_PARM: {
5526 unsigned Idx = 0;
5527 QualType Parm = readType(*Loc.F, Record, Idx);
5528 QualType Replacement = readType(*Loc.F, Record, Idx);
Stephan Tolksdorfe96f8b32014-03-15 10:23:27 +00005529 return Context.getSubstTemplateTypeParmType(
5530 cast<TemplateTypeParmType>(Parm),
5531 Context.getCanonicalType(Replacement));
Guy Benyei11169dd2012-12-18 14:30:41 +00005532 }
5533
5534 case TYPE_SUBST_TEMPLATE_TYPE_PARM_PACK: {
5535 unsigned Idx = 0;
5536 QualType Parm = readType(*Loc.F, Record, Idx);
5537 TemplateArgument ArgPack = ReadTemplateArgument(*Loc.F, Record, Idx);
5538 return Context.getSubstTemplateTypeParmPackType(
5539 cast<TemplateTypeParmType>(Parm),
5540 ArgPack);
5541 }
5542
5543 case TYPE_INJECTED_CLASS_NAME: {
5544 CXXRecordDecl *D = ReadDeclAs<CXXRecordDecl>(*Loc.F, Record, Idx);
5545 QualType TST = readType(*Loc.F, Record, Idx); // probably derivable
5546 // FIXME: ASTContext::getInjectedClassNameType is not currently suitable
5547 // for AST reading, too much interdependencies.
Richard Smith6377f8f2014-10-21 21:15:18 +00005548 const Type *T = nullptr;
5549 for (auto *DI = D; DI; DI = DI->getPreviousDecl()) {
5550 if (const Type *Existing = DI->getTypeForDecl()) {
5551 T = Existing;
5552 break;
5553 }
5554 }
5555 if (!T) {
Richard Smithf17fdbd2014-04-24 02:25:27 +00005556 T = new (Context, TypeAlignment) InjectedClassNameType(D, TST);
Richard Smith6377f8f2014-10-21 21:15:18 +00005557 for (auto *DI = D; DI; DI = DI->getPreviousDecl())
5558 DI->setTypeForDecl(T);
5559 }
Richard Smithf17fdbd2014-04-24 02:25:27 +00005560 return QualType(T, 0);
Guy Benyei11169dd2012-12-18 14:30:41 +00005561 }
5562
5563 case TYPE_TEMPLATE_TYPE_PARM: {
5564 unsigned Idx = 0;
5565 unsigned Depth = Record[Idx++];
5566 unsigned Index = Record[Idx++];
5567 bool Pack = Record[Idx++];
5568 TemplateTypeParmDecl *D
5569 = ReadDeclAs<TemplateTypeParmDecl>(*Loc.F, Record, Idx);
5570 return Context.getTemplateTypeParmType(Depth, Index, Pack, D);
5571 }
5572
5573 case TYPE_DEPENDENT_NAME: {
5574 unsigned Idx = 0;
5575 ElaboratedTypeKeyword Keyword = (ElaboratedTypeKeyword)Record[Idx++];
5576 NestedNameSpecifier *NNS = ReadNestedNameSpecifier(*Loc.F, Record, Idx);
5577 const IdentifierInfo *Name = this->GetIdentifierInfo(*Loc.F, Record, Idx);
5578 QualType Canon = readType(*Loc.F, Record, Idx);
5579 if (!Canon.isNull())
5580 Canon = Context.getCanonicalType(Canon);
5581 return Context.getDependentNameType(Keyword, NNS, Name, Canon);
5582 }
5583
5584 case TYPE_DEPENDENT_TEMPLATE_SPECIALIZATION: {
5585 unsigned Idx = 0;
5586 ElaboratedTypeKeyword Keyword = (ElaboratedTypeKeyword)Record[Idx++];
5587 NestedNameSpecifier *NNS = ReadNestedNameSpecifier(*Loc.F, Record, Idx);
5588 const IdentifierInfo *Name = this->GetIdentifierInfo(*Loc.F, Record, Idx);
5589 unsigned NumArgs = Record[Idx++];
5590 SmallVector<TemplateArgument, 8> Args;
5591 Args.reserve(NumArgs);
5592 while (NumArgs--)
5593 Args.push_back(ReadTemplateArgument(*Loc.F, Record, Idx));
5594 return Context.getDependentTemplateSpecializationType(Keyword, NNS, Name,
5595 Args.size(), Args.data());
5596 }
5597
5598 case TYPE_DEPENDENT_SIZED_ARRAY: {
5599 unsigned Idx = 0;
5600
5601 // ArrayType
5602 QualType ElementType = readType(*Loc.F, Record, Idx);
5603 ArrayType::ArraySizeModifier ASM
5604 = (ArrayType::ArraySizeModifier)Record[Idx++];
5605 unsigned IndexTypeQuals = Record[Idx++];
5606
5607 // DependentSizedArrayType
5608 Expr *NumElts = ReadExpr(*Loc.F);
5609 SourceRange Brackets = ReadSourceRange(*Loc.F, Record, Idx);
5610
5611 return Context.getDependentSizedArrayType(ElementType, NumElts, ASM,
5612 IndexTypeQuals, Brackets);
5613 }
5614
5615 case TYPE_TEMPLATE_SPECIALIZATION: {
5616 unsigned Idx = 0;
5617 bool IsDependent = Record[Idx++];
5618 TemplateName Name = ReadTemplateName(*Loc.F, Record, Idx);
5619 SmallVector<TemplateArgument, 8> Args;
5620 ReadTemplateArgumentList(Args, *Loc.F, Record, Idx);
5621 QualType Underlying = readType(*Loc.F, Record, Idx);
5622 QualType T;
5623 if (Underlying.isNull())
5624 T = Context.getCanonicalTemplateSpecializationType(Name, Args.data(),
5625 Args.size());
5626 else
5627 T = Context.getTemplateSpecializationType(Name, Args.data(),
5628 Args.size(), Underlying);
5629 const_cast<Type*>(T.getTypePtr())->setDependent(IsDependent);
5630 return T;
5631 }
5632
5633 case TYPE_ATOMIC: {
5634 if (Record.size() != 1) {
5635 Error("Incorrect encoding of atomic type");
5636 return QualType();
5637 }
5638 QualType ValueType = readType(*Loc.F, Record, Idx);
5639 return Context.getAtomicType(ValueType);
5640 }
5641 }
5642 llvm_unreachable("Invalid TypeCode!");
5643}
5644
Richard Smith564417a2014-03-20 21:47:22 +00005645void ASTReader::readExceptionSpec(ModuleFile &ModuleFile,
5646 SmallVectorImpl<QualType> &Exceptions,
Richard Smith8acb4282014-07-31 21:57:55 +00005647 FunctionProtoType::ExceptionSpecInfo &ESI,
Richard Smith564417a2014-03-20 21:47:22 +00005648 const RecordData &Record, unsigned &Idx) {
5649 ExceptionSpecificationType EST =
5650 static_cast<ExceptionSpecificationType>(Record[Idx++]);
Richard Smith8acb4282014-07-31 21:57:55 +00005651 ESI.Type = EST;
Richard Smith564417a2014-03-20 21:47:22 +00005652 if (EST == EST_Dynamic) {
Richard Smith8acb4282014-07-31 21:57:55 +00005653 for (unsigned I = 0, N = Record[Idx++]; I != N; ++I)
Richard Smith564417a2014-03-20 21:47:22 +00005654 Exceptions.push_back(readType(ModuleFile, Record, Idx));
Richard Smith8acb4282014-07-31 21:57:55 +00005655 ESI.Exceptions = Exceptions;
Richard Smith564417a2014-03-20 21:47:22 +00005656 } else if (EST == EST_ComputedNoexcept) {
Richard Smith8acb4282014-07-31 21:57:55 +00005657 ESI.NoexceptExpr = ReadExpr(ModuleFile);
Richard Smith564417a2014-03-20 21:47:22 +00005658 } else if (EST == EST_Uninstantiated) {
Richard Smith8acb4282014-07-31 21:57:55 +00005659 ESI.SourceDecl = ReadDeclAs<FunctionDecl>(ModuleFile, Record, Idx);
5660 ESI.SourceTemplate = ReadDeclAs<FunctionDecl>(ModuleFile, Record, Idx);
Richard Smith564417a2014-03-20 21:47:22 +00005661 } else if (EST == EST_Unevaluated) {
Richard Smith8acb4282014-07-31 21:57:55 +00005662 ESI.SourceDecl = ReadDeclAs<FunctionDecl>(ModuleFile, Record, Idx);
Richard Smith564417a2014-03-20 21:47:22 +00005663 }
5664}
5665
Guy Benyei11169dd2012-12-18 14:30:41 +00005666class clang::TypeLocReader : public TypeLocVisitor<TypeLocReader> {
5667 ASTReader &Reader;
5668 ModuleFile &F;
5669 const ASTReader::RecordData &Record;
5670 unsigned &Idx;
5671
5672 SourceLocation ReadSourceLocation(const ASTReader::RecordData &R,
5673 unsigned &I) {
5674 return Reader.ReadSourceLocation(F, R, I);
5675 }
5676
5677 template<typename T>
5678 T *ReadDeclAs(const ASTReader::RecordData &Record, unsigned &Idx) {
5679 return Reader.ReadDeclAs<T>(F, Record, Idx);
5680 }
5681
5682public:
5683 TypeLocReader(ASTReader &Reader, ModuleFile &F,
5684 const ASTReader::RecordData &Record, unsigned &Idx)
5685 : Reader(Reader), F(F), Record(Record), Idx(Idx)
5686 { }
5687
5688 // We want compile-time assurance that we've enumerated all of
5689 // these, so unfortunately we have to declare them first, then
5690 // define them out-of-line.
5691#define ABSTRACT_TYPELOC(CLASS, PARENT)
5692#define TYPELOC(CLASS, PARENT) \
5693 void Visit##CLASS##TypeLoc(CLASS##TypeLoc TyLoc);
5694#include "clang/AST/TypeLocNodes.def"
5695
5696 void VisitFunctionTypeLoc(FunctionTypeLoc);
5697 void VisitArrayTypeLoc(ArrayTypeLoc);
5698};
5699
5700void TypeLocReader::VisitQualifiedTypeLoc(QualifiedTypeLoc TL) {
5701 // nothing to do
5702}
5703void TypeLocReader::VisitBuiltinTypeLoc(BuiltinTypeLoc TL) {
5704 TL.setBuiltinLoc(ReadSourceLocation(Record, Idx));
5705 if (TL.needsExtraLocalData()) {
5706 TL.setWrittenTypeSpec(static_cast<DeclSpec::TST>(Record[Idx++]));
5707 TL.setWrittenSignSpec(static_cast<DeclSpec::TSS>(Record[Idx++]));
5708 TL.setWrittenWidthSpec(static_cast<DeclSpec::TSW>(Record[Idx++]));
5709 TL.setModeAttr(Record[Idx++]);
5710 }
5711}
5712void TypeLocReader::VisitComplexTypeLoc(ComplexTypeLoc TL) {
5713 TL.setNameLoc(ReadSourceLocation(Record, Idx));
5714}
5715void TypeLocReader::VisitPointerTypeLoc(PointerTypeLoc TL) {
5716 TL.setStarLoc(ReadSourceLocation(Record, Idx));
5717}
Reid Kleckner8a365022013-06-24 17:51:48 +00005718void TypeLocReader::VisitDecayedTypeLoc(DecayedTypeLoc TL) {
5719 // nothing to do
5720}
Reid Kleckner0503a872013-12-05 01:23:43 +00005721void TypeLocReader::VisitAdjustedTypeLoc(AdjustedTypeLoc TL) {
5722 // nothing to do
5723}
Guy Benyei11169dd2012-12-18 14:30:41 +00005724void TypeLocReader::VisitBlockPointerTypeLoc(BlockPointerTypeLoc TL) {
5725 TL.setCaretLoc(ReadSourceLocation(Record, Idx));
5726}
5727void TypeLocReader::VisitLValueReferenceTypeLoc(LValueReferenceTypeLoc TL) {
5728 TL.setAmpLoc(ReadSourceLocation(Record, Idx));
5729}
5730void TypeLocReader::VisitRValueReferenceTypeLoc(RValueReferenceTypeLoc TL) {
5731 TL.setAmpAmpLoc(ReadSourceLocation(Record, Idx));
5732}
5733void TypeLocReader::VisitMemberPointerTypeLoc(MemberPointerTypeLoc TL) {
5734 TL.setStarLoc(ReadSourceLocation(Record, Idx));
5735 TL.setClassTInfo(Reader.GetTypeSourceInfo(F, Record, Idx));
5736}
5737void TypeLocReader::VisitArrayTypeLoc(ArrayTypeLoc TL) {
5738 TL.setLBracketLoc(ReadSourceLocation(Record, Idx));
5739 TL.setRBracketLoc(ReadSourceLocation(Record, Idx));
5740 if (Record[Idx++])
5741 TL.setSizeExpr(Reader.ReadExpr(F));
5742 else
Craig Toppera13603a2014-05-22 05:54:18 +00005743 TL.setSizeExpr(nullptr);
Guy Benyei11169dd2012-12-18 14:30:41 +00005744}
5745void TypeLocReader::VisitConstantArrayTypeLoc(ConstantArrayTypeLoc TL) {
5746 VisitArrayTypeLoc(TL);
5747}
5748void TypeLocReader::VisitIncompleteArrayTypeLoc(IncompleteArrayTypeLoc TL) {
5749 VisitArrayTypeLoc(TL);
5750}
5751void TypeLocReader::VisitVariableArrayTypeLoc(VariableArrayTypeLoc TL) {
5752 VisitArrayTypeLoc(TL);
5753}
5754void TypeLocReader::VisitDependentSizedArrayTypeLoc(
5755 DependentSizedArrayTypeLoc TL) {
5756 VisitArrayTypeLoc(TL);
5757}
5758void TypeLocReader::VisitDependentSizedExtVectorTypeLoc(
5759 DependentSizedExtVectorTypeLoc TL) {
5760 TL.setNameLoc(ReadSourceLocation(Record, Idx));
5761}
5762void TypeLocReader::VisitVectorTypeLoc(VectorTypeLoc TL) {
5763 TL.setNameLoc(ReadSourceLocation(Record, Idx));
5764}
5765void TypeLocReader::VisitExtVectorTypeLoc(ExtVectorTypeLoc TL) {
5766 TL.setNameLoc(ReadSourceLocation(Record, Idx));
5767}
5768void TypeLocReader::VisitFunctionTypeLoc(FunctionTypeLoc TL) {
5769 TL.setLocalRangeBegin(ReadSourceLocation(Record, Idx));
5770 TL.setLParenLoc(ReadSourceLocation(Record, Idx));
5771 TL.setRParenLoc(ReadSourceLocation(Record, Idx));
5772 TL.setLocalRangeEnd(ReadSourceLocation(Record, Idx));
Alp Tokerb3fd5cf2014-01-21 00:32:38 +00005773 for (unsigned i = 0, e = TL.getNumParams(); i != e; ++i) {
5774 TL.setParam(i, ReadDeclAs<ParmVarDecl>(Record, Idx));
Guy Benyei11169dd2012-12-18 14:30:41 +00005775 }
5776}
5777void TypeLocReader::VisitFunctionProtoTypeLoc(FunctionProtoTypeLoc TL) {
5778 VisitFunctionTypeLoc(TL);
5779}
5780void TypeLocReader::VisitFunctionNoProtoTypeLoc(FunctionNoProtoTypeLoc TL) {
5781 VisitFunctionTypeLoc(TL);
5782}
5783void TypeLocReader::VisitUnresolvedUsingTypeLoc(UnresolvedUsingTypeLoc TL) {
5784 TL.setNameLoc(ReadSourceLocation(Record, Idx));
5785}
5786void TypeLocReader::VisitTypedefTypeLoc(TypedefTypeLoc TL) {
5787 TL.setNameLoc(ReadSourceLocation(Record, Idx));
5788}
5789void TypeLocReader::VisitTypeOfExprTypeLoc(TypeOfExprTypeLoc TL) {
5790 TL.setTypeofLoc(ReadSourceLocation(Record, Idx));
5791 TL.setLParenLoc(ReadSourceLocation(Record, Idx));
5792 TL.setRParenLoc(ReadSourceLocation(Record, Idx));
5793}
5794void TypeLocReader::VisitTypeOfTypeLoc(TypeOfTypeLoc TL) {
5795 TL.setTypeofLoc(ReadSourceLocation(Record, Idx));
5796 TL.setLParenLoc(ReadSourceLocation(Record, Idx));
5797 TL.setRParenLoc(ReadSourceLocation(Record, Idx));
5798 TL.setUnderlyingTInfo(Reader.GetTypeSourceInfo(F, Record, Idx));
5799}
5800void TypeLocReader::VisitDecltypeTypeLoc(DecltypeTypeLoc TL) {
5801 TL.setNameLoc(ReadSourceLocation(Record, Idx));
5802}
5803void TypeLocReader::VisitUnaryTransformTypeLoc(UnaryTransformTypeLoc TL) {
5804 TL.setKWLoc(ReadSourceLocation(Record, Idx));
5805 TL.setLParenLoc(ReadSourceLocation(Record, Idx));
5806 TL.setRParenLoc(ReadSourceLocation(Record, Idx));
5807 TL.setUnderlyingTInfo(Reader.GetTypeSourceInfo(F, Record, Idx));
5808}
5809void TypeLocReader::VisitAutoTypeLoc(AutoTypeLoc TL) {
5810 TL.setNameLoc(ReadSourceLocation(Record, Idx));
5811}
5812void TypeLocReader::VisitRecordTypeLoc(RecordTypeLoc TL) {
5813 TL.setNameLoc(ReadSourceLocation(Record, Idx));
5814}
5815void TypeLocReader::VisitEnumTypeLoc(EnumTypeLoc TL) {
5816 TL.setNameLoc(ReadSourceLocation(Record, Idx));
5817}
5818void TypeLocReader::VisitAttributedTypeLoc(AttributedTypeLoc TL) {
5819 TL.setAttrNameLoc(ReadSourceLocation(Record, Idx));
5820 if (TL.hasAttrOperand()) {
5821 SourceRange range;
5822 range.setBegin(ReadSourceLocation(Record, Idx));
5823 range.setEnd(ReadSourceLocation(Record, Idx));
5824 TL.setAttrOperandParensRange(range);
5825 }
5826 if (TL.hasAttrExprOperand()) {
5827 if (Record[Idx++])
5828 TL.setAttrExprOperand(Reader.ReadExpr(F));
5829 else
Craig Toppera13603a2014-05-22 05:54:18 +00005830 TL.setAttrExprOperand(nullptr);
Guy Benyei11169dd2012-12-18 14:30:41 +00005831 } else if (TL.hasAttrEnumOperand())
5832 TL.setAttrEnumOperandLoc(ReadSourceLocation(Record, Idx));
5833}
5834void TypeLocReader::VisitTemplateTypeParmTypeLoc(TemplateTypeParmTypeLoc TL) {
5835 TL.setNameLoc(ReadSourceLocation(Record, Idx));
5836}
5837void TypeLocReader::VisitSubstTemplateTypeParmTypeLoc(
5838 SubstTemplateTypeParmTypeLoc TL) {
5839 TL.setNameLoc(ReadSourceLocation(Record, Idx));
5840}
5841void TypeLocReader::VisitSubstTemplateTypeParmPackTypeLoc(
5842 SubstTemplateTypeParmPackTypeLoc TL) {
5843 TL.setNameLoc(ReadSourceLocation(Record, Idx));
5844}
5845void TypeLocReader::VisitTemplateSpecializationTypeLoc(
5846 TemplateSpecializationTypeLoc TL) {
5847 TL.setTemplateKeywordLoc(ReadSourceLocation(Record, Idx));
5848 TL.setTemplateNameLoc(ReadSourceLocation(Record, Idx));
5849 TL.setLAngleLoc(ReadSourceLocation(Record, Idx));
5850 TL.setRAngleLoc(ReadSourceLocation(Record, Idx));
5851 for (unsigned i = 0, e = TL.getNumArgs(); i != e; ++i)
5852 TL.setArgLocInfo(i,
5853 Reader.GetTemplateArgumentLocInfo(F,
5854 TL.getTypePtr()->getArg(i).getKind(),
5855 Record, Idx));
5856}
5857void TypeLocReader::VisitParenTypeLoc(ParenTypeLoc TL) {
5858 TL.setLParenLoc(ReadSourceLocation(Record, Idx));
5859 TL.setRParenLoc(ReadSourceLocation(Record, Idx));
5860}
5861void TypeLocReader::VisitElaboratedTypeLoc(ElaboratedTypeLoc TL) {
5862 TL.setElaboratedKeywordLoc(ReadSourceLocation(Record, Idx));
5863 TL.setQualifierLoc(Reader.ReadNestedNameSpecifierLoc(F, Record, Idx));
5864}
5865void TypeLocReader::VisitInjectedClassNameTypeLoc(InjectedClassNameTypeLoc TL) {
5866 TL.setNameLoc(ReadSourceLocation(Record, Idx));
5867}
5868void TypeLocReader::VisitDependentNameTypeLoc(DependentNameTypeLoc TL) {
5869 TL.setElaboratedKeywordLoc(ReadSourceLocation(Record, Idx));
5870 TL.setQualifierLoc(Reader.ReadNestedNameSpecifierLoc(F, Record, Idx));
5871 TL.setNameLoc(ReadSourceLocation(Record, Idx));
5872}
5873void TypeLocReader::VisitDependentTemplateSpecializationTypeLoc(
5874 DependentTemplateSpecializationTypeLoc TL) {
5875 TL.setElaboratedKeywordLoc(ReadSourceLocation(Record, Idx));
5876 TL.setQualifierLoc(Reader.ReadNestedNameSpecifierLoc(F, Record, Idx));
5877 TL.setTemplateKeywordLoc(ReadSourceLocation(Record, Idx));
5878 TL.setTemplateNameLoc(ReadSourceLocation(Record, Idx));
5879 TL.setLAngleLoc(ReadSourceLocation(Record, Idx));
5880 TL.setRAngleLoc(ReadSourceLocation(Record, Idx));
5881 for (unsigned I = 0, E = TL.getNumArgs(); I != E; ++I)
5882 TL.setArgLocInfo(I,
5883 Reader.GetTemplateArgumentLocInfo(F,
5884 TL.getTypePtr()->getArg(I).getKind(),
5885 Record, Idx));
5886}
5887void TypeLocReader::VisitPackExpansionTypeLoc(PackExpansionTypeLoc TL) {
5888 TL.setEllipsisLoc(ReadSourceLocation(Record, Idx));
5889}
5890void TypeLocReader::VisitObjCInterfaceTypeLoc(ObjCInterfaceTypeLoc TL) {
5891 TL.setNameLoc(ReadSourceLocation(Record, Idx));
5892}
5893void TypeLocReader::VisitObjCObjectTypeLoc(ObjCObjectTypeLoc TL) {
5894 TL.setHasBaseTypeAsWritten(Record[Idx++]);
5895 TL.setLAngleLoc(ReadSourceLocation(Record, Idx));
5896 TL.setRAngleLoc(ReadSourceLocation(Record, Idx));
5897 for (unsigned i = 0, e = TL.getNumProtocols(); i != e; ++i)
5898 TL.setProtocolLoc(i, ReadSourceLocation(Record, Idx));
5899}
5900void TypeLocReader::VisitObjCObjectPointerTypeLoc(ObjCObjectPointerTypeLoc TL) {
5901 TL.setStarLoc(ReadSourceLocation(Record, Idx));
5902}
5903void TypeLocReader::VisitAtomicTypeLoc(AtomicTypeLoc TL) {
5904 TL.setKWLoc(ReadSourceLocation(Record, Idx));
5905 TL.setLParenLoc(ReadSourceLocation(Record, Idx));
5906 TL.setRParenLoc(ReadSourceLocation(Record, Idx));
5907}
5908
5909TypeSourceInfo *ASTReader::GetTypeSourceInfo(ModuleFile &F,
5910 const RecordData &Record,
5911 unsigned &Idx) {
5912 QualType InfoTy = readType(F, Record, Idx);
5913 if (InfoTy.isNull())
Craig Toppera13603a2014-05-22 05:54:18 +00005914 return nullptr;
Guy Benyei11169dd2012-12-18 14:30:41 +00005915
5916 TypeSourceInfo *TInfo = getContext().CreateTypeSourceInfo(InfoTy);
5917 TypeLocReader TLR(*this, F, Record, Idx);
5918 for (TypeLoc TL = TInfo->getTypeLoc(); !TL.isNull(); TL = TL.getNextTypeLoc())
5919 TLR.Visit(TL);
5920 return TInfo;
5921}
5922
5923QualType ASTReader::GetType(TypeID ID) {
5924 unsigned FastQuals = ID & Qualifiers::FastMask;
5925 unsigned Index = ID >> Qualifiers::FastWidth;
5926
5927 if (Index < NUM_PREDEF_TYPE_IDS) {
5928 QualType T;
5929 switch ((PredefinedTypeIDs)Index) {
5930 case PREDEF_TYPE_NULL_ID: return QualType();
5931 case PREDEF_TYPE_VOID_ID: T = Context.VoidTy; break;
5932 case PREDEF_TYPE_BOOL_ID: T = Context.BoolTy; break;
5933
5934 case PREDEF_TYPE_CHAR_U_ID:
5935 case PREDEF_TYPE_CHAR_S_ID:
5936 // FIXME: Check that the signedness of CharTy is correct!
5937 T = Context.CharTy;
5938 break;
5939
5940 case PREDEF_TYPE_UCHAR_ID: T = Context.UnsignedCharTy; break;
5941 case PREDEF_TYPE_USHORT_ID: T = Context.UnsignedShortTy; break;
5942 case PREDEF_TYPE_UINT_ID: T = Context.UnsignedIntTy; break;
5943 case PREDEF_TYPE_ULONG_ID: T = Context.UnsignedLongTy; break;
5944 case PREDEF_TYPE_ULONGLONG_ID: T = Context.UnsignedLongLongTy; break;
5945 case PREDEF_TYPE_UINT128_ID: T = Context.UnsignedInt128Ty; break;
5946 case PREDEF_TYPE_SCHAR_ID: T = Context.SignedCharTy; break;
5947 case PREDEF_TYPE_WCHAR_ID: T = Context.WCharTy; break;
5948 case PREDEF_TYPE_SHORT_ID: T = Context.ShortTy; break;
5949 case PREDEF_TYPE_INT_ID: T = Context.IntTy; break;
5950 case PREDEF_TYPE_LONG_ID: T = Context.LongTy; break;
5951 case PREDEF_TYPE_LONGLONG_ID: T = Context.LongLongTy; break;
5952 case PREDEF_TYPE_INT128_ID: T = Context.Int128Ty; break;
5953 case PREDEF_TYPE_HALF_ID: T = Context.HalfTy; break;
5954 case PREDEF_TYPE_FLOAT_ID: T = Context.FloatTy; break;
5955 case PREDEF_TYPE_DOUBLE_ID: T = Context.DoubleTy; break;
5956 case PREDEF_TYPE_LONGDOUBLE_ID: T = Context.LongDoubleTy; break;
5957 case PREDEF_TYPE_OVERLOAD_ID: T = Context.OverloadTy; break;
5958 case PREDEF_TYPE_BOUND_MEMBER: T = Context.BoundMemberTy; break;
5959 case PREDEF_TYPE_PSEUDO_OBJECT: T = Context.PseudoObjectTy; break;
5960 case PREDEF_TYPE_DEPENDENT_ID: T = Context.DependentTy; break;
5961 case PREDEF_TYPE_UNKNOWN_ANY: T = Context.UnknownAnyTy; break;
5962 case PREDEF_TYPE_NULLPTR_ID: T = Context.NullPtrTy; break;
5963 case PREDEF_TYPE_CHAR16_ID: T = Context.Char16Ty; break;
5964 case PREDEF_TYPE_CHAR32_ID: T = Context.Char32Ty; break;
5965 case PREDEF_TYPE_OBJC_ID: T = Context.ObjCBuiltinIdTy; break;
5966 case PREDEF_TYPE_OBJC_CLASS: T = Context.ObjCBuiltinClassTy; break;
5967 case PREDEF_TYPE_OBJC_SEL: T = Context.ObjCBuiltinSelTy; break;
Guy Benyeid8a08ea2012-12-18 14:38:23 +00005968 case PREDEF_TYPE_IMAGE1D_ID: T = Context.OCLImage1dTy; break;
5969 case PREDEF_TYPE_IMAGE1D_ARR_ID: T = Context.OCLImage1dArrayTy; break;
5970 case PREDEF_TYPE_IMAGE1D_BUFF_ID: T = Context.OCLImage1dBufferTy; break;
5971 case PREDEF_TYPE_IMAGE2D_ID: T = Context.OCLImage2dTy; break;
5972 case PREDEF_TYPE_IMAGE2D_ARR_ID: T = Context.OCLImage2dArrayTy; break;
5973 case PREDEF_TYPE_IMAGE3D_ID: T = Context.OCLImage3dTy; break;
Guy Benyei61054192013-02-07 10:55:47 +00005974 case PREDEF_TYPE_SAMPLER_ID: T = Context.OCLSamplerTy; break;
Guy Benyei1b4fb3e2013-01-20 12:31:11 +00005975 case PREDEF_TYPE_EVENT_ID: T = Context.OCLEventTy; break;
Guy Benyei11169dd2012-12-18 14:30:41 +00005976 case PREDEF_TYPE_AUTO_DEDUCT: T = Context.getAutoDeductType(); break;
5977
5978 case PREDEF_TYPE_AUTO_RREF_DEDUCT:
5979 T = Context.getAutoRRefDeductType();
5980 break;
5981
5982 case PREDEF_TYPE_ARC_UNBRIDGED_CAST:
5983 T = Context.ARCUnbridgedCastTy;
5984 break;
5985
5986 case PREDEF_TYPE_VA_LIST_TAG:
5987 T = Context.getVaListTagType();
5988 break;
5989
5990 case PREDEF_TYPE_BUILTIN_FN:
5991 T = Context.BuiltinFnTy;
5992 break;
5993 }
5994
5995 assert(!T.isNull() && "Unknown predefined type");
5996 return T.withFastQualifiers(FastQuals);
5997 }
5998
5999 Index -= NUM_PREDEF_TYPE_IDS;
6000 assert(Index < TypesLoaded.size() && "Type index out-of-range");
6001 if (TypesLoaded[Index].isNull()) {
6002 TypesLoaded[Index] = readTypeRecord(Index);
6003 if (TypesLoaded[Index].isNull())
6004 return QualType();
6005
6006 TypesLoaded[Index]->setFromAST();
6007 if (DeserializationListener)
6008 DeserializationListener->TypeRead(TypeIdx::fromTypeID(ID),
6009 TypesLoaded[Index]);
6010 }
6011
6012 return TypesLoaded[Index].withFastQualifiers(FastQuals);
6013}
6014
6015QualType ASTReader::getLocalType(ModuleFile &F, unsigned LocalID) {
6016 return GetType(getGlobalTypeID(F, LocalID));
6017}
6018
6019serialization::TypeID
6020ASTReader::getGlobalTypeID(ModuleFile &F, unsigned LocalID) const {
6021 unsigned FastQuals = LocalID & Qualifiers::FastMask;
6022 unsigned LocalIndex = LocalID >> Qualifiers::FastWidth;
6023
6024 if (LocalIndex < NUM_PREDEF_TYPE_IDS)
6025 return LocalID;
6026
6027 ContinuousRangeMap<uint32_t, int, 2>::iterator I
6028 = F.TypeRemap.find(LocalIndex - NUM_PREDEF_TYPE_IDS);
6029 assert(I != F.TypeRemap.end() && "Invalid index into type index remap");
6030
6031 unsigned GlobalIndex = LocalIndex + I->second;
6032 return (GlobalIndex << Qualifiers::FastWidth) | FastQuals;
6033}
6034
6035TemplateArgumentLocInfo
6036ASTReader::GetTemplateArgumentLocInfo(ModuleFile &F,
6037 TemplateArgument::ArgKind Kind,
6038 const RecordData &Record,
6039 unsigned &Index) {
6040 switch (Kind) {
6041 case TemplateArgument::Expression:
6042 return ReadExpr(F);
6043 case TemplateArgument::Type:
6044 return GetTypeSourceInfo(F, Record, Index);
6045 case TemplateArgument::Template: {
6046 NestedNameSpecifierLoc QualifierLoc = ReadNestedNameSpecifierLoc(F, Record,
6047 Index);
6048 SourceLocation TemplateNameLoc = ReadSourceLocation(F, Record, Index);
6049 return TemplateArgumentLocInfo(QualifierLoc, TemplateNameLoc,
6050 SourceLocation());
6051 }
6052 case TemplateArgument::TemplateExpansion: {
6053 NestedNameSpecifierLoc QualifierLoc = ReadNestedNameSpecifierLoc(F, Record,
6054 Index);
6055 SourceLocation TemplateNameLoc = ReadSourceLocation(F, Record, Index);
6056 SourceLocation EllipsisLoc = ReadSourceLocation(F, Record, Index);
6057 return TemplateArgumentLocInfo(QualifierLoc, TemplateNameLoc,
6058 EllipsisLoc);
6059 }
6060 case TemplateArgument::Null:
6061 case TemplateArgument::Integral:
6062 case TemplateArgument::Declaration:
6063 case TemplateArgument::NullPtr:
6064 case TemplateArgument::Pack:
6065 // FIXME: Is this right?
6066 return TemplateArgumentLocInfo();
6067 }
6068 llvm_unreachable("unexpected template argument loc");
6069}
6070
6071TemplateArgumentLoc
6072ASTReader::ReadTemplateArgumentLoc(ModuleFile &F,
6073 const RecordData &Record, unsigned &Index) {
6074 TemplateArgument Arg = ReadTemplateArgument(F, Record, Index);
6075
6076 if (Arg.getKind() == TemplateArgument::Expression) {
6077 if (Record[Index++]) // bool InfoHasSameExpr.
6078 return TemplateArgumentLoc(Arg, TemplateArgumentLocInfo(Arg.getAsExpr()));
6079 }
6080 return TemplateArgumentLoc(Arg, GetTemplateArgumentLocInfo(F, Arg.getKind(),
6081 Record, Index));
6082}
6083
Enea Zaffanella6dbe1872013-08-10 07:24:53 +00006084const ASTTemplateArgumentListInfo*
6085ASTReader::ReadASTTemplateArgumentListInfo(ModuleFile &F,
6086 const RecordData &Record,
6087 unsigned &Index) {
6088 SourceLocation LAngleLoc = ReadSourceLocation(F, Record, Index);
6089 SourceLocation RAngleLoc = ReadSourceLocation(F, Record, Index);
6090 unsigned NumArgsAsWritten = Record[Index++];
6091 TemplateArgumentListInfo TemplArgsInfo(LAngleLoc, RAngleLoc);
6092 for (unsigned i = 0; i != NumArgsAsWritten; ++i)
6093 TemplArgsInfo.addArgument(ReadTemplateArgumentLoc(F, Record, Index));
6094 return ASTTemplateArgumentListInfo::Create(getContext(), TemplArgsInfo);
6095}
6096
Guy Benyei11169dd2012-12-18 14:30:41 +00006097Decl *ASTReader::GetExternalDecl(uint32_t ID) {
6098 return GetDecl(ID);
6099}
6100
Richard Smith053f6c62014-05-16 23:01:30 +00006101void ASTReader::CompleteRedeclChain(const Decl *D) {
Richard Smith851072e2014-05-19 20:59:20 +00006102 if (NumCurrentElementsDeserializing) {
6103 // We arrange to not care about the complete redeclaration chain while we're
6104 // deserializing. Just remember that the AST has marked this one as complete
6105 // but that it's not actually complete yet, so we know we still need to
6106 // complete it later.
6107 PendingIncompleteDeclChains.push_back(const_cast<Decl*>(D));
6108 return;
6109 }
6110
Richard Smith053f6c62014-05-16 23:01:30 +00006111 const DeclContext *DC = D->getDeclContext()->getRedeclContext();
6112
Richard Smith053f6c62014-05-16 23:01:30 +00006113 // If this is a named declaration, complete it by looking it up
6114 // within its context.
6115 //
Richard Smith01bdb7a2014-08-28 05:44:07 +00006116 // FIXME: Merging a function definition should merge
Richard Smith053f6c62014-05-16 23:01:30 +00006117 // all mergeable entities within it.
6118 if (isa<TranslationUnitDecl>(DC) || isa<NamespaceDecl>(DC) ||
6119 isa<CXXRecordDecl>(DC) || isa<EnumDecl>(DC)) {
6120 if (DeclarationName Name = cast<NamedDecl>(D)->getDeclName()) {
6121 auto *II = Name.getAsIdentifierInfo();
6122 if (isa<TranslationUnitDecl>(DC) && II) {
6123 // Outside of C++, we don't have a lookup table for the TU, so update
6124 // the identifier instead. In C++, either way should work fine.
6125 if (II->isOutOfDate())
6126 updateOutOfDateIdentifier(*II);
6127 } else
6128 DC->lookup(Name);
Richard Smith01bdb7a2014-08-28 05:44:07 +00006129 } else if (needsAnonymousDeclarationNumber(cast<NamedDecl>(D))) {
6130 // FIXME: It'd be nice to do something a bit more targeted here.
6131 D->getDeclContext()->decls_begin();
Richard Smith053f6c62014-05-16 23:01:30 +00006132 }
6133 }
6134}
6135
Richard Smithcd45dbc2014-04-19 03:48:30 +00006136uint64_t ASTReader::readCXXBaseSpecifiers(ModuleFile &M,
6137 const RecordData &Record,
6138 unsigned &Idx) {
6139 if (Idx >= Record.size() || Record[Idx] > M.LocalNumCXXBaseSpecifiers) {
6140 Error("malformed AST file: missing C++ base specifier");
Guy Benyei11169dd2012-12-18 14:30:41 +00006141 return 0;
Richard Smithcd45dbc2014-04-19 03:48:30 +00006142 }
6143
Guy Benyei11169dd2012-12-18 14:30:41 +00006144 unsigned LocalID = Record[Idx++];
6145 return getGlobalBitOffset(M, M.CXXBaseSpecifiersOffsets[LocalID - 1]);
6146}
6147
6148CXXBaseSpecifier *ASTReader::GetExternalCXXBaseSpecifiers(uint64_t Offset) {
6149 RecordLocation Loc = getLocalBitOffset(Offset);
Chris Lattner7fb3bef2013-01-20 00:56:42 +00006150 BitstreamCursor &Cursor = Loc.F->DeclsCursor;
Guy Benyei11169dd2012-12-18 14:30:41 +00006151 SavedStreamPosition SavedPosition(Cursor);
6152 Cursor.JumpToBit(Loc.Offset);
6153 ReadingKindTracker ReadingKind(Read_Decl, *this);
6154 RecordData Record;
6155 unsigned Code = Cursor.ReadCode();
Chris Lattner0e6c9402013-01-20 02:38:54 +00006156 unsigned RecCode = Cursor.readRecord(Code, Record);
Guy Benyei11169dd2012-12-18 14:30:41 +00006157 if (RecCode != DECL_CXX_BASE_SPECIFIERS) {
Richard Smithcd45dbc2014-04-19 03:48:30 +00006158 Error("malformed AST file: missing C++ base specifiers");
Craig Toppera13603a2014-05-22 05:54:18 +00006159 return nullptr;
Guy Benyei11169dd2012-12-18 14:30:41 +00006160 }
6161
6162 unsigned Idx = 0;
6163 unsigned NumBases = Record[Idx++];
6164 void *Mem = Context.Allocate(sizeof(CXXBaseSpecifier) * NumBases);
6165 CXXBaseSpecifier *Bases = new (Mem) CXXBaseSpecifier [NumBases];
6166 for (unsigned I = 0; I != NumBases; ++I)
6167 Bases[I] = ReadCXXBaseSpecifier(*Loc.F, Record, Idx);
6168 return Bases;
6169}
6170
6171serialization::DeclID
6172ASTReader::getGlobalDeclID(ModuleFile &F, LocalDeclID LocalID) const {
6173 if (LocalID < NUM_PREDEF_DECL_IDS)
6174 return LocalID;
6175
6176 ContinuousRangeMap<uint32_t, int, 2>::iterator I
6177 = F.DeclRemap.find(LocalID - NUM_PREDEF_DECL_IDS);
6178 assert(I != F.DeclRemap.end() && "Invalid index into decl index remap");
6179
6180 return LocalID + I->second;
6181}
6182
6183bool ASTReader::isDeclIDFromModule(serialization::GlobalDeclID ID,
6184 ModuleFile &M) const {
6185 GlobalDeclMapType::const_iterator I = GlobalDeclMap.find(ID);
6186 assert(I != GlobalDeclMap.end() && "Corrupted global declaration map");
6187 return &M == I->second;
6188}
6189
Douglas Gregor9f782892013-01-21 15:25:38 +00006190ModuleFile *ASTReader::getOwningModuleFile(const Decl *D) {
Guy Benyei11169dd2012-12-18 14:30:41 +00006191 if (!D->isFromASTFile())
Craig Toppera13603a2014-05-22 05:54:18 +00006192 return nullptr;
Guy Benyei11169dd2012-12-18 14:30:41 +00006193 GlobalDeclMapType::const_iterator I = GlobalDeclMap.find(D->getGlobalID());
6194 assert(I != GlobalDeclMap.end() && "Corrupted global declaration map");
6195 return I->second;
6196}
6197
6198SourceLocation ASTReader::getSourceLocationForDeclID(GlobalDeclID ID) {
6199 if (ID < NUM_PREDEF_DECL_IDS)
6200 return SourceLocation();
Richard Smithcd45dbc2014-04-19 03:48:30 +00006201
Guy Benyei11169dd2012-12-18 14:30:41 +00006202 unsigned Index = ID - NUM_PREDEF_DECL_IDS;
6203
6204 if (Index > DeclsLoaded.size()) {
6205 Error("declaration ID out-of-range for AST file");
6206 return SourceLocation();
6207 }
Richard Smithcd45dbc2014-04-19 03:48:30 +00006208
Guy Benyei11169dd2012-12-18 14:30:41 +00006209 if (Decl *D = DeclsLoaded[Index])
6210 return D->getLocation();
6211
6212 unsigned RawLocation = 0;
6213 RecordLocation Rec = DeclCursorForID(ID, RawLocation);
6214 return ReadSourceLocation(*Rec.F, RawLocation);
6215}
6216
Richard Smithcd45dbc2014-04-19 03:48:30 +00006217Decl *ASTReader::GetExistingDecl(DeclID ID) {
6218 if (ID < NUM_PREDEF_DECL_IDS) {
Guy Benyei11169dd2012-12-18 14:30:41 +00006219 switch ((PredefinedDeclIDs)ID) {
6220 case PREDEF_DECL_NULL_ID:
Craig Toppera13603a2014-05-22 05:54:18 +00006221 return nullptr;
Richard Smithcd45dbc2014-04-19 03:48:30 +00006222
Guy Benyei11169dd2012-12-18 14:30:41 +00006223 case PREDEF_DECL_TRANSLATION_UNIT_ID:
6224 return Context.getTranslationUnitDecl();
Richard Smithcd45dbc2014-04-19 03:48:30 +00006225
Guy Benyei11169dd2012-12-18 14:30:41 +00006226 case PREDEF_DECL_OBJC_ID_ID:
6227 return Context.getObjCIdDecl();
6228
6229 case PREDEF_DECL_OBJC_SEL_ID:
6230 return Context.getObjCSelDecl();
6231
6232 case PREDEF_DECL_OBJC_CLASS_ID:
6233 return Context.getObjCClassDecl();
Richard Smithcd45dbc2014-04-19 03:48:30 +00006234
Guy Benyei11169dd2012-12-18 14:30:41 +00006235 case PREDEF_DECL_OBJC_PROTOCOL_ID:
6236 return Context.getObjCProtocolDecl();
Richard Smithcd45dbc2014-04-19 03:48:30 +00006237
Guy Benyei11169dd2012-12-18 14:30:41 +00006238 case PREDEF_DECL_INT_128_ID:
6239 return Context.getInt128Decl();
6240
6241 case PREDEF_DECL_UNSIGNED_INT_128_ID:
6242 return Context.getUInt128Decl();
Richard Smithcd45dbc2014-04-19 03:48:30 +00006243
Guy Benyei11169dd2012-12-18 14:30:41 +00006244 case PREDEF_DECL_OBJC_INSTANCETYPE_ID:
6245 return Context.getObjCInstanceTypeDecl();
6246
6247 case PREDEF_DECL_BUILTIN_VA_LIST_ID:
6248 return Context.getBuiltinVaListDecl();
6249 }
6250 }
Richard Smithcd45dbc2014-04-19 03:48:30 +00006251
Guy Benyei11169dd2012-12-18 14:30:41 +00006252 unsigned Index = ID - NUM_PREDEF_DECL_IDS;
6253
6254 if (Index >= DeclsLoaded.size()) {
6255 assert(0 && "declaration ID out-of-range for AST file");
6256 Error("declaration ID out-of-range for AST file");
Craig Toppera13603a2014-05-22 05:54:18 +00006257 return nullptr;
Guy Benyei11169dd2012-12-18 14:30:41 +00006258 }
Richard Smithcd45dbc2014-04-19 03:48:30 +00006259
6260 return DeclsLoaded[Index];
6261}
6262
6263Decl *ASTReader::GetDecl(DeclID ID) {
6264 if (ID < NUM_PREDEF_DECL_IDS)
6265 return GetExistingDecl(ID);
6266
6267 unsigned Index = ID - NUM_PREDEF_DECL_IDS;
6268
6269 if (Index >= DeclsLoaded.size()) {
6270 assert(0 && "declaration ID out-of-range for AST file");
6271 Error("declaration ID out-of-range for AST file");
Craig Toppera13603a2014-05-22 05:54:18 +00006272 return nullptr;
Richard Smithcd45dbc2014-04-19 03:48:30 +00006273 }
6274
Guy Benyei11169dd2012-12-18 14:30:41 +00006275 if (!DeclsLoaded[Index]) {
6276 ReadDeclRecord(ID);
6277 if (DeserializationListener)
6278 DeserializationListener->DeclRead(ID, DeclsLoaded[Index]);
6279 }
6280
6281 return DeclsLoaded[Index];
6282}
6283
6284DeclID ASTReader::mapGlobalIDToModuleFileGlobalID(ModuleFile &M,
6285 DeclID GlobalID) {
6286 if (GlobalID < NUM_PREDEF_DECL_IDS)
6287 return GlobalID;
6288
6289 GlobalDeclMapType::const_iterator I = GlobalDeclMap.find(GlobalID);
6290 assert(I != GlobalDeclMap.end() && "Corrupted global declaration map");
6291 ModuleFile *Owner = I->second;
6292
6293 llvm::DenseMap<ModuleFile *, serialization::DeclID>::iterator Pos
6294 = M.GlobalToLocalDeclIDs.find(Owner);
6295 if (Pos == M.GlobalToLocalDeclIDs.end())
6296 return 0;
6297
6298 return GlobalID - Owner->BaseDeclID + Pos->second;
6299}
6300
6301serialization::DeclID ASTReader::ReadDeclID(ModuleFile &F,
6302 const RecordData &Record,
6303 unsigned &Idx) {
6304 if (Idx >= Record.size()) {
6305 Error("Corrupted AST file");
6306 return 0;
6307 }
6308
6309 return getGlobalDeclID(F, Record[Idx++]);
6310}
6311
6312/// \brief Resolve the offset of a statement into a statement.
6313///
6314/// This operation will read a new statement from the external
6315/// source each time it is called, and is meant to be used via a
6316/// LazyOffsetPtr (which is used by Decls for the body of functions, etc).
6317Stmt *ASTReader::GetExternalDeclStmt(uint64_t Offset) {
6318 // Switch case IDs are per Decl.
6319 ClearSwitchCaseIDs();
6320
6321 // Offset here is a global offset across the entire chain.
6322 RecordLocation Loc = getLocalBitOffset(Offset);
6323 Loc.F->DeclsCursor.JumpToBit(Loc.Offset);
6324 return ReadStmtFromStream(*Loc.F);
6325}
6326
6327namespace {
6328 class FindExternalLexicalDeclsVisitor {
6329 ASTReader &Reader;
6330 const DeclContext *DC;
6331 bool (*isKindWeWant)(Decl::Kind);
6332
6333 SmallVectorImpl<Decl*> &Decls;
6334 bool PredefsVisited[NUM_PREDEF_DECL_IDS];
6335
6336 public:
6337 FindExternalLexicalDeclsVisitor(ASTReader &Reader, const DeclContext *DC,
6338 bool (*isKindWeWant)(Decl::Kind),
6339 SmallVectorImpl<Decl*> &Decls)
6340 : Reader(Reader), DC(DC), isKindWeWant(isKindWeWant), Decls(Decls)
6341 {
6342 for (unsigned I = 0; I != NUM_PREDEF_DECL_IDS; ++I)
6343 PredefsVisited[I] = false;
6344 }
6345
6346 static bool visit(ModuleFile &M, bool Preorder, void *UserData) {
6347 if (Preorder)
6348 return false;
6349
6350 FindExternalLexicalDeclsVisitor *This
6351 = static_cast<FindExternalLexicalDeclsVisitor *>(UserData);
6352
6353 ModuleFile::DeclContextInfosMap::iterator Info
6354 = M.DeclContextInfos.find(This->DC);
6355 if (Info == M.DeclContextInfos.end() || !Info->second.LexicalDecls)
6356 return false;
6357
6358 // Load all of the declaration IDs
6359 for (const KindDeclIDPair *ID = Info->second.LexicalDecls,
6360 *IDE = ID + Info->second.NumLexicalDecls;
6361 ID != IDE; ++ID) {
6362 if (This->isKindWeWant && !This->isKindWeWant((Decl::Kind)ID->first))
6363 continue;
6364
6365 // Don't add predefined declarations to the lexical context more
6366 // than once.
6367 if (ID->second < NUM_PREDEF_DECL_IDS) {
6368 if (This->PredefsVisited[ID->second])
6369 continue;
6370
6371 This->PredefsVisited[ID->second] = true;
6372 }
6373
6374 if (Decl *D = This->Reader.GetLocalDecl(M, ID->second)) {
6375 if (!This->DC->isDeclInLexicalTraversal(D))
6376 This->Decls.push_back(D);
6377 }
6378 }
6379
6380 return false;
6381 }
6382 };
6383}
6384
6385ExternalLoadResult ASTReader::FindExternalLexicalDecls(const DeclContext *DC,
6386 bool (*isKindWeWant)(Decl::Kind),
6387 SmallVectorImpl<Decl*> &Decls) {
6388 // There might be lexical decls in multiple modules, for the TU at
6389 // least. Walk all of the modules in the order they were loaded.
6390 FindExternalLexicalDeclsVisitor Visitor(*this, DC, isKindWeWant, Decls);
6391 ModuleMgr.visitDepthFirst(&FindExternalLexicalDeclsVisitor::visit, &Visitor);
6392 ++NumLexicalDeclContextsRead;
6393 return ELR_Success;
6394}
6395
6396namespace {
6397
6398class DeclIDComp {
6399 ASTReader &Reader;
6400 ModuleFile &Mod;
6401
6402public:
6403 DeclIDComp(ASTReader &Reader, ModuleFile &M) : Reader(Reader), Mod(M) {}
6404
6405 bool operator()(LocalDeclID L, LocalDeclID R) const {
6406 SourceLocation LHS = getLocation(L);
6407 SourceLocation RHS = getLocation(R);
6408 return Reader.getSourceManager().isBeforeInTranslationUnit(LHS, RHS);
6409 }
6410
6411 bool operator()(SourceLocation LHS, LocalDeclID R) const {
6412 SourceLocation RHS = getLocation(R);
6413 return Reader.getSourceManager().isBeforeInTranslationUnit(LHS, RHS);
6414 }
6415
6416 bool operator()(LocalDeclID L, SourceLocation RHS) const {
6417 SourceLocation LHS = getLocation(L);
6418 return Reader.getSourceManager().isBeforeInTranslationUnit(LHS, RHS);
6419 }
6420
6421 SourceLocation getLocation(LocalDeclID ID) const {
6422 return Reader.getSourceManager().getFileLoc(
6423 Reader.getSourceLocationForDeclID(Reader.getGlobalDeclID(Mod, ID)));
6424 }
6425};
6426
6427}
6428
6429void ASTReader::FindFileRegionDecls(FileID File,
6430 unsigned Offset, unsigned Length,
6431 SmallVectorImpl<Decl *> &Decls) {
6432 SourceManager &SM = getSourceManager();
6433
6434 llvm::DenseMap<FileID, FileDeclsInfo>::iterator I = FileDeclIDs.find(File);
6435 if (I == FileDeclIDs.end())
6436 return;
6437
6438 FileDeclsInfo &DInfo = I->second;
6439 if (DInfo.Decls.empty())
6440 return;
6441
6442 SourceLocation
6443 BeginLoc = SM.getLocForStartOfFile(File).getLocWithOffset(Offset);
6444 SourceLocation EndLoc = BeginLoc.getLocWithOffset(Length);
6445
6446 DeclIDComp DIDComp(*this, *DInfo.Mod);
6447 ArrayRef<serialization::LocalDeclID>::iterator
6448 BeginIt = std::lower_bound(DInfo.Decls.begin(), DInfo.Decls.end(),
6449 BeginLoc, DIDComp);
6450 if (BeginIt != DInfo.Decls.begin())
6451 --BeginIt;
6452
6453 // If we are pointing at a top-level decl inside an objc container, we need
6454 // to backtrack until we find it otherwise we will fail to report that the
6455 // region overlaps with an objc container.
6456 while (BeginIt != DInfo.Decls.begin() &&
6457 GetDecl(getGlobalDeclID(*DInfo.Mod, *BeginIt))
6458 ->isTopLevelDeclInObjCContainer())
6459 --BeginIt;
6460
6461 ArrayRef<serialization::LocalDeclID>::iterator
6462 EndIt = std::upper_bound(DInfo.Decls.begin(), DInfo.Decls.end(),
6463 EndLoc, DIDComp);
6464 if (EndIt != DInfo.Decls.end())
6465 ++EndIt;
6466
6467 for (ArrayRef<serialization::LocalDeclID>::iterator
6468 DIt = BeginIt; DIt != EndIt; ++DIt)
6469 Decls.push_back(GetDecl(getGlobalDeclID(*DInfo.Mod, *DIt)));
6470}
6471
6472namespace {
6473 /// \brief ModuleFile visitor used to perform name lookup into a
6474 /// declaration context.
6475 class DeclContextNameLookupVisitor {
6476 ASTReader &Reader;
Richard Smith8c913ec2014-08-14 02:21:01 +00006477 ArrayRef<const DeclContext *> Contexts;
Guy Benyei11169dd2012-12-18 14:30:41 +00006478 DeclarationName Name;
6479 SmallVectorImpl<NamedDecl *> &Decls;
6480
6481 public:
Richard Smith8c913ec2014-08-14 02:21:01 +00006482 DeclContextNameLookupVisitor(ASTReader &Reader,
6483 ArrayRef<const DeclContext *> Contexts,
Guy Benyei11169dd2012-12-18 14:30:41 +00006484 DeclarationName Name,
6485 SmallVectorImpl<NamedDecl *> &Decls)
6486 : Reader(Reader), Contexts(Contexts), Name(Name), Decls(Decls) { }
6487
6488 static bool visit(ModuleFile &M, void *UserData) {
6489 DeclContextNameLookupVisitor *This
6490 = static_cast<DeclContextNameLookupVisitor *>(UserData);
6491
6492 // Check whether we have any visible declaration information for
6493 // this context in this module.
6494 ModuleFile::DeclContextInfosMap::iterator Info;
6495 bool FoundInfo = false;
Richard Smith8c913ec2014-08-14 02:21:01 +00006496 for (auto *DC : This->Contexts) {
6497 Info = M.DeclContextInfos.find(DC);
6498 if (Info != M.DeclContextInfos.end() &&
Guy Benyei11169dd2012-12-18 14:30:41 +00006499 Info->second.NameLookupTableData) {
6500 FoundInfo = true;
6501 break;
6502 }
6503 }
6504
6505 if (!FoundInfo)
6506 return false;
Richard Smith8c913ec2014-08-14 02:21:01 +00006507
Guy Benyei11169dd2012-12-18 14:30:41 +00006508 // Look for this name within this module.
Richard Smith52e3fba2014-03-11 07:17:35 +00006509 ASTDeclContextNameLookupTable *LookupTable =
Guy Benyei11169dd2012-12-18 14:30:41 +00006510 Info->second.NameLookupTableData;
6511 ASTDeclContextNameLookupTable::iterator Pos
6512 = LookupTable->find(This->Name);
6513 if (Pos == LookupTable->end())
6514 return false;
6515
6516 bool FoundAnything = false;
6517 ASTDeclContextNameLookupTrait::data_type Data = *Pos;
6518 for (; Data.first != Data.second; ++Data.first) {
6519 NamedDecl *ND = This->Reader.GetLocalDeclAs<NamedDecl>(M, *Data.first);
6520 if (!ND)
6521 continue;
6522
6523 if (ND->getDeclName() != This->Name) {
6524 // A name might be null because the decl's redeclarable part is
6525 // currently read before reading its name. The lookup is triggered by
6526 // building that decl (likely indirectly), and so it is later in the
6527 // sense of "already existing" and can be ignored here.
Richard Smith8c913ec2014-08-14 02:21:01 +00006528 // FIXME: This should not happen; deserializing declarations should
6529 // not perform lookups since that can lead to deserialization cycles.
Guy Benyei11169dd2012-12-18 14:30:41 +00006530 continue;
6531 }
Richard Smith8c913ec2014-08-14 02:21:01 +00006532
Guy Benyei11169dd2012-12-18 14:30:41 +00006533 // Record this declaration.
6534 FoundAnything = true;
6535 This->Decls.push_back(ND);
6536 }
6537
6538 return FoundAnything;
6539 }
6540 };
6541}
6542
Douglas Gregor9f782892013-01-21 15:25:38 +00006543/// \brief Retrieve the "definitive" module file for the definition of the
6544/// given declaration context, if there is one.
6545///
6546/// The "definitive" module file is the only place where we need to look to
6547/// find information about the declarations within the given declaration
6548/// context. For example, C++ and Objective-C classes, C structs/unions, and
6549/// Objective-C protocols, categories, and extensions are all defined in a
6550/// single place in the source code, so they have definitive module files
6551/// associated with them. C++ namespaces, on the other hand, can have
6552/// definitions in multiple different module files.
6553///
6554/// Note: this needs to be kept in sync with ASTWriter::AddedVisibleDecl's
6555/// NDEBUG checking.
6556static ModuleFile *getDefinitiveModuleFileFor(const DeclContext *DC,
6557 ASTReader &Reader) {
Douglas Gregor7a6e2002013-01-22 17:08:30 +00006558 if (const DeclContext *DefDC = getDefinitiveDeclContext(DC))
6559 return Reader.getOwningModuleFile(cast<Decl>(DefDC));
Douglas Gregor9f782892013-01-21 15:25:38 +00006560
Craig Toppera13603a2014-05-22 05:54:18 +00006561 return nullptr;
Douglas Gregor9f782892013-01-21 15:25:38 +00006562}
6563
Richard Smith9ce12e32013-02-07 03:30:24 +00006564bool
Guy Benyei11169dd2012-12-18 14:30:41 +00006565ASTReader::FindExternalVisibleDeclsByName(const DeclContext *DC,
6566 DeclarationName Name) {
6567 assert(DC->hasExternalVisibleStorage() &&
6568 "DeclContext has no visible decls in storage");
6569 if (!Name)
Richard Smith9ce12e32013-02-07 03:30:24 +00006570 return false;
Guy Benyei11169dd2012-12-18 14:30:41 +00006571
Richard Smith8c913ec2014-08-14 02:21:01 +00006572 Deserializing LookupResults(this);
6573
Guy Benyei11169dd2012-12-18 14:30:41 +00006574 SmallVector<NamedDecl *, 64> Decls;
Richard Smith8c913ec2014-08-14 02:21:01 +00006575
Guy Benyei11169dd2012-12-18 14:30:41 +00006576 // Compute the declaration contexts we need to look into. Multiple such
6577 // declaration contexts occur when two declaration contexts from disjoint
6578 // modules get merged, e.g., when two namespaces with the same name are
6579 // independently defined in separate modules.
6580 SmallVector<const DeclContext *, 2> Contexts;
6581 Contexts.push_back(DC);
Richard Smith8c913ec2014-08-14 02:21:01 +00006582
Guy Benyei11169dd2012-12-18 14:30:41 +00006583 if (DC->isNamespace()) {
Richard Smithcd45dbc2014-04-19 03:48:30 +00006584 auto Merged = MergedDecls.find(const_cast<Decl *>(cast<Decl>(DC)));
Guy Benyei11169dd2012-12-18 14:30:41 +00006585 if (Merged != MergedDecls.end()) {
6586 for (unsigned I = 0, N = Merged->second.size(); I != N; ++I)
6587 Contexts.push_back(cast<DeclContext>(GetDecl(Merged->second[I])));
6588 }
6589 }
Richard Smith8c913ec2014-08-14 02:21:01 +00006590
6591 auto LookUpInContexts = [&](ArrayRef<const DeclContext*> Contexts) {
6592 DeclContextNameLookupVisitor Visitor(*this, Contexts, Name, Decls);
6593
6594 // If we can definitively determine which module file to look into,
6595 // only look there. Otherwise, look in all module files.
6596 ModuleFile *Definitive;
6597 if (Contexts.size() == 1 &&
6598 (Definitive = getDefinitiveModuleFileFor(Contexts[0], *this))) {
6599 DeclContextNameLookupVisitor::visit(*Definitive, &Visitor);
6600 } else {
6601 ModuleMgr.visit(&DeclContextNameLookupVisitor::visit, &Visitor);
6602 }
6603 };
6604
6605 LookUpInContexts(Contexts);
6606
6607 // If this might be an implicit special member function, then also search
6608 // all merged definitions of the surrounding class. We need to search them
6609 // individually, because finding an entity in one of them doesn't imply that
6610 // we can't find a different entity in another one.
Richard Smithcd45dbc2014-04-19 03:48:30 +00006611 if (isa<CXXRecordDecl>(DC)) {
Richard Smith8c913ec2014-08-14 02:21:01 +00006612 auto Kind = Name.getNameKind();
6613 if (Kind == DeclarationName::CXXConstructorName ||
6614 Kind == DeclarationName::CXXDestructorName ||
6615 (Kind == DeclarationName::CXXOperatorName &&
6616 Name.getCXXOverloadedOperator() == OO_Equal)) {
6617 auto Merged = MergedLookups.find(DC);
6618 if (Merged != MergedLookups.end())
6619 for (auto *MergedDC : Merged->second)
6620 LookUpInContexts(MergedDC);
6621 }
Richard Smithcd45dbc2014-04-19 03:48:30 +00006622 }
6623
Guy Benyei11169dd2012-12-18 14:30:41 +00006624 ++NumVisibleDeclContextsRead;
6625 SetExternalVisibleDeclsForName(DC, Name, Decls);
Richard Smith9ce12e32013-02-07 03:30:24 +00006626 return !Decls.empty();
Guy Benyei11169dd2012-12-18 14:30:41 +00006627}
6628
6629namespace {
6630 /// \brief ModuleFile visitor used to retrieve all visible names in a
6631 /// declaration context.
6632 class DeclContextAllNamesVisitor {
6633 ASTReader &Reader;
Dmitri Gribenkof8579502013-01-12 19:30:44 +00006634 SmallVectorImpl<const DeclContext *> &Contexts;
Craig Topper3598eb72013-07-05 04:43:31 +00006635 DeclsMap &Decls;
Argyrios Kyrtzidis2810e9d2012-12-19 22:21:18 +00006636 bool VisitAll;
Guy Benyei11169dd2012-12-18 14:30:41 +00006637
6638 public:
6639 DeclContextAllNamesVisitor(ASTReader &Reader,
6640 SmallVectorImpl<const DeclContext *> &Contexts,
Craig Topper3598eb72013-07-05 04:43:31 +00006641 DeclsMap &Decls, bool VisitAll)
Argyrios Kyrtzidis2810e9d2012-12-19 22:21:18 +00006642 : Reader(Reader), Contexts(Contexts), Decls(Decls), VisitAll(VisitAll) { }
Guy Benyei11169dd2012-12-18 14:30:41 +00006643
6644 static bool visit(ModuleFile &M, void *UserData) {
6645 DeclContextAllNamesVisitor *This
6646 = static_cast<DeclContextAllNamesVisitor *>(UserData);
6647
6648 // Check whether we have any visible declaration information for
6649 // this context in this module.
6650 ModuleFile::DeclContextInfosMap::iterator Info;
6651 bool FoundInfo = false;
6652 for (unsigned I = 0, N = This->Contexts.size(); I != N; ++I) {
6653 Info = M.DeclContextInfos.find(This->Contexts[I]);
6654 if (Info != M.DeclContextInfos.end() &&
6655 Info->second.NameLookupTableData) {
6656 FoundInfo = true;
6657 break;
6658 }
6659 }
6660
6661 if (!FoundInfo)
6662 return false;
6663
Richard Smith52e3fba2014-03-11 07:17:35 +00006664 ASTDeclContextNameLookupTable *LookupTable =
Guy Benyei11169dd2012-12-18 14:30:41 +00006665 Info->second.NameLookupTableData;
6666 bool FoundAnything = false;
6667 for (ASTDeclContextNameLookupTable::data_iterator
Douglas Gregor5e306b12013-01-23 22:38:11 +00006668 I = LookupTable->data_begin(), E = LookupTable->data_end();
6669 I != E;
6670 ++I) {
Guy Benyei11169dd2012-12-18 14:30:41 +00006671 ASTDeclContextNameLookupTrait::data_type Data = *I;
6672 for (; Data.first != Data.second; ++Data.first) {
6673 NamedDecl *ND = This->Reader.GetLocalDeclAs<NamedDecl>(M,
6674 *Data.first);
6675 if (!ND)
6676 continue;
6677
6678 // Record this declaration.
6679 FoundAnything = true;
6680 This->Decls[ND->getDeclName()].push_back(ND);
6681 }
6682 }
6683
Argyrios Kyrtzidis2810e9d2012-12-19 22:21:18 +00006684 return FoundAnything && !This->VisitAll;
Guy Benyei11169dd2012-12-18 14:30:41 +00006685 }
6686 };
6687}
6688
6689void ASTReader::completeVisibleDeclsMap(const DeclContext *DC) {
6690 if (!DC->hasExternalVisibleStorage())
6691 return;
Craig Topper79be4cd2013-07-05 04:33:53 +00006692 DeclsMap Decls;
Guy Benyei11169dd2012-12-18 14:30:41 +00006693
6694 // Compute the declaration contexts we need to look into. Multiple such
6695 // declaration contexts occur when two declaration contexts from disjoint
6696 // modules get merged, e.g., when two namespaces with the same name are
6697 // independently defined in separate modules.
6698 SmallVector<const DeclContext *, 2> Contexts;
6699 Contexts.push_back(DC);
6700
6701 if (DC->isNamespace()) {
6702 MergedDeclsMap::iterator Merged
6703 = MergedDecls.find(const_cast<Decl *>(cast<Decl>(DC)));
6704 if (Merged != MergedDecls.end()) {
6705 for (unsigned I = 0, N = Merged->second.size(); I != N; ++I)
6706 Contexts.push_back(cast<DeclContext>(GetDecl(Merged->second[I])));
6707 }
6708 }
6709
Argyrios Kyrtzidis2810e9d2012-12-19 22:21:18 +00006710 DeclContextAllNamesVisitor Visitor(*this, Contexts, Decls,
6711 /*VisitAll=*/DC->isFileContext());
Guy Benyei11169dd2012-12-18 14:30:41 +00006712 ModuleMgr.visit(&DeclContextAllNamesVisitor::visit, &Visitor);
6713 ++NumVisibleDeclContextsRead;
6714
Craig Topper79be4cd2013-07-05 04:33:53 +00006715 for (DeclsMap::iterator I = Decls.begin(), E = Decls.end(); I != E; ++I) {
Guy Benyei11169dd2012-12-18 14:30:41 +00006716 SetExternalVisibleDeclsForName(DC, I->first, I->second);
6717 }
6718 const_cast<DeclContext *>(DC)->setHasExternalVisibleStorage(false);
6719}
6720
6721/// \brief Under non-PCH compilation the consumer receives the objc methods
6722/// before receiving the implementation, and codegen depends on this.
6723/// We simulate this by deserializing and passing to consumer the methods of the
6724/// implementation before passing the deserialized implementation decl.
6725static void PassObjCImplDeclToConsumer(ObjCImplDecl *ImplD,
6726 ASTConsumer *Consumer) {
6727 assert(ImplD && Consumer);
6728
Aaron Ballmanaff18c02014-03-13 19:03:34 +00006729 for (auto *I : ImplD->methods())
6730 Consumer->HandleInterestingDecl(DeclGroupRef(I));
Guy Benyei11169dd2012-12-18 14:30:41 +00006731
6732 Consumer->HandleInterestingDecl(DeclGroupRef(ImplD));
6733}
6734
6735void ASTReader::PassInterestingDeclsToConsumer() {
6736 assert(Consumer);
Richard Smith04d05b52014-03-23 00:27:18 +00006737
6738 if (PassingDeclsToConsumer)
6739 return;
6740
6741 // Guard variable to avoid recursively redoing the process of passing
6742 // decls to consumer.
6743 SaveAndRestore<bool> GuardPassingDeclsToConsumer(PassingDeclsToConsumer,
6744 true);
6745
Guy Benyei11169dd2012-12-18 14:30:41 +00006746 while (!InterestingDecls.empty()) {
6747 Decl *D = InterestingDecls.front();
6748 InterestingDecls.pop_front();
6749
6750 PassInterestingDeclToConsumer(D);
6751 }
6752}
6753
6754void ASTReader::PassInterestingDeclToConsumer(Decl *D) {
6755 if (ObjCImplDecl *ImplD = dyn_cast<ObjCImplDecl>(D))
6756 PassObjCImplDeclToConsumer(ImplD, Consumer);
6757 else
6758 Consumer->HandleInterestingDecl(DeclGroupRef(D));
6759}
6760
6761void ASTReader::StartTranslationUnit(ASTConsumer *Consumer) {
6762 this->Consumer = Consumer;
6763
6764 if (!Consumer)
6765 return;
6766
Ben Langmuir332aafe2014-01-31 01:06:56 +00006767 for (unsigned I = 0, N = EagerlyDeserializedDecls.size(); I != N; ++I) {
Guy Benyei11169dd2012-12-18 14:30:41 +00006768 // Force deserialization of this decl, which will cause it to be queued for
6769 // passing to the consumer.
Ben Langmuir332aafe2014-01-31 01:06:56 +00006770 GetDecl(EagerlyDeserializedDecls[I]);
Guy Benyei11169dd2012-12-18 14:30:41 +00006771 }
Ben Langmuir332aafe2014-01-31 01:06:56 +00006772 EagerlyDeserializedDecls.clear();
Guy Benyei11169dd2012-12-18 14:30:41 +00006773
6774 PassInterestingDeclsToConsumer();
6775}
6776
6777void ASTReader::PrintStats() {
6778 std::fprintf(stderr, "*** AST File Statistics:\n");
6779
6780 unsigned NumTypesLoaded
6781 = TypesLoaded.size() - std::count(TypesLoaded.begin(), TypesLoaded.end(),
6782 QualType());
6783 unsigned NumDeclsLoaded
6784 = DeclsLoaded.size() - std::count(DeclsLoaded.begin(), DeclsLoaded.end(),
Craig Toppera13603a2014-05-22 05:54:18 +00006785 (Decl *)nullptr);
Guy Benyei11169dd2012-12-18 14:30:41 +00006786 unsigned NumIdentifiersLoaded
6787 = IdentifiersLoaded.size() - std::count(IdentifiersLoaded.begin(),
6788 IdentifiersLoaded.end(),
Craig Toppera13603a2014-05-22 05:54:18 +00006789 (IdentifierInfo *)nullptr);
Guy Benyei11169dd2012-12-18 14:30:41 +00006790 unsigned NumMacrosLoaded
6791 = MacrosLoaded.size() - std::count(MacrosLoaded.begin(),
6792 MacrosLoaded.end(),
Craig Toppera13603a2014-05-22 05:54:18 +00006793 (MacroInfo *)nullptr);
Guy Benyei11169dd2012-12-18 14:30:41 +00006794 unsigned NumSelectorsLoaded
6795 = SelectorsLoaded.size() - std::count(SelectorsLoaded.begin(),
6796 SelectorsLoaded.end(),
6797 Selector());
6798
6799 if (unsigned TotalNumSLocEntries = getTotalNumSLocs())
6800 std::fprintf(stderr, " %u/%u source location entries read (%f%%)\n",
6801 NumSLocEntriesRead, TotalNumSLocEntries,
6802 ((float)NumSLocEntriesRead/TotalNumSLocEntries * 100));
6803 if (!TypesLoaded.empty())
6804 std::fprintf(stderr, " %u/%u types read (%f%%)\n",
6805 NumTypesLoaded, (unsigned)TypesLoaded.size(),
6806 ((float)NumTypesLoaded/TypesLoaded.size() * 100));
6807 if (!DeclsLoaded.empty())
6808 std::fprintf(stderr, " %u/%u declarations read (%f%%)\n",
6809 NumDeclsLoaded, (unsigned)DeclsLoaded.size(),
6810 ((float)NumDeclsLoaded/DeclsLoaded.size() * 100));
6811 if (!IdentifiersLoaded.empty())
6812 std::fprintf(stderr, " %u/%u identifiers read (%f%%)\n",
6813 NumIdentifiersLoaded, (unsigned)IdentifiersLoaded.size(),
6814 ((float)NumIdentifiersLoaded/IdentifiersLoaded.size() * 100));
6815 if (!MacrosLoaded.empty())
6816 std::fprintf(stderr, " %u/%u macros read (%f%%)\n",
6817 NumMacrosLoaded, (unsigned)MacrosLoaded.size(),
6818 ((float)NumMacrosLoaded/MacrosLoaded.size() * 100));
6819 if (!SelectorsLoaded.empty())
6820 std::fprintf(stderr, " %u/%u selectors read (%f%%)\n",
6821 NumSelectorsLoaded, (unsigned)SelectorsLoaded.size(),
6822 ((float)NumSelectorsLoaded/SelectorsLoaded.size() * 100));
6823 if (TotalNumStatements)
6824 std::fprintf(stderr, " %u/%u statements read (%f%%)\n",
6825 NumStatementsRead, TotalNumStatements,
6826 ((float)NumStatementsRead/TotalNumStatements * 100));
6827 if (TotalNumMacros)
6828 std::fprintf(stderr, " %u/%u macros read (%f%%)\n",
6829 NumMacrosRead, TotalNumMacros,
6830 ((float)NumMacrosRead/TotalNumMacros * 100));
6831 if (TotalLexicalDeclContexts)
6832 std::fprintf(stderr, " %u/%u lexical declcontexts read (%f%%)\n",
6833 NumLexicalDeclContextsRead, TotalLexicalDeclContexts,
6834 ((float)NumLexicalDeclContextsRead/TotalLexicalDeclContexts
6835 * 100));
6836 if (TotalVisibleDeclContexts)
6837 std::fprintf(stderr, " %u/%u visible declcontexts read (%f%%)\n",
6838 NumVisibleDeclContextsRead, TotalVisibleDeclContexts,
6839 ((float)NumVisibleDeclContextsRead/TotalVisibleDeclContexts
6840 * 100));
6841 if (TotalNumMethodPoolEntries) {
6842 std::fprintf(stderr, " %u/%u method pool entries read (%f%%)\n",
6843 NumMethodPoolEntriesRead, TotalNumMethodPoolEntries,
6844 ((float)NumMethodPoolEntriesRead/TotalNumMethodPoolEntries
6845 * 100));
Guy Benyei11169dd2012-12-18 14:30:41 +00006846 }
Douglas Gregorad2f7a52013-01-28 17:54:36 +00006847 if (NumMethodPoolLookups) {
6848 std::fprintf(stderr, " %u/%u method pool lookups succeeded (%f%%)\n",
6849 NumMethodPoolHits, NumMethodPoolLookups,
6850 ((float)NumMethodPoolHits/NumMethodPoolLookups * 100.0));
6851 }
6852 if (NumMethodPoolTableLookups) {
6853 std::fprintf(stderr, " %u/%u method pool table lookups succeeded (%f%%)\n",
6854 NumMethodPoolTableHits, NumMethodPoolTableLookups,
6855 ((float)NumMethodPoolTableHits/NumMethodPoolTableLookups
6856 * 100.0));
6857 }
6858
Douglas Gregor00a50f72013-01-25 00:38:33 +00006859 if (NumIdentifierLookupHits) {
6860 std::fprintf(stderr,
6861 " %u / %u identifier table lookups succeeded (%f%%)\n",
6862 NumIdentifierLookupHits, NumIdentifierLookups,
6863 (double)NumIdentifierLookupHits*100.0/NumIdentifierLookups);
6864 }
6865
Douglas Gregore060e572013-01-25 01:03:03 +00006866 if (GlobalIndex) {
6867 std::fprintf(stderr, "\n");
6868 GlobalIndex->printStats();
6869 }
6870
Guy Benyei11169dd2012-12-18 14:30:41 +00006871 std::fprintf(stderr, "\n");
6872 dump();
6873 std::fprintf(stderr, "\n");
6874}
6875
6876template<typename Key, typename ModuleFile, unsigned InitialCapacity>
6877static void
6878dumpModuleIDMap(StringRef Name,
6879 const ContinuousRangeMap<Key, ModuleFile *,
6880 InitialCapacity> &Map) {
6881 if (Map.begin() == Map.end())
6882 return;
6883
6884 typedef ContinuousRangeMap<Key, ModuleFile *, InitialCapacity> MapType;
6885 llvm::errs() << Name << ":\n";
6886 for (typename MapType::const_iterator I = Map.begin(), IEnd = Map.end();
6887 I != IEnd; ++I) {
6888 llvm::errs() << " " << I->first << " -> " << I->second->FileName
6889 << "\n";
6890 }
6891}
6892
6893void ASTReader::dump() {
6894 llvm::errs() << "*** PCH/ModuleFile Remappings:\n";
6895 dumpModuleIDMap("Global bit offset map", GlobalBitOffsetsMap);
6896 dumpModuleIDMap("Global source location entry map", GlobalSLocEntryMap);
6897 dumpModuleIDMap("Global type map", GlobalTypeMap);
6898 dumpModuleIDMap("Global declaration map", GlobalDeclMap);
6899 dumpModuleIDMap("Global identifier map", GlobalIdentifierMap);
6900 dumpModuleIDMap("Global macro map", GlobalMacroMap);
6901 dumpModuleIDMap("Global submodule map", GlobalSubmoduleMap);
6902 dumpModuleIDMap("Global selector map", GlobalSelectorMap);
6903 dumpModuleIDMap("Global preprocessed entity map",
6904 GlobalPreprocessedEntityMap);
6905
6906 llvm::errs() << "\n*** PCH/Modules Loaded:";
6907 for (ModuleManager::ModuleConstIterator M = ModuleMgr.begin(),
6908 MEnd = ModuleMgr.end();
6909 M != MEnd; ++M)
6910 (*M)->dump();
6911}
6912
6913/// Return the amount of memory used by memory buffers, breaking down
6914/// by heap-backed versus mmap'ed memory.
6915void ASTReader::getMemoryBufferSizes(MemoryBufferSizes &sizes) const {
6916 for (ModuleConstIterator I = ModuleMgr.begin(),
6917 E = ModuleMgr.end(); I != E; ++I) {
6918 if (llvm::MemoryBuffer *buf = (*I)->Buffer.get()) {
6919 size_t bytes = buf->getBufferSize();
6920 switch (buf->getBufferKind()) {
6921 case llvm::MemoryBuffer::MemoryBuffer_Malloc:
6922 sizes.malloc_bytes += bytes;
6923 break;
6924 case llvm::MemoryBuffer::MemoryBuffer_MMap:
6925 sizes.mmap_bytes += bytes;
6926 break;
6927 }
6928 }
6929 }
6930}
6931
6932void ASTReader::InitializeSema(Sema &S) {
6933 SemaObj = &S;
6934 S.addExternalSource(this);
6935
6936 // Makes sure any declarations that were deserialized "too early"
6937 // still get added to the identifier's declaration chains.
Ben Langmuir5418f402014-09-10 21:29:41 +00006938 for (uint64_t ID : PreloadedDeclIDs) {
6939 NamedDecl *D = cast<NamedDecl>(GetDecl(ID));
6940 pushExternalDeclIntoScope(D, D->getDeclName());
Guy Benyei11169dd2012-12-18 14:30:41 +00006941 }
Ben Langmuir5418f402014-09-10 21:29:41 +00006942 PreloadedDeclIDs.clear();
Guy Benyei11169dd2012-12-18 14:30:41 +00006943
Richard Smith3d8e97e2013-10-18 06:54:39 +00006944 // FIXME: What happens if these are changed by a module import?
Guy Benyei11169dd2012-12-18 14:30:41 +00006945 if (!FPPragmaOptions.empty()) {
6946 assert(FPPragmaOptions.size() == 1 && "Wrong number of FP_PRAGMA_OPTIONS");
6947 SemaObj->FPFeatures.fp_contract = FPPragmaOptions[0];
6948 }
6949
Richard Smith3d8e97e2013-10-18 06:54:39 +00006950 // FIXME: What happens if these are changed by a module import?
Guy Benyei11169dd2012-12-18 14:30:41 +00006951 if (!OpenCLExtensions.empty()) {
6952 unsigned I = 0;
6953#define OPENCLEXT(nm) SemaObj->OpenCLFeatures.nm = OpenCLExtensions[I++];
6954#include "clang/Basic/OpenCLExtensions.def"
6955
6956 assert(OpenCLExtensions.size() == I && "Wrong number of OPENCL_EXTENSIONS");
6957 }
Richard Smith3d8e97e2013-10-18 06:54:39 +00006958
6959 UpdateSema();
6960}
6961
6962void ASTReader::UpdateSema() {
6963 assert(SemaObj && "no Sema to update");
6964
6965 // Load the offsets of the declarations that Sema references.
6966 // They will be lazily deserialized when needed.
6967 if (!SemaDeclRefs.empty()) {
6968 assert(SemaDeclRefs.size() % 2 == 0);
6969 for (unsigned I = 0; I != SemaDeclRefs.size(); I += 2) {
6970 if (!SemaObj->StdNamespace)
6971 SemaObj->StdNamespace = SemaDeclRefs[I];
6972 if (!SemaObj->StdBadAlloc)
6973 SemaObj->StdBadAlloc = SemaDeclRefs[I+1];
6974 }
6975 SemaDeclRefs.clear();
6976 }
Dario Domizioli13a0a382014-05-23 12:13:25 +00006977
6978 // Update the state of 'pragma clang optimize'. Use the same API as if we had
6979 // encountered the pragma in the source.
6980 if(OptimizeOffPragmaLocation.isValid())
6981 SemaObj->ActOnPragmaOptimize(/* IsOn = */ false, OptimizeOffPragmaLocation);
Guy Benyei11169dd2012-12-18 14:30:41 +00006982}
6983
6984IdentifierInfo* ASTReader::get(const char *NameStart, const char *NameEnd) {
6985 // Note that we are loading an identifier.
6986 Deserializing AnIdentifier(this);
Douglas Gregore060e572013-01-25 01:03:03 +00006987 StringRef Name(NameStart, NameEnd - NameStart);
6988
6989 // If there is a global index, look there first to determine which modules
6990 // provably do not have any results for this identifier.
Douglas Gregor7211ac12013-01-25 23:32:03 +00006991 GlobalModuleIndex::HitSet Hits;
Craig Toppera13603a2014-05-22 05:54:18 +00006992 GlobalModuleIndex::HitSet *HitsPtr = nullptr;
Douglas Gregore060e572013-01-25 01:03:03 +00006993 if (!loadGlobalIndex()) {
Douglas Gregor7211ac12013-01-25 23:32:03 +00006994 if (GlobalIndex->lookupIdentifier(Name, Hits)) {
6995 HitsPtr = &Hits;
Douglas Gregore060e572013-01-25 01:03:03 +00006996 }
6997 }
Douglas Gregor7211ac12013-01-25 23:32:03 +00006998 IdentifierLookupVisitor Visitor(Name, /*PriorGeneration=*/0,
Douglas Gregor00a50f72013-01-25 00:38:33 +00006999 NumIdentifierLookups,
7000 NumIdentifierLookupHits);
Douglas Gregor7211ac12013-01-25 23:32:03 +00007001 ModuleMgr.visit(IdentifierLookupVisitor::visit, &Visitor, HitsPtr);
Guy Benyei11169dd2012-12-18 14:30:41 +00007002 IdentifierInfo *II = Visitor.getIdentifierInfo();
7003 markIdentifierUpToDate(II);
7004 return II;
7005}
7006
7007namespace clang {
7008 /// \brief An identifier-lookup iterator that enumerates all of the
7009 /// identifiers stored within a set of AST files.
7010 class ASTIdentifierIterator : public IdentifierIterator {
7011 /// \brief The AST reader whose identifiers are being enumerated.
7012 const ASTReader &Reader;
7013
7014 /// \brief The current index into the chain of AST files stored in
7015 /// the AST reader.
7016 unsigned Index;
7017
7018 /// \brief The current position within the identifier lookup table
7019 /// of the current AST file.
7020 ASTIdentifierLookupTable::key_iterator Current;
7021
7022 /// \brief The end position within the identifier lookup table of
7023 /// the current AST file.
7024 ASTIdentifierLookupTable::key_iterator End;
7025
7026 public:
7027 explicit ASTIdentifierIterator(const ASTReader &Reader);
7028
Craig Topper3e89dfe2014-03-13 02:13:41 +00007029 StringRef Next() override;
Guy Benyei11169dd2012-12-18 14:30:41 +00007030 };
7031}
7032
7033ASTIdentifierIterator::ASTIdentifierIterator(const ASTReader &Reader)
7034 : Reader(Reader), Index(Reader.ModuleMgr.size() - 1) {
7035 ASTIdentifierLookupTable *IdTable
7036 = (ASTIdentifierLookupTable *)Reader.ModuleMgr[Index].IdentifierLookupTable;
7037 Current = IdTable->key_begin();
7038 End = IdTable->key_end();
7039}
7040
7041StringRef ASTIdentifierIterator::Next() {
7042 while (Current == End) {
7043 // If we have exhausted all of our AST files, we're done.
7044 if (Index == 0)
7045 return StringRef();
7046
7047 --Index;
7048 ASTIdentifierLookupTable *IdTable
7049 = (ASTIdentifierLookupTable *)Reader.ModuleMgr[Index].
7050 IdentifierLookupTable;
7051 Current = IdTable->key_begin();
7052 End = IdTable->key_end();
7053 }
7054
7055 // We have any identifiers remaining in the current AST file; return
7056 // the next one.
Douglas Gregorbfd73d72013-01-23 18:53:14 +00007057 StringRef Result = *Current;
Guy Benyei11169dd2012-12-18 14:30:41 +00007058 ++Current;
Douglas Gregorbfd73d72013-01-23 18:53:14 +00007059 return Result;
Guy Benyei11169dd2012-12-18 14:30:41 +00007060}
7061
Argyrios Kyrtzidis9aca3c62013-04-17 22:10:55 +00007062IdentifierIterator *ASTReader::getIdentifiers() {
7063 if (!loadGlobalIndex())
7064 return GlobalIndex->createIdentifierIterator();
7065
Guy Benyei11169dd2012-12-18 14:30:41 +00007066 return new ASTIdentifierIterator(*this);
7067}
7068
7069namespace clang { namespace serialization {
7070 class ReadMethodPoolVisitor {
7071 ASTReader &Reader;
7072 Selector Sel;
7073 unsigned PriorGeneration;
Argyrios Kyrtzidisd3da6e02013-04-17 00:08:58 +00007074 unsigned InstanceBits;
7075 unsigned FactoryBits;
Dmitri Gribenkof8579502013-01-12 19:30:44 +00007076 SmallVector<ObjCMethodDecl *, 4> InstanceMethods;
7077 SmallVector<ObjCMethodDecl *, 4> FactoryMethods;
Guy Benyei11169dd2012-12-18 14:30:41 +00007078
7079 public:
7080 ReadMethodPoolVisitor(ASTReader &Reader, Selector Sel,
7081 unsigned PriorGeneration)
Argyrios Kyrtzidisd3da6e02013-04-17 00:08:58 +00007082 : Reader(Reader), Sel(Sel), PriorGeneration(PriorGeneration),
7083 InstanceBits(0), FactoryBits(0) { }
Guy Benyei11169dd2012-12-18 14:30:41 +00007084
7085 static bool visit(ModuleFile &M, void *UserData) {
7086 ReadMethodPoolVisitor *This
7087 = static_cast<ReadMethodPoolVisitor *>(UserData);
7088
7089 if (!M.SelectorLookupTable)
7090 return false;
7091
7092 // If we've already searched this module file, skip it now.
7093 if (M.Generation <= This->PriorGeneration)
7094 return true;
7095
Douglas Gregorad2f7a52013-01-28 17:54:36 +00007096 ++This->Reader.NumMethodPoolTableLookups;
Guy Benyei11169dd2012-12-18 14:30:41 +00007097 ASTSelectorLookupTable *PoolTable
7098 = (ASTSelectorLookupTable*)M.SelectorLookupTable;
7099 ASTSelectorLookupTable::iterator Pos = PoolTable->find(This->Sel);
7100 if (Pos == PoolTable->end())
7101 return false;
Douglas Gregorad2f7a52013-01-28 17:54:36 +00007102
7103 ++This->Reader.NumMethodPoolTableHits;
Guy Benyei11169dd2012-12-18 14:30:41 +00007104 ++This->Reader.NumSelectorsRead;
7105 // FIXME: Not quite happy with the statistics here. We probably should
7106 // disable this tracking when called via LoadSelector.
7107 // Also, should entries without methods count as misses?
7108 ++This->Reader.NumMethodPoolEntriesRead;
7109 ASTSelectorLookupTrait::data_type Data = *Pos;
7110 if (This->Reader.DeserializationListener)
7111 This->Reader.DeserializationListener->SelectorRead(Data.ID,
7112 This->Sel);
7113
7114 This->InstanceMethods.append(Data.Instance.begin(), Data.Instance.end());
7115 This->FactoryMethods.append(Data.Factory.begin(), Data.Factory.end());
Argyrios Kyrtzidisd3da6e02013-04-17 00:08:58 +00007116 This->InstanceBits = Data.InstanceBits;
7117 This->FactoryBits = Data.FactoryBits;
Guy Benyei11169dd2012-12-18 14:30:41 +00007118 return true;
7119 }
7120
7121 /// \brief Retrieve the instance methods found by this visitor.
7122 ArrayRef<ObjCMethodDecl *> getInstanceMethods() const {
7123 return InstanceMethods;
7124 }
7125
7126 /// \brief Retrieve the instance methods found by this visitor.
7127 ArrayRef<ObjCMethodDecl *> getFactoryMethods() const {
7128 return FactoryMethods;
7129 }
Argyrios Kyrtzidisd3da6e02013-04-17 00:08:58 +00007130
7131 unsigned getInstanceBits() const { return InstanceBits; }
7132 unsigned getFactoryBits() const { return FactoryBits; }
Guy Benyei11169dd2012-12-18 14:30:41 +00007133 };
7134} } // end namespace clang::serialization
7135
7136/// \brief Add the given set of methods to the method list.
7137static void addMethodsToPool(Sema &S, ArrayRef<ObjCMethodDecl *> Methods,
7138 ObjCMethodList &List) {
7139 for (unsigned I = 0, N = Methods.size(); I != N; ++I) {
7140 S.addMethodToGlobalList(&List, Methods[I]);
7141 }
7142}
7143
7144void ASTReader::ReadMethodPool(Selector Sel) {
7145 // Get the selector generation and update it to the current generation.
7146 unsigned &Generation = SelectorGeneration[Sel];
7147 unsigned PriorGeneration = Generation;
Richard Smith053f6c62014-05-16 23:01:30 +00007148 Generation = getGeneration();
Guy Benyei11169dd2012-12-18 14:30:41 +00007149
7150 // Search for methods defined with this selector.
Douglas Gregorad2f7a52013-01-28 17:54:36 +00007151 ++NumMethodPoolLookups;
Guy Benyei11169dd2012-12-18 14:30:41 +00007152 ReadMethodPoolVisitor Visitor(*this, Sel, PriorGeneration);
7153 ModuleMgr.visit(&ReadMethodPoolVisitor::visit, &Visitor);
7154
7155 if (Visitor.getInstanceMethods().empty() &&
Douglas Gregorad2f7a52013-01-28 17:54:36 +00007156 Visitor.getFactoryMethods().empty())
Guy Benyei11169dd2012-12-18 14:30:41 +00007157 return;
Douglas Gregorad2f7a52013-01-28 17:54:36 +00007158
7159 ++NumMethodPoolHits;
7160
Guy Benyei11169dd2012-12-18 14:30:41 +00007161 if (!getSema())
7162 return;
7163
7164 Sema &S = *getSema();
7165 Sema::GlobalMethodPool::iterator Pos
7166 = S.MethodPool.insert(std::make_pair(Sel, Sema::GlobalMethods())).first;
7167
7168 addMethodsToPool(S, Visitor.getInstanceMethods(), Pos->second.first);
7169 addMethodsToPool(S, Visitor.getFactoryMethods(), Pos->second.second);
Argyrios Kyrtzidisd3da6e02013-04-17 00:08:58 +00007170 Pos->second.first.setBits(Visitor.getInstanceBits());
7171 Pos->second.second.setBits(Visitor.getFactoryBits());
Guy Benyei11169dd2012-12-18 14:30:41 +00007172}
7173
7174void ASTReader::ReadKnownNamespaces(
7175 SmallVectorImpl<NamespaceDecl *> &Namespaces) {
7176 Namespaces.clear();
7177
7178 for (unsigned I = 0, N = KnownNamespaces.size(); I != N; ++I) {
7179 if (NamespaceDecl *Namespace
7180 = dyn_cast_or_null<NamespaceDecl>(GetDecl(KnownNamespaces[I])))
7181 Namespaces.push_back(Namespace);
7182 }
7183}
7184
Nick Lewycky9c7eb1d2013-02-01 08:13:20 +00007185void ASTReader::ReadUndefinedButUsed(
Nick Lewyckyf0f56162013-01-31 03:23:57 +00007186 llvm::DenseMap<NamedDecl*, SourceLocation> &Undefined) {
Nick Lewycky9c7eb1d2013-02-01 08:13:20 +00007187 for (unsigned Idx = 0, N = UndefinedButUsed.size(); Idx != N;) {
7188 NamedDecl *D = cast<NamedDecl>(GetDecl(UndefinedButUsed[Idx++]));
Nick Lewycky8334af82013-01-26 00:35:08 +00007189 SourceLocation Loc =
Nick Lewycky9c7eb1d2013-02-01 08:13:20 +00007190 SourceLocation::getFromRawEncoding(UndefinedButUsed[Idx++]);
Nick Lewycky8334af82013-01-26 00:35:08 +00007191 Undefined.insert(std::make_pair(D, Loc));
7192 }
7193}
Nick Lewycky8334af82013-01-26 00:35:08 +00007194
Guy Benyei11169dd2012-12-18 14:30:41 +00007195void ASTReader::ReadTentativeDefinitions(
7196 SmallVectorImpl<VarDecl *> &TentativeDefs) {
7197 for (unsigned I = 0, N = TentativeDefinitions.size(); I != N; ++I) {
7198 VarDecl *Var = dyn_cast_or_null<VarDecl>(GetDecl(TentativeDefinitions[I]));
7199 if (Var)
7200 TentativeDefs.push_back(Var);
7201 }
7202 TentativeDefinitions.clear();
7203}
7204
7205void ASTReader::ReadUnusedFileScopedDecls(
7206 SmallVectorImpl<const DeclaratorDecl *> &Decls) {
7207 for (unsigned I = 0, N = UnusedFileScopedDecls.size(); I != N; ++I) {
7208 DeclaratorDecl *D
7209 = dyn_cast_or_null<DeclaratorDecl>(GetDecl(UnusedFileScopedDecls[I]));
7210 if (D)
7211 Decls.push_back(D);
7212 }
7213 UnusedFileScopedDecls.clear();
7214}
7215
7216void ASTReader::ReadDelegatingConstructors(
7217 SmallVectorImpl<CXXConstructorDecl *> &Decls) {
7218 for (unsigned I = 0, N = DelegatingCtorDecls.size(); I != N; ++I) {
7219 CXXConstructorDecl *D
7220 = dyn_cast_or_null<CXXConstructorDecl>(GetDecl(DelegatingCtorDecls[I]));
7221 if (D)
7222 Decls.push_back(D);
7223 }
7224 DelegatingCtorDecls.clear();
7225}
7226
7227void ASTReader::ReadExtVectorDecls(SmallVectorImpl<TypedefNameDecl *> &Decls) {
7228 for (unsigned I = 0, N = ExtVectorDecls.size(); I != N; ++I) {
7229 TypedefNameDecl *D
7230 = dyn_cast_or_null<TypedefNameDecl>(GetDecl(ExtVectorDecls[I]));
7231 if (D)
7232 Decls.push_back(D);
7233 }
7234 ExtVectorDecls.clear();
7235}
7236
7237void ASTReader::ReadDynamicClasses(SmallVectorImpl<CXXRecordDecl *> &Decls) {
7238 for (unsigned I = 0, N = DynamicClasses.size(); I != N; ++I) {
7239 CXXRecordDecl *D
7240 = dyn_cast_or_null<CXXRecordDecl>(GetDecl(DynamicClasses[I]));
7241 if (D)
7242 Decls.push_back(D);
7243 }
7244 DynamicClasses.clear();
7245}
7246
Nico Weber72889432014-09-06 01:25:55 +00007247void ASTReader::ReadUnusedLocalTypedefNameCandidates(
7248 llvm::SmallSetVector<const TypedefNameDecl *, 4> &Decls) {
7249 for (unsigned I = 0, N = UnusedLocalTypedefNameCandidates.size(); I != N;
7250 ++I) {
7251 TypedefNameDecl *D = dyn_cast_or_null<TypedefNameDecl>(
7252 GetDecl(UnusedLocalTypedefNameCandidates[I]));
7253 if (D)
7254 Decls.insert(D);
7255 }
7256 UnusedLocalTypedefNameCandidates.clear();
7257}
7258
Guy Benyei11169dd2012-12-18 14:30:41 +00007259void
Richard Smith78165b52013-01-10 23:43:47 +00007260ASTReader::ReadLocallyScopedExternCDecls(SmallVectorImpl<NamedDecl *> &Decls) {
7261 for (unsigned I = 0, N = LocallyScopedExternCDecls.size(); I != N; ++I) {
7262 NamedDecl *D
7263 = dyn_cast_or_null<NamedDecl>(GetDecl(LocallyScopedExternCDecls[I]));
Guy Benyei11169dd2012-12-18 14:30:41 +00007264 if (D)
7265 Decls.push_back(D);
7266 }
Richard Smith78165b52013-01-10 23:43:47 +00007267 LocallyScopedExternCDecls.clear();
Guy Benyei11169dd2012-12-18 14:30:41 +00007268}
7269
7270void ASTReader::ReadReferencedSelectors(
7271 SmallVectorImpl<std::pair<Selector, SourceLocation> > &Sels) {
7272 if (ReferencedSelectorsData.empty())
7273 return;
7274
7275 // If there are @selector references added them to its pool. This is for
7276 // implementation of -Wselector.
7277 unsigned int DataSize = ReferencedSelectorsData.size()-1;
7278 unsigned I = 0;
7279 while (I < DataSize) {
7280 Selector Sel = DecodeSelector(ReferencedSelectorsData[I++]);
7281 SourceLocation SelLoc
7282 = SourceLocation::getFromRawEncoding(ReferencedSelectorsData[I++]);
7283 Sels.push_back(std::make_pair(Sel, SelLoc));
7284 }
7285 ReferencedSelectorsData.clear();
7286}
7287
7288void ASTReader::ReadWeakUndeclaredIdentifiers(
7289 SmallVectorImpl<std::pair<IdentifierInfo *, WeakInfo> > &WeakIDs) {
7290 if (WeakUndeclaredIdentifiers.empty())
7291 return;
7292
7293 for (unsigned I = 0, N = WeakUndeclaredIdentifiers.size(); I < N; /*none*/) {
7294 IdentifierInfo *WeakId
7295 = DecodeIdentifierInfo(WeakUndeclaredIdentifiers[I++]);
7296 IdentifierInfo *AliasId
7297 = DecodeIdentifierInfo(WeakUndeclaredIdentifiers[I++]);
7298 SourceLocation Loc
7299 = SourceLocation::getFromRawEncoding(WeakUndeclaredIdentifiers[I++]);
7300 bool Used = WeakUndeclaredIdentifiers[I++];
7301 WeakInfo WI(AliasId, Loc);
7302 WI.setUsed(Used);
7303 WeakIDs.push_back(std::make_pair(WeakId, WI));
7304 }
7305 WeakUndeclaredIdentifiers.clear();
7306}
7307
7308void ASTReader::ReadUsedVTables(SmallVectorImpl<ExternalVTableUse> &VTables) {
7309 for (unsigned Idx = 0, N = VTableUses.size(); Idx < N; /* In loop */) {
7310 ExternalVTableUse VT;
7311 VT.Record = dyn_cast_or_null<CXXRecordDecl>(GetDecl(VTableUses[Idx++]));
7312 VT.Location = SourceLocation::getFromRawEncoding(VTableUses[Idx++]);
7313 VT.DefinitionRequired = VTableUses[Idx++];
7314 VTables.push_back(VT);
7315 }
7316
7317 VTableUses.clear();
7318}
7319
7320void ASTReader::ReadPendingInstantiations(
7321 SmallVectorImpl<std::pair<ValueDecl *, SourceLocation> > &Pending) {
7322 for (unsigned Idx = 0, N = PendingInstantiations.size(); Idx < N;) {
7323 ValueDecl *D = cast<ValueDecl>(GetDecl(PendingInstantiations[Idx++]));
7324 SourceLocation Loc
7325 = SourceLocation::getFromRawEncoding(PendingInstantiations[Idx++]);
7326
7327 Pending.push_back(std::make_pair(D, Loc));
7328 }
7329 PendingInstantiations.clear();
7330}
7331
Richard Smithe40f2ba2013-08-07 21:41:30 +00007332void ASTReader::ReadLateParsedTemplates(
7333 llvm::DenseMap<const FunctionDecl *, LateParsedTemplate *> &LPTMap) {
7334 for (unsigned Idx = 0, N = LateParsedTemplates.size(); Idx < N;
7335 /* In loop */) {
7336 FunctionDecl *FD = cast<FunctionDecl>(GetDecl(LateParsedTemplates[Idx++]));
7337
7338 LateParsedTemplate *LT = new LateParsedTemplate;
7339 LT->D = GetDecl(LateParsedTemplates[Idx++]);
7340
7341 ModuleFile *F = getOwningModuleFile(LT->D);
7342 assert(F && "No module");
7343
7344 unsigned TokN = LateParsedTemplates[Idx++];
7345 LT->Toks.reserve(TokN);
7346 for (unsigned T = 0; T < TokN; ++T)
7347 LT->Toks.push_back(ReadToken(*F, LateParsedTemplates, Idx));
7348
7349 LPTMap[FD] = LT;
7350 }
7351
7352 LateParsedTemplates.clear();
7353}
7354
Guy Benyei11169dd2012-12-18 14:30:41 +00007355void ASTReader::LoadSelector(Selector Sel) {
7356 // It would be complicated to avoid reading the methods anyway. So don't.
7357 ReadMethodPool(Sel);
7358}
7359
7360void ASTReader::SetIdentifierInfo(IdentifierID ID, IdentifierInfo *II) {
7361 assert(ID && "Non-zero identifier ID required");
7362 assert(ID <= IdentifiersLoaded.size() && "identifier ID out of range");
7363 IdentifiersLoaded[ID - 1] = II;
7364 if (DeserializationListener)
7365 DeserializationListener->IdentifierRead(ID, II);
7366}
7367
7368/// \brief Set the globally-visible declarations associated with the given
7369/// identifier.
7370///
7371/// If the AST reader is currently in a state where the given declaration IDs
7372/// cannot safely be resolved, they are queued until it is safe to resolve
7373/// them.
7374///
7375/// \param II an IdentifierInfo that refers to one or more globally-visible
7376/// declarations.
7377///
7378/// \param DeclIDs the set of declaration IDs with the name @p II that are
7379/// visible at global scope.
7380///
Douglas Gregor6168bd22013-02-18 15:53:43 +00007381/// \param Decls if non-null, this vector will be populated with the set of
7382/// deserialized declarations. These declarations will not be pushed into
7383/// scope.
Guy Benyei11169dd2012-12-18 14:30:41 +00007384void
7385ASTReader::SetGloballyVisibleDecls(IdentifierInfo *II,
7386 const SmallVectorImpl<uint32_t> &DeclIDs,
Douglas Gregor6168bd22013-02-18 15:53:43 +00007387 SmallVectorImpl<Decl *> *Decls) {
7388 if (NumCurrentElementsDeserializing && !Decls) {
7389 PendingIdentifierInfos[II].append(DeclIDs.begin(), DeclIDs.end());
Guy Benyei11169dd2012-12-18 14:30:41 +00007390 return;
7391 }
7392
7393 for (unsigned I = 0, N = DeclIDs.size(); I != N; ++I) {
Ben Langmuir5418f402014-09-10 21:29:41 +00007394 if (!SemaObj) {
Guy Benyei11169dd2012-12-18 14:30:41 +00007395 // Queue this declaration so that it will be added to the
7396 // translation unit scope and identifier's declaration chain
7397 // once a Sema object is known.
Ben Langmuir5418f402014-09-10 21:29:41 +00007398 PreloadedDeclIDs.push_back(DeclIDs[I]);
7399 continue;
Guy Benyei11169dd2012-12-18 14:30:41 +00007400 }
Ben Langmuir5418f402014-09-10 21:29:41 +00007401
7402 NamedDecl *D = cast<NamedDecl>(GetDecl(DeclIDs[I]));
7403
7404 // If we're simply supposed to record the declarations, do so now.
7405 if (Decls) {
7406 Decls->push_back(D);
7407 continue;
7408 }
7409
7410 // Introduce this declaration into the translation-unit scope
7411 // and add it to the declaration chain for this identifier, so
7412 // that (unqualified) name lookup will find it.
7413 pushExternalDeclIntoScope(D, II);
Guy Benyei11169dd2012-12-18 14:30:41 +00007414 }
7415}
7416
Douglas Gregorc8a992f2013-01-21 16:52:34 +00007417IdentifierInfo *ASTReader::DecodeIdentifierInfo(IdentifierID ID) {
Guy Benyei11169dd2012-12-18 14:30:41 +00007418 if (ID == 0)
Craig Toppera13603a2014-05-22 05:54:18 +00007419 return nullptr;
Guy Benyei11169dd2012-12-18 14:30:41 +00007420
7421 if (IdentifiersLoaded.empty()) {
7422 Error("no identifier table in AST file");
Craig Toppera13603a2014-05-22 05:54:18 +00007423 return nullptr;
Guy Benyei11169dd2012-12-18 14:30:41 +00007424 }
7425
7426 ID -= 1;
7427 if (!IdentifiersLoaded[ID]) {
7428 GlobalIdentifierMapType::iterator I = GlobalIdentifierMap.find(ID + 1);
7429 assert(I != GlobalIdentifierMap.end() && "Corrupted global identifier map");
7430 ModuleFile *M = I->second;
7431 unsigned Index = ID - M->BaseIdentifierID;
7432 const char *Str = M->IdentifierTableData + M->IdentifierOffsets[Index];
7433
7434 // All of the strings in the AST file are preceded by a 16-bit length.
7435 // Extract that 16-bit length to avoid having to execute strlen().
7436 // NOTE: 'StrLenPtr' is an 'unsigned char*' so that we load bytes as
7437 // unsigned integers. This is important to avoid integer overflow when
7438 // we cast them to 'unsigned'.
7439 const unsigned char *StrLenPtr = (const unsigned char*) Str - 2;
7440 unsigned StrLen = (((unsigned) StrLenPtr[0])
7441 | (((unsigned) StrLenPtr[1]) << 8)) - 1;
Douglas Gregorc8a992f2013-01-21 16:52:34 +00007442 IdentifiersLoaded[ID]
7443 = &PP.getIdentifierTable().get(StringRef(Str, StrLen));
Guy Benyei11169dd2012-12-18 14:30:41 +00007444 if (DeserializationListener)
7445 DeserializationListener->IdentifierRead(ID + 1, IdentifiersLoaded[ID]);
7446 }
7447
7448 return IdentifiersLoaded[ID];
7449}
7450
Douglas Gregorc8a992f2013-01-21 16:52:34 +00007451IdentifierInfo *ASTReader::getLocalIdentifier(ModuleFile &M, unsigned LocalID) {
7452 return DecodeIdentifierInfo(getGlobalIdentifierID(M, LocalID));
Guy Benyei11169dd2012-12-18 14:30:41 +00007453}
7454
7455IdentifierID ASTReader::getGlobalIdentifierID(ModuleFile &M, unsigned LocalID) {
7456 if (LocalID < NUM_PREDEF_IDENT_IDS)
7457 return LocalID;
7458
7459 ContinuousRangeMap<uint32_t, int, 2>::iterator I
7460 = M.IdentifierRemap.find(LocalID - NUM_PREDEF_IDENT_IDS);
7461 assert(I != M.IdentifierRemap.end()
7462 && "Invalid index into identifier index remap");
7463
7464 return LocalID + I->second;
7465}
7466
Argyrios Kyrtzidiseb663da2013-03-22 21:12:57 +00007467MacroInfo *ASTReader::getMacro(MacroID ID) {
Guy Benyei11169dd2012-12-18 14:30:41 +00007468 if (ID == 0)
Craig Toppera13603a2014-05-22 05:54:18 +00007469 return nullptr;
Guy Benyei11169dd2012-12-18 14:30:41 +00007470
7471 if (MacrosLoaded.empty()) {
7472 Error("no macro table in AST file");
Craig Toppera13603a2014-05-22 05:54:18 +00007473 return nullptr;
Guy Benyei11169dd2012-12-18 14:30:41 +00007474 }
7475
7476 ID -= NUM_PREDEF_MACRO_IDS;
7477 if (!MacrosLoaded[ID]) {
7478 GlobalMacroMapType::iterator I
7479 = GlobalMacroMap.find(ID + NUM_PREDEF_MACRO_IDS);
7480 assert(I != GlobalMacroMap.end() && "Corrupted global macro map");
7481 ModuleFile *M = I->second;
7482 unsigned Index = ID - M->BaseMacroID;
Argyrios Kyrtzidiseb663da2013-03-22 21:12:57 +00007483 MacrosLoaded[ID] = ReadMacroRecord(*M, M->MacroOffsets[Index]);
7484
7485 if (DeserializationListener)
7486 DeserializationListener->MacroRead(ID + NUM_PREDEF_MACRO_IDS,
7487 MacrosLoaded[ID]);
Guy Benyei11169dd2012-12-18 14:30:41 +00007488 }
7489
7490 return MacrosLoaded[ID];
7491}
7492
7493MacroID ASTReader::getGlobalMacroID(ModuleFile &M, unsigned LocalID) {
7494 if (LocalID < NUM_PREDEF_MACRO_IDS)
7495 return LocalID;
7496
7497 ContinuousRangeMap<uint32_t, int, 2>::iterator I
7498 = M.MacroRemap.find(LocalID - NUM_PREDEF_MACRO_IDS);
7499 assert(I != M.MacroRemap.end() && "Invalid index into macro index remap");
7500
7501 return LocalID + I->second;
7502}
7503
7504serialization::SubmoduleID
7505ASTReader::getGlobalSubmoduleID(ModuleFile &M, unsigned LocalID) {
7506 if (LocalID < NUM_PREDEF_SUBMODULE_IDS)
7507 return LocalID;
7508
7509 ContinuousRangeMap<uint32_t, int, 2>::iterator I
7510 = M.SubmoduleRemap.find(LocalID - NUM_PREDEF_SUBMODULE_IDS);
7511 assert(I != M.SubmoduleRemap.end()
7512 && "Invalid index into submodule index remap");
7513
7514 return LocalID + I->second;
7515}
7516
7517Module *ASTReader::getSubmodule(SubmoduleID GlobalID) {
7518 if (GlobalID < NUM_PREDEF_SUBMODULE_IDS) {
7519 assert(GlobalID == 0 && "Unhandled global submodule ID");
Craig Toppera13603a2014-05-22 05:54:18 +00007520 return nullptr;
Guy Benyei11169dd2012-12-18 14:30:41 +00007521 }
7522
7523 if (GlobalID > SubmodulesLoaded.size()) {
7524 Error("submodule ID out of range in AST file");
Craig Toppera13603a2014-05-22 05:54:18 +00007525 return nullptr;
Guy Benyei11169dd2012-12-18 14:30:41 +00007526 }
7527
7528 return SubmodulesLoaded[GlobalID - NUM_PREDEF_SUBMODULE_IDS];
7529}
Douglas Gregorc147b0b2013-01-12 01:29:50 +00007530
7531Module *ASTReader::getModule(unsigned ID) {
7532 return getSubmodule(ID);
7533}
7534
Guy Benyei11169dd2012-12-18 14:30:41 +00007535Selector ASTReader::getLocalSelector(ModuleFile &M, unsigned LocalID) {
7536 return DecodeSelector(getGlobalSelectorID(M, LocalID));
7537}
7538
7539Selector ASTReader::DecodeSelector(serialization::SelectorID ID) {
7540 if (ID == 0)
7541 return Selector();
7542
7543 if (ID > SelectorsLoaded.size()) {
7544 Error("selector ID out of range in AST file");
7545 return Selector();
7546 }
7547
Craig Toppera13603a2014-05-22 05:54:18 +00007548 if (SelectorsLoaded[ID - 1].getAsOpaquePtr() == nullptr) {
Guy Benyei11169dd2012-12-18 14:30:41 +00007549 // Load this selector from the selector table.
7550 GlobalSelectorMapType::iterator I = GlobalSelectorMap.find(ID);
7551 assert(I != GlobalSelectorMap.end() && "Corrupted global selector map");
7552 ModuleFile &M = *I->second;
7553 ASTSelectorLookupTrait Trait(*this, M);
7554 unsigned Idx = ID - M.BaseSelectorID - NUM_PREDEF_SELECTOR_IDS;
7555 SelectorsLoaded[ID - 1] =
7556 Trait.ReadKey(M.SelectorLookupTableData + M.SelectorOffsets[Idx], 0);
7557 if (DeserializationListener)
7558 DeserializationListener->SelectorRead(ID, SelectorsLoaded[ID - 1]);
7559 }
7560
7561 return SelectorsLoaded[ID - 1];
7562}
7563
7564Selector ASTReader::GetExternalSelector(serialization::SelectorID ID) {
7565 return DecodeSelector(ID);
7566}
7567
7568uint32_t ASTReader::GetNumExternalSelectors() {
7569 // ID 0 (the null selector) is considered an external selector.
7570 return getTotalNumSelectors() + 1;
7571}
7572
7573serialization::SelectorID
7574ASTReader::getGlobalSelectorID(ModuleFile &M, unsigned LocalID) const {
7575 if (LocalID < NUM_PREDEF_SELECTOR_IDS)
7576 return LocalID;
7577
7578 ContinuousRangeMap<uint32_t, int, 2>::iterator I
7579 = M.SelectorRemap.find(LocalID - NUM_PREDEF_SELECTOR_IDS);
7580 assert(I != M.SelectorRemap.end()
7581 && "Invalid index into selector index remap");
7582
7583 return LocalID + I->second;
7584}
7585
7586DeclarationName
7587ASTReader::ReadDeclarationName(ModuleFile &F,
7588 const RecordData &Record, unsigned &Idx) {
7589 DeclarationName::NameKind Kind = (DeclarationName::NameKind)Record[Idx++];
7590 switch (Kind) {
7591 case DeclarationName::Identifier:
Douglas Gregorc8a992f2013-01-21 16:52:34 +00007592 return DeclarationName(GetIdentifierInfo(F, Record, Idx));
Guy Benyei11169dd2012-12-18 14:30:41 +00007593
7594 case DeclarationName::ObjCZeroArgSelector:
7595 case DeclarationName::ObjCOneArgSelector:
7596 case DeclarationName::ObjCMultiArgSelector:
7597 return DeclarationName(ReadSelector(F, Record, Idx));
7598
7599 case DeclarationName::CXXConstructorName:
7600 return Context.DeclarationNames.getCXXConstructorName(
7601 Context.getCanonicalType(readType(F, Record, Idx)));
7602
7603 case DeclarationName::CXXDestructorName:
7604 return Context.DeclarationNames.getCXXDestructorName(
7605 Context.getCanonicalType(readType(F, Record, Idx)));
7606
7607 case DeclarationName::CXXConversionFunctionName:
7608 return Context.DeclarationNames.getCXXConversionFunctionName(
7609 Context.getCanonicalType(readType(F, Record, Idx)));
7610
7611 case DeclarationName::CXXOperatorName:
7612 return Context.DeclarationNames.getCXXOperatorName(
7613 (OverloadedOperatorKind)Record[Idx++]);
7614
7615 case DeclarationName::CXXLiteralOperatorName:
7616 return Context.DeclarationNames.getCXXLiteralOperatorName(
7617 GetIdentifierInfo(F, Record, Idx));
7618
7619 case DeclarationName::CXXUsingDirective:
7620 return DeclarationName::getUsingDirectiveName();
7621 }
7622
7623 llvm_unreachable("Invalid NameKind!");
7624}
7625
7626void ASTReader::ReadDeclarationNameLoc(ModuleFile &F,
7627 DeclarationNameLoc &DNLoc,
7628 DeclarationName Name,
7629 const RecordData &Record, unsigned &Idx) {
7630 switch (Name.getNameKind()) {
7631 case DeclarationName::CXXConstructorName:
7632 case DeclarationName::CXXDestructorName:
7633 case DeclarationName::CXXConversionFunctionName:
7634 DNLoc.NamedType.TInfo = GetTypeSourceInfo(F, Record, Idx);
7635 break;
7636
7637 case DeclarationName::CXXOperatorName:
7638 DNLoc.CXXOperatorName.BeginOpNameLoc
7639 = ReadSourceLocation(F, Record, Idx).getRawEncoding();
7640 DNLoc.CXXOperatorName.EndOpNameLoc
7641 = ReadSourceLocation(F, Record, Idx).getRawEncoding();
7642 break;
7643
7644 case DeclarationName::CXXLiteralOperatorName:
7645 DNLoc.CXXLiteralOperatorName.OpNameLoc
7646 = ReadSourceLocation(F, Record, Idx).getRawEncoding();
7647 break;
7648
7649 case DeclarationName::Identifier:
7650 case DeclarationName::ObjCZeroArgSelector:
7651 case DeclarationName::ObjCOneArgSelector:
7652 case DeclarationName::ObjCMultiArgSelector:
7653 case DeclarationName::CXXUsingDirective:
7654 break;
7655 }
7656}
7657
7658void ASTReader::ReadDeclarationNameInfo(ModuleFile &F,
7659 DeclarationNameInfo &NameInfo,
7660 const RecordData &Record, unsigned &Idx) {
7661 NameInfo.setName(ReadDeclarationName(F, Record, Idx));
7662 NameInfo.setLoc(ReadSourceLocation(F, Record, Idx));
7663 DeclarationNameLoc DNLoc;
7664 ReadDeclarationNameLoc(F, DNLoc, NameInfo.getName(), Record, Idx);
7665 NameInfo.setInfo(DNLoc);
7666}
7667
7668void ASTReader::ReadQualifierInfo(ModuleFile &F, QualifierInfo &Info,
7669 const RecordData &Record, unsigned &Idx) {
7670 Info.QualifierLoc = ReadNestedNameSpecifierLoc(F, Record, Idx);
7671 unsigned NumTPLists = Record[Idx++];
7672 Info.NumTemplParamLists = NumTPLists;
7673 if (NumTPLists) {
7674 Info.TemplParamLists = new (Context) TemplateParameterList*[NumTPLists];
7675 for (unsigned i=0; i != NumTPLists; ++i)
7676 Info.TemplParamLists[i] = ReadTemplateParameterList(F, Record, Idx);
7677 }
7678}
7679
7680TemplateName
7681ASTReader::ReadTemplateName(ModuleFile &F, const RecordData &Record,
7682 unsigned &Idx) {
7683 TemplateName::NameKind Kind = (TemplateName::NameKind)Record[Idx++];
7684 switch (Kind) {
7685 case TemplateName::Template:
7686 return TemplateName(ReadDeclAs<TemplateDecl>(F, Record, Idx));
7687
7688 case TemplateName::OverloadedTemplate: {
7689 unsigned size = Record[Idx++];
7690 UnresolvedSet<8> Decls;
7691 while (size--)
7692 Decls.addDecl(ReadDeclAs<NamedDecl>(F, Record, Idx));
7693
7694 return Context.getOverloadedTemplateName(Decls.begin(), Decls.end());
7695 }
7696
7697 case TemplateName::QualifiedTemplate: {
7698 NestedNameSpecifier *NNS = ReadNestedNameSpecifier(F, Record, Idx);
7699 bool hasTemplKeyword = Record[Idx++];
7700 TemplateDecl *Template = ReadDeclAs<TemplateDecl>(F, Record, Idx);
7701 return Context.getQualifiedTemplateName(NNS, hasTemplKeyword, Template);
7702 }
7703
7704 case TemplateName::DependentTemplate: {
7705 NestedNameSpecifier *NNS = ReadNestedNameSpecifier(F, Record, Idx);
7706 if (Record[Idx++]) // isIdentifier
7707 return Context.getDependentTemplateName(NNS,
7708 GetIdentifierInfo(F, Record,
7709 Idx));
7710 return Context.getDependentTemplateName(NNS,
7711 (OverloadedOperatorKind)Record[Idx++]);
7712 }
7713
7714 case TemplateName::SubstTemplateTemplateParm: {
7715 TemplateTemplateParmDecl *param
7716 = ReadDeclAs<TemplateTemplateParmDecl>(F, Record, Idx);
7717 if (!param) return TemplateName();
7718 TemplateName replacement = ReadTemplateName(F, Record, Idx);
7719 return Context.getSubstTemplateTemplateParm(param, replacement);
7720 }
7721
7722 case TemplateName::SubstTemplateTemplateParmPack: {
7723 TemplateTemplateParmDecl *Param
7724 = ReadDeclAs<TemplateTemplateParmDecl>(F, Record, Idx);
7725 if (!Param)
7726 return TemplateName();
7727
7728 TemplateArgument ArgPack = ReadTemplateArgument(F, Record, Idx);
7729 if (ArgPack.getKind() != TemplateArgument::Pack)
7730 return TemplateName();
7731
7732 return Context.getSubstTemplateTemplateParmPack(Param, ArgPack);
7733 }
7734 }
7735
7736 llvm_unreachable("Unhandled template name kind!");
7737}
7738
7739TemplateArgument
7740ASTReader::ReadTemplateArgument(ModuleFile &F,
7741 const RecordData &Record, unsigned &Idx) {
7742 TemplateArgument::ArgKind Kind = (TemplateArgument::ArgKind)Record[Idx++];
7743 switch (Kind) {
7744 case TemplateArgument::Null:
7745 return TemplateArgument();
7746 case TemplateArgument::Type:
7747 return TemplateArgument(readType(F, Record, Idx));
7748 case TemplateArgument::Declaration: {
7749 ValueDecl *D = ReadDeclAs<ValueDecl>(F, Record, Idx);
David Blaikie0f62c8d2014-10-16 04:21:25 +00007750 return TemplateArgument(D, readType(F, Record, Idx));
Guy Benyei11169dd2012-12-18 14:30:41 +00007751 }
7752 case TemplateArgument::NullPtr:
7753 return TemplateArgument(readType(F, Record, Idx), /*isNullPtr*/true);
7754 case TemplateArgument::Integral: {
7755 llvm::APSInt Value = ReadAPSInt(Record, Idx);
7756 QualType T = readType(F, Record, Idx);
7757 return TemplateArgument(Context, Value, T);
7758 }
7759 case TemplateArgument::Template:
7760 return TemplateArgument(ReadTemplateName(F, Record, Idx));
7761 case TemplateArgument::TemplateExpansion: {
7762 TemplateName Name = ReadTemplateName(F, Record, Idx);
David Blaikie05785d12013-02-20 22:23:23 +00007763 Optional<unsigned> NumTemplateExpansions;
Guy Benyei11169dd2012-12-18 14:30:41 +00007764 if (unsigned NumExpansions = Record[Idx++])
7765 NumTemplateExpansions = NumExpansions - 1;
7766 return TemplateArgument(Name, NumTemplateExpansions);
7767 }
7768 case TemplateArgument::Expression:
7769 return TemplateArgument(ReadExpr(F));
7770 case TemplateArgument::Pack: {
7771 unsigned NumArgs = Record[Idx++];
7772 TemplateArgument *Args = new (Context) TemplateArgument[NumArgs];
7773 for (unsigned I = 0; I != NumArgs; ++I)
7774 Args[I] = ReadTemplateArgument(F, Record, Idx);
7775 return TemplateArgument(Args, NumArgs);
7776 }
7777 }
7778
7779 llvm_unreachable("Unhandled template argument kind!");
7780}
7781
7782TemplateParameterList *
7783ASTReader::ReadTemplateParameterList(ModuleFile &F,
7784 const RecordData &Record, unsigned &Idx) {
7785 SourceLocation TemplateLoc = ReadSourceLocation(F, Record, Idx);
7786 SourceLocation LAngleLoc = ReadSourceLocation(F, Record, Idx);
7787 SourceLocation RAngleLoc = ReadSourceLocation(F, Record, Idx);
7788
7789 unsigned NumParams = Record[Idx++];
7790 SmallVector<NamedDecl *, 16> Params;
7791 Params.reserve(NumParams);
7792 while (NumParams--)
7793 Params.push_back(ReadDeclAs<NamedDecl>(F, Record, Idx));
7794
7795 TemplateParameterList* TemplateParams =
7796 TemplateParameterList::Create(Context, TemplateLoc, LAngleLoc,
7797 Params.data(), Params.size(), RAngleLoc);
7798 return TemplateParams;
7799}
7800
7801void
7802ASTReader::
Craig Topper5603df42013-07-05 19:34:19 +00007803ReadTemplateArgumentList(SmallVectorImpl<TemplateArgument> &TemplArgs,
Guy Benyei11169dd2012-12-18 14:30:41 +00007804 ModuleFile &F, const RecordData &Record,
7805 unsigned &Idx) {
7806 unsigned NumTemplateArgs = Record[Idx++];
7807 TemplArgs.reserve(NumTemplateArgs);
7808 while (NumTemplateArgs--)
7809 TemplArgs.push_back(ReadTemplateArgument(F, Record, Idx));
7810}
7811
7812/// \brief Read a UnresolvedSet structure.
Richard Smitha4ba74c2013-08-30 04:46:40 +00007813void ASTReader::ReadUnresolvedSet(ModuleFile &F, LazyASTUnresolvedSet &Set,
Guy Benyei11169dd2012-12-18 14:30:41 +00007814 const RecordData &Record, unsigned &Idx) {
7815 unsigned NumDecls = Record[Idx++];
7816 Set.reserve(Context, NumDecls);
7817 while (NumDecls--) {
Richard Smitha4ba74c2013-08-30 04:46:40 +00007818 DeclID ID = ReadDeclID(F, Record, Idx);
Guy Benyei11169dd2012-12-18 14:30:41 +00007819 AccessSpecifier AS = (AccessSpecifier)Record[Idx++];
Richard Smitha4ba74c2013-08-30 04:46:40 +00007820 Set.addLazyDecl(Context, ID, AS);
Guy Benyei11169dd2012-12-18 14:30:41 +00007821 }
7822}
7823
7824CXXBaseSpecifier
7825ASTReader::ReadCXXBaseSpecifier(ModuleFile &F,
7826 const RecordData &Record, unsigned &Idx) {
7827 bool isVirtual = static_cast<bool>(Record[Idx++]);
7828 bool isBaseOfClass = static_cast<bool>(Record[Idx++]);
7829 AccessSpecifier AS = static_cast<AccessSpecifier>(Record[Idx++]);
7830 bool inheritConstructors = static_cast<bool>(Record[Idx++]);
7831 TypeSourceInfo *TInfo = GetTypeSourceInfo(F, Record, Idx);
7832 SourceRange Range = ReadSourceRange(F, Record, Idx);
7833 SourceLocation EllipsisLoc = ReadSourceLocation(F, Record, Idx);
7834 CXXBaseSpecifier Result(Range, isVirtual, isBaseOfClass, AS, TInfo,
7835 EllipsisLoc);
7836 Result.setInheritConstructors(inheritConstructors);
7837 return Result;
7838}
7839
7840std::pair<CXXCtorInitializer **, unsigned>
7841ASTReader::ReadCXXCtorInitializers(ModuleFile &F, const RecordData &Record,
7842 unsigned &Idx) {
Craig Toppera13603a2014-05-22 05:54:18 +00007843 CXXCtorInitializer **CtorInitializers = nullptr;
Guy Benyei11169dd2012-12-18 14:30:41 +00007844 unsigned NumInitializers = Record[Idx++];
7845 if (NumInitializers) {
7846 CtorInitializers
7847 = new (Context) CXXCtorInitializer*[NumInitializers];
7848 for (unsigned i=0; i != NumInitializers; ++i) {
Craig Toppera13603a2014-05-22 05:54:18 +00007849 TypeSourceInfo *TInfo = nullptr;
Guy Benyei11169dd2012-12-18 14:30:41 +00007850 bool IsBaseVirtual = false;
Craig Toppera13603a2014-05-22 05:54:18 +00007851 FieldDecl *Member = nullptr;
7852 IndirectFieldDecl *IndirectMember = nullptr;
Guy Benyei11169dd2012-12-18 14:30:41 +00007853
7854 CtorInitializerType Type = (CtorInitializerType)Record[Idx++];
7855 switch (Type) {
7856 case CTOR_INITIALIZER_BASE:
7857 TInfo = GetTypeSourceInfo(F, Record, Idx);
7858 IsBaseVirtual = Record[Idx++];
7859 break;
7860
7861 case CTOR_INITIALIZER_DELEGATING:
7862 TInfo = GetTypeSourceInfo(F, Record, Idx);
7863 break;
7864
7865 case CTOR_INITIALIZER_MEMBER:
7866 Member = ReadDeclAs<FieldDecl>(F, Record, Idx);
7867 break;
7868
7869 case CTOR_INITIALIZER_INDIRECT_MEMBER:
7870 IndirectMember = ReadDeclAs<IndirectFieldDecl>(F, Record, Idx);
7871 break;
7872 }
7873
7874 SourceLocation MemberOrEllipsisLoc = ReadSourceLocation(F, Record, Idx);
7875 Expr *Init = ReadExpr(F);
7876 SourceLocation LParenLoc = ReadSourceLocation(F, Record, Idx);
7877 SourceLocation RParenLoc = ReadSourceLocation(F, Record, Idx);
7878 bool IsWritten = Record[Idx++];
7879 unsigned SourceOrderOrNumArrayIndices;
7880 SmallVector<VarDecl *, 8> Indices;
7881 if (IsWritten) {
7882 SourceOrderOrNumArrayIndices = Record[Idx++];
7883 } else {
7884 SourceOrderOrNumArrayIndices = Record[Idx++];
7885 Indices.reserve(SourceOrderOrNumArrayIndices);
7886 for (unsigned i=0; i != SourceOrderOrNumArrayIndices; ++i)
7887 Indices.push_back(ReadDeclAs<VarDecl>(F, Record, Idx));
7888 }
7889
7890 CXXCtorInitializer *BOMInit;
7891 if (Type == CTOR_INITIALIZER_BASE) {
7892 BOMInit = new (Context) CXXCtorInitializer(Context, TInfo, IsBaseVirtual,
7893 LParenLoc, Init, RParenLoc,
7894 MemberOrEllipsisLoc);
7895 } else if (Type == CTOR_INITIALIZER_DELEGATING) {
7896 BOMInit = new (Context) CXXCtorInitializer(Context, TInfo, LParenLoc,
7897 Init, RParenLoc);
7898 } else if (IsWritten) {
7899 if (Member)
7900 BOMInit = new (Context) CXXCtorInitializer(Context, Member, MemberOrEllipsisLoc,
7901 LParenLoc, Init, RParenLoc);
7902 else
7903 BOMInit = new (Context) CXXCtorInitializer(Context, IndirectMember,
7904 MemberOrEllipsisLoc, LParenLoc,
7905 Init, RParenLoc);
7906 } else {
Argyrios Kyrtzidis794671d2013-05-30 23:59:46 +00007907 if (IndirectMember) {
7908 assert(Indices.empty() && "Indirect field improperly initialized");
7909 BOMInit = new (Context) CXXCtorInitializer(Context, IndirectMember,
7910 MemberOrEllipsisLoc, LParenLoc,
7911 Init, RParenLoc);
7912 } else {
7913 BOMInit = CXXCtorInitializer::Create(Context, Member, MemberOrEllipsisLoc,
7914 LParenLoc, Init, RParenLoc,
7915 Indices.data(), Indices.size());
7916 }
Guy Benyei11169dd2012-12-18 14:30:41 +00007917 }
7918
7919 if (IsWritten)
7920 BOMInit->setSourceOrder(SourceOrderOrNumArrayIndices);
7921 CtorInitializers[i] = BOMInit;
7922 }
7923 }
7924
7925 return std::make_pair(CtorInitializers, NumInitializers);
7926}
7927
7928NestedNameSpecifier *
7929ASTReader::ReadNestedNameSpecifier(ModuleFile &F,
7930 const RecordData &Record, unsigned &Idx) {
7931 unsigned N = Record[Idx++];
Craig Toppera13603a2014-05-22 05:54:18 +00007932 NestedNameSpecifier *NNS = nullptr, *Prev = nullptr;
Guy Benyei11169dd2012-12-18 14:30:41 +00007933 for (unsigned I = 0; I != N; ++I) {
7934 NestedNameSpecifier::SpecifierKind Kind
7935 = (NestedNameSpecifier::SpecifierKind)Record[Idx++];
7936 switch (Kind) {
7937 case NestedNameSpecifier::Identifier: {
7938 IdentifierInfo *II = GetIdentifierInfo(F, Record, Idx);
7939 NNS = NestedNameSpecifier::Create(Context, Prev, II);
7940 break;
7941 }
7942
7943 case NestedNameSpecifier::Namespace: {
7944 NamespaceDecl *NS = ReadDeclAs<NamespaceDecl>(F, Record, Idx);
7945 NNS = NestedNameSpecifier::Create(Context, Prev, NS);
7946 break;
7947 }
7948
7949 case NestedNameSpecifier::NamespaceAlias: {
7950 NamespaceAliasDecl *Alias =ReadDeclAs<NamespaceAliasDecl>(F, Record, Idx);
7951 NNS = NestedNameSpecifier::Create(Context, Prev, Alias);
7952 break;
7953 }
7954
7955 case NestedNameSpecifier::TypeSpec:
7956 case NestedNameSpecifier::TypeSpecWithTemplate: {
7957 const Type *T = readType(F, Record, Idx).getTypePtrOrNull();
7958 if (!T)
Craig Toppera13603a2014-05-22 05:54:18 +00007959 return nullptr;
7960
Guy Benyei11169dd2012-12-18 14:30:41 +00007961 bool Template = Record[Idx++];
7962 NNS = NestedNameSpecifier::Create(Context, Prev, Template, T);
7963 break;
7964 }
7965
7966 case NestedNameSpecifier::Global: {
7967 NNS = NestedNameSpecifier::GlobalSpecifier(Context);
7968 // No associated value, and there can't be a prefix.
7969 break;
7970 }
Nikola Smiljanic67860242014-09-26 00:28:20 +00007971
7972 case NestedNameSpecifier::Super: {
7973 CXXRecordDecl *RD = ReadDeclAs<CXXRecordDecl>(F, Record, Idx);
7974 NNS = NestedNameSpecifier::SuperSpecifier(Context, RD);
7975 break;
7976 }
Guy Benyei11169dd2012-12-18 14:30:41 +00007977 }
7978 Prev = NNS;
7979 }
7980 return NNS;
7981}
7982
7983NestedNameSpecifierLoc
7984ASTReader::ReadNestedNameSpecifierLoc(ModuleFile &F, const RecordData &Record,
7985 unsigned &Idx) {
7986 unsigned N = Record[Idx++];
7987 NestedNameSpecifierLocBuilder Builder;
7988 for (unsigned I = 0; I != N; ++I) {
7989 NestedNameSpecifier::SpecifierKind Kind
7990 = (NestedNameSpecifier::SpecifierKind)Record[Idx++];
7991 switch (Kind) {
7992 case NestedNameSpecifier::Identifier: {
7993 IdentifierInfo *II = GetIdentifierInfo(F, Record, Idx);
7994 SourceRange Range = ReadSourceRange(F, Record, Idx);
7995 Builder.Extend(Context, II, Range.getBegin(), Range.getEnd());
7996 break;
7997 }
7998
7999 case NestedNameSpecifier::Namespace: {
8000 NamespaceDecl *NS = ReadDeclAs<NamespaceDecl>(F, Record, Idx);
8001 SourceRange Range = ReadSourceRange(F, Record, Idx);
8002 Builder.Extend(Context, NS, Range.getBegin(), Range.getEnd());
8003 break;
8004 }
8005
8006 case NestedNameSpecifier::NamespaceAlias: {
8007 NamespaceAliasDecl *Alias =ReadDeclAs<NamespaceAliasDecl>(F, Record, Idx);
8008 SourceRange Range = ReadSourceRange(F, Record, Idx);
8009 Builder.Extend(Context, Alias, Range.getBegin(), Range.getEnd());
8010 break;
8011 }
8012
8013 case NestedNameSpecifier::TypeSpec:
8014 case NestedNameSpecifier::TypeSpecWithTemplate: {
8015 bool Template = Record[Idx++];
8016 TypeSourceInfo *T = GetTypeSourceInfo(F, Record, Idx);
8017 if (!T)
8018 return NestedNameSpecifierLoc();
8019 SourceLocation ColonColonLoc = ReadSourceLocation(F, Record, Idx);
8020
8021 // FIXME: 'template' keyword location not saved anywhere, so we fake it.
8022 Builder.Extend(Context,
8023 Template? T->getTypeLoc().getBeginLoc() : SourceLocation(),
8024 T->getTypeLoc(), ColonColonLoc);
8025 break;
8026 }
8027
8028 case NestedNameSpecifier::Global: {
8029 SourceLocation ColonColonLoc = ReadSourceLocation(F, Record, Idx);
8030 Builder.MakeGlobal(Context, ColonColonLoc);
8031 break;
8032 }
Nikola Smiljanic67860242014-09-26 00:28:20 +00008033
8034 case NestedNameSpecifier::Super: {
8035 CXXRecordDecl *RD = ReadDeclAs<CXXRecordDecl>(F, Record, Idx);
8036 SourceRange Range = ReadSourceRange(F, Record, Idx);
8037 Builder.MakeSuper(Context, RD, Range.getBegin(), Range.getEnd());
8038 break;
8039 }
Guy Benyei11169dd2012-12-18 14:30:41 +00008040 }
8041 }
Nikola Smiljanic67860242014-09-26 00:28:20 +00008042
Guy Benyei11169dd2012-12-18 14:30:41 +00008043 return Builder.getWithLocInContext(Context);
8044}
8045
8046SourceRange
8047ASTReader::ReadSourceRange(ModuleFile &F, const RecordData &Record,
8048 unsigned &Idx) {
8049 SourceLocation beg = ReadSourceLocation(F, Record, Idx);
8050 SourceLocation end = ReadSourceLocation(F, Record, Idx);
8051 return SourceRange(beg, end);
8052}
8053
8054/// \brief Read an integral value
8055llvm::APInt ASTReader::ReadAPInt(const RecordData &Record, unsigned &Idx) {
8056 unsigned BitWidth = Record[Idx++];
8057 unsigned NumWords = llvm::APInt::getNumWords(BitWidth);
8058 llvm::APInt Result(BitWidth, NumWords, &Record[Idx]);
8059 Idx += NumWords;
8060 return Result;
8061}
8062
8063/// \brief Read a signed integral value
8064llvm::APSInt ASTReader::ReadAPSInt(const RecordData &Record, unsigned &Idx) {
8065 bool isUnsigned = Record[Idx++];
8066 return llvm::APSInt(ReadAPInt(Record, Idx), isUnsigned);
8067}
8068
8069/// \brief Read a floating-point value
Tim Northover178723a2013-01-22 09:46:51 +00008070llvm::APFloat ASTReader::ReadAPFloat(const RecordData &Record,
8071 const llvm::fltSemantics &Sem,
8072 unsigned &Idx) {
8073 return llvm::APFloat(Sem, ReadAPInt(Record, Idx));
Guy Benyei11169dd2012-12-18 14:30:41 +00008074}
8075
8076// \brief Read a string
8077std::string ASTReader::ReadString(const RecordData &Record, unsigned &Idx) {
8078 unsigned Len = Record[Idx++];
8079 std::string Result(Record.data() + Idx, Record.data() + Idx + Len);
8080 Idx += Len;
8081 return Result;
8082}
8083
8084VersionTuple ASTReader::ReadVersionTuple(const RecordData &Record,
8085 unsigned &Idx) {
8086 unsigned Major = Record[Idx++];
8087 unsigned Minor = Record[Idx++];
8088 unsigned Subminor = Record[Idx++];
8089 if (Minor == 0)
8090 return VersionTuple(Major);
8091 if (Subminor == 0)
8092 return VersionTuple(Major, Minor - 1);
8093 return VersionTuple(Major, Minor - 1, Subminor - 1);
8094}
8095
8096CXXTemporary *ASTReader::ReadCXXTemporary(ModuleFile &F,
8097 const RecordData &Record,
8098 unsigned &Idx) {
8099 CXXDestructorDecl *Decl = ReadDeclAs<CXXDestructorDecl>(F, Record, Idx);
8100 return CXXTemporary::Create(Context, Decl);
8101}
8102
8103DiagnosticBuilder ASTReader::Diag(unsigned DiagID) {
Argyrios Kyrtzidisdc9fdaf2013-05-24 05:44:08 +00008104 return Diag(CurrentImportLoc, DiagID);
Guy Benyei11169dd2012-12-18 14:30:41 +00008105}
8106
8107DiagnosticBuilder ASTReader::Diag(SourceLocation Loc, unsigned DiagID) {
8108 return Diags.Report(Loc, DiagID);
8109}
8110
8111/// \brief Retrieve the identifier table associated with the
8112/// preprocessor.
8113IdentifierTable &ASTReader::getIdentifierTable() {
8114 return PP.getIdentifierTable();
8115}
8116
8117/// \brief Record that the given ID maps to the given switch-case
8118/// statement.
8119void ASTReader::RecordSwitchCaseID(SwitchCase *SC, unsigned ID) {
Craig Toppera13603a2014-05-22 05:54:18 +00008120 assert((*CurrSwitchCaseStmts)[ID] == nullptr &&
Guy Benyei11169dd2012-12-18 14:30:41 +00008121 "Already have a SwitchCase with this ID");
8122 (*CurrSwitchCaseStmts)[ID] = SC;
8123}
8124
8125/// \brief Retrieve the switch-case statement with the given ID.
8126SwitchCase *ASTReader::getSwitchCaseWithID(unsigned ID) {
Craig Toppera13603a2014-05-22 05:54:18 +00008127 assert((*CurrSwitchCaseStmts)[ID] != nullptr && "No SwitchCase with this ID");
Guy Benyei11169dd2012-12-18 14:30:41 +00008128 return (*CurrSwitchCaseStmts)[ID];
8129}
8130
8131void ASTReader::ClearSwitchCaseIDs() {
8132 CurrSwitchCaseStmts->clear();
8133}
8134
8135void ASTReader::ReadComments() {
8136 std::vector<RawComment *> Comments;
Chris Lattner7fb3bef2013-01-20 00:56:42 +00008137 for (SmallVectorImpl<std::pair<BitstreamCursor,
Guy Benyei11169dd2012-12-18 14:30:41 +00008138 serialization::ModuleFile *> >::iterator
8139 I = CommentsCursors.begin(),
8140 E = CommentsCursors.end();
8141 I != E; ++I) {
Dmitri Gribenko9ee0e302014-03-27 15:40:39 +00008142 Comments.clear();
Chris Lattner7fb3bef2013-01-20 00:56:42 +00008143 BitstreamCursor &Cursor = I->first;
Guy Benyei11169dd2012-12-18 14:30:41 +00008144 serialization::ModuleFile &F = *I->second;
8145 SavedStreamPosition SavedPosition(Cursor);
8146
8147 RecordData Record;
8148 while (true) {
Chris Lattner7fb3bef2013-01-20 00:56:42 +00008149 llvm::BitstreamEntry Entry =
8150 Cursor.advanceSkippingSubblocks(BitstreamCursor::AF_DontPopBlockAtEnd);
Dmitri Gribenko9ee0e302014-03-27 15:40:39 +00008151
Chris Lattner7fb3bef2013-01-20 00:56:42 +00008152 switch (Entry.Kind) {
8153 case llvm::BitstreamEntry::SubBlock: // Handled for us already.
8154 case llvm::BitstreamEntry::Error:
8155 Error("malformed block record in AST file");
8156 return;
8157 case llvm::BitstreamEntry::EndBlock:
8158 goto NextCursor;
8159 case llvm::BitstreamEntry::Record:
8160 // The interesting case.
Guy Benyei11169dd2012-12-18 14:30:41 +00008161 break;
Guy Benyei11169dd2012-12-18 14:30:41 +00008162 }
8163
8164 // Read a record.
8165 Record.clear();
Chris Lattner0e6c9402013-01-20 02:38:54 +00008166 switch ((CommentRecordTypes)Cursor.readRecord(Entry.ID, Record)) {
Guy Benyei11169dd2012-12-18 14:30:41 +00008167 case COMMENTS_RAW_COMMENT: {
8168 unsigned Idx = 0;
8169 SourceRange SR = ReadSourceRange(F, Record, Idx);
8170 RawComment::CommentKind Kind =
8171 (RawComment::CommentKind) Record[Idx++];
8172 bool IsTrailingComment = Record[Idx++];
8173 bool IsAlmostTrailingComment = Record[Idx++];
Dmitri Gribenkoa7d16ce2013-04-10 15:35:17 +00008174 Comments.push_back(new (Context) RawComment(
8175 SR, Kind, IsTrailingComment, IsAlmostTrailingComment,
8176 Context.getLangOpts().CommentOpts.ParseAllComments));
Guy Benyei11169dd2012-12-18 14:30:41 +00008177 break;
8178 }
8179 }
8180 }
Dmitri Gribenko9ee0e302014-03-27 15:40:39 +00008181 NextCursor:
8182 Context.Comments.addDeserializedComments(Comments);
Guy Benyei11169dd2012-12-18 14:30:41 +00008183 }
Guy Benyei11169dd2012-12-18 14:30:41 +00008184}
8185
Richard Smithcd45dbc2014-04-19 03:48:30 +00008186std::string ASTReader::getOwningModuleNameForDiagnostic(const Decl *D) {
8187 // If we know the owning module, use it.
8188 if (Module *M = D->getOwningModule())
8189 return M->getFullModuleName();
8190
8191 // Otherwise, use the name of the top-level module the decl is within.
8192 if (ModuleFile *M = getOwningModuleFile(D))
8193 return M->ModuleName;
8194
8195 // Not from a module.
8196 return "";
8197}
8198
Guy Benyei11169dd2012-12-18 14:30:41 +00008199void ASTReader::finishPendingActions() {
Richard Smith851072e2014-05-19 20:59:20 +00008200 while (!PendingIdentifierInfos.empty() ||
8201 !PendingIncompleteDeclChains.empty() || !PendingDeclChains.empty() ||
Richard Smith2b9e3e32013-10-18 06:05:18 +00008202 !PendingMacroIDs.empty() || !PendingDeclContextInfos.empty() ||
Richard Smitha0ce9c42014-07-29 23:23:27 +00008203 !PendingUpdateRecords.empty()) {
Guy Benyei11169dd2012-12-18 14:30:41 +00008204 // If any identifiers with corresponding top-level declarations have
8205 // been loaded, load those declarations now.
Craig Topper79be4cd2013-07-05 04:33:53 +00008206 typedef llvm::DenseMap<IdentifierInfo *, SmallVector<Decl *, 2> >
8207 TopLevelDeclsMap;
8208 TopLevelDeclsMap TopLevelDecls;
8209
Guy Benyei11169dd2012-12-18 14:30:41 +00008210 while (!PendingIdentifierInfos.empty()) {
Douglas Gregor6168bd22013-02-18 15:53:43 +00008211 IdentifierInfo *II = PendingIdentifierInfos.back().first;
Richard Smithf0ae3c2d2014-03-28 17:31:23 +00008212 SmallVector<uint32_t, 4> DeclIDs =
8213 std::move(PendingIdentifierInfos.back().second);
Douglas Gregorcb15f082013-02-19 18:26:28 +00008214 PendingIdentifierInfos.pop_back();
Douglas Gregor6168bd22013-02-18 15:53:43 +00008215
8216 SetGloballyVisibleDecls(II, DeclIDs, &TopLevelDecls[II]);
Guy Benyei11169dd2012-12-18 14:30:41 +00008217 }
Richard Smithf0ae3c2d2014-03-28 17:31:23 +00008218
Richard Smith851072e2014-05-19 20:59:20 +00008219 // For each decl chain that we wanted to complete while deserializing, mark
8220 // it as "still needs to be completed".
8221 for (unsigned I = 0; I != PendingIncompleteDeclChains.size(); ++I) {
8222 markIncompleteDeclChain(PendingIncompleteDeclChains[I]);
8223 }
8224 PendingIncompleteDeclChains.clear();
8225
Guy Benyei11169dd2012-12-18 14:30:41 +00008226 // Load pending declaration chains.
8227 for (unsigned I = 0; I != PendingDeclChains.size(); ++I) {
8228 loadPendingDeclChain(PendingDeclChains[I]);
8229 PendingDeclChainsKnown.erase(PendingDeclChains[I]);
8230 }
8231 PendingDeclChains.clear();
8232
Douglas Gregor6168bd22013-02-18 15:53:43 +00008233 // Make the most recent of the top-level declarations visible.
Craig Topper79be4cd2013-07-05 04:33:53 +00008234 for (TopLevelDeclsMap::iterator TLD = TopLevelDecls.begin(),
8235 TLDEnd = TopLevelDecls.end(); TLD != TLDEnd; ++TLD) {
Douglas Gregor6168bd22013-02-18 15:53:43 +00008236 IdentifierInfo *II = TLD->first;
8237 for (unsigned I = 0, N = TLD->second.size(); I != N; ++I) {
Argyrios Kyrtzidise5edbf92013-04-26 21:33:35 +00008238 pushExternalDeclIntoScope(cast<NamedDecl>(TLD->second[I]), II);
Douglas Gregor6168bd22013-02-18 15:53:43 +00008239 }
8240 }
8241
Guy Benyei11169dd2012-12-18 14:30:41 +00008242 // Load any pending macro definitions.
8243 for (unsigned I = 0; I != PendingMacroIDs.size(); ++I) {
Argyrios Kyrtzidiseb663da2013-03-22 21:12:57 +00008244 IdentifierInfo *II = PendingMacroIDs.begin()[I].first;
8245 SmallVector<PendingMacroInfo, 2> GlobalIDs;
8246 GlobalIDs.swap(PendingMacroIDs.begin()[I].second);
8247 // Initialize the macro history from chained-PCHs ahead of module imports.
Richard Smith49f906a2014-03-01 00:08:04 +00008248 for (unsigned IDIdx = 0, NumIDs = GlobalIDs.size(); IDIdx != NumIDs;
Argyrios Kyrtzidis719736c2013-01-19 03:14:56 +00008249 ++IDIdx) {
Argyrios Kyrtzidiseb663da2013-03-22 21:12:57 +00008250 const PendingMacroInfo &Info = GlobalIDs[IDIdx];
Richard Smithe842a472014-10-22 02:05:46 +00008251 if (Info.M->Kind != MK_ImplicitModule &&
8252 Info.M->Kind != MK_ExplicitModule)
Argyrios Kyrtzidiseb663da2013-03-22 21:12:57 +00008253 resolvePendingMacro(II, Info);
8254 }
8255 // Handle module imports.
Richard Smith49f906a2014-03-01 00:08:04 +00008256 for (unsigned IDIdx = 0, NumIDs = GlobalIDs.size(); IDIdx != NumIDs;
Argyrios Kyrtzidiseb663da2013-03-22 21:12:57 +00008257 ++IDIdx) {
8258 const PendingMacroInfo &Info = GlobalIDs[IDIdx];
Richard Smithe842a472014-10-22 02:05:46 +00008259 if (Info.M->Kind == MK_ImplicitModule ||
8260 Info.M->Kind == MK_ExplicitModule)
Argyrios Kyrtzidiseb663da2013-03-22 21:12:57 +00008261 resolvePendingMacro(II, Info);
Guy Benyei11169dd2012-12-18 14:30:41 +00008262 }
8263 }
8264 PendingMacroIDs.clear();
Argyrios Kyrtzidis83a6e3b2013-02-16 00:48:59 +00008265
8266 // Wire up the DeclContexts for Decls that we delayed setting until
8267 // recursive loading is completed.
8268 while (!PendingDeclContextInfos.empty()) {
8269 PendingDeclContextInfo Info = PendingDeclContextInfos.front();
8270 PendingDeclContextInfos.pop_front();
8271 DeclContext *SemaDC = cast<DeclContext>(GetDecl(Info.SemaDC));
8272 DeclContext *LexicalDC = cast<DeclContext>(GetDecl(Info.LexicalDC));
8273 Info.D->setDeclContextsImpl(SemaDC, LexicalDC, getContext());
8274 }
Richard Smith2b9e3e32013-10-18 06:05:18 +00008275
Richard Smithd1c46742014-04-30 02:24:17 +00008276 // Perform any pending declaration updates.
Richard Smithd6db68c2014-08-07 20:58:41 +00008277 while (!PendingUpdateRecords.empty()) {
Richard Smithd1c46742014-04-30 02:24:17 +00008278 auto Update = PendingUpdateRecords.pop_back_val();
8279 ReadingKindTracker ReadingKind(Read_Decl, *this);
8280 loadDeclUpdateRecords(Update.first, Update.second);
8281 }
Guy Benyei11169dd2012-12-18 14:30:41 +00008282 }
8283
8284 // If we deserialized any C++ or Objective-C class definitions, any
8285 // Objective-C protocol definitions, or any redeclarable templates, make sure
8286 // that all redeclarations point to the definitions. Note that this can only
8287 // happen now, after the redeclaration chains have been fully wired.
Craig Topperc6914d02014-08-25 04:15:02 +00008288 for (Decl *D : PendingDefinitions) {
8289 if (TagDecl *TD = dyn_cast<TagDecl>(D)) {
Richard Smith5b21db82014-04-23 18:20:42 +00008290 if (const TagType *TagT = dyn_cast<TagType>(TD->getTypeForDecl())) {
Guy Benyei11169dd2012-12-18 14:30:41 +00008291 // Make sure that the TagType points at the definition.
8292 const_cast<TagType*>(TagT)->decl = TD;
8293 }
8294
Craig Topperc6914d02014-08-25 04:15:02 +00008295 if (auto RD = dyn_cast<CXXRecordDecl>(D)) {
Richard Smith2c381642014-08-27 23:11:59 +00008296 for (auto R : RD->redecls()) {
8297 assert((R == D) == R->isThisDeclarationADefinition() &&
8298 "declaration thinks it's the definition but it isn't");
Aaron Ballman86c93902014-03-06 23:45:36 +00008299 cast<CXXRecordDecl>(R)->DefinitionData = RD->DefinitionData;
Richard Smith2c381642014-08-27 23:11:59 +00008300 }
Guy Benyei11169dd2012-12-18 14:30:41 +00008301 }
8302
8303 continue;
8304 }
8305
Craig Topperc6914d02014-08-25 04:15:02 +00008306 if (auto ID = dyn_cast<ObjCInterfaceDecl>(D)) {
Guy Benyei11169dd2012-12-18 14:30:41 +00008307 // Make sure that the ObjCInterfaceType points at the definition.
8308 const_cast<ObjCInterfaceType *>(cast<ObjCInterfaceType>(ID->TypeForDecl))
8309 ->Decl = ID;
8310
Aaron Ballman86c93902014-03-06 23:45:36 +00008311 for (auto R : ID->redecls())
Guy Benyei11169dd2012-12-18 14:30:41 +00008312 R->Data = ID->Data;
8313
8314 continue;
8315 }
8316
Craig Topperc6914d02014-08-25 04:15:02 +00008317 if (auto PD = dyn_cast<ObjCProtocolDecl>(D)) {
Aaron Ballman86c93902014-03-06 23:45:36 +00008318 for (auto R : PD->redecls())
Guy Benyei11169dd2012-12-18 14:30:41 +00008319 R->Data = PD->Data;
8320
8321 continue;
8322 }
8323
Craig Topperc6914d02014-08-25 04:15:02 +00008324 auto RTD = cast<RedeclarableTemplateDecl>(D)->getCanonicalDecl();
Aaron Ballman86c93902014-03-06 23:45:36 +00008325 for (auto R : RTD->redecls())
Guy Benyei11169dd2012-12-18 14:30:41 +00008326 R->Common = RTD->Common;
8327 }
8328 PendingDefinitions.clear();
8329
8330 // Load the bodies of any functions or methods we've encountered. We do
8331 // this now (delayed) so that we can be sure that the declaration chains
8332 // have been fully wired up.
8333 for (PendingBodiesMap::iterator PB = PendingBodies.begin(),
8334 PBEnd = PendingBodies.end();
8335 PB != PBEnd; ++PB) {
8336 if (FunctionDecl *FD = dyn_cast<FunctionDecl>(PB->first)) {
8337 // FIXME: Check for =delete/=default?
8338 // FIXME: Complain about ODR violations here?
8339 if (!getContext().getLangOpts().Modules || !FD->hasBody())
8340 FD->setLazyBody(PB->second);
8341 continue;
8342 }
8343
8344 ObjCMethodDecl *MD = cast<ObjCMethodDecl>(PB->first);
8345 if (!getContext().getLangOpts().Modules || !MD->hasBody())
8346 MD->setLazyBody(PB->second);
8347 }
8348 PendingBodies.clear();
Richard Smitha0ce9c42014-07-29 23:23:27 +00008349}
8350
8351void ASTReader::diagnoseOdrViolations() {
Richard Smithbb853c72014-08-13 01:23:33 +00008352 if (PendingOdrMergeFailures.empty() && PendingOdrMergeChecks.empty())
8353 return;
8354
Richard Smitha0ce9c42014-07-29 23:23:27 +00008355 // Trigger the import of the full definition of each class that had any
8356 // odr-merging problems, so we can produce better diagnostics for them.
Richard Smithbb853c72014-08-13 01:23:33 +00008357 // These updates may in turn find and diagnose some ODR failures, so take
8358 // ownership of the set first.
8359 auto OdrMergeFailures = std::move(PendingOdrMergeFailures);
8360 PendingOdrMergeFailures.clear();
8361 for (auto &Merge : OdrMergeFailures) {
Richard Smitha0ce9c42014-07-29 23:23:27 +00008362 Merge.first->buildLookup();
8363 Merge.first->decls_begin();
8364 Merge.first->bases_begin();
8365 Merge.first->vbases_begin();
8366 for (auto *RD : Merge.second) {
8367 RD->decls_begin();
8368 RD->bases_begin();
8369 RD->vbases_begin();
8370 }
8371 }
8372
8373 // For each declaration from a merged context, check that the canonical
8374 // definition of that context also contains a declaration of the same
8375 // entity.
8376 //
8377 // Caution: this loop does things that might invalidate iterators into
8378 // PendingOdrMergeChecks. Don't turn this into a range-based for loop!
8379 while (!PendingOdrMergeChecks.empty()) {
8380 NamedDecl *D = PendingOdrMergeChecks.pop_back_val();
8381
8382 // FIXME: Skip over implicit declarations for now. This matters for things
8383 // like implicitly-declared special member functions. This isn't entirely
8384 // correct; we can end up with multiple unmerged declarations of the same
8385 // implicit entity.
8386 if (D->isImplicit())
8387 continue;
8388
8389 DeclContext *CanonDef = D->getDeclContext();
Richard Smitha0ce9c42014-07-29 23:23:27 +00008390
8391 bool Found = false;
8392 const Decl *DCanon = D->getCanonicalDecl();
8393
Richard Smith01bdb7a2014-08-28 05:44:07 +00008394 for (auto RI : D->redecls()) {
8395 if (RI->getLexicalDeclContext() == CanonDef) {
8396 Found = true;
8397 break;
8398 }
8399 }
8400 if (Found)
8401 continue;
8402
Richard Smitha0ce9c42014-07-29 23:23:27 +00008403 llvm::SmallVector<const NamedDecl*, 4> Candidates;
Richard Smith01bdb7a2014-08-28 05:44:07 +00008404 DeclContext::lookup_result R = CanonDef->lookup(D->getDeclName());
Richard Smitha0ce9c42014-07-29 23:23:27 +00008405 for (DeclContext::lookup_iterator I = R.begin(), E = R.end();
8406 !Found && I != E; ++I) {
8407 for (auto RI : (*I)->redecls()) {
8408 if (RI->getLexicalDeclContext() == CanonDef) {
8409 // This declaration is present in the canonical definition. If it's
8410 // in the same redecl chain, it's the one we're looking for.
8411 if (RI->getCanonicalDecl() == DCanon)
8412 Found = true;
8413 else
8414 Candidates.push_back(cast<NamedDecl>(RI));
8415 break;
8416 }
8417 }
8418 }
8419
8420 if (!Found) {
Richard Smithd08aeb62014-08-28 01:33:39 +00008421 // The AST doesn't like TagDecls becoming invalid after they've been
8422 // completed. We only really need to mark FieldDecls as invalid here.
8423 if (!isa<TagDecl>(D))
8424 D->setInvalidDecl();
Richard Smitha0ce9c42014-07-29 23:23:27 +00008425
8426 std::string CanonDefModule =
8427 getOwningModuleNameForDiagnostic(cast<Decl>(CanonDef));
8428 Diag(D->getLocation(), diag::err_module_odr_violation_missing_decl)
8429 << D << getOwningModuleNameForDiagnostic(D)
8430 << CanonDef << CanonDefModule.empty() << CanonDefModule;
8431
8432 if (Candidates.empty())
8433 Diag(cast<Decl>(CanonDef)->getLocation(),
8434 diag::note_module_odr_violation_no_possible_decls) << D;
8435 else {
8436 for (unsigned I = 0, N = Candidates.size(); I != N; ++I)
8437 Diag(Candidates[I]->getLocation(),
8438 diag::note_module_odr_violation_possible_decl)
8439 << Candidates[I];
8440 }
8441
8442 DiagnosedOdrMergeFailures.insert(CanonDef);
8443 }
8444 }
Richard Smithcd45dbc2014-04-19 03:48:30 +00008445
8446 // Issue any pending ODR-failure diagnostics.
Richard Smithbb853c72014-08-13 01:23:33 +00008447 for (auto &Merge : OdrMergeFailures) {
Richard Smitha0ce9c42014-07-29 23:23:27 +00008448 // If we've already pointed out a specific problem with this class, don't
8449 // bother issuing a general "something's different" diagnostic.
Richard Smithcd45dbc2014-04-19 03:48:30 +00008450 if (!DiagnosedOdrMergeFailures.insert(Merge.first))
8451 continue;
8452
8453 bool Diagnosed = false;
8454 for (auto *RD : Merge.second) {
8455 // Multiple different declarations got merged together; tell the user
8456 // where they came from.
8457 if (Merge.first != RD) {
8458 // FIXME: Walk the definition, figure out what's different,
8459 // and diagnose that.
8460 if (!Diagnosed) {
8461 std::string Module = getOwningModuleNameForDiagnostic(Merge.first);
8462 Diag(Merge.first->getLocation(),
8463 diag::err_module_odr_violation_different_definitions)
8464 << Merge.first << Module.empty() << Module;
8465 Diagnosed = true;
8466 }
8467
8468 Diag(RD->getLocation(),
8469 diag::note_module_odr_violation_different_definitions)
8470 << getOwningModuleNameForDiagnostic(RD);
8471 }
8472 }
8473
8474 if (!Diagnosed) {
8475 // All definitions are updates to the same declaration. This happens if a
8476 // module instantiates the declaration of a class template specialization
8477 // and two or more other modules instantiate its definition.
8478 //
8479 // FIXME: Indicate which modules had instantiations of this definition.
8480 // FIXME: How can this even happen?
8481 Diag(Merge.first->getLocation(),
8482 diag::err_module_odr_violation_different_instantiations)
8483 << Merge.first;
8484 }
8485 }
Guy Benyei11169dd2012-12-18 14:30:41 +00008486}
8487
8488void ASTReader::FinishedDeserializing() {
8489 assert(NumCurrentElementsDeserializing &&
8490 "FinishedDeserializing not paired with StartedDeserializing");
8491 if (NumCurrentElementsDeserializing == 1) {
8492 // We decrease NumCurrentElementsDeserializing only after pending actions
8493 // are finished, to avoid recursively re-calling finishPendingActions().
8494 finishPendingActions();
8495 }
8496 --NumCurrentElementsDeserializing;
8497
Richard Smitha0ce9c42014-07-29 23:23:27 +00008498 if (NumCurrentElementsDeserializing == 0) {
8499 diagnoseOdrViolations();
8500
Richard Smith04d05b52014-03-23 00:27:18 +00008501 // We are not in recursive loading, so it's safe to pass the "interesting"
8502 // decls to the consumer.
Richard Smitha0ce9c42014-07-29 23:23:27 +00008503 if (Consumer)
8504 PassInterestingDeclsToConsumer();
Guy Benyei11169dd2012-12-18 14:30:41 +00008505 }
8506}
8507
Argyrios Kyrtzidise5edbf92013-04-26 21:33:35 +00008508void ASTReader::pushExternalDeclIntoScope(NamedDecl *D, DeclarationName Name) {
Rafael Espindola7b56f6c2013-10-19 16:55:03 +00008509 D = D->getMostRecentDecl();
Argyrios Kyrtzidise5edbf92013-04-26 21:33:35 +00008510
8511 if (SemaObj->IdResolver.tryAddTopLevelDecl(D, Name) && SemaObj->TUScope) {
8512 SemaObj->TUScope->AddDecl(D);
8513 } else if (SemaObj->TUScope) {
8514 // Adding the decl to IdResolver may have failed because it was already in
8515 // (even though it was not added in scope). If it is already in, make sure
8516 // it gets in the scope as well.
8517 if (std::find(SemaObj->IdResolver.begin(Name),
8518 SemaObj->IdResolver.end(), D) != SemaObj->IdResolver.end())
8519 SemaObj->TUScope->AddDecl(D);
8520 }
8521}
8522
Nico Weber824285e2014-05-08 04:26:47 +00008523ASTReader::ASTReader(Preprocessor &PP, ASTContext &Context, StringRef isysroot,
8524 bool DisableValidation, bool AllowASTWithCompilerErrors,
8525 bool AllowConfigurationMismatch, bool ValidateSystemInputs,
Ben Langmuir2cb4a782014-02-05 22:21:15 +00008526 bool UseGlobalIndex)
Craig Toppera13603a2014-05-22 05:54:18 +00008527 : Listener(new PCHValidator(PP, *this)), DeserializationListener(nullptr),
Nico Weber824285e2014-05-08 04:26:47 +00008528 OwnsDeserializationListener(false), SourceMgr(PP.getSourceManager()),
Craig Toppera13603a2014-05-22 05:54:18 +00008529 FileMgr(PP.getFileManager()), Diags(PP.getDiagnostics()),
8530 SemaObj(nullptr), PP(PP), Context(Context), Consumer(nullptr),
8531 ModuleMgr(PP.getFileManager()), isysroot(isysroot),
8532 DisableValidation(DisableValidation),
Nico Weber824285e2014-05-08 04:26:47 +00008533 AllowASTWithCompilerErrors(AllowASTWithCompilerErrors),
8534 AllowConfigurationMismatch(AllowConfigurationMismatch),
8535 ValidateSystemInputs(ValidateSystemInputs),
8536 UseGlobalIndex(UseGlobalIndex), TriedLoadingGlobalIndex(false),
Richard Smith053f6c62014-05-16 23:01:30 +00008537 CurrSwitchCaseStmts(&SwitchCaseStmts),
Nico Weber824285e2014-05-08 04:26:47 +00008538 NumSLocEntriesRead(0), TotalNumSLocEntries(0), NumStatementsRead(0),
8539 TotalNumStatements(0), NumMacrosRead(0), TotalNumMacros(0),
8540 NumIdentifierLookups(0), NumIdentifierLookupHits(0), NumSelectorsRead(0),
8541 NumMethodPoolEntriesRead(0), NumMethodPoolLookups(0),
8542 NumMethodPoolHits(0), NumMethodPoolTableLookups(0),
8543 NumMethodPoolTableHits(0), TotalNumMethodPoolEntries(0),
8544 NumLexicalDeclContextsRead(0), TotalLexicalDeclContexts(0),
8545 NumVisibleDeclContextsRead(0), TotalVisibleDeclContexts(0),
8546 TotalModulesSizeInBits(0), NumCurrentElementsDeserializing(0),
8547 PassingDeclsToConsumer(false), NumCXXBaseSpecifiersLoaded(0),
8548 ReadingKind(Read_None) {
Guy Benyei11169dd2012-12-18 14:30:41 +00008549 SourceMgr.setExternalSLocEntrySource(this);
8550}
8551
8552ASTReader::~ASTReader() {
Nico Weber824285e2014-05-08 04:26:47 +00008553 if (OwnsDeserializationListener)
8554 delete DeserializationListener;
8555
Guy Benyei11169dd2012-12-18 14:30:41 +00008556 for (DeclContextVisibleUpdatesPending::iterator
8557 I = PendingVisibleUpdates.begin(),
8558 E = PendingVisibleUpdates.end();
8559 I != E; ++I) {
8560 for (DeclContextVisibleUpdates::iterator J = I->second.begin(),
8561 F = I->second.end();
8562 J != F; ++J)
8563 delete J->first;
8564 }
8565}