blob: 419f6b3200870d795540e700b467a5331ee7f798 [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
392 // module import.
393 // 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];
399 if (TopImport->Kind != MK_Module)
400 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 \"";
546 SuggestedPredefines +=
547 HeaderSearch::NormalizeDashIncludePath(File, FileMgr);
548 SuggestedPredefines += "\"\n";
549 }
550
551 for (unsigned I = 0, N = ExistingPPOpts.MacroIncludes.size(); I != N; ++I) {
552 StringRef File = ExistingPPOpts.MacroIncludes[I];
553 if (std::find(PPOpts.MacroIncludes.begin(), PPOpts.MacroIncludes.end(),
554 File)
555 != PPOpts.MacroIncludes.end())
556 continue;
557
558 SuggestedPredefines += "#__include_macros \"";
559 SuggestedPredefines +=
560 HeaderSearch::NormalizeDashIncludePath(File, FileMgr);
561 SuggestedPredefines += "\"\n##\n";
562 }
563
564 return false;
565}
566
567bool PCHValidator::ReadPreprocessorOptions(const PreprocessorOptions &PPOpts,
568 bool Complain,
569 std::string &SuggestedPredefines) {
570 const PreprocessorOptions &ExistingPPOpts = PP.getPreprocessorOpts();
571
572 return checkPreprocessorOptions(PPOpts, ExistingPPOpts,
Craig Toppera13603a2014-05-22 05:54:18 +0000573 Complain? &Reader.Diags : nullptr,
Guy Benyei11169dd2012-12-18 14:30:41 +0000574 PP.getFileManager(),
Argyrios Kyrtzidisd3afa0c2013-04-26 21:33:40 +0000575 SuggestedPredefines,
576 PP.getLangOpts());
Guy Benyei11169dd2012-12-18 14:30:41 +0000577}
578
Guy Benyei11169dd2012-12-18 14:30:41 +0000579void PCHValidator::ReadCounter(const ModuleFile &M, unsigned Value) {
580 PP.setCounterValue(Value);
581}
582
583//===----------------------------------------------------------------------===//
584// AST reader implementation
585//===----------------------------------------------------------------------===//
586
Nico Weber824285e2014-05-08 04:26:47 +0000587void ASTReader::setDeserializationListener(ASTDeserializationListener *Listener,
588 bool TakeOwnership) {
Guy Benyei11169dd2012-12-18 14:30:41 +0000589 DeserializationListener = Listener;
Nico Weber824285e2014-05-08 04:26:47 +0000590 OwnsDeserializationListener = TakeOwnership;
Guy Benyei11169dd2012-12-18 14:30:41 +0000591}
592
593
594
595unsigned ASTSelectorLookupTrait::ComputeHash(Selector Sel) {
596 return serialization::ComputeHash(Sel);
597}
598
599
600std::pair<unsigned, unsigned>
601ASTSelectorLookupTrait::ReadKeyDataLength(const unsigned char*& d) {
Justin Bogner57ba0b22014-03-28 22:03:24 +0000602 using namespace llvm::support;
603 unsigned KeyLen = endian::readNext<uint16_t, little, unaligned>(d);
604 unsigned DataLen = endian::readNext<uint16_t, little, unaligned>(d);
Guy Benyei11169dd2012-12-18 14:30:41 +0000605 return std::make_pair(KeyLen, DataLen);
606}
607
608ASTSelectorLookupTrait::internal_key_type
609ASTSelectorLookupTrait::ReadKey(const unsigned char* d, unsigned) {
Justin Bogner57ba0b22014-03-28 22:03:24 +0000610 using namespace llvm::support;
Guy Benyei11169dd2012-12-18 14:30:41 +0000611 SelectorTable &SelTable = Reader.getContext().Selectors;
Justin Bogner57ba0b22014-03-28 22:03:24 +0000612 unsigned N = endian::readNext<uint16_t, little, unaligned>(d);
613 IdentifierInfo *FirstII = Reader.getLocalIdentifier(
614 F, endian::readNext<uint32_t, little, unaligned>(d));
Guy Benyei11169dd2012-12-18 14:30:41 +0000615 if (N == 0)
616 return SelTable.getNullarySelector(FirstII);
617 else if (N == 1)
618 return SelTable.getUnarySelector(FirstII);
619
620 SmallVector<IdentifierInfo *, 16> Args;
621 Args.push_back(FirstII);
622 for (unsigned I = 1; I != N; ++I)
Justin Bogner57ba0b22014-03-28 22:03:24 +0000623 Args.push_back(Reader.getLocalIdentifier(
624 F, endian::readNext<uint32_t, little, unaligned>(d)));
Guy Benyei11169dd2012-12-18 14:30:41 +0000625
626 return SelTable.getSelector(N, Args.data());
627}
628
629ASTSelectorLookupTrait::data_type
630ASTSelectorLookupTrait::ReadData(Selector, const unsigned char* d,
631 unsigned DataLen) {
Justin Bogner57ba0b22014-03-28 22:03:24 +0000632 using namespace llvm::support;
Guy Benyei11169dd2012-12-18 14:30:41 +0000633
634 data_type Result;
635
Justin Bogner57ba0b22014-03-28 22:03:24 +0000636 Result.ID = Reader.getGlobalSelectorID(
637 F, endian::readNext<uint32_t, little, unaligned>(d));
638 unsigned NumInstanceMethodsAndBits =
639 endian::readNext<uint16_t, little, unaligned>(d);
640 unsigned NumFactoryMethodsAndBits =
641 endian::readNext<uint16_t, little, unaligned>(d);
Argyrios Kyrtzidisd3da6e02013-04-17 00:08:58 +0000642 Result.InstanceBits = NumInstanceMethodsAndBits & 0x3;
643 Result.FactoryBits = NumFactoryMethodsAndBits & 0x3;
644 unsigned NumInstanceMethods = NumInstanceMethodsAndBits >> 2;
645 unsigned NumFactoryMethods = NumFactoryMethodsAndBits >> 2;
Guy Benyei11169dd2012-12-18 14:30:41 +0000646
647 // Load instance methods
648 for (unsigned I = 0; I != NumInstanceMethods; ++I) {
Justin Bogner57ba0b22014-03-28 22:03:24 +0000649 if (ObjCMethodDecl *Method = Reader.GetLocalDeclAs<ObjCMethodDecl>(
650 F, endian::readNext<uint32_t, little, unaligned>(d)))
Guy Benyei11169dd2012-12-18 14:30:41 +0000651 Result.Instance.push_back(Method);
652 }
653
654 // Load factory methods
655 for (unsigned I = 0; I != NumFactoryMethods; ++I) {
Justin Bogner57ba0b22014-03-28 22:03:24 +0000656 if (ObjCMethodDecl *Method = Reader.GetLocalDeclAs<ObjCMethodDecl>(
657 F, endian::readNext<uint32_t, little, unaligned>(d)))
Guy Benyei11169dd2012-12-18 14:30:41 +0000658 Result.Factory.push_back(Method);
659 }
660
661 return Result;
662}
663
Douglas Gregorbfd73d72013-01-23 18:53:14 +0000664unsigned ASTIdentifierLookupTraitBase::ComputeHash(const internal_key_type& a) {
665 return llvm::HashString(a);
Guy Benyei11169dd2012-12-18 14:30:41 +0000666}
667
668std::pair<unsigned, unsigned>
Douglas Gregorbfd73d72013-01-23 18:53:14 +0000669ASTIdentifierLookupTraitBase::ReadKeyDataLength(const unsigned char*& d) {
Justin Bogner57ba0b22014-03-28 22:03:24 +0000670 using namespace llvm::support;
671 unsigned DataLen = endian::readNext<uint16_t, little, unaligned>(d);
672 unsigned KeyLen = endian::readNext<uint16_t, little, unaligned>(d);
Guy Benyei11169dd2012-12-18 14:30:41 +0000673 return std::make_pair(KeyLen, DataLen);
674}
675
Douglas Gregorbfd73d72013-01-23 18:53:14 +0000676ASTIdentifierLookupTraitBase::internal_key_type
677ASTIdentifierLookupTraitBase::ReadKey(const unsigned char* d, unsigned n) {
Guy Benyei11169dd2012-12-18 14:30:41 +0000678 assert(n >= 2 && d[n-1] == '\0');
Douglas Gregorbfd73d72013-01-23 18:53:14 +0000679 return StringRef((const char*) d, n-1);
Guy Benyei11169dd2012-12-18 14:30:41 +0000680}
681
Douglas Gregordcf25082013-02-11 18:16:18 +0000682/// \brief Whether the given identifier is "interesting".
683static bool isInterestingIdentifier(IdentifierInfo &II) {
684 return II.isPoisoned() ||
685 II.isExtensionToken() ||
686 II.getObjCOrBuiltinID() ||
687 II.hasRevertedTokenIDToIdentifier() ||
688 II.hadMacroDefinition() ||
689 II.getFETokenInfo<void>();
690}
691
Guy Benyei11169dd2012-12-18 14:30:41 +0000692IdentifierInfo *ASTIdentifierLookupTrait::ReadData(const internal_key_type& k,
693 const unsigned char* d,
694 unsigned DataLen) {
Justin Bogner57ba0b22014-03-28 22:03:24 +0000695 using namespace llvm::support;
696 unsigned RawID = endian::readNext<uint32_t, little, unaligned>(d);
Guy Benyei11169dd2012-12-18 14:30:41 +0000697 bool IsInteresting = RawID & 0x01;
698
699 // Wipe out the "is interesting" bit.
700 RawID = RawID >> 1;
701
702 IdentID ID = Reader.getGlobalIdentifierID(F, RawID);
703 if (!IsInteresting) {
704 // For uninteresting identifiers, just build the IdentifierInfo
705 // and associate it with the persistent ID.
706 IdentifierInfo *II = KnownII;
707 if (!II) {
Douglas Gregorbfd73d72013-01-23 18:53:14 +0000708 II = &Reader.getIdentifierTable().getOwn(k);
Guy Benyei11169dd2012-12-18 14:30:41 +0000709 KnownII = II;
710 }
711 Reader.SetIdentifierInfo(ID, II);
Douglas Gregordcf25082013-02-11 18:16:18 +0000712 if (!II->isFromAST()) {
713 bool WasInteresting = isInterestingIdentifier(*II);
714 II->setIsFromAST();
715 if (WasInteresting)
716 II->setChangedSinceDeserialization();
717 }
718 Reader.markIdentifierUpToDate(II);
Guy Benyei11169dd2012-12-18 14:30:41 +0000719 return II;
720 }
721
Justin Bogner57ba0b22014-03-28 22:03:24 +0000722 unsigned ObjCOrBuiltinID = endian::readNext<uint16_t, little, unaligned>(d);
723 unsigned Bits = endian::readNext<uint16_t, little, unaligned>(d);
Guy Benyei11169dd2012-12-18 14:30:41 +0000724 bool CPlusPlusOperatorKeyword = Bits & 0x01;
725 Bits >>= 1;
726 bool HasRevertedTokenIDToIdentifier = Bits & 0x01;
727 Bits >>= 1;
728 bool Poisoned = Bits & 0x01;
729 Bits >>= 1;
730 bool ExtensionToken = Bits & 0x01;
731 Bits >>= 1;
Argyrios Kyrtzidiseb663da2013-03-22 21:12:57 +0000732 bool hasSubmoduleMacros = Bits & 0x01;
733 Bits >>= 1;
Guy Benyei11169dd2012-12-18 14:30:41 +0000734 bool hadMacroDefinition = Bits & 0x01;
735 Bits >>= 1;
736
737 assert(Bits == 0 && "Extra bits in the identifier?");
738 DataLen -= 8;
739
740 // Build the IdentifierInfo itself and link the identifier ID with
741 // the new IdentifierInfo.
742 IdentifierInfo *II = KnownII;
743 if (!II) {
Douglas Gregorbfd73d72013-01-23 18:53:14 +0000744 II = &Reader.getIdentifierTable().getOwn(StringRef(k));
Guy Benyei11169dd2012-12-18 14:30:41 +0000745 KnownII = II;
746 }
747 Reader.markIdentifierUpToDate(II);
Douglas Gregordcf25082013-02-11 18:16:18 +0000748 if (!II->isFromAST()) {
749 bool WasInteresting = isInterestingIdentifier(*II);
750 II->setIsFromAST();
751 if (WasInteresting)
752 II->setChangedSinceDeserialization();
753 }
Guy Benyei11169dd2012-12-18 14:30:41 +0000754
755 // Set or check the various bits in the IdentifierInfo structure.
756 // Token IDs are read-only.
Argyrios Kyrtzidisddee8c92013-02-27 01:13:51 +0000757 if (HasRevertedTokenIDToIdentifier && II->getTokenID() != tok::identifier)
Guy Benyei11169dd2012-12-18 14:30:41 +0000758 II->RevertTokenIDToIdentifier();
759 II->setObjCOrBuiltinID(ObjCOrBuiltinID);
760 assert(II->isExtensionToken() == ExtensionToken &&
761 "Incorrect extension token flag");
762 (void)ExtensionToken;
763 if (Poisoned)
764 II->setIsPoisoned(true);
765 assert(II->isCPlusPlusOperatorKeyword() == CPlusPlusOperatorKeyword &&
766 "Incorrect C++ operator keyword flag");
767 (void)CPlusPlusOperatorKeyword;
768
769 // If this identifier is a macro, deserialize the macro
770 // definition.
771 if (hadMacroDefinition) {
Justin Bogner57ba0b22014-03-28 22:03:24 +0000772 uint32_t MacroDirectivesOffset =
773 endian::readNext<uint32_t, little, unaligned>(d);
Argyrios Kyrtzidiseb663da2013-03-22 21:12:57 +0000774 DataLen -= 4;
775 SmallVector<uint32_t, 8> LocalMacroIDs;
776 if (hasSubmoduleMacros) {
Justin Bogner57ba0b22014-03-28 22:03:24 +0000777 while (uint32_t LocalMacroID =
778 endian::readNext<uint32_t, little, unaligned>(d)) {
Argyrios Kyrtzidiseb663da2013-03-22 21:12:57 +0000779 DataLen -= 4;
780 LocalMacroIDs.push_back(LocalMacroID);
781 }
Argyrios Kyrtzidis719736c2013-01-19 03:14:56 +0000782 DataLen -= 4;
783 }
Argyrios Kyrtzidiseb663da2013-03-22 21:12:57 +0000784
785 if (F.Kind == MK_Module) {
Richard Smith49f906a2014-03-01 00:08:04 +0000786 // Macro definitions are stored from newest to oldest, so reverse them
787 // before registering them.
788 llvm::SmallVector<unsigned, 8> MacroSizes;
Argyrios Kyrtzidiseb663da2013-03-22 21:12:57 +0000789 for (SmallVectorImpl<uint32_t>::iterator
Richard Smith49f906a2014-03-01 00:08:04 +0000790 I = LocalMacroIDs.begin(), E = LocalMacroIDs.end(); I != E; /**/) {
791 unsigned Size = 1;
792
793 static const uint32_t HasOverridesFlag = 0x80000000U;
794 if (I + 1 != E && (I[1] & HasOverridesFlag))
795 Size += 1 + (I[1] & ~HasOverridesFlag);
796
797 MacroSizes.push_back(Size);
798 I += Size;
Argyrios Kyrtzidiseb663da2013-03-22 21:12:57 +0000799 }
Richard Smith49f906a2014-03-01 00:08:04 +0000800
801 SmallVectorImpl<uint32_t>::iterator I = LocalMacroIDs.end();
802 for (SmallVectorImpl<unsigned>::reverse_iterator SI = MacroSizes.rbegin(),
803 SE = MacroSizes.rend();
804 SI != SE; ++SI) {
805 I -= *SI;
806
807 uint32_t LocalMacroID = *I;
Craig Topper00bbdcf2014-06-28 23:22:23 +0000808 ArrayRef<uint32_t> Overrides;
Richard Smith49f906a2014-03-01 00:08:04 +0000809 if (*SI != 1)
810 Overrides = llvm::makeArrayRef(&I[2], *SI - 2);
811 Reader.addPendingMacroFromModule(II, &F, LocalMacroID, Overrides);
812 }
813 assert(I == LocalMacroIDs.begin());
Argyrios Kyrtzidiseb663da2013-03-22 21:12:57 +0000814 } else {
815 Reader.addPendingMacroFromPCH(II, &F, MacroDirectivesOffset);
816 }
Guy Benyei11169dd2012-12-18 14:30:41 +0000817 }
818
819 Reader.SetIdentifierInfo(ID, II);
820
821 // Read all of the declarations visible at global scope with this
822 // name.
823 if (DataLen > 0) {
824 SmallVector<uint32_t, 4> DeclIDs;
825 for (; DataLen > 0; DataLen -= 4)
Justin Bogner57ba0b22014-03-28 22:03:24 +0000826 DeclIDs.push_back(Reader.getGlobalDeclID(
827 F, endian::readNext<uint32_t, little, unaligned>(d)));
Guy Benyei11169dd2012-12-18 14:30:41 +0000828 Reader.SetGloballyVisibleDecls(II, DeclIDs);
829 }
830
831 return II;
832}
833
834unsigned
835ASTDeclContextNameLookupTrait::ComputeHash(const DeclNameKey &Key) const {
836 llvm::FoldingSetNodeID ID;
837 ID.AddInteger(Key.Kind);
838
839 switch (Key.Kind) {
840 case DeclarationName::Identifier:
841 case DeclarationName::CXXLiteralOperatorName:
842 ID.AddString(((IdentifierInfo*)Key.Data)->getName());
843 break;
844 case DeclarationName::ObjCZeroArgSelector:
845 case DeclarationName::ObjCOneArgSelector:
846 case DeclarationName::ObjCMultiArgSelector:
847 ID.AddInteger(serialization::ComputeHash(Selector(Key.Data)));
848 break;
849 case DeclarationName::CXXOperatorName:
850 ID.AddInteger((OverloadedOperatorKind)Key.Data);
851 break;
852 case DeclarationName::CXXConstructorName:
853 case DeclarationName::CXXDestructorName:
854 case DeclarationName::CXXConversionFunctionName:
855 case DeclarationName::CXXUsingDirective:
856 break;
857 }
858
859 return ID.ComputeHash();
860}
861
862ASTDeclContextNameLookupTrait::internal_key_type
863ASTDeclContextNameLookupTrait::GetInternalKey(
864 const external_key_type& Name) const {
865 DeclNameKey Key;
866 Key.Kind = Name.getNameKind();
867 switch (Name.getNameKind()) {
868 case DeclarationName::Identifier:
869 Key.Data = (uint64_t)Name.getAsIdentifierInfo();
870 break;
871 case DeclarationName::ObjCZeroArgSelector:
872 case DeclarationName::ObjCOneArgSelector:
873 case DeclarationName::ObjCMultiArgSelector:
874 Key.Data = (uint64_t)Name.getObjCSelector().getAsOpaquePtr();
875 break;
876 case DeclarationName::CXXOperatorName:
877 Key.Data = Name.getCXXOverloadedOperator();
878 break;
879 case DeclarationName::CXXLiteralOperatorName:
880 Key.Data = (uint64_t)Name.getCXXLiteralIdentifier();
881 break;
882 case DeclarationName::CXXConstructorName:
883 case DeclarationName::CXXDestructorName:
884 case DeclarationName::CXXConversionFunctionName:
885 case DeclarationName::CXXUsingDirective:
886 Key.Data = 0;
887 break;
888 }
889
890 return Key;
891}
892
893std::pair<unsigned, unsigned>
894ASTDeclContextNameLookupTrait::ReadKeyDataLength(const unsigned char*& d) {
Justin Bogner57ba0b22014-03-28 22:03:24 +0000895 using namespace llvm::support;
896 unsigned KeyLen = endian::readNext<uint16_t, little, unaligned>(d);
897 unsigned DataLen = endian::readNext<uint16_t, little, unaligned>(d);
Guy Benyei11169dd2012-12-18 14:30:41 +0000898 return std::make_pair(KeyLen, DataLen);
899}
900
901ASTDeclContextNameLookupTrait::internal_key_type
902ASTDeclContextNameLookupTrait::ReadKey(const unsigned char* d, unsigned) {
Justin Bogner57ba0b22014-03-28 22:03:24 +0000903 using namespace llvm::support;
Guy Benyei11169dd2012-12-18 14:30:41 +0000904
905 DeclNameKey Key;
906 Key.Kind = (DeclarationName::NameKind)*d++;
907 switch (Key.Kind) {
908 case DeclarationName::Identifier:
Justin Bogner57ba0b22014-03-28 22:03:24 +0000909 Key.Data = (uint64_t)Reader.getLocalIdentifier(
910 F, endian::readNext<uint32_t, little, unaligned>(d));
Guy Benyei11169dd2012-12-18 14:30:41 +0000911 break;
912 case DeclarationName::ObjCZeroArgSelector:
913 case DeclarationName::ObjCOneArgSelector:
914 case DeclarationName::ObjCMultiArgSelector:
915 Key.Data =
Justin Bogner57ba0b22014-03-28 22:03:24 +0000916 (uint64_t)Reader.getLocalSelector(
917 F, endian::readNext<uint32_t, little, unaligned>(
918 d)).getAsOpaquePtr();
Guy Benyei11169dd2012-12-18 14:30:41 +0000919 break;
920 case DeclarationName::CXXOperatorName:
921 Key.Data = *d++; // OverloadedOperatorKind
922 break;
923 case DeclarationName::CXXLiteralOperatorName:
Justin Bogner57ba0b22014-03-28 22:03:24 +0000924 Key.Data = (uint64_t)Reader.getLocalIdentifier(
925 F, endian::readNext<uint32_t, little, unaligned>(d));
Guy Benyei11169dd2012-12-18 14:30:41 +0000926 break;
927 case DeclarationName::CXXConstructorName:
928 case DeclarationName::CXXDestructorName:
929 case DeclarationName::CXXConversionFunctionName:
930 case DeclarationName::CXXUsingDirective:
931 Key.Data = 0;
932 break;
933 }
934
935 return Key;
936}
937
938ASTDeclContextNameLookupTrait::data_type
939ASTDeclContextNameLookupTrait::ReadData(internal_key_type,
940 const unsigned char* d,
941 unsigned DataLen) {
Justin Bogner57ba0b22014-03-28 22:03:24 +0000942 using namespace llvm::support;
943 unsigned NumDecls = endian::readNext<uint16_t, little, unaligned>(d);
Argyrios Kyrtzidisc57e5032013-01-11 22:29:49 +0000944 LE32DeclID *Start = reinterpret_cast<LE32DeclID *>(
945 const_cast<unsigned char *>(d));
Guy Benyei11169dd2012-12-18 14:30:41 +0000946 return std::make_pair(Start, Start + NumDecls);
947}
948
949bool ASTReader::ReadDeclContextStorage(ModuleFile &M,
Chris Lattner7fb3bef2013-01-20 00:56:42 +0000950 BitstreamCursor &Cursor,
Guy Benyei11169dd2012-12-18 14:30:41 +0000951 const std::pair<uint64_t, uint64_t> &Offsets,
952 DeclContextInfo &Info) {
953 SavedStreamPosition SavedPosition(Cursor);
954 // First the lexical decls.
955 if (Offsets.first != 0) {
956 Cursor.JumpToBit(Offsets.first);
957
958 RecordData Record;
Chris Lattner0e6c9402013-01-20 02:38:54 +0000959 StringRef Blob;
Guy Benyei11169dd2012-12-18 14:30:41 +0000960 unsigned Code = Cursor.ReadCode();
Chris Lattner0e6c9402013-01-20 02:38:54 +0000961 unsigned RecCode = Cursor.readRecord(Code, Record, &Blob);
Guy Benyei11169dd2012-12-18 14:30:41 +0000962 if (RecCode != DECL_CONTEXT_LEXICAL) {
963 Error("Expected lexical block");
964 return true;
965 }
966
Chris Lattner0e6c9402013-01-20 02:38:54 +0000967 Info.LexicalDecls = reinterpret_cast<const KindDeclIDPair*>(Blob.data());
968 Info.NumLexicalDecls = Blob.size() / sizeof(KindDeclIDPair);
Guy Benyei11169dd2012-12-18 14:30:41 +0000969 }
970
971 // Now the lookup table.
972 if (Offsets.second != 0) {
973 Cursor.JumpToBit(Offsets.second);
974
975 RecordData Record;
Chris Lattner0e6c9402013-01-20 02:38:54 +0000976 StringRef Blob;
Guy Benyei11169dd2012-12-18 14:30:41 +0000977 unsigned Code = Cursor.ReadCode();
Chris Lattner0e6c9402013-01-20 02:38:54 +0000978 unsigned RecCode = Cursor.readRecord(Code, Record, &Blob);
Guy Benyei11169dd2012-12-18 14:30:41 +0000979 if (RecCode != DECL_CONTEXT_VISIBLE) {
980 Error("Expected visible lookup table block");
981 return true;
982 }
Justin Bognerda4e6502014-04-14 16:34:29 +0000983 Info.NameLookupTableData = ASTDeclContextNameLookupTable::Create(
984 (const unsigned char *)Blob.data() + Record[0],
985 (const unsigned char *)Blob.data() + sizeof(uint32_t),
986 (const unsigned char *)Blob.data(),
987 ASTDeclContextNameLookupTrait(*this, M));
Guy Benyei11169dd2012-12-18 14:30:41 +0000988 }
989
990 return false;
991}
992
993void ASTReader::Error(StringRef Msg) {
994 Error(diag::err_fe_pch_malformed, Msg);
Douglas Gregor940e8052013-05-10 22:15:13 +0000995 if (Context.getLangOpts().Modules && !Diags.isDiagnosticInFlight()) {
996 Diag(diag::note_module_cache_path)
997 << PP.getHeaderSearchInfo().getModuleCachePath();
998 }
Guy Benyei11169dd2012-12-18 14:30:41 +0000999}
1000
1001void ASTReader::Error(unsigned DiagID,
1002 StringRef Arg1, StringRef Arg2) {
1003 if (Diags.isDiagnosticInFlight())
1004 Diags.SetDelayedDiagnostic(DiagID, Arg1, Arg2);
1005 else
1006 Diag(DiagID) << Arg1 << Arg2;
1007}
1008
1009//===----------------------------------------------------------------------===//
1010// Source Manager Deserialization
1011//===----------------------------------------------------------------------===//
1012
1013/// \brief Read the line table in the source manager block.
1014/// \returns true if there was an error.
1015bool ASTReader::ParseLineTable(ModuleFile &F,
1016 SmallVectorImpl<uint64_t> &Record) {
1017 unsigned Idx = 0;
1018 LineTableInfo &LineTable = SourceMgr.getLineTable();
1019
1020 // Parse the file names
1021 std::map<int, int> FileIDs;
1022 for (int I = 0, N = Record[Idx++]; I != N; ++I) {
1023 // Extract the file name
1024 unsigned FilenameLen = Record[Idx++];
1025 std::string Filename(&Record[Idx], &Record[Idx] + FilenameLen);
1026 Idx += FilenameLen;
1027 MaybeAddSystemRootToFilename(F, Filename);
1028 FileIDs[I] = LineTable.getLineTableFilenameID(Filename);
1029 }
1030
1031 // Parse the line entries
1032 std::vector<LineEntry> Entries;
1033 while (Idx < Record.size()) {
1034 int FID = Record[Idx++];
1035 assert(FID >= 0 && "Serialized line entries for non-local file.");
1036 // Remap FileID from 1-based old view.
1037 FID += F.SLocEntryBaseID - 1;
1038
1039 // Extract the line entries
1040 unsigned NumEntries = Record[Idx++];
1041 assert(NumEntries && "Numentries is 00000");
1042 Entries.clear();
1043 Entries.reserve(NumEntries);
1044 for (unsigned I = 0; I != NumEntries; ++I) {
1045 unsigned FileOffset = Record[Idx++];
1046 unsigned LineNo = Record[Idx++];
1047 int FilenameID = FileIDs[Record[Idx++]];
1048 SrcMgr::CharacteristicKind FileKind
1049 = (SrcMgr::CharacteristicKind)Record[Idx++];
1050 unsigned IncludeOffset = Record[Idx++];
1051 Entries.push_back(LineEntry::get(FileOffset, LineNo, FilenameID,
1052 FileKind, IncludeOffset));
1053 }
1054 LineTable.AddEntry(FileID::get(FID), Entries);
1055 }
1056
1057 return false;
1058}
1059
1060/// \brief Read a source manager block
1061bool ASTReader::ReadSourceManagerBlock(ModuleFile &F) {
1062 using namespace SrcMgr;
1063
Chris Lattner7fb3bef2013-01-20 00:56:42 +00001064 BitstreamCursor &SLocEntryCursor = F.SLocEntryCursor;
Guy Benyei11169dd2012-12-18 14:30:41 +00001065
1066 // Set the source-location entry cursor to the current position in
1067 // the stream. This cursor will be used to read the contents of the
1068 // source manager block initially, and then lazily read
1069 // source-location entries as needed.
1070 SLocEntryCursor = F.Stream;
1071
1072 // The stream itself is going to skip over the source manager block.
1073 if (F.Stream.SkipBlock()) {
1074 Error("malformed block record in AST file");
1075 return true;
1076 }
1077
1078 // Enter the source manager block.
1079 if (SLocEntryCursor.EnterSubBlock(SOURCE_MANAGER_BLOCK_ID)) {
1080 Error("malformed source manager block record in AST file");
1081 return true;
1082 }
1083
1084 RecordData Record;
1085 while (true) {
Chris Lattnere7b154b2013-01-19 21:39:22 +00001086 llvm::BitstreamEntry E = SLocEntryCursor.advanceSkippingSubblocks();
1087
1088 switch (E.Kind) {
1089 case llvm::BitstreamEntry::SubBlock: // Handled for us already.
1090 case llvm::BitstreamEntry::Error:
1091 Error("malformed block record in AST file");
1092 return true;
1093 case llvm::BitstreamEntry::EndBlock:
Guy Benyei11169dd2012-12-18 14:30:41 +00001094 return false;
Chris Lattnere7b154b2013-01-19 21:39:22 +00001095 case llvm::BitstreamEntry::Record:
1096 // The interesting case.
1097 break;
Guy Benyei11169dd2012-12-18 14:30:41 +00001098 }
Chris Lattnere7b154b2013-01-19 21:39:22 +00001099
Guy Benyei11169dd2012-12-18 14:30:41 +00001100 // Read a record.
Guy Benyei11169dd2012-12-18 14:30:41 +00001101 Record.clear();
Chris Lattner15c3e7d2013-01-21 18:28:26 +00001102 StringRef Blob;
1103 switch (SLocEntryCursor.readRecord(E.ID, Record, &Blob)) {
Guy Benyei11169dd2012-12-18 14:30:41 +00001104 default: // Default behavior: ignore.
1105 break;
1106
1107 case SM_SLOC_FILE_ENTRY:
1108 case SM_SLOC_BUFFER_ENTRY:
1109 case SM_SLOC_EXPANSION_ENTRY:
1110 // Once we hit one of the source location entries, we're done.
1111 return false;
1112 }
1113 }
1114}
1115
1116/// \brief If a header file is not found at the path that we expect it to be
1117/// and the PCH file was moved from its original location, try to resolve the
1118/// file by assuming that header+PCH were moved together and the header is in
1119/// the same place relative to the PCH.
1120static std::string
1121resolveFileRelativeToOriginalDir(const std::string &Filename,
1122 const std::string &OriginalDir,
1123 const std::string &CurrDir) {
1124 assert(OriginalDir != CurrDir &&
1125 "No point trying to resolve the file if the PCH dir didn't change");
1126 using namespace llvm::sys;
1127 SmallString<128> filePath(Filename);
1128 fs::make_absolute(filePath);
1129 assert(path::is_absolute(OriginalDir));
1130 SmallString<128> currPCHPath(CurrDir);
1131
1132 path::const_iterator fileDirI = path::begin(path::parent_path(filePath)),
1133 fileDirE = path::end(path::parent_path(filePath));
1134 path::const_iterator origDirI = path::begin(OriginalDir),
1135 origDirE = path::end(OriginalDir);
1136 // Skip the common path components from filePath and OriginalDir.
1137 while (fileDirI != fileDirE && origDirI != origDirE &&
1138 *fileDirI == *origDirI) {
1139 ++fileDirI;
1140 ++origDirI;
1141 }
1142 for (; origDirI != origDirE; ++origDirI)
1143 path::append(currPCHPath, "..");
1144 path::append(currPCHPath, fileDirI, fileDirE);
1145 path::append(currPCHPath, path::filename(Filename));
1146 return currPCHPath.str();
1147}
1148
1149bool ASTReader::ReadSLocEntry(int ID) {
1150 if (ID == 0)
1151 return false;
1152
1153 if (unsigned(-ID) - 2 >= getTotalNumSLocs() || ID > 0) {
1154 Error("source location entry ID out-of-range for AST file");
1155 return true;
1156 }
1157
1158 ModuleFile *F = GlobalSLocEntryMap.find(-ID)->second;
1159 F->SLocEntryCursor.JumpToBit(F->SLocEntryOffsets[ID - F->SLocEntryBaseID]);
Chris Lattner7fb3bef2013-01-20 00:56:42 +00001160 BitstreamCursor &SLocEntryCursor = F->SLocEntryCursor;
Guy Benyei11169dd2012-12-18 14:30:41 +00001161 unsigned BaseOffset = F->SLocEntryBaseOffset;
1162
1163 ++NumSLocEntriesRead;
Chris Lattnere7b154b2013-01-19 21:39:22 +00001164 llvm::BitstreamEntry Entry = SLocEntryCursor.advance();
1165 if (Entry.Kind != llvm::BitstreamEntry::Record) {
Guy Benyei11169dd2012-12-18 14:30:41 +00001166 Error("incorrectly-formatted source location entry in AST file");
1167 return true;
1168 }
Chris Lattnere7b154b2013-01-19 21:39:22 +00001169
Guy Benyei11169dd2012-12-18 14:30:41 +00001170 RecordData Record;
Chris Lattner0e6c9402013-01-20 02:38:54 +00001171 StringRef Blob;
1172 switch (SLocEntryCursor.readRecord(Entry.ID, Record, &Blob)) {
Guy Benyei11169dd2012-12-18 14:30:41 +00001173 default:
1174 Error("incorrectly-formatted source location entry in AST file");
1175 return true;
1176
1177 case SM_SLOC_FILE_ENTRY: {
1178 // We will detect whether a file changed and return 'Failure' for it, but
1179 // we will also try to fail gracefully by setting up the SLocEntry.
1180 unsigned InputID = Record[4];
1181 InputFile IF = getInputFile(*F, InputID);
Argyrios Kyrtzidis61c3d872013-03-01 03:26:04 +00001182 const FileEntry *File = IF.getFile();
1183 bool OverriddenBuffer = IF.isOverridden();
Guy Benyei11169dd2012-12-18 14:30:41 +00001184
Argyrios Kyrtzidis61c3d872013-03-01 03:26:04 +00001185 // Note that we only check if a File was returned. If it was out-of-date
1186 // we have complained but we will continue creating a FileID to recover
1187 // gracefully.
1188 if (!File)
Guy Benyei11169dd2012-12-18 14:30:41 +00001189 return true;
1190
1191 SourceLocation IncludeLoc = ReadSourceLocation(*F, Record[1]);
1192 if (IncludeLoc.isInvalid() && F->Kind != MK_MainFile) {
1193 // This is the module's main file.
1194 IncludeLoc = getImportLocation(F);
1195 }
1196 SrcMgr::CharacteristicKind
1197 FileCharacter = (SrcMgr::CharacteristicKind)Record[2];
1198 FileID FID = SourceMgr.createFileID(File, IncludeLoc, FileCharacter,
1199 ID, BaseOffset + Record[0]);
1200 SrcMgr::FileInfo &FileInfo =
1201 const_cast<SrcMgr::FileInfo&>(SourceMgr.getSLocEntry(FID).getFile());
1202 FileInfo.NumCreatedFIDs = Record[5];
1203 if (Record[3])
1204 FileInfo.setHasLineDirectives();
1205
1206 const DeclID *FirstDecl = F->FileSortedDecls + Record[6];
1207 unsigned NumFileDecls = Record[7];
1208 if (NumFileDecls) {
1209 assert(F->FileSortedDecls && "FILE_SORTED_DECLS not encountered yet ?");
1210 FileDeclIDs[FID] = FileDeclsInfo(F, llvm::makeArrayRef(FirstDecl,
1211 NumFileDecls));
1212 }
1213
1214 const SrcMgr::ContentCache *ContentCache
1215 = SourceMgr.getOrCreateContentCache(File,
1216 /*isSystemFile=*/FileCharacter != SrcMgr::C_User);
1217 if (OverriddenBuffer && !ContentCache->BufferOverridden &&
1218 ContentCache->ContentsEntry == ContentCache->OrigEntry) {
1219 unsigned Code = SLocEntryCursor.ReadCode();
1220 Record.clear();
Chris Lattner0e6c9402013-01-20 02:38:54 +00001221 unsigned RecCode = SLocEntryCursor.readRecord(Code, Record, &Blob);
Guy Benyei11169dd2012-12-18 14:30:41 +00001222
1223 if (RecCode != SM_SLOC_BUFFER_BLOB) {
1224 Error("AST record has invalid code");
1225 return true;
1226 }
1227
1228 llvm::MemoryBuffer *Buffer
Chris Lattner0e6c9402013-01-20 02:38:54 +00001229 = llvm::MemoryBuffer::getMemBuffer(Blob.drop_back(1), File->getName());
Guy Benyei11169dd2012-12-18 14:30:41 +00001230 SourceMgr.overrideFileContents(File, Buffer);
1231 }
1232
1233 break;
1234 }
1235
1236 case SM_SLOC_BUFFER_ENTRY: {
Chris Lattner0e6c9402013-01-20 02:38:54 +00001237 const char *Name = Blob.data();
Guy Benyei11169dd2012-12-18 14:30:41 +00001238 unsigned Offset = Record[0];
1239 SrcMgr::CharacteristicKind
1240 FileCharacter = (SrcMgr::CharacteristicKind)Record[2];
1241 SourceLocation IncludeLoc = ReadSourceLocation(*F, Record[1]);
1242 if (IncludeLoc.isInvalid() && F->Kind == MK_Module) {
1243 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
1255 llvm::MemoryBuffer *Buffer
Chris Lattner0e6c9402013-01-20 02:38:54 +00001256 = llvm::MemoryBuffer::getMemBuffer(Blob.drop_back(1), Name);
Alp Toker6ac2cd02014-05-16 17:23:01 +00001257 SourceMgr.createFileID(Buffer, FileCharacter, ID, BaseOffset + Offset,
1258 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;
1288 if (M->Kind != MK_Module)
1289 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
1735 DefMacroDirective *import(Preprocessor &PP, SourceLocation ImportLoc) const {
1736 if (!MI)
Craig Toppera13603a2014-05-22 05:54:18 +00001737 return nullptr;
Richard Smith49f906a2014-03-01 00:08:04 +00001738 return PP.AllocateDefMacroDirective(MI, ImportLoc, /*isImported=*/true);
1739 }
1740};
1741
1742ASTReader::ModuleMacroInfo *
1743ASTReader::getModuleMacro(const PendingMacroInfo &PMInfo) {
1744 ModuleMacroInfo Info;
1745
1746 uint32_t ID = PMInfo.ModuleMacroData.MacID;
1747 if (ID & 1) {
1748 // Macro undefinition.
1749 Info.SubModID = getGlobalSubmoduleID(*PMInfo.M, ID >> 1);
Craig Toppera13603a2014-05-22 05:54:18 +00001750 Info.MI = nullptr;
Richard Smith49f906a2014-03-01 00:08:04 +00001751 } else {
1752 // Macro definition.
1753 GlobalMacroID GMacID = getGlobalMacroID(*PMInfo.M, ID >> 1);
1754 assert(GMacID);
1755
1756 // If this macro has already been loaded, don't do so again.
1757 // FIXME: This is highly dubious. Multiple macro definitions can have the
1758 // same MacroInfo (and hence the same GMacID) due to #pragma push_macro etc.
1759 if (MacrosLoaded[GMacID - NUM_PREDEF_MACRO_IDS])
Craig Toppera13603a2014-05-22 05:54:18 +00001760 return nullptr;
Richard Smith49f906a2014-03-01 00:08:04 +00001761
1762 Info.MI = getMacro(GMacID);
1763 Info.SubModID = Info.MI->getOwningModuleID();
1764 }
1765 Info.Overrides = PMInfo.ModuleMacroData.Overrides;
1766 Info.F = PMInfo.M;
1767
1768 return new (Context) ModuleMacroInfo(Info);
1769}
1770
Argyrios Kyrtzidiseb663da2013-03-22 21:12:57 +00001771void ASTReader::resolvePendingMacro(IdentifierInfo *II,
1772 const PendingMacroInfo &PMInfo) {
1773 assert(II);
1774
1775 if (PMInfo.M->Kind != MK_Module) {
1776 installPCHMacroDirectives(II, *PMInfo.M,
1777 PMInfo.PCHMacroData.MacroDirectivesOffset);
1778 return;
1779 }
Richard Smith49f906a2014-03-01 00:08:04 +00001780
Argyrios Kyrtzidiseb663da2013-03-22 21:12:57 +00001781 // Module Macro.
1782
Richard Smith49f906a2014-03-01 00:08:04 +00001783 ModuleMacroInfo *MMI = getModuleMacro(PMInfo);
1784 if (!MMI)
Argyrios Kyrtzidiseb663da2013-03-22 21:12:57 +00001785 return;
1786
Richard Smith49f906a2014-03-01 00:08:04 +00001787 Module *Owner = getSubmodule(MMI->getSubmoduleID());
1788 if (Owner && Owner->NameVisibility == Module::Hidden) {
1789 // Macros in the owning module are hidden. Just remember this macro to
1790 // install if we make this module visible.
1791 HiddenNamesMap[Owner].HiddenMacros.insert(std::make_pair(II, MMI));
1792 } else {
Richard Smithe657bbd2014-07-18 22:13:40 +00001793 installImportedMacro(II, MMI, Owner, /*FromFinalization*/false);
Argyrios Kyrtzidiseb663da2013-03-22 21:12:57 +00001794 }
Argyrios Kyrtzidiseb663da2013-03-22 21:12:57 +00001795}
1796
1797void ASTReader::installPCHMacroDirectives(IdentifierInfo *II,
1798 ModuleFile &M, uint64_t Offset) {
1799 assert(M.Kind != MK_Module);
1800
1801 BitstreamCursor &Cursor = M.MacroCursor;
1802 SavedStreamPosition SavedPosition(Cursor);
1803 Cursor.JumpToBit(Offset);
1804
1805 llvm::BitstreamEntry Entry =
1806 Cursor.advance(BitstreamCursor::AF_DontPopBlockAtEnd);
1807 if (Entry.Kind != llvm::BitstreamEntry::Record) {
1808 Error("malformed block record in AST file");
1809 return;
1810 }
1811
1812 RecordData Record;
1813 PreprocessorRecordTypes RecType =
1814 (PreprocessorRecordTypes)Cursor.readRecord(Entry.ID, Record);
1815 if (RecType != PP_MACRO_DIRECTIVE_HISTORY) {
1816 Error("malformed block record in AST file");
1817 return;
1818 }
1819
1820 // Deserialize the macro directives history in reverse source-order.
Craig Toppera13603a2014-05-22 05:54:18 +00001821 MacroDirective *Latest = nullptr, *Earliest = nullptr;
Argyrios Kyrtzidiseb663da2013-03-22 21:12:57 +00001822 unsigned Idx = 0, N = Record.size();
1823 while (Idx < N) {
Craig Toppera13603a2014-05-22 05:54:18 +00001824 MacroDirective *MD = nullptr;
Argyrios Kyrtzidiseb663da2013-03-22 21:12:57 +00001825 SourceLocation Loc = ReadSourceLocation(M, Record, Idx);
Argyrios Kyrtzidisb6210df2013-03-26 17:17:01 +00001826 MacroDirective::Kind K = (MacroDirective::Kind)Record[Idx++];
1827 switch (K) {
1828 case MacroDirective::MD_Define: {
1829 GlobalMacroID GMacID = getGlobalMacroID(M, Record[Idx++]);
1830 MacroInfo *MI = getMacro(GMacID);
1831 bool isImported = Record[Idx++];
1832 bool isAmbiguous = Record[Idx++];
1833 DefMacroDirective *DefMD =
1834 PP.AllocateDefMacroDirective(MI, Loc, isImported);
1835 DefMD->setAmbiguous(isAmbiguous);
1836 MD = DefMD;
1837 break;
1838 }
1839 case MacroDirective::MD_Undefine:
1840 MD = PP.AllocateUndefMacroDirective(Loc);
1841 break;
1842 case MacroDirective::MD_Visibility: {
1843 bool isPublic = Record[Idx++];
1844 MD = PP.AllocateVisibilityMacroDirective(Loc, isPublic);
1845 break;
1846 }
1847 }
Argyrios Kyrtzidiseb663da2013-03-22 21:12:57 +00001848
1849 if (!Latest)
1850 Latest = MD;
1851 if (Earliest)
1852 Earliest->setPrevious(MD);
1853 Earliest = MD;
1854 }
1855
1856 PP.setLoadedMacroDirective(II, Latest);
1857}
1858
Argyrios Kyrtzidis3a9c42c2013-03-27 01:25:34 +00001859/// \brief For the given macro definitions, check if they are both in system
Douglas Gregor0b202052013-04-12 21:00:54 +00001860/// modules.
1861static bool areDefinedInSystemModules(MacroInfo *PrevMI, MacroInfo *NewMI,
Douglas Gregor5e461192013-06-07 22:56:11 +00001862 Module *NewOwner, ASTReader &Reader) {
Argyrios Kyrtzidis3a9c42c2013-03-27 01:25:34 +00001863 assert(PrevMI && NewMI);
Craig Toppera13603a2014-05-22 05:54:18 +00001864 Module *PrevOwner = nullptr;
Argyrios Kyrtzidis3a9c42c2013-03-27 01:25:34 +00001865 if (SubmoduleID PrevModID = PrevMI->getOwningModuleID())
1866 PrevOwner = Reader.getSubmodule(PrevModID);
Douglas Gregor5e461192013-06-07 22:56:11 +00001867 SourceManager &SrcMgr = Reader.getSourceManager();
1868 bool PrevInSystem
1869 = PrevOwner? PrevOwner->IsSystem
1870 : SrcMgr.isInSystemHeader(PrevMI->getDefinitionLoc());
1871 bool NewInSystem
1872 = NewOwner? NewOwner->IsSystem
1873 : SrcMgr.isInSystemHeader(NewMI->getDefinitionLoc());
1874 if (PrevOwner && PrevOwner == NewOwner)
Argyrios Kyrtzidis3a9c42c2013-03-27 01:25:34 +00001875 return false;
Douglas Gregor5e461192013-06-07 22:56:11 +00001876 return PrevInSystem && NewInSystem;
Argyrios Kyrtzidis3a9c42c2013-03-27 01:25:34 +00001877}
1878
Richard Smith49f906a2014-03-01 00:08:04 +00001879void ASTReader::removeOverriddenMacros(IdentifierInfo *II,
1880 AmbiguousMacros &Ambig,
Craig Topper00bbdcf2014-06-28 23:22:23 +00001881 ArrayRef<SubmoduleID> Overrides) {
Richard Smith49f906a2014-03-01 00:08:04 +00001882 for (unsigned OI = 0, ON = Overrides.size(); OI != ON; ++OI) {
1883 SubmoduleID OwnerID = Overrides[OI];
Argyrios Kyrtzidiseb663da2013-03-22 21:12:57 +00001884
Richard Smith49f906a2014-03-01 00:08:04 +00001885 // If this macro is not yet visible, remove it from the hidden names list.
1886 Module *Owner = getSubmodule(OwnerID);
1887 HiddenNames &Hidden = HiddenNamesMap[Owner];
1888 HiddenMacrosMap::iterator HI = Hidden.HiddenMacros.find(II);
1889 if (HI != Hidden.HiddenMacros.end()) {
Richard Smith9d100862014-03-06 03:16:27 +00001890 auto SubOverrides = HI->second->getOverriddenSubmodules();
Richard Smith49f906a2014-03-01 00:08:04 +00001891 Hidden.HiddenMacros.erase(HI);
Richard Smith9d100862014-03-06 03:16:27 +00001892 removeOverriddenMacros(II, Ambig, SubOverrides);
Richard Smith49f906a2014-03-01 00:08:04 +00001893 }
1894
1895 // If this macro is already in our list of conflicts, remove it from there.
Richard Smithbb29e512014-03-06 00:33:23 +00001896 Ambig.erase(
1897 std::remove_if(Ambig.begin(), Ambig.end(), [&](DefMacroDirective *MD) {
1898 return MD->getInfo()->getOwningModuleID() == OwnerID;
1899 }),
1900 Ambig.end());
Richard Smith49f906a2014-03-01 00:08:04 +00001901 }
1902}
1903
1904ASTReader::AmbiguousMacros *
1905ASTReader::removeOverriddenMacros(IdentifierInfo *II,
Craig Topper00bbdcf2014-06-28 23:22:23 +00001906 ArrayRef<SubmoduleID> Overrides) {
Argyrios Kyrtzidiseb663da2013-03-22 21:12:57 +00001907 MacroDirective *Prev = PP.getMacroDirective(II);
Richard Smith49f906a2014-03-01 00:08:04 +00001908 if (!Prev && Overrides.empty())
Craig Toppera13603a2014-05-22 05:54:18 +00001909 return nullptr;
Richard Smith49f906a2014-03-01 00:08:04 +00001910
Craig Toppera13603a2014-05-22 05:54:18 +00001911 DefMacroDirective *PrevDef = Prev ? Prev->getDefinition().getDirective()
1912 : nullptr;
Richard Smith49f906a2014-03-01 00:08:04 +00001913 if (PrevDef && PrevDef->isAmbiguous()) {
1914 // We had a prior ambiguity. Check whether we resolve it (or make it worse).
1915 AmbiguousMacros &Ambig = AmbiguousMacroDefs[II];
1916 Ambig.push_back(PrevDef);
1917
1918 removeOverriddenMacros(II, Ambig, Overrides);
1919
1920 if (!Ambig.empty())
1921 return &Ambig;
1922
1923 AmbiguousMacroDefs.erase(II);
1924 } else {
1925 // There's no ambiguity yet. Maybe we're introducing one.
Benjamin Kramer834652a2014-05-03 18:44:26 +00001926 AmbiguousMacros Ambig;
Richard Smith49f906a2014-03-01 00:08:04 +00001927 if (PrevDef)
1928 Ambig.push_back(PrevDef);
1929
1930 removeOverriddenMacros(II, Ambig, Overrides);
1931
1932 if (!Ambig.empty()) {
1933 AmbiguousMacros &Result = AmbiguousMacroDefs[II];
Benjamin Kramer834652a2014-05-03 18:44:26 +00001934 std::swap(Result, Ambig);
Richard Smith49f906a2014-03-01 00:08:04 +00001935 return &Result;
Argyrios Kyrtzidisb6210df2013-03-26 17:17:01 +00001936 }
Argyrios Kyrtzidiseb663da2013-03-22 21:12:57 +00001937 }
Richard Smith49f906a2014-03-01 00:08:04 +00001938
1939 // We ended up with no ambiguity.
Craig Toppera13603a2014-05-22 05:54:18 +00001940 return nullptr;
Richard Smith49f906a2014-03-01 00:08:04 +00001941}
1942
1943void ASTReader::installImportedMacro(IdentifierInfo *II, ModuleMacroInfo *MMI,
Richard Smithe657bbd2014-07-18 22:13:40 +00001944 Module *Owner, bool FromFinalization) {
Richard Smith49f906a2014-03-01 00:08:04 +00001945 assert(II && Owner);
1946
1947 SourceLocation ImportLoc = Owner->MacroVisibilityLoc;
Richard Smithe657bbd2014-07-18 22:13:40 +00001948 if (ImportLoc.isInvalid() && !FromFinalization) {
Richard Smith49f906a2014-03-01 00:08:04 +00001949 // FIXME: If we made macros from this module visible but didn't provide a
1950 // source location for the import, we don't have a location for the macro.
1951 // Use the location at which the containing module file was first imported
1952 // for now.
1953 ImportLoc = MMI->F->DirectImportLoc;
Richard Smith56be7542014-03-21 00:33:59 +00001954 assert(ImportLoc.isValid() && "no import location for a visible macro?");
Richard Smith49f906a2014-03-01 00:08:04 +00001955 }
1956
Benjamin Kramer834652a2014-05-03 18:44:26 +00001957 AmbiguousMacros *Prev =
Richard Smith49f906a2014-03-01 00:08:04 +00001958 removeOverriddenMacros(II, MMI->getOverriddenSubmodules());
1959
Richard Smith49f906a2014-03-01 00:08:04 +00001960 // Create a synthetic macro definition corresponding to the import (or null
1961 // if this was an undefinition of the macro).
1962 DefMacroDirective *MD = MMI->import(PP, ImportLoc);
1963
1964 // If there's no ambiguity, just install the macro.
1965 if (!Prev) {
1966 if (MD)
1967 PP.appendMacroDirective(II, MD);
1968 else
1969 PP.appendMacroDirective(II, PP.AllocateUndefMacroDirective(ImportLoc));
1970 return;
1971 }
1972 assert(!Prev->empty());
1973
1974 if (!MD) {
1975 // We imported a #undef that didn't remove all prior definitions. The most
1976 // recent prior definition remains, and we install it in the place of the
1977 // imported directive.
1978 MacroInfo *NewMI = Prev->back()->getInfo();
1979 Prev->pop_back();
1980 MD = PP.AllocateDefMacroDirective(NewMI, ImportLoc, /*Imported*/true);
1981 }
1982
1983 // We're introducing a macro definition that creates or adds to an ambiguity.
1984 // We can resolve that ambiguity if this macro is token-for-token identical to
1985 // all of the existing definitions.
1986 MacroInfo *NewMI = MD->getInfo();
1987 assert(NewMI && "macro definition with no MacroInfo?");
1988 while (!Prev->empty()) {
1989 MacroInfo *PrevMI = Prev->back()->getInfo();
1990 assert(PrevMI && "macro definition with no MacroInfo?");
1991
1992 // Before marking the macros as ambiguous, check if this is a case where
1993 // both macros are in system headers. If so, we trust that the system
1994 // did not get it wrong. This also handles cases where Clang's own
1995 // headers have a different spelling of certain system macros:
1996 // #define LONG_MAX __LONG_MAX__ (clang's limits.h)
1997 // #define LONG_MAX 0x7fffffffffffffffL (system's limits.h)
1998 //
1999 // FIXME: Remove the defined-in-system-headers check. clang's limits.h
2000 // overrides the system limits.h's macros, so there's no conflict here.
2001 if (NewMI != PrevMI &&
2002 !PrevMI->isIdenticalTo(*NewMI, PP, /*Syntactically=*/true) &&
2003 !areDefinedInSystemModules(PrevMI, NewMI, Owner, *this))
2004 break;
2005
2006 // The previous definition is the same as this one (or both are defined in
2007 // system modules so we can assume they're equivalent); we don't need to
2008 // track it any more.
2009 Prev->pop_back();
2010 }
2011
2012 if (!Prev->empty())
2013 MD->setAmbiguous(true);
2014
Argyrios Kyrtzidisb6210df2013-03-26 17:17:01 +00002015 PP.appendMacroDirective(II, MD);
Argyrios Kyrtzidiseb663da2013-03-22 21:12:57 +00002016}
2017
Argyrios Kyrtzidisce9b49e2014-03-14 02:26:27 +00002018ASTReader::InputFileInfo
2019ASTReader::readInputFileInfo(ModuleFile &F, unsigned ID) {
Ben Langmuir198c1682014-03-07 07:27:49 +00002020 // Go find this input file.
2021 BitstreamCursor &Cursor = F.InputFilesCursor;
2022 SavedStreamPosition SavedPosition(Cursor);
2023 Cursor.JumpToBit(F.InputFileOffsets[ID-1]);
2024
2025 unsigned Code = Cursor.ReadCode();
2026 RecordData Record;
2027 StringRef Blob;
2028
2029 unsigned Result = Cursor.readRecord(Code, Record, &Blob);
2030 assert(static_cast<InputFileRecordTypes>(Result) == INPUT_FILE &&
2031 "invalid record type for input file");
2032 (void)Result;
2033
Argyrios Kyrtzidisce9b49e2014-03-14 02:26:27 +00002034 std::string Filename;
2035 off_t StoredSize;
2036 time_t StoredTime;
2037 bool Overridden;
2038
Ben Langmuir198c1682014-03-07 07:27:49 +00002039 assert(Record[0] == ID && "Bogus stored ID or offset");
2040 StoredSize = static_cast<off_t>(Record[1]);
2041 StoredTime = static_cast<time_t>(Record[2]);
2042 Overridden = static_cast<bool>(Record[3]);
2043 Filename = Blob;
2044 MaybeAddSystemRootToFilename(F, Filename);
Argyrios Kyrtzidisce9b49e2014-03-14 02:26:27 +00002045
Hans Wennborg73945142014-03-14 17:45:06 +00002046 InputFileInfo R = { std::move(Filename), StoredSize, StoredTime, Overridden };
2047 return R;
Ben Langmuir198c1682014-03-07 07:27:49 +00002048}
2049
2050std::string ASTReader::getInputFileName(ModuleFile &F, unsigned int ID) {
Argyrios Kyrtzidisce9b49e2014-03-14 02:26:27 +00002051 return readInputFileInfo(F, ID).Filename;
Ben Langmuir198c1682014-03-07 07:27:49 +00002052}
2053
Argyrios Kyrtzidis61c3d872013-03-01 03:26:04 +00002054InputFile ASTReader::getInputFile(ModuleFile &F, unsigned ID, bool Complain) {
Guy Benyei11169dd2012-12-18 14:30:41 +00002055 // If this ID is bogus, just return an empty input file.
2056 if (ID == 0 || ID > F.InputFilesLoaded.size())
2057 return InputFile();
2058
2059 // If we've already loaded this input file, return it.
Argyrios Kyrtzidis61c3d872013-03-01 03:26:04 +00002060 if (F.InputFilesLoaded[ID-1].getFile())
Guy Benyei11169dd2012-12-18 14:30:41 +00002061 return F.InputFilesLoaded[ID-1];
2062
Argyrios Kyrtzidis9308f0a2014-01-08 19:13:34 +00002063 if (F.InputFilesLoaded[ID-1].isNotFound())
2064 return InputFile();
2065
Guy Benyei11169dd2012-12-18 14:30:41 +00002066 // Go find this input file.
Chris Lattner7fb3bef2013-01-20 00:56:42 +00002067 BitstreamCursor &Cursor = F.InputFilesCursor;
Guy Benyei11169dd2012-12-18 14:30:41 +00002068 SavedStreamPosition SavedPosition(Cursor);
2069 Cursor.JumpToBit(F.InputFileOffsets[ID-1]);
2070
Argyrios Kyrtzidisce9b49e2014-03-14 02:26:27 +00002071 InputFileInfo FI = readInputFileInfo(F, ID);
2072 off_t StoredSize = FI.StoredSize;
2073 time_t StoredTime = FI.StoredTime;
2074 bool Overridden = FI.Overridden;
2075 StringRef Filename = FI.Filename;
Argyrios Kyrtzidis61c3d872013-03-01 03:26:04 +00002076
Ben Langmuir198c1682014-03-07 07:27:49 +00002077 const FileEntry *File
2078 = Overridden? FileMgr.getVirtualFile(Filename, StoredSize, StoredTime)
2079 : FileMgr.getFile(Filename, /*OpenFile=*/false);
2080
2081 // If we didn't find the file, resolve it relative to the
2082 // original directory from which this AST file was created.
Craig Toppera13603a2014-05-22 05:54:18 +00002083 if (File == nullptr && !F.OriginalDir.empty() && !CurrentDir.empty() &&
Ben Langmuir198c1682014-03-07 07:27:49 +00002084 F.OriginalDir != CurrentDir) {
2085 std::string Resolved = resolveFileRelativeToOriginalDir(Filename,
2086 F.OriginalDir,
2087 CurrentDir);
2088 if (!Resolved.empty())
2089 File = FileMgr.getFile(Resolved);
2090 }
2091
2092 // For an overridden file, create a virtual file with the stored
2093 // size/timestamp.
Craig Toppera13603a2014-05-22 05:54:18 +00002094 if (Overridden && File == nullptr) {
Ben Langmuir198c1682014-03-07 07:27:49 +00002095 File = FileMgr.getVirtualFile(Filename, StoredSize, StoredTime);
2096 }
2097
Craig Toppera13603a2014-05-22 05:54:18 +00002098 if (File == nullptr) {
Ben Langmuir198c1682014-03-07 07:27:49 +00002099 if (Complain) {
2100 std::string ErrorStr = "could not find file '";
2101 ErrorStr += Filename;
2102 ErrorStr += "' referenced by AST file";
2103 Error(ErrorStr.c_str());
Guy Benyei11169dd2012-12-18 14:30:41 +00002104 }
Ben Langmuir198c1682014-03-07 07:27:49 +00002105 // Record that we didn't find the file.
2106 F.InputFilesLoaded[ID-1] = InputFile::getNotFound();
2107 return InputFile();
2108 }
Guy Benyei11169dd2012-12-18 14:30:41 +00002109
Ben Langmuir198c1682014-03-07 07:27:49 +00002110 // Check if there was a request to override the contents of the file
2111 // that was part of the precompiled header. Overridding such a file
2112 // can lead to problems when lexing using the source locations from the
2113 // PCH.
2114 SourceManager &SM = getSourceManager();
2115 if (!Overridden && SM.isFileOverridden(File)) {
2116 if (Complain)
2117 Error(diag::err_fe_pch_file_overridden, Filename);
2118 // After emitting the diagnostic, recover by disabling the override so
2119 // that the original file will be used.
2120 SM.disableFileContentsOverride(File);
2121 // The FileEntry is a virtual file entry with the size of the contents
2122 // that would override the original contents. Set it to the original's
2123 // size/time.
2124 FileMgr.modifyFileEntry(const_cast<FileEntry*>(File),
2125 StoredSize, StoredTime);
2126 }
Guy Benyei11169dd2012-12-18 14:30:41 +00002127
Ben Langmuir198c1682014-03-07 07:27:49 +00002128 bool IsOutOfDate = false;
2129
2130 // For an overridden file, there is nothing to validate.
2131 if (!Overridden && (StoredSize != File->getSize()
Guy Benyei11169dd2012-12-18 14:30:41 +00002132#if !defined(LLVM_ON_WIN32)
Ben Langmuir198c1682014-03-07 07:27:49 +00002133 // In our regression testing, the Windows file system seems to
2134 // have inconsistent modification times that sometimes
2135 // erroneously trigger this error-handling path.
2136 || StoredTime != File->getModificationTime()
Guy Benyei11169dd2012-12-18 14:30:41 +00002137#endif
Ben Langmuir198c1682014-03-07 07:27:49 +00002138 )) {
2139 if (Complain) {
2140 // Build a list of the PCH imports that got us here (in reverse).
2141 SmallVector<ModuleFile *, 4> ImportStack(1, &F);
2142 while (ImportStack.back()->ImportedBy.size() > 0)
2143 ImportStack.push_back(ImportStack.back()->ImportedBy[0]);
Ben Langmuire82630d2014-01-17 00:19:09 +00002144
Ben Langmuir198c1682014-03-07 07:27:49 +00002145 // The top-level PCH is stale.
2146 StringRef TopLevelPCHName(ImportStack.back()->FileName);
2147 Error(diag::err_fe_pch_file_modified, Filename, TopLevelPCHName);
Ben Langmuire82630d2014-01-17 00:19:09 +00002148
Ben Langmuir198c1682014-03-07 07:27:49 +00002149 // Print the import stack.
2150 if (ImportStack.size() > 1 && !Diags.isDiagnosticInFlight()) {
2151 Diag(diag::note_pch_required_by)
2152 << Filename << ImportStack[0]->FileName;
2153 for (unsigned I = 1; I < ImportStack.size(); ++I)
Ben Langmuire82630d2014-01-17 00:19:09 +00002154 Diag(diag::note_pch_required_by)
Ben Langmuir198c1682014-03-07 07:27:49 +00002155 << ImportStack[I-1]->FileName << ImportStack[I]->FileName;
Douglas Gregor7029ce12013-03-19 00:28:20 +00002156 }
2157
Ben Langmuir198c1682014-03-07 07:27:49 +00002158 if (!Diags.isDiagnosticInFlight())
2159 Diag(diag::note_pch_rebuild_required) << TopLevelPCHName;
Guy Benyei11169dd2012-12-18 14:30:41 +00002160 }
2161
Ben Langmuir198c1682014-03-07 07:27:49 +00002162 IsOutOfDate = true;
Guy Benyei11169dd2012-12-18 14:30:41 +00002163 }
2164
Ben Langmuir198c1682014-03-07 07:27:49 +00002165 InputFile IF = InputFile(File, Overridden, IsOutOfDate);
2166
2167 // Note that we've loaded this input file.
2168 F.InputFilesLoaded[ID-1] = IF;
2169 return IF;
Guy Benyei11169dd2012-12-18 14:30:41 +00002170}
2171
2172const FileEntry *ASTReader::getFileEntry(StringRef filenameStrRef) {
2173 ModuleFile &M = ModuleMgr.getPrimaryModule();
2174 std::string Filename = filenameStrRef;
2175 MaybeAddSystemRootToFilename(M, Filename);
2176 const FileEntry *File = FileMgr.getFile(Filename);
Craig Toppera13603a2014-05-22 05:54:18 +00002177 if (File == nullptr && !M.OriginalDir.empty() && !CurrentDir.empty() &&
Guy Benyei11169dd2012-12-18 14:30:41 +00002178 M.OriginalDir != CurrentDir) {
2179 std::string resolved = resolveFileRelativeToOriginalDir(Filename,
2180 M.OriginalDir,
2181 CurrentDir);
2182 if (!resolved.empty())
2183 File = FileMgr.getFile(resolved);
2184 }
2185
2186 return File;
2187}
2188
2189/// \brief If we are loading a relocatable PCH file, and the filename is
2190/// not an absolute path, add the system root to the beginning of the file
2191/// name.
2192void ASTReader::MaybeAddSystemRootToFilename(ModuleFile &M,
2193 std::string &Filename) {
2194 // If this is not a relocatable PCH file, there's nothing to do.
2195 if (!M.RelocatablePCH)
2196 return;
2197
2198 if (Filename.empty() || llvm::sys::path::is_absolute(Filename))
2199 return;
2200
2201 if (isysroot.empty()) {
2202 // If no system root was given, default to '/'
2203 Filename.insert(Filename.begin(), '/');
2204 return;
2205 }
2206
2207 unsigned Length = isysroot.size();
2208 if (isysroot[Length - 1] != '/')
2209 Filename.insert(Filename.begin(), '/');
2210
2211 Filename.insert(Filename.begin(), isysroot.begin(), isysroot.end());
2212}
2213
2214ASTReader::ASTReadResult
2215ASTReader::ReadControlBlock(ModuleFile &F,
Dmitri Gribenkof8579502013-01-12 19:30:44 +00002216 SmallVectorImpl<ImportedModule> &Loaded,
Ben Langmuirbeee15e2014-04-14 18:00:01 +00002217 const ModuleFile *ImportedBy,
Guy Benyei11169dd2012-12-18 14:30:41 +00002218 unsigned ClientLoadCapabilities) {
Chris Lattner7fb3bef2013-01-20 00:56:42 +00002219 BitstreamCursor &Stream = F.Stream;
Guy Benyei11169dd2012-12-18 14:30:41 +00002220
2221 if (Stream.EnterSubBlock(CONTROL_BLOCK_ID)) {
2222 Error("malformed block record in AST file");
2223 return Failure;
2224 }
2225
2226 // Read all of the records and blocks in the control block.
2227 RecordData Record;
Chris Lattnere7b154b2013-01-19 21:39:22 +00002228 while (1) {
2229 llvm::BitstreamEntry Entry = Stream.advance();
2230
2231 switch (Entry.Kind) {
2232 case llvm::BitstreamEntry::Error:
2233 Error("malformed block record in AST file");
2234 return Failure;
Dmitri Gribenkof430da42014-02-12 10:33:14 +00002235 case llvm::BitstreamEntry::EndBlock: {
2236 // Validate input files.
2237 const HeaderSearchOptions &HSOpts =
2238 PP.getHeaderSearchInfo().getHeaderSearchOpts();
Ben Langmuircb69b572014-03-07 06:40:32 +00002239
2240 // All user input files reside at the index range [0, Record[1]), and
2241 // system input files reside at [Record[1], Record[0]).
2242 // Record is the one from INPUT_FILE_OFFSETS.
2243 unsigned NumInputs = Record[0];
2244 unsigned NumUserInputs = Record[1];
2245
Dmitri Gribenkof430da42014-02-12 10:33:14 +00002246 if (!DisableValidation &&
Ben Langmuir1e258222014-04-08 15:36:28 +00002247 (ValidateSystemInputs || !HSOpts.ModulesValidateOncePerBuildSession ||
Dmitri Gribenkof430da42014-02-12 10:33:14 +00002248 F.InputFilesValidationTimestamp <= HSOpts.BuildSessionTimestamp)) {
Guy Benyei11169dd2012-12-18 14:30:41 +00002249 bool Complain = (ClientLoadCapabilities & ARR_OutOfDate) == 0;
Ben Langmuircb69b572014-03-07 06:40:32 +00002250
Dmitri Gribenkof430da42014-02-12 10:33:14 +00002251 // If we are reading a module, we will create a verification timestamp,
2252 // so we verify all input files. Otherwise, verify only user input
2253 // files.
Ben Langmuircb69b572014-03-07 06:40:32 +00002254
2255 unsigned N = NumUserInputs;
2256 if (ValidateSystemInputs ||
Ben Langmuircb69b572014-03-07 06:40:32 +00002257 (HSOpts.ModulesValidateOncePerBuildSession && F.Kind == MK_Module))
2258 N = NumInputs;
2259
Ben Langmuir3d4417c2014-02-07 17:31:11 +00002260 for (unsigned I = 0; I < N; ++I) {
Argyrios Kyrtzidis61c3d872013-03-01 03:26:04 +00002261 InputFile IF = getInputFile(F, I+1, Complain);
2262 if (!IF.getFile() || IF.isOutOfDate())
Guy Benyei11169dd2012-12-18 14:30:41 +00002263 return OutOfDate;
Argyrios Kyrtzidis61c3d872013-03-01 03:26:04 +00002264 }
Guy Benyei11169dd2012-12-18 14:30:41 +00002265 }
Ben Langmuircb69b572014-03-07 06:40:32 +00002266
Argyrios Kyrtzidis6d0753d2014-03-14 03:07:38 +00002267 if (Listener)
2268 Listener->visitModuleFile(F.FileName);
2269
Ben Langmuircb69b572014-03-07 06:40:32 +00002270 if (Listener && Listener->needsInputFileVisitation()) {
2271 unsigned N = Listener->needsSystemInputFileVisitation() ? NumInputs
2272 : NumUserInputs;
Argyrios Kyrtzidis68ccbe02014-03-14 02:26:31 +00002273 for (unsigned I = 0; I < N; ++I) {
2274 bool IsSystem = I >= NumUserInputs;
2275 InputFileInfo FI = readInputFileInfo(F, I+1);
2276 Listener->visitInputFile(FI.Filename, IsSystem, FI.Overridden);
2277 }
Ben Langmuircb69b572014-03-07 06:40:32 +00002278 }
2279
Guy Benyei11169dd2012-12-18 14:30:41 +00002280 return Success;
Dmitri Gribenkof430da42014-02-12 10:33:14 +00002281 }
2282
Chris Lattnere7b154b2013-01-19 21:39:22 +00002283 case llvm::BitstreamEntry::SubBlock:
2284 switch (Entry.ID) {
Guy Benyei11169dd2012-12-18 14:30:41 +00002285 case INPUT_FILES_BLOCK_ID:
2286 F.InputFilesCursor = Stream;
2287 if (Stream.SkipBlock() || // Skip with the main cursor
2288 // Read the abbreviations
2289 ReadBlockAbbrevs(F.InputFilesCursor, INPUT_FILES_BLOCK_ID)) {
2290 Error("malformed block record in AST file");
2291 return Failure;
2292 }
2293 continue;
Chris Lattnere7b154b2013-01-19 21:39:22 +00002294
Guy Benyei11169dd2012-12-18 14:30:41 +00002295 default:
Chris Lattnere7b154b2013-01-19 21:39:22 +00002296 if (Stream.SkipBlock()) {
2297 Error("malformed block record in AST file");
2298 return Failure;
2299 }
2300 continue;
Guy Benyei11169dd2012-12-18 14:30:41 +00002301 }
Chris Lattnere7b154b2013-01-19 21:39:22 +00002302
2303 case llvm::BitstreamEntry::Record:
2304 // The interesting case.
2305 break;
Guy Benyei11169dd2012-12-18 14:30:41 +00002306 }
2307
2308 // Read and process a record.
2309 Record.clear();
Chris Lattner0e6c9402013-01-20 02:38:54 +00002310 StringRef Blob;
2311 switch ((ControlRecordTypes)Stream.readRecord(Entry.ID, Record, &Blob)) {
Guy Benyei11169dd2012-12-18 14:30:41 +00002312 case METADATA: {
2313 if (Record[0] != VERSION_MAJOR && !DisableValidation) {
2314 if ((ClientLoadCapabilities & ARR_VersionMismatch) == 0)
Dmitri Gribenko2228cd32014-02-11 15:40:09 +00002315 Diag(Record[0] < VERSION_MAJOR? diag::err_pch_version_too_old
2316 : diag::err_pch_version_too_new);
Guy Benyei11169dd2012-12-18 14:30:41 +00002317 return VersionMismatch;
2318 }
2319
2320 bool hasErrors = Record[5];
2321 if (hasErrors && !DisableValidation && !AllowASTWithCompilerErrors) {
2322 Diag(diag::err_pch_with_compiler_errors);
2323 return HadErrors;
2324 }
2325
2326 F.RelocatablePCH = Record[4];
2327
2328 const std::string &CurBranch = getClangFullRepositoryVersion();
Chris Lattner0e6c9402013-01-20 02:38:54 +00002329 StringRef ASTBranch = Blob;
Guy Benyei11169dd2012-12-18 14:30:41 +00002330 if (StringRef(CurBranch) != ASTBranch && !DisableValidation) {
2331 if ((ClientLoadCapabilities & ARR_VersionMismatch) == 0)
Dmitri Gribenko2228cd32014-02-11 15:40:09 +00002332 Diag(diag::err_pch_different_branch) << ASTBranch << CurBranch;
Guy Benyei11169dd2012-12-18 14:30:41 +00002333 return VersionMismatch;
2334 }
2335 break;
2336 }
2337
2338 case IMPORTS: {
2339 // Load each of the imported PCH files.
2340 unsigned Idx = 0, N = Record.size();
2341 while (Idx < N) {
2342 // Read information about the AST file.
2343 ModuleKind ImportedKind = (ModuleKind)Record[Idx++];
2344 // The import location will be the local one for now; we will adjust
2345 // all import locations of module imports after the global source
2346 // location info are setup.
2347 SourceLocation ImportLoc =
2348 SourceLocation::getFromRawEncoding(Record[Idx++]);
Douglas Gregor7029ce12013-03-19 00:28:20 +00002349 off_t StoredSize = (off_t)Record[Idx++];
2350 time_t StoredModTime = (time_t)Record[Idx++];
Guy Benyei11169dd2012-12-18 14:30:41 +00002351 unsigned Length = Record[Idx++];
2352 SmallString<128> ImportedFile(Record.begin() + Idx,
2353 Record.begin() + Idx + Length);
2354 Idx += Length;
2355
2356 // Load the AST file.
2357 switch(ReadASTCore(ImportedFile, ImportedKind, ImportLoc, &F, Loaded,
Douglas Gregor7029ce12013-03-19 00:28:20 +00002358 StoredSize, StoredModTime,
Guy Benyei11169dd2012-12-18 14:30:41 +00002359 ClientLoadCapabilities)) {
2360 case Failure: return Failure;
2361 // If we have to ignore the dependency, we'll have to ignore this too.
Douglas Gregor2f1806e2013-03-19 00:38:50 +00002362 case Missing:
Guy Benyei11169dd2012-12-18 14:30:41 +00002363 case OutOfDate: return OutOfDate;
2364 case VersionMismatch: return VersionMismatch;
2365 case ConfigurationMismatch: return ConfigurationMismatch;
2366 case HadErrors: return HadErrors;
2367 case Success: break;
2368 }
2369 }
2370 break;
2371 }
2372
2373 case LANGUAGE_OPTIONS: {
2374 bool Complain = (ClientLoadCapabilities & ARR_ConfigurationMismatch) == 0;
2375 if (Listener && &F == *ModuleMgr.begin() &&
2376 ParseLanguageOptions(Record, Complain, *Listener) &&
Ben Langmuir2cb4a782014-02-05 22:21:15 +00002377 !DisableValidation && !AllowConfigurationMismatch)
Guy Benyei11169dd2012-12-18 14:30:41 +00002378 return ConfigurationMismatch;
2379 break;
2380 }
2381
2382 case TARGET_OPTIONS: {
2383 bool Complain = (ClientLoadCapabilities & ARR_ConfigurationMismatch)==0;
2384 if (Listener && &F == *ModuleMgr.begin() &&
2385 ParseTargetOptions(Record, Complain, *Listener) &&
Ben Langmuir2cb4a782014-02-05 22:21:15 +00002386 !DisableValidation && !AllowConfigurationMismatch)
Guy Benyei11169dd2012-12-18 14:30:41 +00002387 return ConfigurationMismatch;
2388 break;
2389 }
2390
2391 case DIAGNOSTIC_OPTIONS: {
Ben Langmuirb92de022014-04-29 16:25:26 +00002392 bool Complain = (ClientLoadCapabilities & ARR_OutOfDate)==0;
Guy Benyei11169dd2012-12-18 14:30:41 +00002393 if (Listener && &F == *ModuleMgr.begin() &&
2394 ParseDiagnosticOptions(Record, Complain, *Listener) &&
Ben Langmuirb92de022014-04-29 16:25:26 +00002395 !DisableValidation)
2396 return OutOfDate;
Guy Benyei11169dd2012-12-18 14:30:41 +00002397 break;
2398 }
2399
2400 case FILE_SYSTEM_OPTIONS: {
2401 bool Complain = (ClientLoadCapabilities & ARR_ConfigurationMismatch)==0;
2402 if (Listener && &F == *ModuleMgr.begin() &&
2403 ParseFileSystemOptions(Record, Complain, *Listener) &&
Ben Langmuir2cb4a782014-02-05 22:21:15 +00002404 !DisableValidation && !AllowConfigurationMismatch)
Guy Benyei11169dd2012-12-18 14:30:41 +00002405 return ConfigurationMismatch;
2406 break;
2407 }
2408
2409 case HEADER_SEARCH_OPTIONS: {
2410 bool Complain = (ClientLoadCapabilities & ARR_ConfigurationMismatch)==0;
2411 if (Listener && &F == *ModuleMgr.begin() &&
2412 ParseHeaderSearchOptions(Record, Complain, *Listener) &&
Ben Langmuir2cb4a782014-02-05 22:21:15 +00002413 !DisableValidation && !AllowConfigurationMismatch)
Guy Benyei11169dd2012-12-18 14:30:41 +00002414 return ConfigurationMismatch;
2415 break;
2416 }
2417
2418 case PREPROCESSOR_OPTIONS: {
2419 bool Complain = (ClientLoadCapabilities & ARR_ConfigurationMismatch)==0;
2420 if (Listener && &F == *ModuleMgr.begin() &&
2421 ParsePreprocessorOptions(Record, Complain, *Listener,
2422 SuggestedPredefines) &&
Ben Langmuir2cb4a782014-02-05 22:21:15 +00002423 !DisableValidation && !AllowConfigurationMismatch)
Guy Benyei11169dd2012-12-18 14:30:41 +00002424 return ConfigurationMismatch;
2425 break;
2426 }
2427
2428 case ORIGINAL_FILE:
2429 F.OriginalSourceFileID = FileID::get(Record[0]);
Chris Lattner0e6c9402013-01-20 02:38:54 +00002430 F.ActualOriginalSourceFileName = Blob;
Guy Benyei11169dd2012-12-18 14:30:41 +00002431 F.OriginalSourceFileName = F.ActualOriginalSourceFileName;
2432 MaybeAddSystemRootToFilename(F, F.OriginalSourceFileName);
2433 break;
2434
2435 case ORIGINAL_FILE_ID:
2436 F.OriginalSourceFileID = FileID::get(Record[0]);
2437 break;
2438
2439 case ORIGINAL_PCH_DIR:
Chris Lattner0e6c9402013-01-20 02:38:54 +00002440 F.OriginalDir = Blob;
Guy Benyei11169dd2012-12-18 14:30:41 +00002441 break;
2442
Ben Langmuirbeee15e2014-04-14 18:00:01 +00002443 case MODULE_NAME:
2444 F.ModuleName = Blob;
Ben Langmuir4f5212a2014-04-14 22:12:44 +00002445 if (Listener)
2446 Listener->ReadModuleName(F.ModuleName);
Ben Langmuirbeee15e2014-04-14 18:00:01 +00002447 break;
2448
2449 case MODULE_MAP_FILE:
2450 F.ModuleMapPath = Blob;
2451
2452 // Try to resolve ModuleName in the current header search context and
2453 // verify that it is found in the same module map file as we saved. If the
2454 // top-level AST file is a main file, skip this check because there is no
2455 // usable header search context.
2456 assert(!F.ModuleName.empty() &&
2457 "MODULE_NAME should come before MOUDLE_MAP_FILE");
2458 if (F.Kind == MK_Module &&
2459 (*ModuleMgr.begin())->Kind != MK_MainFile) {
2460 Module *M = PP.getHeaderSearchInfo().lookupModule(F.ModuleName);
2461 if (!M) {
2462 assert(ImportedBy && "top-level import should be verified");
2463 if ((ClientLoadCapabilities & ARR_Missing) == 0)
2464 Diag(diag::err_imported_module_not_found)
2465 << F.ModuleName << ImportedBy->FileName;
2466 return Missing;
2467 }
2468
2469 const FileEntry *StoredModMap = FileMgr.getFile(F.ModuleMapPath);
2470 if (StoredModMap == nullptr || StoredModMap != M->ModuleMap) {
2471 assert(M->ModuleMap && "found module is missing module map file");
2472 assert(M->Name == F.ModuleName && "found module with different name");
2473 assert(ImportedBy && "top-level import should be verified");
2474 if ((ClientLoadCapabilities & ARR_OutOfDate) == 0)
2475 Diag(diag::err_imported_module_modmap_changed)
2476 << F.ModuleName << ImportedBy->FileName
2477 << M->ModuleMap->getName() << F.ModuleMapPath;
2478 return OutOfDate;
2479 }
2480 }
Ben Langmuir4f5212a2014-04-14 22:12:44 +00002481
2482 if (Listener)
2483 Listener->ReadModuleMapFile(F.ModuleMapPath);
Ben Langmuirbeee15e2014-04-14 18:00:01 +00002484 break;
2485
Guy Benyei11169dd2012-12-18 14:30:41 +00002486 case INPUT_FILE_OFFSETS:
Chris Lattner0e6c9402013-01-20 02:38:54 +00002487 F.InputFileOffsets = (const uint32_t *)Blob.data();
Guy Benyei11169dd2012-12-18 14:30:41 +00002488 F.InputFilesLoaded.resize(Record[0]);
2489 break;
2490 }
2491 }
Guy Benyei11169dd2012-12-18 14:30:41 +00002492}
2493
Ben Langmuir2c9af442014-04-10 17:57:43 +00002494ASTReader::ASTReadResult
2495ASTReader::ReadASTBlock(ModuleFile &F, unsigned ClientLoadCapabilities) {
Chris Lattner7fb3bef2013-01-20 00:56:42 +00002496 BitstreamCursor &Stream = F.Stream;
Guy Benyei11169dd2012-12-18 14:30:41 +00002497
2498 if (Stream.EnterSubBlock(AST_BLOCK_ID)) {
2499 Error("malformed block record in AST file");
Ben Langmuir2c9af442014-04-10 17:57:43 +00002500 return Failure;
Guy Benyei11169dd2012-12-18 14:30:41 +00002501 }
2502
2503 // Read all of the records and blocks for the AST file.
2504 RecordData Record;
Chris Lattnere7b154b2013-01-19 21:39:22 +00002505 while (1) {
2506 llvm::BitstreamEntry Entry = Stream.advance();
2507
2508 switch (Entry.Kind) {
2509 case llvm::BitstreamEntry::Error:
2510 Error("error at end of module block in AST file");
Ben Langmuir2c9af442014-04-10 17:57:43 +00002511 return Failure;
Chris Lattnere7b154b2013-01-19 21:39:22 +00002512 case llvm::BitstreamEntry::EndBlock: {
Richard Smithc0fbba72013-04-03 22:49:41 +00002513 // Outside of C++, we do not store a lookup map for the translation unit.
2514 // Instead, mark it as needing a lookup map to be built if this module
2515 // contains any declarations lexically within it (which it always does!).
2516 // This usually has no cost, since we very rarely need the lookup map for
2517 // the translation unit outside C++.
Guy Benyei11169dd2012-12-18 14:30:41 +00002518 DeclContext *DC = Context.getTranslationUnitDecl();
Richard Smithc0fbba72013-04-03 22:49:41 +00002519 if (DC->hasExternalLexicalStorage() &&
2520 !getContext().getLangOpts().CPlusPlus)
Guy Benyei11169dd2012-12-18 14:30:41 +00002521 DC->setMustBuildLookupTable();
Chris Lattnere7b154b2013-01-19 21:39:22 +00002522
Ben Langmuir2c9af442014-04-10 17:57:43 +00002523 return Success;
Guy Benyei11169dd2012-12-18 14:30:41 +00002524 }
Chris Lattnere7b154b2013-01-19 21:39:22 +00002525 case llvm::BitstreamEntry::SubBlock:
2526 switch (Entry.ID) {
Guy Benyei11169dd2012-12-18 14:30:41 +00002527 case DECLTYPES_BLOCK_ID:
2528 // We lazily load the decls block, but we want to set up the
2529 // DeclsCursor cursor to point into it. Clone our current bitcode
2530 // cursor to it, enter the block and read the abbrevs in that block.
2531 // With the main cursor, we just skip over it.
2532 F.DeclsCursor = Stream;
2533 if (Stream.SkipBlock() || // Skip with the main cursor.
2534 // Read the abbrevs.
2535 ReadBlockAbbrevs(F.DeclsCursor, DECLTYPES_BLOCK_ID)) {
2536 Error("malformed block record in AST file");
Ben Langmuir2c9af442014-04-10 17:57:43 +00002537 return Failure;
Guy Benyei11169dd2012-12-18 14:30:41 +00002538 }
2539 break;
Richard Smithb9eab6d2014-03-20 19:44:17 +00002540
Guy Benyei11169dd2012-12-18 14:30:41 +00002541 case PREPROCESSOR_BLOCK_ID:
2542 F.MacroCursor = Stream;
2543 if (!PP.getExternalSource())
2544 PP.setExternalSource(this);
Chris Lattnere7b154b2013-01-19 21:39:22 +00002545
Guy Benyei11169dd2012-12-18 14:30:41 +00002546 if (Stream.SkipBlock() ||
2547 ReadBlockAbbrevs(F.MacroCursor, PREPROCESSOR_BLOCK_ID)) {
2548 Error("malformed block record in AST file");
Ben Langmuir2c9af442014-04-10 17:57:43 +00002549 return Failure;
Guy Benyei11169dd2012-12-18 14:30:41 +00002550 }
2551 F.MacroStartOffset = F.MacroCursor.GetCurrentBitNo();
2552 break;
Chris Lattnere7b154b2013-01-19 21:39:22 +00002553
Guy Benyei11169dd2012-12-18 14:30:41 +00002554 case PREPROCESSOR_DETAIL_BLOCK_ID:
2555 F.PreprocessorDetailCursor = Stream;
2556 if (Stream.SkipBlock() ||
Chris Lattnere7b154b2013-01-19 21:39:22 +00002557 ReadBlockAbbrevs(F.PreprocessorDetailCursor,
Guy Benyei11169dd2012-12-18 14:30:41 +00002558 PREPROCESSOR_DETAIL_BLOCK_ID)) {
Chris Lattnere7b154b2013-01-19 21:39:22 +00002559 Error("malformed preprocessor detail record in AST file");
Ben Langmuir2c9af442014-04-10 17:57:43 +00002560 return Failure;
Chris Lattnere7b154b2013-01-19 21:39:22 +00002561 }
Guy Benyei11169dd2012-12-18 14:30:41 +00002562 F.PreprocessorDetailStartOffset
Chris Lattnere7b154b2013-01-19 21:39:22 +00002563 = F.PreprocessorDetailCursor.GetCurrentBitNo();
2564
Guy Benyei11169dd2012-12-18 14:30:41 +00002565 if (!PP.getPreprocessingRecord())
2566 PP.createPreprocessingRecord();
2567 if (!PP.getPreprocessingRecord()->getExternalSource())
2568 PP.getPreprocessingRecord()->SetExternalSource(*this);
2569 break;
2570
2571 case SOURCE_MANAGER_BLOCK_ID:
2572 if (ReadSourceManagerBlock(F))
Ben Langmuir2c9af442014-04-10 17:57:43 +00002573 return Failure;
Guy Benyei11169dd2012-12-18 14:30:41 +00002574 break;
Chris Lattnere7b154b2013-01-19 21:39:22 +00002575
Guy Benyei11169dd2012-12-18 14:30:41 +00002576 case SUBMODULE_BLOCK_ID:
Ben Langmuir2c9af442014-04-10 17:57:43 +00002577 if (ASTReadResult Result = ReadSubmoduleBlock(F, ClientLoadCapabilities))
2578 return Result;
Guy Benyei11169dd2012-12-18 14:30:41 +00002579 break;
Chris Lattnere7b154b2013-01-19 21:39:22 +00002580
Guy Benyei11169dd2012-12-18 14:30:41 +00002581 case COMMENTS_BLOCK_ID: {
Chris Lattner7fb3bef2013-01-20 00:56:42 +00002582 BitstreamCursor C = Stream;
Guy Benyei11169dd2012-12-18 14:30:41 +00002583 if (Stream.SkipBlock() ||
2584 ReadBlockAbbrevs(C, COMMENTS_BLOCK_ID)) {
2585 Error("malformed comments block in AST file");
Ben Langmuir2c9af442014-04-10 17:57:43 +00002586 return Failure;
Guy Benyei11169dd2012-12-18 14:30:41 +00002587 }
2588 CommentsCursors.push_back(std::make_pair(C, &F));
2589 break;
2590 }
Chris Lattnere7b154b2013-01-19 21:39:22 +00002591
Guy Benyei11169dd2012-12-18 14:30:41 +00002592 default:
Chris Lattnere7b154b2013-01-19 21:39:22 +00002593 if (Stream.SkipBlock()) {
2594 Error("malformed block record in AST file");
Ben Langmuir2c9af442014-04-10 17:57:43 +00002595 return Failure;
Chris Lattnere7b154b2013-01-19 21:39:22 +00002596 }
2597 break;
Guy Benyei11169dd2012-12-18 14:30:41 +00002598 }
2599 continue;
Chris Lattnere7b154b2013-01-19 21:39:22 +00002600
2601 case llvm::BitstreamEntry::Record:
2602 // The interesting case.
2603 break;
Guy Benyei11169dd2012-12-18 14:30:41 +00002604 }
2605
2606 // Read and process a record.
2607 Record.clear();
Chris Lattner0e6c9402013-01-20 02:38:54 +00002608 StringRef Blob;
2609 switch ((ASTRecordTypes)Stream.readRecord(Entry.ID, Record, &Blob)) {
Guy Benyei11169dd2012-12-18 14:30:41 +00002610 default: // Default behavior: ignore.
2611 break;
2612
2613 case TYPE_OFFSET: {
2614 if (F.LocalNumTypes != 0) {
2615 Error("duplicate TYPE_OFFSET record in AST file");
Ben Langmuir2c9af442014-04-10 17:57:43 +00002616 return Failure;
Guy Benyei11169dd2012-12-18 14:30:41 +00002617 }
Chris Lattner0e6c9402013-01-20 02:38:54 +00002618 F.TypeOffsets = (const uint32_t *)Blob.data();
Guy Benyei11169dd2012-12-18 14:30:41 +00002619 F.LocalNumTypes = Record[0];
2620 unsigned LocalBaseTypeIndex = Record[1];
2621 F.BaseTypeIndex = getTotalNumTypes();
2622
2623 if (F.LocalNumTypes > 0) {
2624 // Introduce the global -> local mapping for types within this module.
2625 GlobalTypeMap.insert(std::make_pair(getTotalNumTypes(), &F));
2626
2627 // Introduce the local -> global mapping for types within this module.
2628 F.TypeRemap.insertOrReplace(
2629 std::make_pair(LocalBaseTypeIndex,
2630 F.BaseTypeIndex - LocalBaseTypeIndex));
2631
2632 TypesLoaded.resize(TypesLoaded.size() + F.LocalNumTypes);
2633 }
2634 break;
2635 }
2636
2637 case DECL_OFFSET: {
2638 if (F.LocalNumDecls != 0) {
2639 Error("duplicate DECL_OFFSET record in AST file");
Ben Langmuir2c9af442014-04-10 17:57:43 +00002640 return Failure;
Guy Benyei11169dd2012-12-18 14:30:41 +00002641 }
Chris Lattner0e6c9402013-01-20 02:38:54 +00002642 F.DeclOffsets = (const DeclOffset *)Blob.data();
Guy Benyei11169dd2012-12-18 14:30:41 +00002643 F.LocalNumDecls = Record[0];
2644 unsigned LocalBaseDeclID = Record[1];
2645 F.BaseDeclID = getTotalNumDecls();
2646
2647 if (F.LocalNumDecls > 0) {
2648 // Introduce the global -> local mapping for declarations within this
2649 // module.
2650 GlobalDeclMap.insert(
2651 std::make_pair(getTotalNumDecls() + NUM_PREDEF_DECL_IDS, &F));
2652
2653 // Introduce the local -> global mapping for declarations within this
2654 // module.
2655 F.DeclRemap.insertOrReplace(
2656 std::make_pair(LocalBaseDeclID, F.BaseDeclID - LocalBaseDeclID));
2657
2658 // Introduce the global -> local mapping for declarations within this
2659 // module.
2660 F.GlobalToLocalDeclIDs[&F] = LocalBaseDeclID;
2661
2662 DeclsLoaded.resize(DeclsLoaded.size() + F.LocalNumDecls);
2663 }
2664 break;
2665 }
2666
2667 case TU_UPDATE_LEXICAL: {
2668 DeclContext *TU = Context.getTranslationUnitDecl();
2669 DeclContextInfo &Info = F.DeclContextInfos[TU];
Chris Lattner0e6c9402013-01-20 02:38:54 +00002670 Info.LexicalDecls = reinterpret_cast<const KindDeclIDPair *>(Blob.data());
Guy Benyei11169dd2012-12-18 14:30:41 +00002671 Info.NumLexicalDecls
Chris Lattner0e6c9402013-01-20 02:38:54 +00002672 = static_cast<unsigned int>(Blob.size() / sizeof(KindDeclIDPair));
Guy Benyei11169dd2012-12-18 14:30:41 +00002673 TU->setHasExternalLexicalStorage(true);
2674 break;
2675 }
2676
2677 case UPDATE_VISIBLE: {
2678 unsigned Idx = 0;
2679 serialization::DeclID ID = ReadDeclID(F, Record, Idx);
2680 ASTDeclContextNameLookupTable *Table =
Justin Bognerda4e6502014-04-14 16:34:29 +00002681 ASTDeclContextNameLookupTable::Create(
2682 (const unsigned char *)Blob.data() + Record[Idx++],
2683 (const unsigned char *)Blob.data() + sizeof(uint32_t),
2684 (const unsigned char *)Blob.data(),
2685 ASTDeclContextNameLookupTrait(*this, F));
Richard Smithcd45dbc2014-04-19 03:48:30 +00002686 if (Decl *D = GetExistingDecl(ID)) {
Richard Smithd9174792014-03-11 03:10:46 +00002687 auto *DC = cast<DeclContext>(D);
2688 DC->getPrimaryContext()->setHasExternalVisibleStorage(true);
Richard Smith52e3fba2014-03-11 07:17:35 +00002689 auto *&LookupTable = F.DeclContextInfos[DC].NameLookupTableData;
Richard Smithcd45dbc2014-04-19 03:48:30 +00002690 // FIXME: There should never be an existing lookup table.
Richard Smith52e3fba2014-03-11 07:17:35 +00002691 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));
2732
2733 IdentifiersLoaded.resize(IdentifiersLoaded.size()
2734 + F.LocalNumIdentifiers);
2735 }
2736 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));
2825
2826 SelectorsLoaded.resize(SelectorsLoaded.size() + F.LocalNumSelectors);
2827 }
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) =
Guy Benyei11169dd2012-12-18 14:30:41 +00002868 SourceMgr.AllocateLoadedSLocEntries(F.LocalNumSLocEntries,
2869 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.
2907 ContinuousRangeMap<uint32_t, int, 2>::Builder SLocRemap(F.SLocRemap);
2908 ContinuousRangeMap<uint32_t, int, 2>::Builder
2909 IdentifierRemap(F.IdentifierRemap);
2910 ContinuousRangeMap<uint32_t, int, 2>::Builder
2911 MacroRemap(F.MacroRemap);
2912 ContinuousRangeMap<uint32_t, int, 2>::Builder
2913 PreprocessedEntityRemap(F.PreprocessedEntityRemap);
2914 ContinuousRangeMap<uint32_t, int, 2>::Builder
2915 SubmoduleRemap(F.SubmoduleRemap);
2916 ContinuousRangeMap<uint32_t, int, 2>::Builder
2917 SelectorRemap(F.SelectorRemap);
2918 ContinuousRangeMap<uint32_t, int, 2>::Builder DeclRemap(F.DeclRemap);
2919 ContinuousRangeMap<uint32_t, int, 2>::Builder TypeRemap(F.TypeRemap);
2920
2921 while(Data < DataEnd) {
Justin Bogner57ba0b22014-03-28 22:03:24 +00002922 using namespace llvm::support;
2923 uint16_t Len = endian::readNext<uint16_t, little, unaligned>(Data);
Guy Benyei11169dd2012-12-18 14:30:41 +00002924 StringRef Name = StringRef((const char*)Data, Len);
2925 Data += Len;
2926 ModuleFile *OM = ModuleMgr.lookup(Name);
2927 if (!OM) {
2928 Error("SourceLocation remap refers to unknown module");
Ben Langmuir2c9af442014-04-10 17:57:43 +00002929 return Failure;
Guy Benyei11169dd2012-12-18 14:30:41 +00002930 }
2931
Justin Bogner57ba0b22014-03-28 22:03:24 +00002932 uint32_t SLocOffset =
2933 endian::readNext<uint32_t, little, unaligned>(Data);
2934 uint32_t IdentifierIDOffset =
2935 endian::readNext<uint32_t, little, unaligned>(Data);
2936 uint32_t MacroIDOffset =
2937 endian::readNext<uint32_t, little, unaligned>(Data);
2938 uint32_t PreprocessedEntityIDOffset =
2939 endian::readNext<uint32_t, little, unaligned>(Data);
2940 uint32_t SubmoduleIDOffset =
2941 endian::readNext<uint32_t, little, unaligned>(Data);
2942 uint32_t SelectorIDOffset =
2943 endian::readNext<uint32_t, little, unaligned>(Data);
2944 uint32_t DeclIDOffset =
2945 endian::readNext<uint32_t, little, unaligned>(Data);
2946 uint32_t TypeIndexOffset =
2947 endian::readNext<uint32_t, little, unaligned>(Data);
2948
Guy Benyei11169dd2012-12-18 14:30:41 +00002949 // Source location offset is mapped to OM->SLocEntryBaseOffset.
2950 SLocRemap.insert(std::make_pair(SLocOffset,
2951 static_cast<int>(OM->SLocEntryBaseOffset - SLocOffset)));
2952 IdentifierRemap.insert(
2953 std::make_pair(IdentifierIDOffset,
2954 OM->BaseIdentifierID - IdentifierIDOffset));
2955 MacroRemap.insert(std::make_pair(MacroIDOffset,
2956 OM->BaseMacroID - MacroIDOffset));
2957 PreprocessedEntityRemap.insert(
2958 std::make_pair(PreprocessedEntityIDOffset,
2959 OM->BasePreprocessedEntityID - PreprocessedEntityIDOffset));
2960 SubmoduleRemap.insert(std::make_pair(SubmoduleIDOffset,
2961 OM->BaseSubmoduleID - SubmoduleIDOffset));
2962 SelectorRemap.insert(std::make_pair(SelectorIDOffset,
2963 OM->BaseSelectorID - SelectorIDOffset));
2964 DeclRemap.insert(std::make_pair(DeclIDOffset,
2965 OM->BaseDeclID - DeclIDOffset));
2966
2967 TypeRemap.insert(std::make_pair(TypeIndexOffset,
2968 OM->BaseTypeIndex - TypeIndexOffset));
2969
2970 // Global -> local mappings.
2971 F.GlobalToLocalDeclIDs[OM] = DeclIDOffset;
2972 }
2973 break;
2974 }
2975
2976 case SOURCE_MANAGER_LINE_TABLE:
2977 if (ParseLineTable(F, Record))
Ben Langmuir2c9af442014-04-10 17:57:43 +00002978 return Failure;
Guy Benyei11169dd2012-12-18 14:30:41 +00002979 break;
2980
2981 case SOURCE_LOCATION_PRELOADS: {
2982 // Need to transform from the local view (1-based IDs) to the global view,
2983 // which is based off F.SLocEntryBaseID.
2984 if (!F.PreloadSLocEntries.empty()) {
2985 Error("Multiple SOURCE_LOCATION_PRELOADS records in AST file");
Ben Langmuir2c9af442014-04-10 17:57:43 +00002986 return Failure;
Guy Benyei11169dd2012-12-18 14:30:41 +00002987 }
2988
2989 F.PreloadSLocEntries.swap(Record);
2990 break;
2991 }
2992
2993 case EXT_VECTOR_DECLS:
2994 for (unsigned I = 0, N = Record.size(); I != N; ++I)
2995 ExtVectorDecls.push_back(getGlobalDeclID(F, Record[I]));
2996 break;
2997
2998 case VTABLE_USES:
2999 if (Record.size() % 3 != 0) {
3000 Error("Invalid VTABLE_USES record");
Ben Langmuir2c9af442014-04-10 17:57:43 +00003001 return Failure;
Guy Benyei11169dd2012-12-18 14:30:41 +00003002 }
3003
3004 // Later tables overwrite earlier ones.
3005 // FIXME: Modules will have some trouble with this. This is clearly not
3006 // the right way to do this.
3007 VTableUses.clear();
3008
3009 for (unsigned Idx = 0, N = Record.size(); Idx != N; /* In loop */) {
3010 VTableUses.push_back(getGlobalDeclID(F, Record[Idx++]));
3011 VTableUses.push_back(
3012 ReadSourceLocation(F, Record, Idx).getRawEncoding());
3013 VTableUses.push_back(Record[Idx++]);
3014 }
3015 break;
3016
3017 case DYNAMIC_CLASSES:
3018 for (unsigned I = 0, N = Record.size(); I != N; ++I)
3019 DynamicClasses.push_back(getGlobalDeclID(F, Record[I]));
3020 break;
3021
3022 case PENDING_IMPLICIT_INSTANTIATIONS:
3023 if (PendingInstantiations.size() % 2 != 0) {
3024 Error("Invalid existing PendingInstantiations");
Ben Langmuir2c9af442014-04-10 17:57:43 +00003025 return Failure;
Guy Benyei11169dd2012-12-18 14:30:41 +00003026 }
3027
3028 if (Record.size() % 2 != 0) {
3029 Error("Invalid PENDING_IMPLICIT_INSTANTIATIONS block");
Ben Langmuir2c9af442014-04-10 17:57:43 +00003030 return Failure;
Guy Benyei11169dd2012-12-18 14:30:41 +00003031 }
3032
3033 for (unsigned I = 0, N = Record.size(); I != N; /* in loop */) {
3034 PendingInstantiations.push_back(getGlobalDeclID(F, Record[I++]));
3035 PendingInstantiations.push_back(
3036 ReadSourceLocation(F, Record, I).getRawEncoding());
3037 }
3038 break;
3039
3040 case SEMA_DECL_REFS:
Richard Smith3d8e97e2013-10-18 06:54:39 +00003041 if (Record.size() != 2) {
3042 Error("Invalid SEMA_DECL_REFS block");
Ben Langmuir2c9af442014-04-10 17:57:43 +00003043 return Failure;
Richard Smith3d8e97e2013-10-18 06:54:39 +00003044 }
Guy Benyei11169dd2012-12-18 14:30:41 +00003045 for (unsigned I = 0, N = Record.size(); I != N; ++I)
3046 SemaDeclRefs.push_back(getGlobalDeclID(F, Record[I]));
3047 break;
3048
3049 case PPD_ENTITIES_OFFSETS: {
Chris Lattner0e6c9402013-01-20 02:38:54 +00003050 F.PreprocessedEntityOffsets = (const PPEntityOffset *)Blob.data();
3051 assert(Blob.size() % sizeof(PPEntityOffset) == 0);
3052 F.NumPreprocessedEntities = Blob.size() / sizeof(PPEntityOffset);
Guy Benyei11169dd2012-12-18 14:30:41 +00003053
3054 unsigned LocalBasePreprocessedEntityID = Record[0];
3055
3056 unsigned StartingID;
3057 if (!PP.getPreprocessingRecord())
3058 PP.createPreprocessingRecord();
3059 if (!PP.getPreprocessingRecord()->getExternalSource())
3060 PP.getPreprocessingRecord()->SetExternalSource(*this);
3061 StartingID
3062 = PP.getPreprocessingRecord()
3063 ->allocateLoadedEntities(F.NumPreprocessedEntities);
3064 F.BasePreprocessedEntityID = StartingID;
3065
3066 if (F.NumPreprocessedEntities > 0) {
3067 // Introduce the global -> local mapping for preprocessed entities in
3068 // this module.
3069 GlobalPreprocessedEntityMap.insert(std::make_pair(StartingID, &F));
3070
3071 // Introduce the local -> global mapping for preprocessed entities in
3072 // this module.
3073 F.PreprocessedEntityRemap.insertOrReplace(
3074 std::make_pair(LocalBasePreprocessedEntityID,
3075 F.BasePreprocessedEntityID - LocalBasePreprocessedEntityID));
3076 }
3077
3078 break;
3079 }
3080
3081 case DECL_UPDATE_OFFSETS: {
3082 if (Record.size() % 2 != 0) {
3083 Error("invalid DECL_UPDATE_OFFSETS block in AST file");
Ben Langmuir2c9af442014-04-10 17:57:43 +00003084 return Failure;
Guy Benyei11169dd2012-12-18 14:30:41 +00003085 }
Richard Smithcd45dbc2014-04-19 03:48:30 +00003086 for (unsigned I = 0, N = Record.size(); I != N; I += 2) {
3087 GlobalDeclID ID = getGlobalDeclID(F, Record[I]);
3088 DeclUpdateOffsets[ID].push_back(std::make_pair(&F, Record[I + 1]));
3089
3090 // If we've already loaded the decl, perform the updates when we finish
3091 // loading this block.
3092 if (Decl *D = GetExistingDecl(ID))
3093 PendingUpdateRecords.push_back(std::make_pair(ID, D));
3094 }
Guy Benyei11169dd2012-12-18 14:30:41 +00003095 break;
3096 }
3097
3098 case DECL_REPLACEMENTS: {
3099 if (Record.size() % 3 != 0) {
3100 Error("invalid DECL_REPLACEMENTS block in AST file");
Ben Langmuir2c9af442014-04-10 17:57:43 +00003101 return Failure;
Guy Benyei11169dd2012-12-18 14:30:41 +00003102 }
3103 for (unsigned I = 0, N = Record.size(); I != N; I += 3)
3104 ReplacedDecls[getGlobalDeclID(F, Record[I])]
3105 = ReplacedDeclInfo(&F, Record[I+1], Record[I+2]);
3106 break;
3107 }
3108
3109 case OBJC_CATEGORIES_MAP: {
3110 if (F.LocalNumObjCCategoriesInMap != 0) {
3111 Error("duplicate OBJC_CATEGORIES_MAP record in AST file");
Ben Langmuir2c9af442014-04-10 17:57:43 +00003112 return Failure;
Guy Benyei11169dd2012-12-18 14:30:41 +00003113 }
3114
3115 F.LocalNumObjCCategoriesInMap = Record[0];
Chris Lattner0e6c9402013-01-20 02:38:54 +00003116 F.ObjCCategoriesMap = (const ObjCCategoriesInfo *)Blob.data();
Guy Benyei11169dd2012-12-18 14:30:41 +00003117 break;
3118 }
3119
3120 case OBJC_CATEGORIES:
3121 F.ObjCCategories.swap(Record);
3122 break;
3123
3124 case CXX_BASE_SPECIFIER_OFFSETS: {
3125 if (F.LocalNumCXXBaseSpecifiers != 0) {
3126 Error("duplicate CXX_BASE_SPECIFIER_OFFSETS record in AST file");
Ben Langmuir2c9af442014-04-10 17:57:43 +00003127 return Failure;
Guy Benyei11169dd2012-12-18 14:30:41 +00003128 }
3129
3130 F.LocalNumCXXBaseSpecifiers = Record[0];
Chris Lattner0e6c9402013-01-20 02:38:54 +00003131 F.CXXBaseSpecifiersOffsets = (const uint32_t *)Blob.data();
Guy Benyei11169dd2012-12-18 14:30:41 +00003132 NumCXXBaseSpecifiersLoaded += F.LocalNumCXXBaseSpecifiers;
3133 break;
3134 }
3135
3136 case DIAG_PRAGMA_MAPPINGS:
3137 if (F.PragmaDiagMappings.empty())
3138 F.PragmaDiagMappings.swap(Record);
3139 else
3140 F.PragmaDiagMappings.insert(F.PragmaDiagMappings.end(),
3141 Record.begin(), Record.end());
3142 break;
3143
3144 case CUDA_SPECIAL_DECL_REFS:
3145 // Later tables overwrite earlier ones.
3146 // FIXME: Modules will have trouble with this.
3147 CUDASpecialDeclRefs.clear();
3148 for (unsigned I = 0, N = Record.size(); I != N; ++I)
3149 CUDASpecialDeclRefs.push_back(getGlobalDeclID(F, Record[I]));
3150 break;
3151
3152 case HEADER_SEARCH_TABLE: {
Chris Lattner0e6c9402013-01-20 02:38:54 +00003153 F.HeaderFileInfoTableData = Blob.data();
Guy Benyei11169dd2012-12-18 14:30:41 +00003154 F.LocalNumHeaderFileInfos = Record[1];
Guy Benyei11169dd2012-12-18 14:30:41 +00003155 if (Record[0]) {
3156 F.HeaderFileInfoTable
3157 = HeaderFileInfoLookupTable::Create(
3158 (const unsigned char *)F.HeaderFileInfoTableData + Record[0],
3159 (const unsigned char *)F.HeaderFileInfoTableData,
3160 HeaderFileInfoTrait(*this, F,
3161 &PP.getHeaderSearchInfo(),
Chris Lattner0e6c9402013-01-20 02:38:54 +00003162 Blob.data() + Record[2]));
Guy Benyei11169dd2012-12-18 14:30:41 +00003163
3164 PP.getHeaderSearchInfo().SetExternalSource(this);
3165 if (!PP.getHeaderSearchInfo().getExternalLookup())
3166 PP.getHeaderSearchInfo().SetExternalLookup(this);
3167 }
3168 break;
3169 }
3170
3171 case FP_PRAGMA_OPTIONS:
3172 // Later tables overwrite earlier ones.
3173 FPPragmaOptions.swap(Record);
3174 break;
3175
3176 case OPENCL_EXTENSIONS:
3177 // Later tables overwrite earlier ones.
3178 OpenCLExtensions.swap(Record);
3179 break;
3180
3181 case TENTATIVE_DEFINITIONS:
3182 for (unsigned I = 0, N = Record.size(); I != N; ++I)
3183 TentativeDefinitions.push_back(getGlobalDeclID(F, Record[I]));
3184 break;
3185
3186 case KNOWN_NAMESPACES:
3187 for (unsigned I = 0, N = Record.size(); I != N; ++I)
3188 KnownNamespaces.push_back(getGlobalDeclID(F, Record[I]));
3189 break;
Nick Lewycky8334af82013-01-26 00:35:08 +00003190
Nick Lewycky9c7eb1d2013-02-01 08:13:20 +00003191 case UNDEFINED_BUT_USED:
3192 if (UndefinedButUsed.size() % 2 != 0) {
3193 Error("Invalid existing UndefinedButUsed");
Ben Langmuir2c9af442014-04-10 17:57:43 +00003194 return Failure;
Nick Lewycky8334af82013-01-26 00:35:08 +00003195 }
3196
3197 if (Record.size() % 2 != 0) {
Nick Lewycky9c7eb1d2013-02-01 08:13:20 +00003198 Error("invalid undefined-but-used record");
Ben Langmuir2c9af442014-04-10 17:57:43 +00003199 return Failure;
Nick Lewycky8334af82013-01-26 00:35:08 +00003200 }
3201 for (unsigned I = 0, N = Record.size(); I != N; /* in loop */) {
Nick Lewycky9c7eb1d2013-02-01 08:13:20 +00003202 UndefinedButUsed.push_back(getGlobalDeclID(F, Record[I++]));
3203 UndefinedButUsed.push_back(
Nick Lewycky8334af82013-01-26 00:35:08 +00003204 ReadSourceLocation(F, Record, I).getRawEncoding());
3205 }
3206 break;
3207
Guy Benyei11169dd2012-12-18 14:30:41 +00003208 case IMPORTED_MODULES: {
3209 if (F.Kind != MK_Module) {
3210 // If we aren't loading a module (which has its own exports), make
3211 // all of the imported modules visible.
3212 // FIXME: Deal with macros-only imports.
Richard Smith56be7542014-03-21 00:33:59 +00003213 for (unsigned I = 0, N = Record.size(); I != N; /**/) {
3214 unsigned GlobalID = getGlobalSubmoduleID(F, Record[I++]);
3215 SourceLocation Loc = ReadSourceLocation(F, Record, I);
3216 if (GlobalID)
Aaron Ballman4f45b712014-03-21 15:22:56 +00003217 ImportedModules.push_back(ImportedSubmodule(GlobalID, Loc));
Guy Benyei11169dd2012-12-18 14:30:41 +00003218 }
3219 }
3220 break;
3221 }
3222
3223 case LOCAL_REDECLARATIONS: {
3224 F.RedeclarationChains.swap(Record);
3225 break;
3226 }
3227
3228 case LOCAL_REDECLARATIONS_MAP: {
3229 if (F.LocalNumRedeclarationsInMap != 0) {
3230 Error("duplicate LOCAL_REDECLARATIONS_MAP record in AST file");
Ben Langmuir2c9af442014-04-10 17:57:43 +00003231 return Failure;
Guy Benyei11169dd2012-12-18 14:30:41 +00003232 }
3233
3234 F.LocalNumRedeclarationsInMap = Record[0];
Chris Lattner0e6c9402013-01-20 02:38:54 +00003235 F.RedeclarationsMap = (const LocalRedeclarationsInfo *)Blob.data();
Guy Benyei11169dd2012-12-18 14:30:41 +00003236 break;
3237 }
3238
3239 case MERGED_DECLARATIONS: {
3240 for (unsigned Idx = 0; Idx < Record.size(); /* increment in loop */) {
3241 GlobalDeclID CanonID = getGlobalDeclID(F, Record[Idx++]);
3242 SmallVectorImpl<GlobalDeclID> &Decls = StoredMergedDecls[CanonID];
3243 for (unsigned N = Record[Idx++]; N > 0; --N)
3244 Decls.push_back(getGlobalDeclID(F, Record[Idx++]));
3245 }
3246 break;
3247 }
3248
3249 case MACRO_OFFSET: {
3250 if (F.LocalNumMacros != 0) {
3251 Error("duplicate MACRO_OFFSET record in AST file");
Ben Langmuir2c9af442014-04-10 17:57:43 +00003252 return Failure;
Guy Benyei11169dd2012-12-18 14:30:41 +00003253 }
Chris Lattner0e6c9402013-01-20 02:38:54 +00003254 F.MacroOffsets = (const uint32_t *)Blob.data();
Guy Benyei11169dd2012-12-18 14:30:41 +00003255 F.LocalNumMacros = Record[0];
3256 unsigned LocalBaseMacroID = Record[1];
3257 F.BaseMacroID = getTotalNumMacros();
3258
3259 if (F.LocalNumMacros > 0) {
3260 // Introduce the global -> local mapping for macros within this module.
3261 GlobalMacroMap.insert(std::make_pair(getTotalNumMacros() + 1, &F));
3262
3263 // Introduce the local -> global mapping for macros within this module.
3264 F.MacroRemap.insertOrReplace(
3265 std::make_pair(LocalBaseMacroID,
3266 F.BaseMacroID - LocalBaseMacroID));
3267
3268 MacrosLoaded.resize(MacrosLoaded.size() + F.LocalNumMacros);
3269 }
3270 break;
3271 }
3272
Argyrios Kyrtzidiseb663da2013-03-22 21:12:57 +00003273 case MACRO_TABLE: {
3274 // FIXME: Not used yet.
Guy Benyei11169dd2012-12-18 14:30:41 +00003275 break;
3276 }
Richard Smithe40f2ba2013-08-07 21:41:30 +00003277
3278 case LATE_PARSED_TEMPLATE: {
3279 LateParsedTemplates.append(Record.begin(), Record.end());
3280 break;
3281 }
Dario Domizioli13a0a382014-05-23 12:13:25 +00003282
3283 case OPTIMIZE_PRAGMA_OPTIONS:
3284 if (Record.size() != 1) {
3285 Error("invalid pragma optimize record");
3286 return Failure;
3287 }
3288 OptimizeOffPragmaLocation = ReadSourceLocation(F, Record[0]);
3289 break;
Guy Benyei11169dd2012-12-18 14:30:41 +00003290 }
3291 }
Guy Benyei11169dd2012-12-18 14:30:41 +00003292}
3293
Douglas Gregorc1489562013-02-12 23:36:21 +00003294/// \brief Move the given method to the back of the global list of methods.
3295static void moveMethodToBackOfGlobalList(Sema &S, ObjCMethodDecl *Method) {
3296 // Find the entry for this selector in the method pool.
3297 Sema::GlobalMethodPool::iterator Known
3298 = S.MethodPool.find(Method->getSelector());
3299 if (Known == S.MethodPool.end())
3300 return;
3301
3302 // Retrieve the appropriate method list.
3303 ObjCMethodList &Start = Method->isInstanceMethod()? Known->second.first
3304 : Known->second.second;
3305 bool Found = false;
Argyrios Kyrtzidisd3da6e02013-04-17 00:08:58 +00003306 for (ObjCMethodList *List = &Start; List; List = List->getNext()) {
Douglas Gregorc1489562013-02-12 23:36:21 +00003307 if (!Found) {
3308 if (List->Method == Method) {
3309 Found = true;
3310 } else {
3311 // Keep searching.
3312 continue;
3313 }
3314 }
3315
Argyrios Kyrtzidisd3da6e02013-04-17 00:08:58 +00003316 if (List->getNext())
3317 List->Method = List->getNext()->Method;
Douglas Gregorc1489562013-02-12 23:36:21 +00003318 else
3319 List->Method = Method;
3320 }
3321}
3322
Richard Smithe657bbd2014-07-18 22:13:40 +00003323void ASTReader::makeNamesVisible(const HiddenNames &Names, Module *Owner,
3324 bool FromFinalization) {
3325 // FIXME: Only do this if Owner->NameVisibility == AllVisible.
Richard Smith49f906a2014-03-01 00:08:04 +00003326 for (unsigned I = 0, N = Names.HiddenDecls.size(); I != N; ++I) {
3327 Decl *D = Names.HiddenDecls[I];
3328 bool wasHidden = D->Hidden;
3329 D->Hidden = false;
Guy Benyei11169dd2012-12-18 14:30:41 +00003330
Richard Smith49f906a2014-03-01 00:08:04 +00003331 if (wasHidden && SemaObj) {
3332 if (ObjCMethodDecl *Method = dyn_cast<ObjCMethodDecl>(D)) {
3333 moveMethodToBackOfGlobalList(*SemaObj, Method);
Douglas Gregorc1489562013-02-12 23:36:21 +00003334 }
Guy Benyei11169dd2012-12-18 14:30:41 +00003335 }
3336 }
Richard Smith49f906a2014-03-01 00:08:04 +00003337
Richard Smithe657bbd2014-07-18 22:13:40 +00003338 assert((FromFinalization || Owner->NameVisibility >= Module::MacrosVisible) &&
3339 "nothing to make visible?");
Richard Smith49f906a2014-03-01 00:08:04 +00003340 for (HiddenMacrosMap::const_iterator I = Names.HiddenMacros.begin(),
3341 E = Names.HiddenMacros.end();
3342 I != E; ++I)
Richard Smithe657bbd2014-07-18 22:13:40 +00003343 installImportedMacro(I->first, I->second, Owner, FromFinalization);
Guy Benyei11169dd2012-12-18 14:30:41 +00003344}
3345
Richard Smith49f906a2014-03-01 00:08:04 +00003346void ASTReader::makeModuleVisible(Module *Mod,
Argyrios Kyrtzidis125df052013-02-01 16:36:12 +00003347 Module::NameVisibilityKind NameVisibility,
Douglas Gregorfb912652013-03-20 21:10:35 +00003348 SourceLocation ImportLoc,
3349 bool Complain) {
Guy Benyei11169dd2012-12-18 14:30:41 +00003350 llvm::SmallPtrSet<Module *, 4> Visited;
Dmitri Gribenkof8579502013-01-12 19:30:44 +00003351 SmallVector<Module *, 4> Stack;
Robert Wilhelm25284cc2013-08-23 16:11:15 +00003352 Stack.push_back(Mod);
Guy Benyei11169dd2012-12-18 14:30:41 +00003353 while (!Stack.empty()) {
Robert Wilhelm25284cc2013-08-23 16:11:15 +00003354 Mod = Stack.pop_back_val();
Guy Benyei11169dd2012-12-18 14:30:41 +00003355
3356 if (NameVisibility <= Mod->NameVisibility) {
Robert Wilhelm25284cc2013-08-23 16:11:15 +00003357 // This module already has this level of visibility (or greater), so
Guy Benyei11169dd2012-12-18 14:30:41 +00003358 // there is nothing more to do.
3359 continue;
3360 }
Richard Smith49f906a2014-03-01 00:08:04 +00003361
Guy Benyei11169dd2012-12-18 14:30:41 +00003362 if (!Mod->isAvailable()) {
3363 // Modules that aren't available cannot be made visible.
3364 continue;
3365 }
3366
3367 // Update the module's name visibility.
Richard Smith49f906a2014-03-01 00:08:04 +00003368 if (NameVisibility >= Module::MacrosVisible &&
3369 Mod->NameVisibility < Module::MacrosVisible)
3370 Mod->MacroVisibilityLoc = ImportLoc;
Guy Benyei11169dd2012-12-18 14:30:41 +00003371 Mod->NameVisibility = NameVisibility;
Richard Smith49f906a2014-03-01 00:08:04 +00003372
Guy Benyei11169dd2012-12-18 14:30:41 +00003373 // If we've already deserialized any names from this module,
3374 // mark them as visible.
3375 HiddenNamesMapType::iterator Hidden = HiddenNamesMap.find(Mod);
3376 if (Hidden != HiddenNamesMap.end()) {
Richard Smithe657bbd2014-07-18 22:13:40 +00003377 makeNamesVisible(Hidden->second, Hidden->first,
3378 /*FromFinalization*/false);
Guy Benyei11169dd2012-12-18 14:30:41 +00003379 HiddenNamesMap.erase(Hidden);
3380 }
Dmitri Gribenkoe9bcf5b2013-11-04 21:51:33 +00003381
Guy Benyei11169dd2012-12-18 14:30:41 +00003382 // Push any exported modules onto the stack to be marked as visible.
Argyrios Kyrtzidis8739f7b2013-02-19 19:34:40 +00003383 SmallVector<Module *, 16> Exports;
3384 Mod->getExportedModules(Exports);
3385 for (SmallVectorImpl<Module *>::iterator
3386 I = Exports.begin(), E = Exports.end(); I != E; ++I) {
3387 Module *Exported = *I;
3388 if (Visited.insert(Exported))
3389 Stack.push_back(Exported);
Guy Benyei11169dd2012-12-18 14:30:41 +00003390 }
Douglas Gregorfb912652013-03-20 21:10:35 +00003391
3392 // Detect any conflicts.
3393 if (Complain) {
3394 assert(ImportLoc.isValid() && "Missing import location");
3395 for (unsigned I = 0, N = Mod->Conflicts.size(); I != N; ++I) {
3396 if (Mod->Conflicts[I].Other->NameVisibility >= NameVisibility) {
3397 Diag(ImportLoc, diag::warn_module_conflict)
3398 << Mod->getFullModuleName()
3399 << Mod->Conflicts[I].Other->getFullModuleName()
3400 << Mod->Conflicts[I].Message;
3401 // FIXME: Need note where the other module was imported.
3402 }
3403 }
3404 }
Guy Benyei11169dd2012-12-18 14:30:41 +00003405 }
3406}
3407
Douglas Gregore060e572013-01-25 01:03:03 +00003408bool ASTReader::loadGlobalIndex() {
3409 if (GlobalIndex)
3410 return false;
3411
3412 if (TriedLoadingGlobalIndex || !UseGlobalIndex ||
3413 !Context.getLangOpts().Modules)
3414 return true;
3415
3416 // Try to load the global index.
3417 TriedLoadingGlobalIndex = true;
3418 StringRef ModuleCachePath
3419 = getPreprocessor().getHeaderSearchInfo().getModuleCachePath();
3420 std::pair<GlobalModuleIndex *, GlobalModuleIndex::ErrorCode> Result
Douglas Gregor7029ce12013-03-19 00:28:20 +00003421 = GlobalModuleIndex::readIndex(ModuleCachePath);
Douglas Gregore060e572013-01-25 01:03:03 +00003422 if (!Result.first)
3423 return true;
3424
3425 GlobalIndex.reset(Result.first);
Douglas Gregor7211ac12013-01-25 23:32:03 +00003426 ModuleMgr.setGlobalIndex(GlobalIndex.get());
Douglas Gregore060e572013-01-25 01:03:03 +00003427 return false;
3428}
3429
3430bool ASTReader::isGlobalIndexUnavailable() const {
3431 return Context.getLangOpts().Modules && UseGlobalIndex &&
3432 !hasGlobalIndex() && TriedLoadingGlobalIndex;
3433}
3434
Dmitri Gribenkof430da42014-02-12 10:33:14 +00003435static void updateModuleTimestamp(ModuleFile &MF) {
3436 // Overwrite the timestamp file contents so that file's mtime changes.
3437 std::string TimestampFilename = MF.getTimestampFilename();
3438 std::string ErrorInfo;
Rafael Espindola04a13be2014-02-24 15:06:52 +00003439 llvm::raw_fd_ostream OS(TimestampFilename.c_str(), ErrorInfo,
Rafael Espindola4fbd3732014-02-24 18:20:21 +00003440 llvm::sys::fs::F_Text);
Dmitri Gribenkof430da42014-02-12 10:33:14 +00003441 if (!ErrorInfo.empty())
3442 return;
3443 OS << "Timestamp file\n";
3444}
3445
Guy Benyei11169dd2012-12-18 14:30:41 +00003446ASTReader::ASTReadResult ASTReader::ReadAST(const std::string &FileName,
3447 ModuleKind Type,
3448 SourceLocation ImportLoc,
3449 unsigned ClientLoadCapabilities) {
Argyrios Kyrtzidisdc9fdaf2013-05-24 05:44:08 +00003450 llvm::SaveAndRestore<SourceLocation>
3451 SetCurImportLocRAII(CurrentImportLoc, ImportLoc);
3452
Richard Smithd1c46742014-04-30 02:24:17 +00003453 // Defer any pending actions until we get to the end of reading the AST file.
3454 Deserializing AnASTFile(this);
3455
Guy Benyei11169dd2012-12-18 14:30:41 +00003456 // Bump the generation number.
Richard Smith053f6c62014-05-16 23:01:30 +00003457 unsigned PreviousGeneration = incrementGeneration(Context);
Guy Benyei11169dd2012-12-18 14:30:41 +00003458
3459 unsigned NumModules = ModuleMgr.size();
Dmitri Gribenkof8579502013-01-12 19:30:44 +00003460 SmallVector<ImportedModule, 4> Loaded;
Guy Benyei11169dd2012-12-18 14:30:41 +00003461 switch(ASTReadResult ReadResult = ReadASTCore(FileName, Type, ImportLoc,
Craig Toppera13603a2014-05-22 05:54:18 +00003462 /*ImportedBy=*/nullptr, Loaded,
Douglas Gregor7029ce12013-03-19 00:28:20 +00003463 0, 0,
Guy Benyei11169dd2012-12-18 14:30:41 +00003464 ClientLoadCapabilities)) {
3465 case Failure:
Douglas Gregor7029ce12013-03-19 00:28:20 +00003466 case Missing:
Guy Benyei11169dd2012-12-18 14:30:41 +00003467 case OutOfDate:
3468 case VersionMismatch:
3469 case ConfigurationMismatch:
Ben Langmuir9801b252014-06-20 00:24:56 +00003470 case HadErrors: {
3471 llvm::SmallPtrSet<ModuleFile *, 4> LoadedSet;
3472 for (const ImportedModule &IM : Loaded)
3473 LoadedSet.insert(IM.Mod);
3474
Douglas Gregor7029ce12013-03-19 00:28:20 +00003475 ModuleMgr.removeModules(ModuleMgr.begin() + NumModules, ModuleMgr.end(),
Ben Langmuir9801b252014-06-20 00:24:56 +00003476 LoadedSet,
Douglas Gregor7029ce12013-03-19 00:28:20 +00003477 Context.getLangOpts().Modules
3478 ? &PP.getHeaderSearchInfo().getModuleMap()
Craig Toppera13603a2014-05-22 05:54:18 +00003479 : nullptr);
Douglas Gregore060e572013-01-25 01:03:03 +00003480
3481 // If we find that any modules are unusable, the global index is going
3482 // to be out-of-date. Just remove it.
3483 GlobalIndex.reset();
Craig Toppera13603a2014-05-22 05:54:18 +00003484 ModuleMgr.setGlobalIndex(nullptr);
Guy Benyei11169dd2012-12-18 14:30:41 +00003485 return ReadResult;
Ben Langmuir9801b252014-06-20 00:24:56 +00003486 }
Guy Benyei11169dd2012-12-18 14:30:41 +00003487 case Success:
3488 break;
3489 }
3490
3491 // Here comes stuff that we only do once the entire chain is loaded.
3492
3493 // Load the AST blocks of all of the modules that we loaded.
Dmitri Gribenkof8579502013-01-12 19:30:44 +00003494 for (SmallVectorImpl<ImportedModule>::iterator M = Loaded.begin(),
3495 MEnd = Loaded.end();
Guy Benyei11169dd2012-12-18 14:30:41 +00003496 M != MEnd; ++M) {
3497 ModuleFile &F = *M->Mod;
3498
3499 // Read the AST block.
Ben Langmuir2c9af442014-04-10 17:57:43 +00003500 if (ASTReadResult Result = ReadASTBlock(F, ClientLoadCapabilities))
3501 return Result;
Guy Benyei11169dd2012-12-18 14:30:41 +00003502
3503 // Once read, set the ModuleFile bit base offset and update the size in
3504 // bits of all files we've seen.
3505 F.GlobalBitOffset = TotalModulesSizeInBits;
3506 TotalModulesSizeInBits += F.SizeInBits;
3507 GlobalBitOffsetsMap.insert(std::make_pair(F.GlobalBitOffset, &F));
3508
3509 // Preload SLocEntries.
3510 for (unsigned I = 0, N = F.PreloadSLocEntries.size(); I != N; ++I) {
3511 int Index = int(F.PreloadSLocEntries[I] - 1) + F.SLocEntryBaseID;
3512 // Load it through the SourceManager and don't call ReadSLocEntry()
3513 // directly because the entry may have already been loaded in which case
3514 // calling ReadSLocEntry() directly would trigger an assertion in
3515 // SourceManager.
3516 SourceMgr.getLoadedSLocEntryByID(Index);
3517 }
3518 }
3519
Douglas Gregor603cd862013-03-22 18:50:14 +00003520 // Setup the import locations and notify the module manager that we've
3521 // committed to these module files.
Dmitri Gribenkof8579502013-01-12 19:30:44 +00003522 for (SmallVectorImpl<ImportedModule>::iterator M = Loaded.begin(),
3523 MEnd = Loaded.end();
Guy Benyei11169dd2012-12-18 14:30:41 +00003524 M != MEnd; ++M) {
3525 ModuleFile &F = *M->Mod;
Douglas Gregor603cd862013-03-22 18:50:14 +00003526
3527 ModuleMgr.moduleFileAccepted(&F);
3528
3529 // Set the import location.
Argyrios Kyrtzidis71c1af82013-02-01 16:36:14 +00003530 F.DirectImportLoc = ImportLoc;
Guy Benyei11169dd2012-12-18 14:30:41 +00003531 if (!M->ImportedBy)
3532 F.ImportLoc = M->ImportLoc;
3533 else
3534 F.ImportLoc = ReadSourceLocation(*M->ImportedBy,
3535 M->ImportLoc.getRawEncoding());
3536 }
3537
3538 // Mark all of the identifiers in the identifier table as being out of date,
3539 // so that various accessors know to check the loaded modules when the
3540 // identifier is used.
3541 for (IdentifierTable::iterator Id = PP.getIdentifierTable().begin(),
3542 IdEnd = PP.getIdentifierTable().end();
3543 Id != IdEnd; ++Id)
3544 Id->second->setOutOfDate(true);
3545
3546 // Resolve any unresolved module exports.
Douglas Gregorfb912652013-03-20 21:10:35 +00003547 for (unsigned I = 0, N = UnresolvedModuleRefs.size(); I != N; ++I) {
3548 UnresolvedModuleRef &Unresolved = UnresolvedModuleRefs[I];
Guy Benyei11169dd2012-12-18 14:30:41 +00003549 SubmoduleID GlobalID = getGlobalSubmoduleID(*Unresolved.File,Unresolved.ID);
3550 Module *ResolvedMod = getSubmodule(GlobalID);
Douglas Gregorfb912652013-03-20 21:10:35 +00003551
3552 switch (Unresolved.Kind) {
3553 case UnresolvedModuleRef::Conflict:
3554 if (ResolvedMod) {
3555 Module::Conflict Conflict;
3556 Conflict.Other = ResolvedMod;
3557 Conflict.Message = Unresolved.String.str();
3558 Unresolved.Mod->Conflicts.push_back(Conflict);
3559 }
3560 continue;
3561
3562 case UnresolvedModuleRef::Import:
Guy Benyei11169dd2012-12-18 14:30:41 +00003563 if (ResolvedMod)
3564 Unresolved.Mod->Imports.push_back(ResolvedMod);
3565 continue;
Guy Benyei11169dd2012-12-18 14:30:41 +00003566
Douglas Gregorfb912652013-03-20 21:10:35 +00003567 case UnresolvedModuleRef::Export:
3568 if (ResolvedMod || Unresolved.IsWildcard)
3569 Unresolved.Mod->Exports.push_back(
3570 Module::ExportDecl(ResolvedMod, Unresolved.IsWildcard));
3571 continue;
3572 }
Guy Benyei11169dd2012-12-18 14:30:41 +00003573 }
Douglas Gregorfb912652013-03-20 21:10:35 +00003574 UnresolvedModuleRefs.clear();
Daniel Jasperba7f2f72013-09-24 09:14:14 +00003575
3576 // FIXME: How do we load the 'use'd modules? They may not be submodules.
3577 // Might be unnecessary as use declarations are only used to build the
3578 // module itself.
Guy Benyei11169dd2012-12-18 14:30:41 +00003579
3580 InitializeContext();
3581
Richard Smith3d8e97e2013-10-18 06:54:39 +00003582 if (SemaObj)
3583 UpdateSema();
3584
Guy Benyei11169dd2012-12-18 14:30:41 +00003585 if (DeserializationListener)
3586 DeserializationListener->ReaderInitialized(this);
3587
3588 ModuleFile &PrimaryModule = ModuleMgr.getPrimaryModule();
3589 if (!PrimaryModule.OriginalSourceFileID.isInvalid()) {
3590 PrimaryModule.OriginalSourceFileID
3591 = FileID::get(PrimaryModule.SLocEntryBaseID
3592 + PrimaryModule.OriginalSourceFileID.getOpaqueValue() - 1);
3593
3594 // If this AST file is a precompiled preamble, then set the
3595 // preamble file ID of the source manager to the file source file
3596 // from which the preamble was built.
3597 if (Type == MK_Preamble) {
3598 SourceMgr.setPreambleFileID(PrimaryModule.OriginalSourceFileID);
3599 } else if (Type == MK_MainFile) {
3600 SourceMgr.setMainFileID(PrimaryModule.OriginalSourceFileID);
3601 }
3602 }
3603
3604 // For any Objective-C class definitions we have already loaded, make sure
3605 // that we load any additional categories.
3606 for (unsigned I = 0, N = ObjCClassesLoaded.size(); I != N; ++I) {
3607 loadObjCCategories(ObjCClassesLoaded[I]->getGlobalID(),
3608 ObjCClassesLoaded[I],
3609 PreviousGeneration);
3610 }
Douglas Gregore060e572013-01-25 01:03:03 +00003611
Dmitri Gribenkof430da42014-02-12 10:33:14 +00003612 if (PP.getHeaderSearchInfo()
3613 .getHeaderSearchOpts()
3614 .ModulesValidateOncePerBuildSession) {
3615 // Now we are certain that the module and all modules it depends on are
3616 // up to date. Create or update timestamp files for modules that are
3617 // located in the module cache (not for PCH files that could be anywhere
3618 // in the filesystem).
3619 for (unsigned I = 0, N = Loaded.size(); I != N; ++I) {
3620 ImportedModule &M = Loaded[I];
3621 if (M.Mod->Kind == MK_Module) {
3622 updateModuleTimestamp(*M.Mod);
3623 }
3624 }
3625 }
3626
Guy Benyei11169dd2012-12-18 14:30:41 +00003627 return Success;
3628}
3629
3630ASTReader::ASTReadResult
3631ASTReader::ReadASTCore(StringRef FileName,
3632 ModuleKind Type,
3633 SourceLocation ImportLoc,
3634 ModuleFile *ImportedBy,
Dmitri Gribenkof8579502013-01-12 19:30:44 +00003635 SmallVectorImpl<ImportedModule> &Loaded,
Douglas Gregor7029ce12013-03-19 00:28:20 +00003636 off_t ExpectedSize, time_t ExpectedModTime,
Guy Benyei11169dd2012-12-18 14:30:41 +00003637 unsigned ClientLoadCapabilities) {
3638 ModuleFile *M;
Guy Benyei11169dd2012-12-18 14:30:41 +00003639 std::string ErrorStr;
Douglas Gregor7029ce12013-03-19 00:28:20 +00003640 ModuleManager::AddModuleResult AddResult
3641 = ModuleMgr.addModule(FileName, Type, ImportLoc, ImportedBy,
Richard Smith053f6c62014-05-16 23:01:30 +00003642 getGeneration(), ExpectedSize, ExpectedModTime,
Douglas Gregor7029ce12013-03-19 00:28:20 +00003643 M, ErrorStr);
Guy Benyei11169dd2012-12-18 14:30:41 +00003644
Douglas Gregor7029ce12013-03-19 00:28:20 +00003645 switch (AddResult) {
3646 case ModuleManager::AlreadyLoaded:
3647 return Success;
3648
3649 case ModuleManager::NewlyLoaded:
3650 // Load module file below.
3651 break;
3652
3653 case ModuleManager::Missing:
3654 // The module file was missing; if the client handle handle, that, return
3655 // it.
3656 if (ClientLoadCapabilities & ARR_Missing)
3657 return Missing;
3658
3659 // Otherwise, return an error.
3660 {
3661 std::string Msg = "Unable to load module \"" + FileName.str() + "\": "
3662 + ErrorStr;
3663 Error(Msg);
3664 }
3665 return Failure;
3666
3667 case ModuleManager::OutOfDate:
3668 // We couldn't load the module file because it is out-of-date. If the
3669 // client can handle out-of-date, return it.
3670 if (ClientLoadCapabilities & ARR_OutOfDate)
3671 return OutOfDate;
3672
3673 // Otherwise, return an error.
3674 {
3675 std::string Msg = "Unable to load module \"" + FileName.str() + "\": "
3676 + ErrorStr;
3677 Error(Msg);
3678 }
Guy Benyei11169dd2012-12-18 14:30:41 +00003679 return Failure;
3680 }
3681
Douglas Gregor7029ce12013-03-19 00:28:20 +00003682 assert(M && "Missing module file");
Guy Benyei11169dd2012-12-18 14:30:41 +00003683
3684 // FIXME: This seems rather a hack. Should CurrentDir be part of the
3685 // module?
3686 if (FileName != "-") {
3687 CurrentDir = llvm::sys::path::parent_path(FileName);
3688 if (CurrentDir.empty()) CurrentDir = ".";
3689 }
3690
3691 ModuleFile &F = *M;
Chris Lattner7fb3bef2013-01-20 00:56:42 +00003692 BitstreamCursor &Stream = F.Stream;
Guy Benyei11169dd2012-12-18 14:30:41 +00003693 Stream.init(F.StreamFile);
3694 F.SizeInBits = F.Buffer->getBufferSize() * 8;
3695
3696 // Sniff for the signature.
3697 if (Stream.Read(8) != 'C' ||
3698 Stream.Read(8) != 'P' ||
3699 Stream.Read(8) != 'C' ||
3700 Stream.Read(8) != 'H') {
3701 Diag(diag::err_not_a_pch_file) << FileName;
3702 return Failure;
3703 }
3704
3705 // This is used for compatibility with older PCH formats.
3706 bool HaveReadControlBlock = false;
3707
Chris Lattnerefa77172013-01-20 00:00:22 +00003708 while (1) {
3709 llvm::BitstreamEntry Entry = Stream.advance();
3710
3711 switch (Entry.Kind) {
3712 case llvm::BitstreamEntry::Error:
3713 case llvm::BitstreamEntry::EndBlock:
3714 case llvm::BitstreamEntry::Record:
Guy Benyei11169dd2012-12-18 14:30:41 +00003715 Error("invalid record at top-level of AST file");
3716 return Failure;
Chris Lattnerefa77172013-01-20 00:00:22 +00003717
3718 case llvm::BitstreamEntry::SubBlock:
3719 break;
Guy Benyei11169dd2012-12-18 14:30:41 +00003720 }
3721
Guy Benyei11169dd2012-12-18 14:30:41 +00003722 // We only know the control subblock ID.
Chris Lattnerefa77172013-01-20 00:00:22 +00003723 switch (Entry.ID) {
Guy Benyei11169dd2012-12-18 14:30:41 +00003724 case llvm::bitc::BLOCKINFO_BLOCK_ID:
3725 if (Stream.ReadBlockInfoBlock()) {
3726 Error("malformed BlockInfoBlock in AST file");
3727 return Failure;
3728 }
3729 break;
3730 case CONTROL_BLOCK_ID:
3731 HaveReadControlBlock = true;
Ben Langmuirbeee15e2014-04-14 18:00:01 +00003732 switch (ReadControlBlock(F, Loaded, ImportedBy, ClientLoadCapabilities)) {
Guy Benyei11169dd2012-12-18 14:30:41 +00003733 case Success:
3734 break;
3735
3736 case Failure: return Failure;
Douglas Gregor7029ce12013-03-19 00:28:20 +00003737 case Missing: return Missing;
Guy Benyei11169dd2012-12-18 14:30:41 +00003738 case OutOfDate: return OutOfDate;
3739 case VersionMismatch: return VersionMismatch;
3740 case ConfigurationMismatch: return ConfigurationMismatch;
3741 case HadErrors: return HadErrors;
3742 }
3743 break;
3744 case AST_BLOCK_ID:
3745 if (!HaveReadControlBlock) {
3746 if ((ClientLoadCapabilities & ARR_VersionMismatch) == 0)
Dmitri Gribenko2228cd32014-02-11 15:40:09 +00003747 Diag(diag::err_pch_version_too_old);
Guy Benyei11169dd2012-12-18 14:30:41 +00003748 return VersionMismatch;
3749 }
3750
3751 // Record that we've loaded this module.
3752 Loaded.push_back(ImportedModule(M, ImportedBy, ImportLoc));
3753 return Success;
3754
3755 default:
3756 if (Stream.SkipBlock()) {
3757 Error("malformed block record in AST file");
3758 return Failure;
3759 }
3760 break;
3761 }
3762 }
3763
3764 return Success;
3765}
3766
3767void ASTReader::InitializeContext() {
3768 // If there's a listener, notify them that we "read" the translation unit.
3769 if (DeserializationListener)
3770 DeserializationListener->DeclRead(PREDEF_DECL_TRANSLATION_UNIT_ID,
3771 Context.getTranslationUnitDecl());
3772
Guy Benyei11169dd2012-12-18 14:30:41 +00003773 // FIXME: Find a better way to deal with collisions between these
3774 // built-in types. Right now, we just ignore the problem.
3775
3776 // Load the special types.
3777 if (SpecialTypes.size() >= NumSpecialTypeIDs) {
3778 if (unsigned String = SpecialTypes[SPECIAL_TYPE_CF_CONSTANT_STRING]) {
3779 if (!Context.CFConstantStringTypeDecl)
3780 Context.setCFConstantStringType(GetType(String));
3781 }
3782
3783 if (unsigned File = SpecialTypes[SPECIAL_TYPE_FILE]) {
3784 QualType FileType = GetType(File);
3785 if (FileType.isNull()) {
3786 Error("FILE type is NULL");
3787 return;
3788 }
3789
3790 if (!Context.FILEDecl) {
3791 if (const TypedefType *Typedef = FileType->getAs<TypedefType>())
3792 Context.setFILEDecl(Typedef->getDecl());
3793 else {
3794 const TagType *Tag = FileType->getAs<TagType>();
3795 if (!Tag) {
3796 Error("Invalid FILE type in AST file");
3797 return;
3798 }
3799 Context.setFILEDecl(Tag->getDecl());
3800 }
3801 }
3802 }
3803
3804 if (unsigned Jmp_buf = SpecialTypes[SPECIAL_TYPE_JMP_BUF]) {
3805 QualType Jmp_bufType = GetType(Jmp_buf);
3806 if (Jmp_bufType.isNull()) {
3807 Error("jmp_buf type is NULL");
3808 return;
3809 }
3810
3811 if (!Context.jmp_bufDecl) {
3812 if (const TypedefType *Typedef = Jmp_bufType->getAs<TypedefType>())
3813 Context.setjmp_bufDecl(Typedef->getDecl());
3814 else {
3815 const TagType *Tag = Jmp_bufType->getAs<TagType>();
3816 if (!Tag) {
3817 Error("Invalid jmp_buf type in AST file");
3818 return;
3819 }
3820 Context.setjmp_bufDecl(Tag->getDecl());
3821 }
3822 }
3823 }
3824
3825 if (unsigned Sigjmp_buf = SpecialTypes[SPECIAL_TYPE_SIGJMP_BUF]) {
3826 QualType Sigjmp_bufType = GetType(Sigjmp_buf);
3827 if (Sigjmp_bufType.isNull()) {
3828 Error("sigjmp_buf type is NULL");
3829 return;
3830 }
3831
3832 if (!Context.sigjmp_bufDecl) {
3833 if (const TypedefType *Typedef = Sigjmp_bufType->getAs<TypedefType>())
3834 Context.setsigjmp_bufDecl(Typedef->getDecl());
3835 else {
3836 const TagType *Tag = Sigjmp_bufType->getAs<TagType>();
3837 assert(Tag && "Invalid sigjmp_buf type in AST file");
3838 Context.setsigjmp_bufDecl(Tag->getDecl());
3839 }
3840 }
3841 }
3842
3843 if (unsigned ObjCIdRedef
3844 = SpecialTypes[SPECIAL_TYPE_OBJC_ID_REDEFINITION]) {
3845 if (Context.ObjCIdRedefinitionType.isNull())
3846 Context.ObjCIdRedefinitionType = GetType(ObjCIdRedef);
3847 }
3848
3849 if (unsigned ObjCClassRedef
3850 = SpecialTypes[SPECIAL_TYPE_OBJC_CLASS_REDEFINITION]) {
3851 if (Context.ObjCClassRedefinitionType.isNull())
3852 Context.ObjCClassRedefinitionType = GetType(ObjCClassRedef);
3853 }
3854
3855 if (unsigned ObjCSelRedef
3856 = SpecialTypes[SPECIAL_TYPE_OBJC_SEL_REDEFINITION]) {
3857 if (Context.ObjCSelRedefinitionType.isNull())
3858 Context.ObjCSelRedefinitionType = GetType(ObjCSelRedef);
3859 }
3860
3861 if (unsigned Ucontext_t = SpecialTypes[SPECIAL_TYPE_UCONTEXT_T]) {
3862 QualType Ucontext_tType = GetType(Ucontext_t);
3863 if (Ucontext_tType.isNull()) {
3864 Error("ucontext_t type is NULL");
3865 return;
3866 }
3867
3868 if (!Context.ucontext_tDecl) {
3869 if (const TypedefType *Typedef = Ucontext_tType->getAs<TypedefType>())
3870 Context.setucontext_tDecl(Typedef->getDecl());
3871 else {
3872 const TagType *Tag = Ucontext_tType->getAs<TagType>();
3873 assert(Tag && "Invalid ucontext_t type in AST file");
3874 Context.setucontext_tDecl(Tag->getDecl());
3875 }
3876 }
3877 }
3878 }
3879
3880 ReadPragmaDiagnosticMappings(Context.getDiagnostics());
3881
3882 // If there were any CUDA special declarations, deserialize them.
3883 if (!CUDASpecialDeclRefs.empty()) {
3884 assert(CUDASpecialDeclRefs.size() == 1 && "More decl refs than expected!");
3885 Context.setcudaConfigureCallDecl(
3886 cast<FunctionDecl>(GetDecl(CUDASpecialDeclRefs[0])));
3887 }
Richard Smith56be7542014-03-21 00:33:59 +00003888
Guy Benyei11169dd2012-12-18 14:30:41 +00003889 // Re-export any modules that were imported by a non-module AST file.
Richard Smith56be7542014-03-21 00:33:59 +00003890 // FIXME: This does not make macro-only imports visible again. It also doesn't
3891 // make #includes mapped to module imports visible.
3892 for (auto &Import : ImportedModules) {
3893 if (Module *Imported = getSubmodule(Import.ID))
Argyrios Kyrtzidis125df052013-02-01 16:36:12 +00003894 makeModuleVisible(Imported, Module::AllVisible,
Richard Smith56be7542014-03-21 00:33:59 +00003895 /*ImportLoc=*/Import.ImportLoc,
Douglas Gregorfb912652013-03-20 21:10:35 +00003896 /*Complain=*/false);
Guy Benyei11169dd2012-12-18 14:30:41 +00003897 }
3898 ImportedModules.clear();
3899}
3900
3901void ASTReader::finalizeForWriting() {
3902 for (HiddenNamesMapType::iterator Hidden = HiddenNamesMap.begin(),
3903 HiddenEnd = HiddenNamesMap.end();
3904 Hidden != HiddenEnd; ++Hidden) {
Richard Smithe657bbd2014-07-18 22:13:40 +00003905 makeNamesVisible(Hidden->second, Hidden->first, /*FromFinalization*/true);
Guy Benyei11169dd2012-12-18 14:30:41 +00003906 }
3907 HiddenNamesMap.clear();
3908}
3909
Argyrios Kyrtzidisc4cd2c42013-05-06 19:23:40 +00003910/// \brief Given a cursor at the start of an AST file, scan ahead and drop the
3911/// cursor into the start of the given block ID, returning false on success and
3912/// true on failure.
3913static bool SkipCursorToBlock(BitstreamCursor &Cursor, unsigned BlockID) {
Chris Lattner7fb3bef2013-01-20 00:56:42 +00003914 while (1) {
3915 llvm::BitstreamEntry Entry = Cursor.advance();
3916 switch (Entry.Kind) {
3917 case llvm::BitstreamEntry::Error:
3918 case llvm::BitstreamEntry::EndBlock:
3919 return true;
3920
3921 case llvm::BitstreamEntry::Record:
3922 // Ignore top-level records.
3923 Cursor.skipRecord(Entry.ID);
3924 break;
3925
3926 case llvm::BitstreamEntry::SubBlock:
Argyrios Kyrtzidisc4cd2c42013-05-06 19:23:40 +00003927 if (Entry.ID == BlockID) {
3928 if (Cursor.EnterSubBlock(BlockID))
Chris Lattner7fb3bef2013-01-20 00:56:42 +00003929 return true;
3930 // Found it!
3931 return false;
3932 }
3933
3934 if (Cursor.SkipBlock())
3935 return true;
3936 }
3937 }
3938}
3939
Guy Benyei11169dd2012-12-18 14:30:41 +00003940/// \brief Retrieve the name of the original source file name
3941/// directly from the AST file, without actually loading the AST
3942/// file.
3943std::string ASTReader::getOriginalSourceFile(const std::string &ASTFileName,
3944 FileManager &FileMgr,
3945 DiagnosticsEngine &Diags) {
3946 // Open the AST file.
3947 std::string ErrStr;
Ahmed Charlesb8984322014-03-07 20:03:18 +00003948 std::unique_ptr<llvm::MemoryBuffer> Buffer;
Guy Benyei11169dd2012-12-18 14:30:41 +00003949 Buffer.reset(FileMgr.getBufferForFile(ASTFileName, &ErrStr));
3950 if (!Buffer) {
3951 Diags.Report(diag::err_fe_unable_to_read_pch_file) << ASTFileName << ErrStr;
3952 return std::string();
3953 }
3954
3955 // Initialize the stream
3956 llvm::BitstreamReader StreamFile;
Chris Lattner7fb3bef2013-01-20 00:56:42 +00003957 BitstreamCursor Stream;
Guy Benyei11169dd2012-12-18 14:30:41 +00003958 StreamFile.init((const unsigned char *)Buffer->getBufferStart(),
3959 (const unsigned char *)Buffer->getBufferEnd());
3960 Stream.init(StreamFile);
3961
3962 // Sniff for the signature.
3963 if (Stream.Read(8) != 'C' ||
3964 Stream.Read(8) != 'P' ||
3965 Stream.Read(8) != 'C' ||
3966 Stream.Read(8) != 'H') {
3967 Diags.Report(diag::err_fe_not_a_pch_file) << ASTFileName;
3968 return std::string();
3969 }
Chris Lattner7fb3bef2013-01-20 00:56:42 +00003970
Chris Lattnere7b154b2013-01-19 21:39:22 +00003971 // Scan for the CONTROL_BLOCK_ID block.
Argyrios Kyrtzidisc4cd2c42013-05-06 19:23:40 +00003972 if (SkipCursorToBlock(Stream, CONTROL_BLOCK_ID)) {
Chris Lattner7fb3bef2013-01-20 00:56:42 +00003973 Diags.Report(diag::err_fe_pch_malformed_block) << ASTFileName;
3974 return std::string();
Chris Lattnere7b154b2013-01-19 21:39:22 +00003975 }
Guy Benyei11169dd2012-12-18 14:30:41 +00003976
Chris Lattner7fb3bef2013-01-20 00:56:42 +00003977 // Scan for ORIGINAL_FILE inside the control block.
3978 RecordData Record;
Chris Lattnere7b154b2013-01-19 21:39:22 +00003979 while (1) {
Chris Lattner7fb3bef2013-01-20 00:56:42 +00003980 llvm::BitstreamEntry Entry = Stream.advanceSkippingSubblocks();
Chris Lattnere7b154b2013-01-19 21:39:22 +00003981 if (Entry.Kind == llvm::BitstreamEntry::EndBlock)
3982 return std::string();
3983
3984 if (Entry.Kind != llvm::BitstreamEntry::Record) {
3985 Diags.Report(diag::err_fe_pch_malformed_block) << ASTFileName;
3986 return std::string();
Guy Benyei11169dd2012-12-18 14:30:41 +00003987 }
Chris Lattnere7b154b2013-01-19 21:39:22 +00003988
Guy Benyei11169dd2012-12-18 14:30:41 +00003989 Record.clear();
Chris Lattner0e6c9402013-01-20 02:38:54 +00003990 StringRef Blob;
3991 if (Stream.readRecord(Entry.ID, Record, &Blob) == ORIGINAL_FILE)
3992 return Blob.str();
Guy Benyei11169dd2012-12-18 14:30:41 +00003993 }
Guy Benyei11169dd2012-12-18 14:30:41 +00003994}
3995
3996namespace {
3997 class SimplePCHValidator : public ASTReaderListener {
3998 const LangOptions &ExistingLangOpts;
3999 const TargetOptions &ExistingTargetOpts;
4000 const PreprocessorOptions &ExistingPPOpts;
4001 FileManager &FileMgr;
4002
4003 public:
4004 SimplePCHValidator(const LangOptions &ExistingLangOpts,
4005 const TargetOptions &ExistingTargetOpts,
4006 const PreprocessorOptions &ExistingPPOpts,
4007 FileManager &FileMgr)
4008 : ExistingLangOpts(ExistingLangOpts),
4009 ExistingTargetOpts(ExistingTargetOpts),
4010 ExistingPPOpts(ExistingPPOpts),
4011 FileMgr(FileMgr)
4012 {
4013 }
4014
Craig Topper3e89dfe2014-03-13 02:13:41 +00004015 bool ReadLanguageOptions(const LangOptions &LangOpts,
4016 bool Complain) override {
Craig Toppera13603a2014-05-22 05:54:18 +00004017 return checkLanguageOptions(ExistingLangOpts, LangOpts, nullptr);
Guy Benyei11169dd2012-12-18 14:30:41 +00004018 }
Craig Topper3e89dfe2014-03-13 02:13:41 +00004019 bool ReadTargetOptions(const TargetOptions &TargetOpts,
4020 bool Complain) override {
Craig Toppera13603a2014-05-22 05:54:18 +00004021 return checkTargetOptions(ExistingTargetOpts, TargetOpts, nullptr);
Guy Benyei11169dd2012-12-18 14:30:41 +00004022 }
Craig Topper3e89dfe2014-03-13 02:13:41 +00004023 bool ReadPreprocessorOptions(const PreprocessorOptions &PPOpts,
4024 bool Complain,
4025 std::string &SuggestedPredefines) override {
Craig Toppera13603a2014-05-22 05:54:18 +00004026 return checkPreprocessorOptions(ExistingPPOpts, PPOpts, nullptr, FileMgr,
Argyrios Kyrtzidisd3afa0c2013-04-26 21:33:40 +00004027 SuggestedPredefines, ExistingLangOpts);
Guy Benyei11169dd2012-12-18 14:30:41 +00004028 }
4029 };
4030}
4031
4032bool ASTReader::readASTFileControlBlock(StringRef Filename,
4033 FileManager &FileMgr,
4034 ASTReaderListener &Listener) {
4035 // Open the AST file.
4036 std::string ErrStr;
Ahmed Charlesb8984322014-03-07 20:03:18 +00004037 std::unique_ptr<llvm::MemoryBuffer> Buffer;
Guy Benyei11169dd2012-12-18 14:30:41 +00004038 Buffer.reset(FileMgr.getBufferForFile(Filename, &ErrStr));
4039 if (!Buffer) {
4040 return true;
4041 }
4042
4043 // Initialize the stream
4044 llvm::BitstreamReader StreamFile;
Chris Lattner7fb3bef2013-01-20 00:56:42 +00004045 BitstreamCursor Stream;
Guy Benyei11169dd2012-12-18 14:30:41 +00004046 StreamFile.init((const unsigned char *)Buffer->getBufferStart(),
4047 (const unsigned char *)Buffer->getBufferEnd());
4048 Stream.init(StreamFile);
4049
4050 // Sniff for the signature.
4051 if (Stream.Read(8) != 'C' ||
4052 Stream.Read(8) != 'P' ||
4053 Stream.Read(8) != 'C' ||
4054 Stream.Read(8) != 'H') {
4055 return true;
4056 }
4057
Chris Lattner7fb3bef2013-01-20 00:56:42 +00004058 // Scan for the CONTROL_BLOCK_ID block.
Argyrios Kyrtzidisc4cd2c42013-05-06 19:23:40 +00004059 if (SkipCursorToBlock(Stream, CONTROL_BLOCK_ID))
Chris Lattner7fb3bef2013-01-20 00:56:42 +00004060 return true;
Argyrios Kyrtzidisc4cd2c42013-05-06 19:23:40 +00004061
4062 bool NeedsInputFiles = Listener.needsInputFileVisitation();
Ben Langmuircb69b572014-03-07 06:40:32 +00004063 bool NeedsSystemInputFiles = Listener.needsSystemInputFileVisitation();
Argyrios Kyrtzidisc4cd2c42013-05-06 19:23:40 +00004064 BitstreamCursor InputFilesCursor;
4065 if (NeedsInputFiles) {
4066 InputFilesCursor = Stream;
4067 if (SkipCursorToBlock(InputFilesCursor, INPUT_FILES_BLOCK_ID))
4068 return true;
4069
4070 // Read the abbreviations
4071 while (true) {
4072 uint64_t Offset = InputFilesCursor.GetCurrentBitNo();
4073 unsigned Code = InputFilesCursor.ReadCode();
4074
4075 // We expect all abbrevs to be at the start of the block.
4076 if (Code != llvm::bitc::DEFINE_ABBREV) {
4077 InputFilesCursor.JumpToBit(Offset);
4078 break;
4079 }
4080 InputFilesCursor.ReadAbbrevRecord();
4081 }
4082 }
Chris Lattner7fb3bef2013-01-20 00:56:42 +00004083
4084 // Scan for ORIGINAL_FILE inside the control block.
Guy Benyei11169dd2012-12-18 14:30:41 +00004085 RecordData Record;
Chris Lattner7fb3bef2013-01-20 00:56:42 +00004086 while (1) {
4087 llvm::BitstreamEntry Entry = Stream.advanceSkippingSubblocks();
4088 if (Entry.Kind == llvm::BitstreamEntry::EndBlock)
4089 return false;
4090
4091 if (Entry.Kind != llvm::BitstreamEntry::Record)
4092 return true;
4093
Guy Benyei11169dd2012-12-18 14:30:41 +00004094 Record.clear();
Chris Lattner0e6c9402013-01-20 02:38:54 +00004095 StringRef Blob;
4096 unsigned RecCode = Stream.readRecord(Entry.ID, Record, &Blob);
Chris Lattner7fb3bef2013-01-20 00:56:42 +00004097 switch ((ControlRecordTypes)RecCode) {
4098 case METADATA: {
4099 if (Record[0] != VERSION_MAJOR)
4100 return true;
Guy Benyei11169dd2012-12-18 14:30:41 +00004101
Douglas Gregorbf7fc9c2013-03-27 16:47:18 +00004102 if (Listener.ReadFullVersionInformation(Blob))
Chris Lattner7fb3bef2013-01-20 00:56:42 +00004103 return true;
Douglas Gregorbf7fc9c2013-03-27 16:47:18 +00004104
Chris Lattner7fb3bef2013-01-20 00:56:42 +00004105 break;
4106 }
Ben Langmuir4f5212a2014-04-14 22:12:44 +00004107 case MODULE_NAME:
4108 Listener.ReadModuleName(Blob);
4109 break;
4110 case MODULE_MAP_FILE:
4111 Listener.ReadModuleMapFile(Blob);
4112 break;
Chris Lattner7fb3bef2013-01-20 00:56:42 +00004113 case LANGUAGE_OPTIONS:
4114 if (ParseLanguageOptions(Record, false, Listener))
4115 return true;
4116 break;
Guy Benyei11169dd2012-12-18 14:30:41 +00004117
Chris Lattner7fb3bef2013-01-20 00:56:42 +00004118 case TARGET_OPTIONS:
4119 if (ParseTargetOptions(Record, false, Listener))
4120 return true;
4121 break;
Guy Benyei11169dd2012-12-18 14:30:41 +00004122
Chris Lattner7fb3bef2013-01-20 00:56:42 +00004123 case DIAGNOSTIC_OPTIONS:
4124 if (ParseDiagnosticOptions(Record, false, Listener))
4125 return true;
4126 break;
Guy Benyei11169dd2012-12-18 14:30:41 +00004127
Chris Lattner7fb3bef2013-01-20 00:56:42 +00004128 case FILE_SYSTEM_OPTIONS:
4129 if (ParseFileSystemOptions(Record, false, Listener))
4130 return true;
4131 break;
Guy Benyei11169dd2012-12-18 14:30:41 +00004132
Chris Lattner7fb3bef2013-01-20 00:56:42 +00004133 case HEADER_SEARCH_OPTIONS:
4134 if (ParseHeaderSearchOptions(Record, false, Listener))
4135 return true;
4136 break;
Guy Benyei11169dd2012-12-18 14:30:41 +00004137
Chris Lattner7fb3bef2013-01-20 00:56:42 +00004138 case PREPROCESSOR_OPTIONS: {
4139 std::string IgnoredSuggestedPredefines;
4140 if (ParsePreprocessorOptions(Record, false, Listener,
4141 IgnoredSuggestedPredefines))
4142 return true;
4143 break;
4144 }
Guy Benyei11169dd2012-12-18 14:30:41 +00004145
Argyrios Kyrtzidisc4cd2c42013-05-06 19:23:40 +00004146 case INPUT_FILE_OFFSETS: {
4147 if (!NeedsInputFiles)
4148 break;
4149
4150 unsigned NumInputFiles = Record[0];
4151 unsigned NumUserFiles = Record[1];
4152 const uint32_t *InputFileOffs = (const uint32_t *)Blob.data();
4153 for (unsigned I = 0; I != NumInputFiles; ++I) {
4154 // Go find this input file.
4155 bool isSystemFile = I >= NumUserFiles;
Ben Langmuircb69b572014-03-07 06:40:32 +00004156
4157 if (isSystemFile && !NeedsSystemInputFiles)
4158 break; // the rest are system input files
4159
Argyrios Kyrtzidisc4cd2c42013-05-06 19:23:40 +00004160 BitstreamCursor &Cursor = InputFilesCursor;
4161 SavedStreamPosition SavedPosition(Cursor);
4162 Cursor.JumpToBit(InputFileOffs[I]);
4163
4164 unsigned Code = Cursor.ReadCode();
4165 RecordData Record;
4166 StringRef Blob;
4167 bool shouldContinue = false;
4168 switch ((InputFileRecordTypes)Cursor.readRecord(Code, Record, &Blob)) {
4169 case INPUT_FILE:
Argyrios Kyrtzidis68ccbe02014-03-14 02:26:31 +00004170 bool Overridden = static_cast<bool>(Record[3]);
4171 shouldContinue = Listener.visitInputFile(Blob, isSystemFile, Overridden);
Argyrios Kyrtzidisc4cd2c42013-05-06 19:23:40 +00004172 break;
4173 }
4174 if (!shouldContinue)
4175 break;
4176 }
4177 break;
4178 }
4179
Chris Lattner7fb3bef2013-01-20 00:56:42 +00004180 default:
4181 // No other validation to perform.
4182 break;
Guy Benyei11169dd2012-12-18 14:30:41 +00004183 }
4184 }
Guy Benyei11169dd2012-12-18 14:30:41 +00004185}
4186
4187
4188bool ASTReader::isAcceptableASTFile(StringRef Filename,
4189 FileManager &FileMgr,
4190 const LangOptions &LangOpts,
4191 const TargetOptions &TargetOpts,
4192 const PreprocessorOptions &PPOpts) {
4193 SimplePCHValidator validator(LangOpts, TargetOpts, PPOpts, FileMgr);
4194 return !readASTFileControlBlock(Filename, FileMgr, validator);
4195}
4196
Ben Langmuir2c9af442014-04-10 17:57:43 +00004197ASTReader::ASTReadResult
4198ASTReader::ReadSubmoduleBlock(ModuleFile &F, unsigned ClientLoadCapabilities) {
Guy Benyei11169dd2012-12-18 14:30:41 +00004199 // Enter the submodule block.
4200 if (F.Stream.EnterSubBlock(SUBMODULE_BLOCK_ID)) {
4201 Error("malformed submodule block record in AST file");
Ben Langmuir2c9af442014-04-10 17:57:43 +00004202 return Failure;
Guy Benyei11169dd2012-12-18 14:30:41 +00004203 }
4204
4205 ModuleMap &ModMap = PP.getHeaderSearchInfo().getModuleMap();
4206 bool First = true;
Craig Toppera13603a2014-05-22 05:54:18 +00004207 Module *CurrentModule = nullptr;
Guy Benyei11169dd2012-12-18 14:30:41 +00004208 RecordData Record;
4209 while (true) {
Chris Lattner7fb3bef2013-01-20 00:56:42 +00004210 llvm::BitstreamEntry Entry = F.Stream.advanceSkippingSubblocks();
4211
4212 switch (Entry.Kind) {
4213 case llvm::BitstreamEntry::SubBlock: // Handled for us already.
4214 case llvm::BitstreamEntry::Error:
4215 Error("malformed block record in AST file");
Ben Langmuir2c9af442014-04-10 17:57:43 +00004216 return Failure;
Chris Lattner7fb3bef2013-01-20 00:56:42 +00004217 case llvm::BitstreamEntry::EndBlock:
Ben Langmuir2c9af442014-04-10 17:57:43 +00004218 return Success;
Chris Lattner7fb3bef2013-01-20 00:56:42 +00004219 case llvm::BitstreamEntry::Record:
4220 // The interesting case.
4221 break;
Guy Benyei11169dd2012-12-18 14:30:41 +00004222 }
Chris Lattner7fb3bef2013-01-20 00:56:42 +00004223
Guy Benyei11169dd2012-12-18 14:30:41 +00004224 // Read a record.
Chris Lattner0e6c9402013-01-20 02:38:54 +00004225 StringRef Blob;
Guy Benyei11169dd2012-12-18 14:30:41 +00004226 Record.clear();
Chris Lattner0e6c9402013-01-20 02:38:54 +00004227 switch (F.Stream.readRecord(Entry.ID, Record, &Blob)) {
Guy Benyei11169dd2012-12-18 14:30:41 +00004228 default: // Default behavior: ignore.
4229 break;
4230
4231 case SUBMODULE_DEFINITION: {
4232 if (First) {
4233 Error("missing submodule metadata record at beginning of block");
Ben Langmuir2c9af442014-04-10 17:57:43 +00004234 return Failure;
Guy Benyei11169dd2012-12-18 14:30:41 +00004235 }
4236
Douglas Gregor8d932422013-03-20 03:59:18 +00004237 if (Record.size() < 8) {
Guy Benyei11169dd2012-12-18 14:30:41 +00004238 Error("malformed module definition");
Ben Langmuir2c9af442014-04-10 17:57:43 +00004239 return Failure;
Guy Benyei11169dd2012-12-18 14:30:41 +00004240 }
4241
Chris Lattner0e6c9402013-01-20 02:38:54 +00004242 StringRef Name = Blob;
Richard Smith9bca2982014-03-08 00:03:56 +00004243 unsigned Idx = 0;
4244 SubmoduleID GlobalID = getGlobalSubmoduleID(F, Record[Idx++]);
4245 SubmoduleID Parent = getGlobalSubmoduleID(F, Record[Idx++]);
4246 bool IsFramework = Record[Idx++];
4247 bool IsExplicit = Record[Idx++];
4248 bool IsSystem = Record[Idx++];
4249 bool IsExternC = Record[Idx++];
4250 bool InferSubmodules = Record[Idx++];
4251 bool InferExplicitSubmodules = Record[Idx++];
4252 bool InferExportWildcard = Record[Idx++];
4253 bool ConfigMacrosExhaustive = Record[Idx++];
Douglas Gregor8d932422013-03-20 03:59:18 +00004254
Ben Langmuirbeee15e2014-04-14 18:00:01 +00004255 Module *ParentModule = nullptr;
4256 const FileEntry *ModuleMap = nullptr;
4257 if (Parent) {
Guy Benyei11169dd2012-12-18 14:30:41 +00004258 ParentModule = getSubmodule(Parent);
Ben Langmuirbeee15e2014-04-14 18:00:01 +00004259 ModuleMap = ParentModule->ModuleMap;
4260 }
4261
4262 if (!F.ModuleMapPath.empty())
4263 ModuleMap = FileMgr.getFile(F.ModuleMapPath);
4264
Guy Benyei11169dd2012-12-18 14:30:41 +00004265 // Retrieve this (sub)module from the module map, creating it if
4266 // necessary.
Ben Langmuirbeee15e2014-04-14 18:00:01 +00004267 CurrentModule = ModMap.findOrCreateModule(Name, ParentModule, ModuleMap,
Guy Benyei11169dd2012-12-18 14:30:41 +00004268 IsFramework,
4269 IsExplicit).first;
4270 SubmoduleID GlobalIndex = GlobalID - NUM_PREDEF_SUBMODULE_IDS;
4271 if (GlobalIndex >= SubmodulesLoaded.size() ||
4272 SubmodulesLoaded[GlobalIndex]) {
4273 Error("too many submodules");
Ben Langmuir2c9af442014-04-10 17:57:43 +00004274 return Failure;
Guy Benyei11169dd2012-12-18 14:30:41 +00004275 }
Douglas Gregor8a114ab2013-02-06 22:40:31 +00004276
Douglas Gregor7029ce12013-03-19 00:28:20 +00004277 if (!ParentModule) {
4278 if (const FileEntry *CurFile = CurrentModule->getASTFile()) {
4279 if (CurFile != F.File) {
4280 if (!Diags.isDiagnosticInFlight()) {
4281 Diag(diag::err_module_file_conflict)
4282 << CurrentModule->getTopLevelModuleName()
4283 << CurFile->getName()
4284 << F.File->getName();
4285 }
Ben Langmuir2c9af442014-04-10 17:57:43 +00004286 return Failure;
Douglas Gregor8a114ab2013-02-06 22:40:31 +00004287 }
Douglas Gregor8a114ab2013-02-06 22:40:31 +00004288 }
Douglas Gregor7029ce12013-03-19 00:28:20 +00004289
4290 CurrentModule->setASTFile(F.File);
Douglas Gregor8a114ab2013-02-06 22:40:31 +00004291 }
Ben Langmuirbeee15e2014-04-14 18:00:01 +00004292
Guy Benyei11169dd2012-12-18 14:30:41 +00004293 CurrentModule->IsFromModuleFile = true;
4294 CurrentModule->IsSystem = IsSystem || CurrentModule->IsSystem;
Richard Smith9bca2982014-03-08 00:03:56 +00004295 CurrentModule->IsExternC = IsExternC;
Guy Benyei11169dd2012-12-18 14:30:41 +00004296 CurrentModule->InferSubmodules = InferSubmodules;
4297 CurrentModule->InferExplicitSubmodules = InferExplicitSubmodules;
4298 CurrentModule->InferExportWildcard = InferExportWildcard;
Douglas Gregor8d932422013-03-20 03:59:18 +00004299 CurrentModule->ConfigMacrosExhaustive = ConfigMacrosExhaustive;
Guy Benyei11169dd2012-12-18 14:30:41 +00004300 if (DeserializationListener)
4301 DeserializationListener->ModuleRead(GlobalID, CurrentModule);
4302
4303 SubmodulesLoaded[GlobalIndex] = CurrentModule;
Douglas Gregor6ddfca92013-01-14 17:21:00 +00004304
Douglas Gregorfb912652013-03-20 21:10:35 +00004305 // Clear out data that will be replaced by what is the module file.
Douglas Gregor6ddfca92013-01-14 17:21:00 +00004306 CurrentModule->LinkLibraries.clear();
Douglas Gregor8d932422013-03-20 03:59:18 +00004307 CurrentModule->ConfigMacros.clear();
Douglas Gregorfb912652013-03-20 21:10:35 +00004308 CurrentModule->UnresolvedConflicts.clear();
4309 CurrentModule->Conflicts.clear();
Guy Benyei11169dd2012-12-18 14:30:41 +00004310 break;
4311 }
4312
4313 case SUBMODULE_UMBRELLA_HEADER: {
4314 if (First) {
4315 Error("missing submodule metadata record at beginning of block");
Ben Langmuir2c9af442014-04-10 17:57:43 +00004316 return Failure;
Guy Benyei11169dd2012-12-18 14:30:41 +00004317 }
4318
4319 if (!CurrentModule)
4320 break;
4321
Chris Lattner0e6c9402013-01-20 02:38:54 +00004322 if (const FileEntry *Umbrella = PP.getFileManager().getFile(Blob)) {
Guy Benyei11169dd2012-12-18 14:30:41 +00004323 if (!CurrentModule->getUmbrellaHeader())
4324 ModMap.setUmbrellaHeader(CurrentModule, Umbrella);
4325 else if (CurrentModule->getUmbrellaHeader() != Umbrella) {
Ben Langmuir2c9af442014-04-10 17:57:43 +00004326 if ((ClientLoadCapabilities & ARR_OutOfDate) == 0)
4327 Error("mismatched umbrella headers in submodule");
4328 return OutOfDate;
Guy Benyei11169dd2012-12-18 14:30:41 +00004329 }
4330 }
4331 break;
4332 }
4333
4334 case SUBMODULE_HEADER: {
4335 if (First) {
4336 Error("missing submodule metadata record at beginning of block");
Ben Langmuir2c9af442014-04-10 17:57:43 +00004337 return Failure;
Guy Benyei11169dd2012-12-18 14:30:41 +00004338 }
4339
4340 if (!CurrentModule)
4341 break;
4342
Argyrios Kyrtzidisb146baa2013-03-13 21:13:51 +00004343 // We lazily associate headers with their modules via the HeaderInfoTable.
4344 // FIXME: Re-evaluate this section; maybe only store InputFile IDs instead
4345 // of complete filenames or remove it entirely.
Guy Benyei11169dd2012-12-18 14:30:41 +00004346 break;
4347 }
4348
4349 case SUBMODULE_EXCLUDED_HEADER: {
4350 if (First) {
4351 Error("missing submodule metadata record at beginning of block");
Ben Langmuir2c9af442014-04-10 17:57:43 +00004352 return Failure;
Guy Benyei11169dd2012-12-18 14:30:41 +00004353 }
4354
4355 if (!CurrentModule)
4356 break;
4357
Argyrios Kyrtzidisb146baa2013-03-13 21:13:51 +00004358 // We lazily associate headers with their modules via the HeaderInfoTable.
4359 // FIXME: Re-evaluate this section; maybe only store InputFile IDs instead
4360 // of complete filenames or remove it entirely.
Guy Benyei11169dd2012-12-18 14:30:41 +00004361 break;
4362 }
4363
Lawrence Crowlb53e5482013-06-20 21:14:14 +00004364 case SUBMODULE_PRIVATE_HEADER: {
4365 if (First) {
4366 Error("missing submodule metadata record at beginning of block");
Ben Langmuir2c9af442014-04-10 17:57:43 +00004367 return Failure;
Lawrence Crowlb53e5482013-06-20 21:14:14 +00004368 }
4369
4370 if (!CurrentModule)
4371 break;
4372
4373 // We lazily associate headers with their modules via the HeaderInfoTable.
4374 // FIXME: Re-evaluate this section; maybe only store InputFile IDs instead
4375 // of complete filenames or remove it entirely.
4376 break;
4377 }
4378
Guy Benyei11169dd2012-12-18 14:30:41 +00004379 case SUBMODULE_TOPHEADER: {
4380 if (First) {
4381 Error("missing submodule metadata record at beginning of block");
Ben Langmuir2c9af442014-04-10 17:57:43 +00004382 return Failure;
Guy Benyei11169dd2012-12-18 14:30:41 +00004383 }
4384
4385 if (!CurrentModule)
4386 break;
4387
Argyrios Kyrtzidis3c5305c2013-03-13 21:13:43 +00004388 CurrentModule->addTopHeaderFilename(Blob);
Guy Benyei11169dd2012-12-18 14:30:41 +00004389 break;
4390 }
4391
4392 case SUBMODULE_UMBRELLA_DIR: {
4393 if (First) {
4394 Error("missing submodule metadata record at beginning of block");
Ben Langmuir2c9af442014-04-10 17:57:43 +00004395 return Failure;
Guy Benyei11169dd2012-12-18 14:30:41 +00004396 }
4397
4398 if (!CurrentModule)
4399 break;
4400
Guy Benyei11169dd2012-12-18 14:30:41 +00004401 if (const DirectoryEntry *Umbrella
Chris Lattner0e6c9402013-01-20 02:38:54 +00004402 = PP.getFileManager().getDirectory(Blob)) {
Guy Benyei11169dd2012-12-18 14:30:41 +00004403 if (!CurrentModule->getUmbrellaDir())
4404 ModMap.setUmbrellaDir(CurrentModule, Umbrella);
4405 else if (CurrentModule->getUmbrellaDir() != Umbrella) {
Ben Langmuir2c9af442014-04-10 17:57:43 +00004406 if ((ClientLoadCapabilities & ARR_OutOfDate) == 0)
4407 Error("mismatched umbrella directories in submodule");
4408 return OutOfDate;
Guy Benyei11169dd2012-12-18 14:30:41 +00004409 }
4410 }
4411 break;
4412 }
4413
4414 case SUBMODULE_METADATA: {
4415 if (!First) {
4416 Error("submodule metadata record not at beginning of block");
Ben Langmuir2c9af442014-04-10 17:57:43 +00004417 return Failure;
Guy Benyei11169dd2012-12-18 14:30:41 +00004418 }
4419 First = false;
4420
4421 F.BaseSubmoduleID = getTotalNumSubmodules();
4422 F.LocalNumSubmodules = Record[0];
4423 unsigned LocalBaseSubmoduleID = Record[1];
4424 if (F.LocalNumSubmodules > 0) {
4425 // Introduce the global -> local mapping for submodules within this
4426 // module.
4427 GlobalSubmoduleMap.insert(std::make_pair(getTotalNumSubmodules()+1,&F));
4428
4429 // Introduce the local -> global mapping for submodules within this
4430 // module.
4431 F.SubmoduleRemap.insertOrReplace(
4432 std::make_pair(LocalBaseSubmoduleID,
4433 F.BaseSubmoduleID - LocalBaseSubmoduleID));
4434
4435 SubmodulesLoaded.resize(SubmodulesLoaded.size() + F.LocalNumSubmodules);
4436 }
4437 break;
4438 }
4439
4440 case SUBMODULE_IMPORTS: {
4441 if (First) {
4442 Error("missing submodule metadata record at beginning of block");
Ben Langmuir2c9af442014-04-10 17:57:43 +00004443 return Failure;
Guy Benyei11169dd2012-12-18 14:30:41 +00004444 }
4445
4446 if (!CurrentModule)
4447 break;
4448
4449 for (unsigned Idx = 0; Idx != Record.size(); ++Idx) {
Douglas Gregorfb912652013-03-20 21:10:35 +00004450 UnresolvedModuleRef Unresolved;
Guy Benyei11169dd2012-12-18 14:30:41 +00004451 Unresolved.File = &F;
4452 Unresolved.Mod = CurrentModule;
4453 Unresolved.ID = Record[Idx];
Douglas Gregorfb912652013-03-20 21:10:35 +00004454 Unresolved.Kind = UnresolvedModuleRef::Import;
Guy Benyei11169dd2012-12-18 14:30:41 +00004455 Unresolved.IsWildcard = false;
Douglas Gregorfb912652013-03-20 21:10:35 +00004456 UnresolvedModuleRefs.push_back(Unresolved);
Guy Benyei11169dd2012-12-18 14:30:41 +00004457 }
4458 break;
4459 }
4460
4461 case SUBMODULE_EXPORTS: {
4462 if (First) {
4463 Error("missing submodule metadata record at beginning of block");
Ben Langmuir2c9af442014-04-10 17:57:43 +00004464 return Failure;
Guy Benyei11169dd2012-12-18 14:30:41 +00004465 }
4466
4467 if (!CurrentModule)
4468 break;
4469
4470 for (unsigned Idx = 0; Idx + 1 < Record.size(); Idx += 2) {
Douglas Gregorfb912652013-03-20 21:10:35 +00004471 UnresolvedModuleRef Unresolved;
Guy Benyei11169dd2012-12-18 14:30:41 +00004472 Unresolved.File = &F;
4473 Unresolved.Mod = CurrentModule;
4474 Unresolved.ID = Record[Idx];
Douglas Gregorfb912652013-03-20 21:10:35 +00004475 Unresolved.Kind = UnresolvedModuleRef::Export;
Guy Benyei11169dd2012-12-18 14:30:41 +00004476 Unresolved.IsWildcard = Record[Idx + 1];
Douglas Gregorfb912652013-03-20 21:10:35 +00004477 UnresolvedModuleRefs.push_back(Unresolved);
Guy Benyei11169dd2012-12-18 14:30:41 +00004478 }
4479
4480 // Once we've loaded the set of exports, there's no reason to keep
4481 // the parsed, unresolved exports around.
4482 CurrentModule->UnresolvedExports.clear();
4483 break;
4484 }
4485 case SUBMODULE_REQUIRES: {
4486 if (First) {
4487 Error("missing submodule metadata record at beginning of block");
Ben Langmuir2c9af442014-04-10 17:57:43 +00004488 return Failure;
Guy Benyei11169dd2012-12-18 14:30:41 +00004489 }
4490
4491 if (!CurrentModule)
4492 break;
4493
Richard Smitha3feee22013-10-28 22:18:19 +00004494 CurrentModule->addRequirement(Blob, Record[0], Context.getLangOpts(),
Guy Benyei11169dd2012-12-18 14:30:41 +00004495 Context.getTargetInfo());
4496 break;
4497 }
Douglas Gregor6ddfca92013-01-14 17:21:00 +00004498
4499 case SUBMODULE_LINK_LIBRARY:
4500 if (First) {
4501 Error("missing submodule metadata record at beginning of block");
Ben Langmuir2c9af442014-04-10 17:57:43 +00004502 return Failure;
Douglas Gregor6ddfca92013-01-14 17:21:00 +00004503 }
4504
4505 if (!CurrentModule)
4506 break;
4507
4508 CurrentModule->LinkLibraries.push_back(
Chris Lattner0e6c9402013-01-20 02:38:54 +00004509 Module::LinkLibrary(Blob, Record[0]));
Douglas Gregor6ddfca92013-01-14 17:21:00 +00004510 break;
Douglas Gregor35b13ec2013-03-20 00:22:05 +00004511
4512 case SUBMODULE_CONFIG_MACRO:
4513 if (First) {
4514 Error("missing submodule metadata record at beginning of block");
Ben Langmuir2c9af442014-04-10 17:57:43 +00004515 return Failure;
Douglas Gregor35b13ec2013-03-20 00:22:05 +00004516 }
4517
4518 if (!CurrentModule)
4519 break;
4520
4521 CurrentModule->ConfigMacros.push_back(Blob.str());
4522 break;
Douglas Gregorfb912652013-03-20 21:10:35 +00004523
4524 case SUBMODULE_CONFLICT: {
4525 if (First) {
4526 Error("missing submodule metadata record at beginning of block");
Ben Langmuir2c9af442014-04-10 17:57:43 +00004527 return Failure;
Douglas Gregorfb912652013-03-20 21:10:35 +00004528 }
4529
4530 if (!CurrentModule)
4531 break;
4532
4533 UnresolvedModuleRef Unresolved;
4534 Unresolved.File = &F;
4535 Unresolved.Mod = CurrentModule;
4536 Unresolved.ID = Record[0];
4537 Unresolved.Kind = UnresolvedModuleRef::Conflict;
4538 Unresolved.IsWildcard = false;
4539 Unresolved.String = Blob;
4540 UnresolvedModuleRefs.push_back(Unresolved);
4541 break;
4542 }
Guy Benyei11169dd2012-12-18 14:30:41 +00004543 }
4544 }
4545}
4546
4547/// \brief Parse the record that corresponds to a LangOptions data
4548/// structure.
4549///
4550/// This routine parses the language options from the AST file and then gives
4551/// them to the AST listener if one is set.
4552///
4553/// \returns true if the listener deems the file unacceptable, false otherwise.
4554bool ASTReader::ParseLanguageOptions(const RecordData &Record,
4555 bool Complain,
4556 ASTReaderListener &Listener) {
4557 LangOptions LangOpts;
4558 unsigned Idx = 0;
4559#define LANGOPT(Name, Bits, Default, Description) \
4560 LangOpts.Name = Record[Idx++];
4561#define ENUM_LANGOPT(Name, Type, Bits, Default, Description) \
4562 LangOpts.set##Name(static_cast<LangOptions::Type>(Record[Idx++]));
4563#include "clang/Basic/LangOptions.def"
Will Dietzf54319c2013-01-18 11:30:38 +00004564#define SANITIZER(NAME, ID) LangOpts.Sanitize.ID = Record[Idx++];
4565#include "clang/Basic/Sanitizers.def"
Guy Benyei11169dd2012-12-18 14:30:41 +00004566
4567 ObjCRuntime::Kind runtimeKind = (ObjCRuntime::Kind) Record[Idx++];
4568 VersionTuple runtimeVersion = ReadVersionTuple(Record, Idx);
4569 LangOpts.ObjCRuntime = ObjCRuntime(runtimeKind, runtimeVersion);
4570
4571 unsigned Length = Record[Idx++];
4572 LangOpts.CurrentModule.assign(Record.begin() + Idx,
4573 Record.begin() + Idx + Length);
Dmitri Gribenkoacf2e782013-02-22 14:21:27 +00004574
4575 Idx += Length;
4576
4577 // Comment options.
4578 for (unsigned N = Record[Idx++]; N; --N) {
4579 LangOpts.CommentOpts.BlockCommandNames.push_back(
4580 ReadString(Record, Idx));
4581 }
Dmitri Gribenkoa7d16ce2013-04-10 15:35:17 +00004582 LangOpts.CommentOpts.ParseAllComments = Record[Idx++];
Dmitri Gribenkoacf2e782013-02-22 14:21:27 +00004583
Guy Benyei11169dd2012-12-18 14:30:41 +00004584 return Listener.ReadLanguageOptions(LangOpts, Complain);
4585}
4586
4587bool ASTReader::ParseTargetOptions(const RecordData &Record,
4588 bool Complain,
4589 ASTReaderListener &Listener) {
4590 unsigned Idx = 0;
4591 TargetOptions TargetOpts;
4592 TargetOpts.Triple = ReadString(Record, Idx);
4593 TargetOpts.CPU = ReadString(Record, Idx);
4594 TargetOpts.ABI = ReadString(Record, Idx);
Guy Benyei11169dd2012-12-18 14:30:41 +00004595 for (unsigned N = Record[Idx++]; N; --N) {
4596 TargetOpts.FeaturesAsWritten.push_back(ReadString(Record, Idx));
4597 }
4598 for (unsigned N = Record[Idx++]; N; --N) {
4599 TargetOpts.Features.push_back(ReadString(Record, Idx));
4600 }
4601
4602 return Listener.ReadTargetOptions(TargetOpts, Complain);
4603}
4604
4605bool ASTReader::ParseDiagnosticOptions(const RecordData &Record, bool Complain,
4606 ASTReaderListener &Listener) {
Ben Langmuirb92de022014-04-29 16:25:26 +00004607 IntrusiveRefCntPtr<DiagnosticOptions> DiagOpts(new DiagnosticOptions);
Guy Benyei11169dd2012-12-18 14:30:41 +00004608 unsigned Idx = 0;
Ben Langmuirb92de022014-04-29 16:25:26 +00004609#define DIAGOPT(Name, Bits, Default) DiagOpts->Name = Record[Idx++];
Guy Benyei11169dd2012-12-18 14:30:41 +00004610#define ENUM_DIAGOPT(Name, Type, Bits, Default) \
Ben Langmuirb92de022014-04-29 16:25:26 +00004611 DiagOpts->set##Name(static_cast<Type>(Record[Idx++]));
Guy Benyei11169dd2012-12-18 14:30:41 +00004612#include "clang/Basic/DiagnosticOptions.def"
4613
4614 for (unsigned N = Record[Idx++]; N; --N) {
Ben Langmuirb92de022014-04-29 16:25:26 +00004615 DiagOpts->Warnings.push_back(ReadString(Record, Idx));
Guy Benyei11169dd2012-12-18 14:30:41 +00004616 }
4617
4618 return Listener.ReadDiagnosticOptions(DiagOpts, Complain);
4619}
4620
4621bool ASTReader::ParseFileSystemOptions(const RecordData &Record, bool Complain,
4622 ASTReaderListener &Listener) {
4623 FileSystemOptions FSOpts;
4624 unsigned Idx = 0;
4625 FSOpts.WorkingDir = ReadString(Record, Idx);
4626 return Listener.ReadFileSystemOptions(FSOpts, Complain);
4627}
4628
4629bool ASTReader::ParseHeaderSearchOptions(const RecordData &Record,
4630 bool Complain,
4631 ASTReaderListener &Listener) {
4632 HeaderSearchOptions HSOpts;
4633 unsigned Idx = 0;
4634 HSOpts.Sysroot = ReadString(Record, Idx);
4635
4636 // Include entries.
4637 for (unsigned N = Record[Idx++]; N; --N) {
4638 std::string Path = ReadString(Record, Idx);
4639 frontend::IncludeDirGroup Group
4640 = static_cast<frontend::IncludeDirGroup>(Record[Idx++]);
Guy Benyei11169dd2012-12-18 14:30:41 +00004641 bool IsFramework = Record[Idx++];
4642 bool IgnoreSysRoot = Record[Idx++];
Guy Benyei11169dd2012-12-18 14:30:41 +00004643 HSOpts.UserEntries.push_back(
Daniel Dunbar53681732013-01-30 00:34:26 +00004644 HeaderSearchOptions::Entry(Path, Group, IsFramework, IgnoreSysRoot));
Guy Benyei11169dd2012-12-18 14:30:41 +00004645 }
4646
4647 // System header prefixes.
4648 for (unsigned N = Record[Idx++]; N; --N) {
4649 std::string Prefix = ReadString(Record, Idx);
4650 bool IsSystemHeader = Record[Idx++];
4651 HSOpts.SystemHeaderPrefixes.push_back(
4652 HeaderSearchOptions::SystemHeaderPrefix(Prefix, IsSystemHeader));
4653 }
4654
4655 HSOpts.ResourceDir = ReadString(Record, Idx);
4656 HSOpts.ModuleCachePath = ReadString(Record, Idx);
Argyrios Kyrtzidis1594c152014-03-03 08:12:05 +00004657 HSOpts.ModuleUserBuildPath = ReadString(Record, Idx);
Guy Benyei11169dd2012-12-18 14:30:41 +00004658 HSOpts.DisableModuleHash = Record[Idx++];
4659 HSOpts.UseBuiltinIncludes = Record[Idx++];
4660 HSOpts.UseStandardSystemIncludes = Record[Idx++];
4661 HSOpts.UseStandardCXXIncludes = Record[Idx++];
4662 HSOpts.UseLibcxx = Record[Idx++];
4663
4664 return Listener.ReadHeaderSearchOptions(HSOpts, Complain);
4665}
4666
4667bool ASTReader::ParsePreprocessorOptions(const RecordData &Record,
4668 bool Complain,
4669 ASTReaderListener &Listener,
4670 std::string &SuggestedPredefines) {
4671 PreprocessorOptions PPOpts;
4672 unsigned Idx = 0;
4673
4674 // Macro definitions/undefs
4675 for (unsigned N = Record[Idx++]; N; --N) {
4676 std::string Macro = ReadString(Record, Idx);
4677 bool IsUndef = Record[Idx++];
4678 PPOpts.Macros.push_back(std::make_pair(Macro, IsUndef));
4679 }
4680
4681 // Includes
4682 for (unsigned N = Record[Idx++]; N; --N) {
4683 PPOpts.Includes.push_back(ReadString(Record, Idx));
4684 }
4685
4686 // Macro Includes
4687 for (unsigned N = Record[Idx++]; N; --N) {
4688 PPOpts.MacroIncludes.push_back(ReadString(Record, Idx));
4689 }
4690
4691 PPOpts.UsePredefines = Record[Idx++];
Argyrios Kyrtzidisd3afa0c2013-04-26 21:33:40 +00004692 PPOpts.DetailedRecord = Record[Idx++];
Guy Benyei11169dd2012-12-18 14:30:41 +00004693 PPOpts.ImplicitPCHInclude = ReadString(Record, Idx);
4694 PPOpts.ImplicitPTHInclude = ReadString(Record, Idx);
4695 PPOpts.ObjCXXARCStandardLibrary =
4696 static_cast<ObjCXXARCStandardLibraryKind>(Record[Idx++]);
4697 SuggestedPredefines.clear();
4698 return Listener.ReadPreprocessorOptions(PPOpts, Complain,
4699 SuggestedPredefines);
4700}
4701
4702std::pair<ModuleFile *, unsigned>
4703ASTReader::getModulePreprocessedEntity(unsigned GlobalIndex) {
4704 GlobalPreprocessedEntityMapType::iterator
4705 I = GlobalPreprocessedEntityMap.find(GlobalIndex);
4706 assert(I != GlobalPreprocessedEntityMap.end() &&
4707 "Corrupted global preprocessed entity map");
4708 ModuleFile *M = I->second;
4709 unsigned LocalIndex = GlobalIndex - M->BasePreprocessedEntityID;
4710 return std::make_pair(M, LocalIndex);
4711}
4712
4713std::pair<PreprocessingRecord::iterator, PreprocessingRecord::iterator>
4714ASTReader::getModulePreprocessedEntities(ModuleFile &Mod) const {
4715 if (PreprocessingRecord *PPRec = PP.getPreprocessingRecord())
4716 return PPRec->getIteratorsForLoadedRange(Mod.BasePreprocessedEntityID,
4717 Mod.NumPreprocessedEntities);
4718
4719 return std::make_pair(PreprocessingRecord::iterator(),
4720 PreprocessingRecord::iterator());
4721}
4722
4723std::pair<ASTReader::ModuleDeclIterator, ASTReader::ModuleDeclIterator>
4724ASTReader::getModuleFileLevelDecls(ModuleFile &Mod) {
4725 return std::make_pair(ModuleDeclIterator(this, &Mod, Mod.FileSortedDecls),
4726 ModuleDeclIterator(this, &Mod,
4727 Mod.FileSortedDecls + Mod.NumFileSortedDecls));
4728}
4729
4730PreprocessedEntity *ASTReader::ReadPreprocessedEntity(unsigned Index) {
4731 PreprocessedEntityID PPID = Index+1;
4732 std::pair<ModuleFile *, unsigned> PPInfo = getModulePreprocessedEntity(Index);
4733 ModuleFile &M = *PPInfo.first;
4734 unsigned LocalIndex = PPInfo.second;
4735 const PPEntityOffset &PPOffs = M.PreprocessedEntityOffsets[LocalIndex];
4736
Guy Benyei11169dd2012-12-18 14:30:41 +00004737 if (!PP.getPreprocessingRecord()) {
4738 Error("no preprocessing record");
Craig Toppera13603a2014-05-22 05:54:18 +00004739 return nullptr;
Guy Benyei11169dd2012-12-18 14:30:41 +00004740 }
4741
Chris Lattner7fb3bef2013-01-20 00:56:42 +00004742 SavedStreamPosition SavedPosition(M.PreprocessorDetailCursor);
4743 M.PreprocessorDetailCursor.JumpToBit(PPOffs.BitOffset);
4744
4745 llvm::BitstreamEntry Entry =
4746 M.PreprocessorDetailCursor.advance(BitstreamCursor::AF_DontPopBlockAtEnd);
4747 if (Entry.Kind != llvm::BitstreamEntry::Record)
Craig Toppera13603a2014-05-22 05:54:18 +00004748 return nullptr;
Chris Lattner7fb3bef2013-01-20 00:56:42 +00004749
Guy Benyei11169dd2012-12-18 14:30:41 +00004750 // Read the record.
4751 SourceRange Range(ReadSourceLocation(M, PPOffs.Begin),
4752 ReadSourceLocation(M, PPOffs.End));
4753 PreprocessingRecord &PPRec = *PP.getPreprocessingRecord();
Chris Lattner0e6c9402013-01-20 02:38:54 +00004754 StringRef Blob;
Guy Benyei11169dd2012-12-18 14:30:41 +00004755 RecordData Record;
4756 PreprocessorDetailRecordTypes RecType =
Chris Lattner0e6c9402013-01-20 02:38:54 +00004757 (PreprocessorDetailRecordTypes)M.PreprocessorDetailCursor.readRecord(
4758 Entry.ID, Record, &Blob);
Guy Benyei11169dd2012-12-18 14:30:41 +00004759 switch (RecType) {
4760 case PPD_MACRO_EXPANSION: {
4761 bool isBuiltin = Record[0];
Craig Toppera13603a2014-05-22 05:54:18 +00004762 IdentifierInfo *Name = nullptr;
4763 MacroDefinition *Def = nullptr;
Guy Benyei11169dd2012-12-18 14:30:41 +00004764 if (isBuiltin)
4765 Name = getLocalIdentifier(M, Record[1]);
4766 else {
4767 PreprocessedEntityID
4768 GlobalID = getGlobalPreprocessedEntityID(M, Record[1]);
4769 Def =cast<MacroDefinition>(PPRec.getLoadedPreprocessedEntity(GlobalID-1));
4770 }
4771
4772 MacroExpansion *ME;
4773 if (isBuiltin)
4774 ME = new (PPRec) MacroExpansion(Name, Range);
4775 else
4776 ME = new (PPRec) MacroExpansion(Def, Range);
4777
4778 return ME;
4779 }
4780
4781 case PPD_MACRO_DEFINITION: {
4782 // Decode the identifier info and then check again; if the macro is
4783 // still defined and associated with the identifier,
4784 IdentifierInfo *II = getLocalIdentifier(M, Record[0]);
4785 MacroDefinition *MD
4786 = new (PPRec) MacroDefinition(II, Range);
4787
4788 if (DeserializationListener)
4789 DeserializationListener->MacroDefinitionRead(PPID, MD);
4790
4791 return MD;
4792 }
4793
4794 case PPD_INCLUSION_DIRECTIVE: {
Chris Lattner0e6c9402013-01-20 02:38:54 +00004795 const char *FullFileNameStart = Blob.data() + Record[0];
4796 StringRef FullFileName(FullFileNameStart, Blob.size() - Record[0]);
Craig Toppera13603a2014-05-22 05:54:18 +00004797 const FileEntry *File = nullptr;
Guy Benyei11169dd2012-12-18 14:30:41 +00004798 if (!FullFileName.empty())
4799 File = PP.getFileManager().getFile(FullFileName);
4800
4801 // FIXME: Stable encoding
4802 InclusionDirective::InclusionKind Kind
4803 = static_cast<InclusionDirective::InclusionKind>(Record[2]);
4804 InclusionDirective *ID
4805 = new (PPRec) InclusionDirective(PPRec, Kind,
Chris Lattner0e6c9402013-01-20 02:38:54 +00004806 StringRef(Blob.data(), Record[0]),
Guy Benyei11169dd2012-12-18 14:30:41 +00004807 Record[1], Record[3],
4808 File,
4809 Range);
4810 return ID;
4811 }
4812 }
4813
4814 llvm_unreachable("Invalid PreprocessorDetailRecordTypes");
4815}
4816
4817/// \brief \arg SLocMapI points at a chunk of a module that contains no
4818/// preprocessed entities or the entities it contains are not the ones we are
4819/// looking for. Find the next module that contains entities and return the ID
4820/// of the first entry.
4821PreprocessedEntityID ASTReader::findNextPreprocessedEntity(
4822 GlobalSLocOffsetMapType::const_iterator SLocMapI) const {
4823 ++SLocMapI;
4824 for (GlobalSLocOffsetMapType::const_iterator
4825 EndI = GlobalSLocOffsetMap.end(); SLocMapI != EndI; ++SLocMapI) {
4826 ModuleFile &M = *SLocMapI->second;
4827 if (M.NumPreprocessedEntities)
4828 return M.BasePreprocessedEntityID;
4829 }
4830
4831 return getTotalNumPreprocessedEntities();
4832}
4833
4834namespace {
4835
4836template <unsigned PPEntityOffset::*PPLoc>
4837struct PPEntityComp {
4838 const ASTReader &Reader;
4839 ModuleFile &M;
4840
4841 PPEntityComp(const ASTReader &Reader, ModuleFile &M) : Reader(Reader), M(M) { }
4842
4843 bool operator()(const PPEntityOffset &L, const PPEntityOffset &R) const {
4844 SourceLocation LHS = getLoc(L);
4845 SourceLocation RHS = getLoc(R);
4846 return Reader.getSourceManager().isBeforeInTranslationUnit(LHS, RHS);
4847 }
4848
4849 bool operator()(const PPEntityOffset &L, SourceLocation RHS) const {
4850 SourceLocation LHS = getLoc(L);
4851 return Reader.getSourceManager().isBeforeInTranslationUnit(LHS, RHS);
4852 }
4853
4854 bool operator()(SourceLocation LHS, const PPEntityOffset &R) const {
4855 SourceLocation RHS = getLoc(R);
4856 return Reader.getSourceManager().isBeforeInTranslationUnit(LHS, RHS);
4857 }
4858
4859 SourceLocation getLoc(const PPEntityOffset &PPE) const {
4860 return Reader.ReadSourceLocation(M, PPE.*PPLoc);
4861 }
4862};
4863
4864}
4865
Alp Toker2e9ce4c2014-05-16 18:59:21 +00004866PreprocessedEntityID ASTReader::findPreprocessedEntity(SourceLocation Loc,
4867 bool EndsAfter) const {
4868 if (SourceMgr.isLocalSourceLocation(Loc))
Guy Benyei11169dd2012-12-18 14:30:41 +00004869 return getTotalNumPreprocessedEntities();
4870
Alp Toker2e9ce4c2014-05-16 18:59:21 +00004871 GlobalSLocOffsetMapType::const_iterator SLocMapI = GlobalSLocOffsetMap.find(
4872 SourceManager::MaxLoadedOffset - Loc.getOffset() - 1);
Guy Benyei11169dd2012-12-18 14:30:41 +00004873 assert(SLocMapI != GlobalSLocOffsetMap.end() &&
4874 "Corrupted global sloc offset map");
4875
4876 if (SLocMapI->second->NumPreprocessedEntities == 0)
4877 return findNextPreprocessedEntity(SLocMapI);
4878
4879 ModuleFile &M = *SLocMapI->second;
4880 typedef const PPEntityOffset *pp_iterator;
4881 pp_iterator pp_begin = M.PreprocessedEntityOffsets;
4882 pp_iterator pp_end = pp_begin + M.NumPreprocessedEntities;
4883
4884 size_t Count = M.NumPreprocessedEntities;
4885 size_t Half;
4886 pp_iterator First = pp_begin;
4887 pp_iterator PPI;
4888
Alp Toker2e9ce4c2014-05-16 18:59:21 +00004889 if (EndsAfter) {
4890 PPI = std::upper_bound(pp_begin, pp_end, Loc,
4891 PPEntityComp<&PPEntityOffset::Begin>(*this, M));
4892 } else {
4893 // Do a binary search manually instead of using std::lower_bound because
4894 // The end locations of entities may be unordered (when a macro expansion
4895 // is inside another macro argument), but for this case it is not important
4896 // whether we get the first macro expansion or its containing macro.
4897 while (Count > 0) {
4898 Half = Count / 2;
4899 PPI = First;
4900 std::advance(PPI, Half);
4901 if (SourceMgr.isBeforeInTranslationUnit(ReadSourceLocation(M, PPI->End),
4902 Loc)) {
4903 First = PPI;
4904 ++First;
4905 Count = Count - Half - 1;
4906 } else
4907 Count = Half;
4908 }
Guy Benyei11169dd2012-12-18 14:30:41 +00004909 }
4910
4911 if (PPI == pp_end)
4912 return findNextPreprocessedEntity(SLocMapI);
4913
4914 return M.BasePreprocessedEntityID + (PPI - pp_begin);
4915}
4916
Guy Benyei11169dd2012-12-18 14:30:41 +00004917/// \brief Returns a pair of [Begin, End) indices of preallocated
4918/// preprocessed entities that \arg Range encompasses.
4919std::pair<unsigned, unsigned>
4920 ASTReader::findPreprocessedEntitiesInRange(SourceRange Range) {
4921 if (Range.isInvalid())
4922 return std::make_pair(0,0);
4923 assert(!SourceMgr.isBeforeInTranslationUnit(Range.getEnd(),Range.getBegin()));
4924
Alp Toker2e9ce4c2014-05-16 18:59:21 +00004925 PreprocessedEntityID BeginID =
4926 findPreprocessedEntity(Range.getBegin(), false);
4927 PreprocessedEntityID EndID = findPreprocessedEntity(Range.getEnd(), true);
Guy Benyei11169dd2012-12-18 14:30:41 +00004928 return std::make_pair(BeginID, EndID);
4929}
4930
4931/// \brief Optionally returns true or false if the preallocated preprocessed
4932/// entity with index \arg Index came from file \arg FID.
David Blaikie05785d12013-02-20 22:23:23 +00004933Optional<bool> ASTReader::isPreprocessedEntityInFileID(unsigned Index,
Guy Benyei11169dd2012-12-18 14:30:41 +00004934 FileID FID) {
4935 if (FID.isInvalid())
4936 return false;
4937
4938 std::pair<ModuleFile *, unsigned> PPInfo = getModulePreprocessedEntity(Index);
4939 ModuleFile &M = *PPInfo.first;
4940 unsigned LocalIndex = PPInfo.second;
4941 const PPEntityOffset &PPOffs = M.PreprocessedEntityOffsets[LocalIndex];
4942
4943 SourceLocation Loc = ReadSourceLocation(M, PPOffs.Begin);
4944 if (Loc.isInvalid())
4945 return false;
4946
4947 if (SourceMgr.isInFileID(SourceMgr.getFileLoc(Loc), FID))
4948 return true;
4949 else
4950 return false;
4951}
4952
4953namespace {
4954 /// \brief Visitor used to search for information about a header file.
4955 class HeaderFileInfoVisitor {
Guy Benyei11169dd2012-12-18 14:30:41 +00004956 const FileEntry *FE;
4957
David Blaikie05785d12013-02-20 22:23:23 +00004958 Optional<HeaderFileInfo> HFI;
Guy Benyei11169dd2012-12-18 14:30:41 +00004959
4960 public:
Argyrios Kyrtzidis61a38962013-03-06 18:12:44 +00004961 explicit HeaderFileInfoVisitor(const FileEntry *FE)
4962 : FE(FE) { }
Guy Benyei11169dd2012-12-18 14:30:41 +00004963
4964 static bool visit(ModuleFile &M, void *UserData) {
4965 HeaderFileInfoVisitor *This
4966 = static_cast<HeaderFileInfoVisitor *>(UserData);
4967
Guy Benyei11169dd2012-12-18 14:30:41 +00004968 HeaderFileInfoLookupTable *Table
4969 = static_cast<HeaderFileInfoLookupTable *>(M.HeaderFileInfoTable);
4970 if (!Table)
4971 return false;
4972
4973 // Look in the on-disk hash table for an entry for this file name.
Argyrios Kyrtzidis5c2a3452013-03-06 18:12:47 +00004974 HeaderFileInfoLookupTable::iterator Pos = Table->find(This->FE);
Guy Benyei11169dd2012-12-18 14:30:41 +00004975 if (Pos == Table->end())
4976 return false;
4977
4978 This->HFI = *Pos;
4979 return true;
4980 }
4981
David Blaikie05785d12013-02-20 22:23:23 +00004982 Optional<HeaderFileInfo> getHeaderFileInfo() const { return HFI; }
Guy Benyei11169dd2012-12-18 14:30:41 +00004983 };
4984}
4985
4986HeaderFileInfo ASTReader::GetHeaderFileInfo(const FileEntry *FE) {
Argyrios Kyrtzidis61a38962013-03-06 18:12:44 +00004987 HeaderFileInfoVisitor Visitor(FE);
Guy Benyei11169dd2012-12-18 14:30:41 +00004988 ModuleMgr.visit(&HeaderFileInfoVisitor::visit, &Visitor);
Argyrios Kyrtzidis1054bbf2013-05-08 23:46:55 +00004989 if (Optional<HeaderFileInfo> HFI = Visitor.getHeaderFileInfo())
Guy Benyei11169dd2012-12-18 14:30:41 +00004990 return *HFI;
Guy Benyei11169dd2012-12-18 14:30:41 +00004991
4992 return HeaderFileInfo();
4993}
4994
4995void ASTReader::ReadPragmaDiagnosticMappings(DiagnosticsEngine &Diag) {
4996 // FIXME: Make it work properly with modules.
Dmitri Gribenkof8579502013-01-12 19:30:44 +00004997 SmallVector<DiagnosticsEngine::DiagState *, 32> DiagStates;
Guy Benyei11169dd2012-12-18 14:30:41 +00004998 for (ModuleIterator I = ModuleMgr.begin(), E = ModuleMgr.end(); I != E; ++I) {
4999 ModuleFile &F = *(*I);
5000 unsigned Idx = 0;
5001 DiagStates.clear();
5002 assert(!Diag.DiagStates.empty());
5003 DiagStates.push_back(&Diag.DiagStates.front()); // the command-line one.
5004 while (Idx < F.PragmaDiagMappings.size()) {
5005 SourceLocation Loc = ReadSourceLocation(F, F.PragmaDiagMappings[Idx++]);
5006 unsigned DiagStateID = F.PragmaDiagMappings[Idx++];
5007 if (DiagStateID != 0) {
5008 Diag.DiagStatePoints.push_back(
5009 DiagnosticsEngine::DiagStatePoint(DiagStates[DiagStateID-1],
5010 FullSourceLoc(Loc, SourceMgr)));
5011 continue;
5012 }
5013
5014 assert(DiagStateID == 0);
5015 // A new DiagState was created here.
5016 Diag.DiagStates.push_back(*Diag.GetCurDiagState());
5017 DiagnosticsEngine::DiagState *NewState = &Diag.DiagStates.back();
5018 DiagStates.push_back(NewState);
5019 Diag.DiagStatePoints.push_back(
5020 DiagnosticsEngine::DiagStatePoint(NewState,
5021 FullSourceLoc(Loc, SourceMgr)));
5022 while (1) {
5023 assert(Idx < F.PragmaDiagMappings.size() &&
5024 "Invalid data, didn't find '-1' marking end of diag/map pairs");
5025 if (Idx >= F.PragmaDiagMappings.size()) {
5026 break; // Something is messed up but at least avoid infinite loop in
5027 // release build.
5028 }
5029 unsigned DiagID = F.PragmaDiagMappings[Idx++];
5030 if (DiagID == (unsigned)-1) {
5031 break; // no more diag/map pairs for this location.
5032 }
Alp Tokerc726c362014-06-10 09:31:37 +00005033 diag::Severity Map = (diag::Severity)F.PragmaDiagMappings[Idx++];
5034 DiagnosticMapping Mapping = Diag.makeUserMapping(Map, Loc);
5035 Diag.GetCurDiagState()->setMapping(DiagID, Mapping);
Guy Benyei11169dd2012-12-18 14:30:41 +00005036 }
5037 }
5038 }
5039}
5040
5041/// \brief Get the correct cursor and offset for loading a type.
5042ASTReader::RecordLocation ASTReader::TypeCursorForIndex(unsigned Index) {
5043 GlobalTypeMapType::iterator I = GlobalTypeMap.find(Index);
5044 assert(I != GlobalTypeMap.end() && "Corrupted global type map");
5045 ModuleFile *M = I->second;
5046 return RecordLocation(M, M->TypeOffsets[Index - M->BaseTypeIndex]);
5047}
5048
5049/// \brief Read and return the type with the given index..
5050///
5051/// The index is the type ID, shifted and minus the number of predefs. This
5052/// routine actually reads the record corresponding to the type at the given
5053/// location. It is a helper routine for GetType, which deals with reading type
5054/// IDs.
5055QualType ASTReader::readTypeRecord(unsigned Index) {
5056 RecordLocation Loc = TypeCursorForIndex(Index);
Chris Lattner7fb3bef2013-01-20 00:56:42 +00005057 BitstreamCursor &DeclsCursor = Loc.F->DeclsCursor;
Guy Benyei11169dd2012-12-18 14:30:41 +00005058
5059 // Keep track of where we are in the stream, then jump back there
5060 // after reading this type.
5061 SavedStreamPosition SavedPosition(DeclsCursor);
5062
5063 ReadingKindTracker ReadingKind(Read_Type, *this);
5064
5065 // Note that we are loading a type record.
5066 Deserializing AType(this);
5067
5068 unsigned Idx = 0;
5069 DeclsCursor.JumpToBit(Loc.Offset);
5070 RecordData Record;
5071 unsigned Code = DeclsCursor.ReadCode();
Chris Lattner0e6c9402013-01-20 02:38:54 +00005072 switch ((TypeCode)DeclsCursor.readRecord(Code, Record)) {
Guy Benyei11169dd2012-12-18 14:30:41 +00005073 case TYPE_EXT_QUAL: {
5074 if (Record.size() != 2) {
5075 Error("Incorrect encoding of extended qualifier type");
5076 return QualType();
5077 }
5078 QualType Base = readType(*Loc.F, Record, Idx);
5079 Qualifiers Quals = Qualifiers::fromOpaqueValue(Record[Idx++]);
5080 return Context.getQualifiedType(Base, Quals);
5081 }
5082
5083 case TYPE_COMPLEX: {
5084 if (Record.size() != 1) {
5085 Error("Incorrect encoding of complex type");
5086 return QualType();
5087 }
5088 QualType ElemType = readType(*Loc.F, Record, Idx);
5089 return Context.getComplexType(ElemType);
5090 }
5091
5092 case TYPE_POINTER: {
5093 if (Record.size() != 1) {
5094 Error("Incorrect encoding of pointer type");
5095 return QualType();
5096 }
5097 QualType PointeeType = readType(*Loc.F, Record, Idx);
5098 return Context.getPointerType(PointeeType);
5099 }
5100
Reid Kleckner8a365022013-06-24 17:51:48 +00005101 case TYPE_DECAYED: {
5102 if (Record.size() != 1) {
5103 Error("Incorrect encoding of decayed type");
5104 return QualType();
5105 }
5106 QualType OriginalType = readType(*Loc.F, Record, Idx);
5107 QualType DT = Context.getAdjustedParameterType(OriginalType);
5108 if (!isa<DecayedType>(DT))
5109 Error("Decayed type does not decay");
5110 return DT;
5111 }
5112
Reid Kleckner0503a872013-12-05 01:23:43 +00005113 case TYPE_ADJUSTED: {
5114 if (Record.size() != 2) {
5115 Error("Incorrect encoding of adjusted type");
5116 return QualType();
5117 }
5118 QualType OriginalTy = readType(*Loc.F, Record, Idx);
5119 QualType AdjustedTy = readType(*Loc.F, Record, Idx);
5120 return Context.getAdjustedType(OriginalTy, AdjustedTy);
5121 }
5122
Guy Benyei11169dd2012-12-18 14:30:41 +00005123 case TYPE_BLOCK_POINTER: {
5124 if (Record.size() != 1) {
5125 Error("Incorrect encoding of block pointer type");
5126 return QualType();
5127 }
5128 QualType PointeeType = readType(*Loc.F, Record, Idx);
5129 return Context.getBlockPointerType(PointeeType);
5130 }
5131
5132 case TYPE_LVALUE_REFERENCE: {
5133 if (Record.size() != 2) {
5134 Error("Incorrect encoding of lvalue reference type");
5135 return QualType();
5136 }
5137 QualType PointeeType = readType(*Loc.F, Record, Idx);
5138 return Context.getLValueReferenceType(PointeeType, Record[1]);
5139 }
5140
5141 case TYPE_RVALUE_REFERENCE: {
5142 if (Record.size() != 1) {
5143 Error("Incorrect encoding of rvalue reference type");
5144 return QualType();
5145 }
5146 QualType PointeeType = readType(*Loc.F, Record, Idx);
5147 return Context.getRValueReferenceType(PointeeType);
5148 }
5149
5150 case TYPE_MEMBER_POINTER: {
5151 if (Record.size() != 2) {
5152 Error("Incorrect encoding of member pointer type");
5153 return QualType();
5154 }
5155 QualType PointeeType = readType(*Loc.F, Record, Idx);
5156 QualType ClassType = readType(*Loc.F, Record, Idx);
5157 if (PointeeType.isNull() || ClassType.isNull())
5158 return QualType();
5159
5160 return Context.getMemberPointerType(PointeeType, ClassType.getTypePtr());
5161 }
5162
5163 case TYPE_CONSTANT_ARRAY: {
5164 QualType ElementType = readType(*Loc.F, Record, Idx);
5165 ArrayType::ArraySizeModifier ASM = (ArrayType::ArraySizeModifier)Record[1];
5166 unsigned IndexTypeQuals = Record[2];
5167 unsigned Idx = 3;
5168 llvm::APInt Size = ReadAPInt(Record, Idx);
5169 return Context.getConstantArrayType(ElementType, Size,
5170 ASM, IndexTypeQuals);
5171 }
5172
5173 case TYPE_INCOMPLETE_ARRAY: {
5174 QualType ElementType = readType(*Loc.F, Record, Idx);
5175 ArrayType::ArraySizeModifier ASM = (ArrayType::ArraySizeModifier)Record[1];
5176 unsigned IndexTypeQuals = Record[2];
5177 return Context.getIncompleteArrayType(ElementType, ASM, IndexTypeQuals);
5178 }
5179
5180 case TYPE_VARIABLE_ARRAY: {
5181 QualType ElementType = readType(*Loc.F, Record, Idx);
5182 ArrayType::ArraySizeModifier ASM = (ArrayType::ArraySizeModifier)Record[1];
5183 unsigned IndexTypeQuals = Record[2];
5184 SourceLocation LBLoc = ReadSourceLocation(*Loc.F, Record[3]);
5185 SourceLocation RBLoc = ReadSourceLocation(*Loc.F, Record[4]);
5186 return Context.getVariableArrayType(ElementType, ReadExpr(*Loc.F),
5187 ASM, IndexTypeQuals,
5188 SourceRange(LBLoc, RBLoc));
5189 }
5190
5191 case TYPE_VECTOR: {
5192 if (Record.size() != 3) {
5193 Error("incorrect encoding of vector type in AST file");
5194 return QualType();
5195 }
5196
5197 QualType ElementType = readType(*Loc.F, Record, Idx);
5198 unsigned NumElements = Record[1];
5199 unsigned VecKind = Record[2];
5200 return Context.getVectorType(ElementType, NumElements,
5201 (VectorType::VectorKind)VecKind);
5202 }
5203
5204 case TYPE_EXT_VECTOR: {
5205 if (Record.size() != 3) {
5206 Error("incorrect encoding of extended vector type in AST file");
5207 return QualType();
5208 }
5209
5210 QualType ElementType = readType(*Loc.F, Record, Idx);
5211 unsigned NumElements = Record[1];
5212 return Context.getExtVectorType(ElementType, NumElements);
5213 }
5214
5215 case TYPE_FUNCTION_NO_PROTO: {
5216 if (Record.size() != 6) {
5217 Error("incorrect encoding of no-proto function type");
5218 return QualType();
5219 }
5220 QualType ResultType = readType(*Loc.F, Record, Idx);
5221 FunctionType::ExtInfo Info(Record[1], Record[2], Record[3],
5222 (CallingConv)Record[4], Record[5]);
5223 return Context.getFunctionNoProtoType(ResultType, Info);
5224 }
5225
5226 case TYPE_FUNCTION_PROTO: {
5227 QualType ResultType = readType(*Loc.F, Record, Idx);
5228
5229 FunctionProtoType::ExtProtoInfo EPI;
5230 EPI.ExtInfo = FunctionType::ExtInfo(/*noreturn*/ Record[1],
5231 /*hasregparm*/ Record[2],
5232 /*regparm*/ Record[3],
5233 static_cast<CallingConv>(Record[4]),
5234 /*produces*/ Record[5]);
5235
5236 unsigned Idx = 6;
5237 unsigned NumParams = Record[Idx++];
5238 SmallVector<QualType, 16> ParamTypes;
5239 for (unsigned I = 0; I != NumParams; ++I)
5240 ParamTypes.push_back(readType(*Loc.F, Record, Idx));
5241
5242 EPI.Variadic = Record[Idx++];
5243 EPI.HasTrailingReturn = Record[Idx++];
5244 EPI.TypeQuals = Record[Idx++];
5245 EPI.RefQualifier = static_cast<RefQualifierKind>(Record[Idx++]);
Richard Smith564417a2014-03-20 21:47:22 +00005246 SmallVector<QualType, 8> ExceptionStorage;
5247 readExceptionSpec(*Loc.F, ExceptionStorage, EPI, Record, Idx);
Jordan Rose5c382722013-03-08 21:51:21 +00005248 return Context.getFunctionType(ResultType, ParamTypes, EPI);
Guy Benyei11169dd2012-12-18 14:30:41 +00005249 }
5250
5251 case TYPE_UNRESOLVED_USING: {
5252 unsigned Idx = 0;
5253 return Context.getTypeDeclType(
5254 ReadDeclAs<UnresolvedUsingTypenameDecl>(*Loc.F, Record, Idx));
5255 }
5256
5257 case TYPE_TYPEDEF: {
5258 if (Record.size() != 2) {
5259 Error("incorrect encoding of typedef type");
5260 return QualType();
5261 }
5262 unsigned Idx = 0;
5263 TypedefNameDecl *Decl = ReadDeclAs<TypedefNameDecl>(*Loc.F, Record, Idx);
5264 QualType Canonical = readType(*Loc.F, Record, Idx);
5265 if (!Canonical.isNull())
5266 Canonical = Context.getCanonicalType(Canonical);
5267 return Context.getTypedefType(Decl, Canonical);
5268 }
5269
5270 case TYPE_TYPEOF_EXPR:
5271 return Context.getTypeOfExprType(ReadExpr(*Loc.F));
5272
5273 case TYPE_TYPEOF: {
5274 if (Record.size() != 1) {
5275 Error("incorrect encoding of typeof(type) in AST file");
5276 return QualType();
5277 }
5278 QualType UnderlyingType = readType(*Loc.F, Record, Idx);
5279 return Context.getTypeOfType(UnderlyingType);
5280 }
5281
5282 case TYPE_DECLTYPE: {
5283 QualType UnderlyingType = readType(*Loc.F, Record, Idx);
5284 return Context.getDecltypeType(ReadExpr(*Loc.F), UnderlyingType);
5285 }
5286
5287 case TYPE_UNARY_TRANSFORM: {
5288 QualType BaseType = readType(*Loc.F, Record, Idx);
5289 QualType UnderlyingType = readType(*Loc.F, Record, Idx);
5290 UnaryTransformType::UTTKind UKind = (UnaryTransformType::UTTKind)Record[2];
5291 return Context.getUnaryTransformType(BaseType, UnderlyingType, UKind);
5292 }
5293
Richard Smith74aeef52013-04-26 16:15:35 +00005294 case TYPE_AUTO: {
5295 QualType Deduced = readType(*Loc.F, Record, Idx);
5296 bool IsDecltypeAuto = Record[Idx++];
Richard Smith27d807c2013-04-30 13:56:41 +00005297 bool IsDependent = Deduced.isNull() ? Record[Idx++] : false;
Manuel Klimek2fdbea22013-08-22 12:12:24 +00005298 return Context.getAutoType(Deduced, IsDecltypeAuto, IsDependent);
Richard Smith74aeef52013-04-26 16:15:35 +00005299 }
Guy Benyei11169dd2012-12-18 14:30:41 +00005300
5301 case TYPE_RECORD: {
5302 if (Record.size() != 2) {
5303 Error("incorrect encoding of record type");
5304 return QualType();
5305 }
5306 unsigned Idx = 0;
5307 bool IsDependent = Record[Idx++];
5308 RecordDecl *RD = ReadDeclAs<RecordDecl>(*Loc.F, Record, Idx);
5309 RD = cast_or_null<RecordDecl>(RD->getCanonicalDecl());
5310 QualType T = Context.getRecordType(RD);
5311 const_cast<Type*>(T.getTypePtr())->setDependent(IsDependent);
5312 return T;
5313 }
5314
5315 case TYPE_ENUM: {
5316 if (Record.size() != 2) {
5317 Error("incorrect encoding of enum type");
5318 return QualType();
5319 }
5320 unsigned Idx = 0;
5321 bool IsDependent = Record[Idx++];
5322 QualType T
5323 = Context.getEnumType(ReadDeclAs<EnumDecl>(*Loc.F, Record, Idx));
5324 const_cast<Type*>(T.getTypePtr())->setDependent(IsDependent);
5325 return T;
5326 }
5327
5328 case TYPE_ATTRIBUTED: {
5329 if (Record.size() != 3) {
5330 Error("incorrect encoding of attributed type");
5331 return QualType();
5332 }
5333 QualType modifiedType = readType(*Loc.F, Record, Idx);
5334 QualType equivalentType = readType(*Loc.F, Record, Idx);
5335 AttributedType::Kind kind = static_cast<AttributedType::Kind>(Record[2]);
5336 return Context.getAttributedType(kind, modifiedType, equivalentType);
5337 }
5338
5339 case TYPE_PAREN: {
5340 if (Record.size() != 1) {
5341 Error("incorrect encoding of paren type");
5342 return QualType();
5343 }
5344 QualType InnerType = readType(*Loc.F, Record, Idx);
5345 return Context.getParenType(InnerType);
5346 }
5347
5348 case TYPE_PACK_EXPANSION: {
5349 if (Record.size() != 2) {
5350 Error("incorrect encoding of pack expansion type");
5351 return QualType();
5352 }
5353 QualType Pattern = readType(*Loc.F, Record, Idx);
5354 if (Pattern.isNull())
5355 return QualType();
David Blaikie05785d12013-02-20 22:23:23 +00005356 Optional<unsigned> NumExpansions;
Guy Benyei11169dd2012-12-18 14:30:41 +00005357 if (Record[1])
5358 NumExpansions = Record[1] - 1;
5359 return Context.getPackExpansionType(Pattern, NumExpansions);
5360 }
5361
5362 case TYPE_ELABORATED: {
5363 unsigned Idx = 0;
5364 ElaboratedTypeKeyword Keyword = (ElaboratedTypeKeyword)Record[Idx++];
5365 NestedNameSpecifier *NNS = ReadNestedNameSpecifier(*Loc.F, Record, Idx);
5366 QualType NamedType = readType(*Loc.F, Record, Idx);
5367 return Context.getElaboratedType(Keyword, NNS, NamedType);
5368 }
5369
5370 case TYPE_OBJC_INTERFACE: {
5371 unsigned Idx = 0;
5372 ObjCInterfaceDecl *ItfD
5373 = ReadDeclAs<ObjCInterfaceDecl>(*Loc.F, Record, Idx);
5374 return Context.getObjCInterfaceType(ItfD->getCanonicalDecl());
5375 }
5376
5377 case TYPE_OBJC_OBJECT: {
5378 unsigned Idx = 0;
5379 QualType Base = readType(*Loc.F, Record, Idx);
5380 unsigned NumProtos = Record[Idx++];
5381 SmallVector<ObjCProtocolDecl*, 4> Protos;
5382 for (unsigned I = 0; I != NumProtos; ++I)
5383 Protos.push_back(ReadDeclAs<ObjCProtocolDecl>(*Loc.F, Record, Idx));
5384 return Context.getObjCObjectType(Base, Protos.data(), NumProtos);
5385 }
5386
5387 case TYPE_OBJC_OBJECT_POINTER: {
5388 unsigned Idx = 0;
5389 QualType Pointee = readType(*Loc.F, Record, Idx);
5390 return Context.getObjCObjectPointerType(Pointee);
5391 }
5392
5393 case TYPE_SUBST_TEMPLATE_TYPE_PARM: {
5394 unsigned Idx = 0;
5395 QualType Parm = readType(*Loc.F, Record, Idx);
5396 QualType Replacement = readType(*Loc.F, Record, Idx);
Stephan Tolksdorfe96f8b32014-03-15 10:23:27 +00005397 return Context.getSubstTemplateTypeParmType(
5398 cast<TemplateTypeParmType>(Parm),
5399 Context.getCanonicalType(Replacement));
Guy Benyei11169dd2012-12-18 14:30:41 +00005400 }
5401
5402 case TYPE_SUBST_TEMPLATE_TYPE_PARM_PACK: {
5403 unsigned Idx = 0;
5404 QualType Parm = readType(*Loc.F, Record, Idx);
5405 TemplateArgument ArgPack = ReadTemplateArgument(*Loc.F, Record, Idx);
5406 return Context.getSubstTemplateTypeParmPackType(
5407 cast<TemplateTypeParmType>(Parm),
5408 ArgPack);
5409 }
5410
5411 case TYPE_INJECTED_CLASS_NAME: {
5412 CXXRecordDecl *D = ReadDeclAs<CXXRecordDecl>(*Loc.F, Record, Idx);
5413 QualType TST = readType(*Loc.F, Record, Idx); // probably derivable
5414 // FIXME: ASTContext::getInjectedClassNameType is not currently suitable
5415 // for AST reading, too much interdependencies.
Richard Smithf17fdbd2014-04-24 02:25:27 +00005416 const Type *T;
5417 if (const Type *Existing = D->getTypeForDecl())
5418 T = Existing;
5419 else if (auto *Prev = D->getPreviousDecl())
5420 T = Prev->getTypeForDecl();
5421 else
5422 T = new (Context, TypeAlignment) InjectedClassNameType(D, TST);
5423 return QualType(T, 0);
Guy Benyei11169dd2012-12-18 14:30:41 +00005424 }
5425
5426 case TYPE_TEMPLATE_TYPE_PARM: {
5427 unsigned Idx = 0;
5428 unsigned Depth = Record[Idx++];
5429 unsigned Index = Record[Idx++];
5430 bool Pack = Record[Idx++];
5431 TemplateTypeParmDecl *D
5432 = ReadDeclAs<TemplateTypeParmDecl>(*Loc.F, Record, Idx);
5433 return Context.getTemplateTypeParmType(Depth, Index, Pack, D);
5434 }
5435
5436 case TYPE_DEPENDENT_NAME: {
5437 unsigned Idx = 0;
5438 ElaboratedTypeKeyword Keyword = (ElaboratedTypeKeyword)Record[Idx++];
5439 NestedNameSpecifier *NNS = ReadNestedNameSpecifier(*Loc.F, Record, Idx);
5440 const IdentifierInfo *Name = this->GetIdentifierInfo(*Loc.F, Record, Idx);
5441 QualType Canon = readType(*Loc.F, Record, Idx);
5442 if (!Canon.isNull())
5443 Canon = Context.getCanonicalType(Canon);
5444 return Context.getDependentNameType(Keyword, NNS, Name, Canon);
5445 }
5446
5447 case TYPE_DEPENDENT_TEMPLATE_SPECIALIZATION: {
5448 unsigned Idx = 0;
5449 ElaboratedTypeKeyword Keyword = (ElaboratedTypeKeyword)Record[Idx++];
5450 NestedNameSpecifier *NNS = ReadNestedNameSpecifier(*Loc.F, Record, Idx);
5451 const IdentifierInfo *Name = this->GetIdentifierInfo(*Loc.F, Record, Idx);
5452 unsigned NumArgs = Record[Idx++];
5453 SmallVector<TemplateArgument, 8> Args;
5454 Args.reserve(NumArgs);
5455 while (NumArgs--)
5456 Args.push_back(ReadTemplateArgument(*Loc.F, Record, Idx));
5457 return Context.getDependentTemplateSpecializationType(Keyword, NNS, Name,
5458 Args.size(), Args.data());
5459 }
5460
5461 case TYPE_DEPENDENT_SIZED_ARRAY: {
5462 unsigned Idx = 0;
5463
5464 // ArrayType
5465 QualType ElementType = readType(*Loc.F, Record, Idx);
5466 ArrayType::ArraySizeModifier ASM
5467 = (ArrayType::ArraySizeModifier)Record[Idx++];
5468 unsigned IndexTypeQuals = Record[Idx++];
5469
5470 // DependentSizedArrayType
5471 Expr *NumElts = ReadExpr(*Loc.F);
5472 SourceRange Brackets = ReadSourceRange(*Loc.F, Record, Idx);
5473
5474 return Context.getDependentSizedArrayType(ElementType, NumElts, ASM,
5475 IndexTypeQuals, Brackets);
5476 }
5477
5478 case TYPE_TEMPLATE_SPECIALIZATION: {
5479 unsigned Idx = 0;
5480 bool IsDependent = Record[Idx++];
5481 TemplateName Name = ReadTemplateName(*Loc.F, Record, Idx);
5482 SmallVector<TemplateArgument, 8> Args;
5483 ReadTemplateArgumentList(Args, *Loc.F, Record, Idx);
5484 QualType Underlying = readType(*Loc.F, Record, Idx);
5485 QualType T;
5486 if (Underlying.isNull())
5487 T = Context.getCanonicalTemplateSpecializationType(Name, Args.data(),
5488 Args.size());
5489 else
5490 T = Context.getTemplateSpecializationType(Name, Args.data(),
5491 Args.size(), Underlying);
5492 const_cast<Type*>(T.getTypePtr())->setDependent(IsDependent);
5493 return T;
5494 }
5495
5496 case TYPE_ATOMIC: {
5497 if (Record.size() != 1) {
5498 Error("Incorrect encoding of atomic type");
5499 return QualType();
5500 }
5501 QualType ValueType = readType(*Loc.F, Record, Idx);
5502 return Context.getAtomicType(ValueType);
5503 }
5504 }
5505 llvm_unreachable("Invalid TypeCode!");
5506}
5507
Richard Smith564417a2014-03-20 21:47:22 +00005508void ASTReader::readExceptionSpec(ModuleFile &ModuleFile,
5509 SmallVectorImpl<QualType> &Exceptions,
5510 FunctionProtoType::ExtProtoInfo &EPI,
5511 const RecordData &Record, unsigned &Idx) {
5512 ExceptionSpecificationType EST =
5513 static_cast<ExceptionSpecificationType>(Record[Idx++]);
5514 EPI.ExceptionSpecType = EST;
5515 if (EST == EST_Dynamic) {
5516 EPI.NumExceptions = Record[Idx++];
5517 for (unsigned I = 0; I != EPI.NumExceptions; ++I)
5518 Exceptions.push_back(readType(ModuleFile, Record, Idx));
5519 EPI.Exceptions = Exceptions.data();
5520 } else if (EST == EST_ComputedNoexcept) {
5521 EPI.NoexceptExpr = ReadExpr(ModuleFile);
5522 } else if (EST == EST_Uninstantiated) {
5523 EPI.ExceptionSpecDecl = ReadDeclAs<FunctionDecl>(ModuleFile, Record, Idx);
5524 EPI.ExceptionSpecTemplate =
5525 ReadDeclAs<FunctionDecl>(ModuleFile, Record, Idx);
5526 } else if (EST == EST_Unevaluated) {
5527 EPI.ExceptionSpecDecl = ReadDeclAs<FunctionDecl>(ModuleFile, Record, Idx);
5528 }
5529}
5530
Guy Benyei11169dd2012-12-18 14:30:41 +00005531class clang::TypeLocReader : public TypeLocVisitor<TypeLocReader> {
5532 ASTReader &Reader;
5533 ModuleFile &F;
5534 const ASTReader::RecordData &Record;
5535 unsigned &Idx;
5536
5537 SourceLocation ReadSourceLocation(const ASTReader::RecordData &R,
5538 unsigned &I) {
5539 return Reader.ReadSourceLocation(F, R, I);
5540 }
5541
5542 template<typename T>
5543 T *ReadDeclAs(const ASTReader::RecordData &Record, unsigned &Idx) {
5544 return Reader.ReadDeclAs<T>(F, Record, Idx);
5545 }
5546
5547public:
5548 TypeLocReader(ASTReader &Reader, ModuleFile &F,
5549 const ASTReader::RecordData &Record, unsigned &Idx)
5550 : Reader(Reader), F(F), Record(Record), Idx(Idx)
5551 { }
5552
5553 // We want compile-time assurance that we've enumerated all of
5554 // these, so unfortunately we have to declare them first, then
5555 // define them out-of-line.
5556#define ABSTRACT_TYPELOC(CLASS, PARENT)
5557#define TYPELOC(CLASS, PARENT) \
5558 void Visit##CLASS##TypeLoc(CLASS##TypeLoc TyLoc);
5559#include "clang/AST/TypeLocNodes.def"
5560
5561 void VisitFunctionTypeLoc(FunctionTypeLoc);
5562 void VisitArrayTypeLoc(ArrayTypeLoc);
5563};
5564
5565void TypeLocReader::VisitQualifiedTypeLoc(QualifiedTypeLoc TL) {
5566 // nothing to do
5567}
5568void TypeLocReader::VisitBuiltinTypeLoc(BuiltinTypeLoc TL) {
5569 TL.setBuiltinLoc(ReadSourceLocation(Record, Idx));
5570 if (TL.needsExtraLocalData()) {
5571 TL.setWrittenTypeSpec(static_cast<DeclSpec::TST>(Record[Idx++]));
5572 TL.setWrittenSignSpec(static_cast<DeclSpec::TSS>(Record[Idx++]));
5573 TL.setWrittenWidthSpec(static_cast<DeclSpec::TSW>(Record[Idx++]));
5574 TL.setModeAttr(Record[Idx++]);
5575 }
5576}
5577void TypeLocReader::VisitComplexTypeLoc(ComplexTypeLoc TL) {
5578 TL.setNameLoc(ReadSourceLocation(Record, Idx));
5579}
5580void TypeLocReader::VisitPointerTypeLoc(PointerTypeLoc TL) {
5581 TL.setStarLoc(ReadSourceLocation(Record, Idx));
5582}
Reid Kleckner8a365022013-06-24 17:51:48 +00005583void TypeLocReader::VisitDecayedTypeLoc(DecayedTypeLoc TL) {
5584 // nothing to do
5585}
Reid Kleckner0503a872013-12-05 01:23:43 +00005586void TypeLocReader::VisitAdjustedTypeLoc(AdjustedTypeLoc TL) {
5587 // nothing to do
5588}
Guy Benyei11169dd2012-12-18 14:30:41 +00005589void TypeLocReader::VisitBlockPointerTypeLoc(BlockPointerTypeLoc TL) {
5590 TL.setCaretLoc(ReadSourceLocation(Record, Idx));
5591}
5592void TypeLocReader::VisitLValueReferenceTypeLoc(LValueReferenceTypeLoc TL) {
5593 TL.setAmpLoc(ReadSourceLocation(Record, Idx));
5594}
5595void TypeLocReader::VisitRValueReferenceTypeLoc(RValueReferenceTypeLoc TL) {
5596 TL.setAmpAmpLoc(ReadSourceLocation(Record, Idx));
5597}
5598void TypeLocReader::VisitMemberPointerTypeLoc(MemberPointerTypeLoc TL) {
5599 TL.setStarLoc(ReadSourceLocation(Record, Idx));
5600 TL.setClassTInfo(Reader.GetTypeSourceInfo(F, Record, Idx));
5601}
5602void TypeLocReader::VisitArrayTypeLoc(ArrayTypeLoc TL) {
5603 TL.setLBracketLoc(ReadSourceLocation(Record, Idx));
5604 TL.setRBracketLoc(ReadSourceLocation(Record, Idx));
5605 if (Record[Idx++])
5606 TL.setSizeExpr(Reader.ReadExpr(F));
5607 else
Craig Toppera13603a2014-05-22 05:54:18 +00005608 TL.setSizeExpr(nullptr);
Guy Benyei11169dd2012-12-18 14:30:41 +00005609}
5610void TypeLocReader::VisitConstantArrayTypeLoc(ConstantArrayTypeLoc TL) {
5611 VisitArrayTypeLoc(TL);
5612}
5613void TypeLocReader::VisitIncompleteArrayTypeLoc(IncompleteArrayTypeLoc TL) {
5614 VisitArrayTypeLoc(TL);
5615}
5616void TypeLocReader::VisitVariableArrayTypeLoc(VariableArrayTypeLoc TL) {
5617 VisitArrayTypeLoc(TL);
5618}
5619void TypeLocReader::VisitDependentSizedArrayTypeLoc(
5620 DependentSizedArrayTypeLoc TL) {
5621 VisitArrayTypeLoc(TL);
5622}
5623void TypeLocReader::VisitDependentSizedExtVectorTypeLoc(
5624 DependentSizedExtVectorTypeLoc TL) {
5625 TL.setNameLoc(ReadSourceLocation(Record, Idx));
5626}
5627void TypeLocReader::VisitVectorTypeLoc(VectorTypeLoc TL) {
5628 TL.setNameLoc(ReadSourceLocation(Record, Idx));
5629}
5630void TypeLocReader::VisitExtVectorTypeLoc(ExtVectorTypeLoc TL) {
5631 TL.setNameLoc(ReadSourceLocation(Record, Idx));
5632}
5633void TypeLocReader::VisitFunctionTypeLoc(FunctionTypeLoc TL) {
5634 TL.setLocalRangeBegin(ReadSourceLocation(Record, Idx));
5635 TL.setLParenLoc(ReadSourceLocation(Record, Idx));
5636 TL.setRParenLoc(ReadSourceLocation(Record, Idx));
5637 TL.setLocalRangeEnd(ReadSourceLocation(Record, Idx));
Alp Tokerb3fd5cf2014-01-21 00:32:38 +00005638 for (unsigned i = 0, e = TL.getNumParams(); i != e; ++i) {
5639 TL.setParam(i, ReadDeclAs<ParmVarDecl>(Record, Idx));
Guy Benyei11169dd2012-12-18 14:30:41 +00005640 }
5641}
5642void TypeLocReader::VisitFunctionProtoTypeLoc(FunctionProtoTypeLoc TL) {
5643 VisitFunctionTypeLoc(TL);
5644}
5645void TypeLocReader::VisitFunctionNoProtoTypeLoc(FunctionNoProtoTypeLoc TL) {
5646 VisitFunctionTypeLoc(TL);
5647}
5648void TypeLocReader::VisitUnresolvedUsingTypeLoc(UnresolvedUsingTypeLoc TL) {
5649 TL.setNameLoc(ReadSourceLocation(Record, Idx));
5650}
5651void TypeLocReader::VisitTypedefTypeLoc(TypedefTypeLoc TL) {
5652 TL.setNameLoc(ReadSourceLocation(Record, Idx));
5653}
5654void TypeLocReader::VisitTypeOfExprTypeLoc(TypeOfExprTypeLoc TL) {
5655 TL.setTypeofLoc(ReadSourceLocation(Record, Idx));
5656 TL.setLParenLoc(ReadSourceLocation(Record, Idx));
5657 TL.setRParenLoc(ReadSourceLocation(Record, Idx));
5658}
5659void TypeLocReader::VisitTypeOfTypeLoc(TypeOfTypeLoc TL) {
5660 TL.setTypeofLoc(ReadSourceLocation(Record, Idx));
5661 TL.setLParenLoc(ReadSourceLocation(Record, Idx));
5662 TL.setRParenLoc(ReadSourceLocation(Record, Idx));
5663 TL.setUnderlyingTInfo(Reader.GetTypeSourceInfo(F, Record, Idx));
5664}
5665void TypeLocReader::VisitDecltypeTypeLoc(DecltypeTypeLoc TL) {
5666 TL.setNameLoc(ReadSourceLocation(Record, Idx));
5667}
5668void TypeLocReader::VisitUnaryTransformTypeLoc(UnaryTransformTypeLoc TL) {
5669 TL.setKWLoc(ReadSourceLocation(Record, Idx));
5670 TL.setLParenLoc(ReadSourceLocation(Record, Idx));
5671 TL.setRParenLoc(ReadSourceLocation(Record, Idx));
5672 TL.setUnderlyingTInfo(Reader.GetTypeSourceInfo(F, Record, Idx));
5673}
5674void TypeLocReader::VisitAutoTypeLoc(AutoTypeLoc TL) {
5675 TL.setNameLoc(ReadSourceLocation(Record, Idx));
5676}
5677void TypeLocReader::VisitRecordTypeLoc(RecordTypeLoc TL) {
5678 TL.setNameLoc(ReadSourceLocation(Record, Idx));
5679}
5680void TypeLocReader::VisitEnumTypeLoc(EnumTypeLoc TL) {
5681 TL.setNameLoc(ReadSourceLocation(Record, Idx));
5682}
5683void TypeLocReader::VisitAttributedTypeLoc(AttributedTypeLoc TL) {
5684 TL.setAttrNameLoc(ReadSourceLocation(Record, Idx));
5685 if (TL.hasAttrOperand()) {
5686 SourceRange range;
5687 range.setBegin(ReadSourceLocation(Record, Idx));
5688 range.setEnd(ReadSourceLocation(Record, Idx));
5689 TL.setAttrOperandParensRange(range);
5690 }
5691 if (TL.hasAttrExprOperand()) {
5692 if (Record[Idx++])
5693 TL.setAttrExprOperand(Reader.ReadExpr(F));
5694 else
Craig Toppera13603a2014-05-22 05:54:18 +00005695 TL.setAttrExprOperand(nullptr);
Guy Benyei11169dd2012-12-18 14:30:41 +00005696 } else if (TL.hasAttrEnumOperand())
5697 TL.setAttrEnumOperandLoc(ReadSourceLocation(Record, Idx));
5698}
5699void TypeLocReader::VisitTemplateTypeParmTypeLoc(TemplateTypeParmTypeLoc TL) {
5700 TL.setNameLoc(ReadSourceLocation(Record, Idx));
5701}
5702void TypeLocReader::VisitSubstTemplateTypeParmTypeLoc(
5703 SubstTemplateTypeParmTypeLoc TL) {
5704 TL.setNameLoc(ReadSourceLocation(Record, Idx));
5705}
5706void TypeLocReader::VisitSubstTemplateTypeParmPackTypeLoc(
5707 SubstTemplateTypeParmPackTypeLoc TL) {
5708 TL.setNameLoc(ReadSourceLocation(Record, Idx));
5709}
5710void TypeLocReader::VisitTemplateSpecializationTypeLoc(
5711 TemplateSpecializationTypeLoc TL) {
5712 TL.setTemplateKeywordLoc(ReadSourceLocation(Record, Idx));
5713 TL.setTemplateNameLoc(ReadSourceLocation(Record, Idx));
5714 TL.setLAngleLoc(ReadSourceLocation(Record, Idx));
5715 TL.setRAngleLoc(ReadSourceLocation(Record, Idx));
5716 for (unsigned i = 0, e = TL.getNumArgs(); i != e; ++i)
5717 TL.setArgLocInfo(i,
5718 Reader.GetTemplateArgumentLocInfo(F,
5719 TL.getTypePtr()->getArg(i).getKind(),
5720 Record, Idx));
5721}
5722void TypeLocReader::VisitParenTypeLoc(ParenTypeLoc TL) {
5723 TL.setLParenLoc(ReadSourceLocation(Record, Idx));
5724 TL.setRParenLoc(ReadSourceLocation(Record, Idx));
5725}
5726void TypeLocReader::VisitElaboratedTypeLoc(ElaboratedTypeLoc TL) {
5727 TL.setElaboratedKeywordLoc(ReadSourceLocation(Record, Idx));
5728 TL.setQualifierLoc(Reader.ReadNestedNameSpecifierLoc(F, Record, Idx));
5729}
5730void TypeLocReader::VisitInjectedClassNameTypeLoc(InjectedClassNameTypeLoc TL) {
5731 TL.setNameLoc(ReadSourceLocation(Record, Idx));
5732}
5733void TypeLocReader::VisitDependentNameTypeLoc(DependentNameTypeLoc TL) {
5734 TL.setElaboratedKeywordLoc(ReadSourceLocation(Record, Idx));
5735 TL.setQualifierLoc(Reader.ReadNestedNameSpecifierLoc(F, Record, Idx));
5736 TL.setNameLoc(ReadSourceLocation(Record, Idx));
5737}
5738void TypeLocReader::VisitDependentTemplateSpecializationTypeLoc(
5739 DependentTemplateSpecializationTypeLoc TL) {
5740 TL.setElaboratedKeywordLoc(ReadSourceLocation(Record, Idx));
5741 TL.setQualifierLoc(Reader.ReadNestedNameSpecifierLoc(F, Record, Idx));
5742 TL.setTemplateKeywordLoc(ReadSourceLocation(Record, Idx));
5743 TL.setTemplateNameLoc(ReadSourceLocation(Record, Idx));
5744 TL.setLAngleLoc(ReadSourceLocation(Record, Idx));
5745 TL.setRAngleLoc(ReadSourceLocation(Record, Idx));
5746 for (unsigned I = 0, E = TL.getNumArgs(); I != E; ++I)
5747 TL.setArgLocInfo(I,
5748 Reader.GetTemplateArgumentLocInfo(F,
5749 TL.getTypePtr()->getArg(I).getKind(),
5750 Record, Idx));
5751}
5752void TypeLocReader::VisitPackExpansionTypeLoc(PackExpansionTypeLoc TL) {
5753 TL.setEllipsisLoc(ReadSourceLocation(Record, Idx));
5754}
5755void TypeLocReader::VisitObjCInterfaceTypeLoc(ObjCInterfaceTypeLoc TL) {
5756 TL.setNameLoc(ReadSourceLocation(Record, Idx));
5757}
5758void TypeLocReader::VisitObjCObjectTypeLoc(ObjCObjectTypeLoc TL) {
5759 TL.setHasBaseTypeAsWritten(Record[Idx++]);
5760 TL.setLAngleLoc(ReadSourceLocation(Record, Idx));
5761 TL.setRAngleLoc(ReadSourceLocation(Record, Idx));
5762 for (unsigned i = 0, e = TL.getNumProtocols(); i != e; ++i)
5763 TL.setProtocolLoc(i, ReadSourceLocation(Record, Idx));
5764}
5765void TypeLocReader::VisitObjCObjectPointerTypeLoc(ObjCObjectPointerTypeLoc TL) {
5766 TL.setStarLoc(ReadSourceLocation(Record, Idx));
5767}
5768void TypeLocReader::VisitAtomicTypeLoc(AtomicTypeLoc TL) {
5769 TL.setKWLoc(ReadSourceLocation(Record, Idx));
5770 TL.setLParenLoc(ReadSourceLocation(Record, Idx));
5771 TL.setRParenLoc(ReadSourceLocation(Record, Idx));
5772}
5773
5774TypeSourceInfo *ASTReader::GetTypeSourceInfo(ModuleFile &F,
5775 const RecordData &Record,
5776 unsigned &Idx) {
5777 QualType InfoTy = readType(F, Record, Idx);
5778 if (InfoTy.isNull())
Craig Toppera13603a2014-05-22 05:54:18 +00005779 return nullptr;
Guy Benyei11169dd2012-12-18 14:30:41 +00005780
5781 TypeSourceInfo *TInfo = getContext().CreateTypeSourceInfo(InfoTy);
5782 TypeLocReader TLR(*this, F, Record, Idx);
5783 for (TypeLoc TL = TInfo->getTypeLoc(); !TL.isNull(); TL = TL.getNextTypeLoc())
5784 TLR.Visit(TL);
5785 return TInfo;
5786}
5787
5788QualType ASTReader::GetType(TypeID ID) {
5789 unsigned FastQuals = ID & Qualifiers::FastMask;
5790 unsigned Index = ID >> Qualifiers::FastWidth;
5791
5792 if (Index < NUM_PREDEF_TYPE_IDS) {
5793 QualType T;
5794 switch ((PredefinedTypeIDs)Index) {
5795 case PREDEF_TYPE_NULL_ID: return QualType();
5796 case PREDEF_TYPE_VOID_ID: T = Context.VoidTy; break;
5797 case PREDEF_TYPE_BOOL_ID: T = Context.BoolTy; break;
5798
5799 case PREDEF_TYPE_CHAR_U_ID:
5800 case PREDEF_TYPE_CHAR_S_ID:
5801 // FIXME: Check that the signedness of CharTy is correct!
5802 T = Context.CharTy;
5803 break;
5804
5805 case PREDEF_TYPE_UCHAR_ID: T = Context.UnsignedCharTy; break;
5806 case PREDEF_TYPE_USHORT_ID: T = Context.UnsignedShortTy; break;
5807 case PREDEF_TYPE_UINT_ID: T = Context.UnsignedIntTy; break;
5808 case PREDEF_TYPE_ULONG_ID: T = Context.UnsignedLongTy; break;
5809 case PREDEF_TYPE_ULONGLONG_ID: T = Context.UnsignedLongLongTy; break;
5810 case PREDEF_TYPE_UINT128_ID: T = Context.UnsignedInt128Ty; break;
5811 case PREDEF_TYPE_SCHAR_ID: T = Context.SignedCharTy; break;
5812 case PREDEF_TYPE_WCHAR_ID: T = Context.WCharTy; break;
5813 case PREDEF_TYPE_SHORT_ID: T = Context.ShortTy; break;
5814 case PREDEF_TYPE_INT_ID: T = Context.IntTy; break;
5815 case PREDEF_TYPE_LONG_ID: T = Context.LongTy; break;
5816 case PREDEF_TYPE_LONGLONG_ID: T = Context.LongLongTy; break;
5817 case PREDEF_TYPE_INT128_ID: T = Context.Int128Ty; break;
5818 case PREDEF_TYPE_HALF_ID: T = Context.HalfTy; break;
5819 case PREDEF_TYPE_FLOAT_ID: T = Context.FloatTy; break;
5820 case PREDEF_TYPE_DOUBLE_ID: T = Context.DoubleTy; break;
5821 case PREDEF_TYPE_LONGDOUBLE_ID: T = Context.LongDoubleTy; break;
5822 case PREDEF_TYPE_OVERLOAD_ID: T = Context.OverloadTy; break;
5823 case PREDEF_TYPE_BOUND_MEMBER: T = Context.BoundMemberTy; break;
5824 case PREDEF_TYPE_PSEUDO_OBJECT: T = Context.PseudoObjectTy; break;
5825 case PREDEF_TYPE_DEPENDENT_ID: T = Context.DependentTy; break;
5826 case PREDEF_TYPE_UNKNOWN_ANY: T = Context.UnknownAnyTy; break;
5827 case PREDEF_TYPE_NULLPTR_ID: T = Context.NullPtrTy; break;
5828 case PREDEF_TYPE_CHAR16_ID: T = Context.Char16Ty; break;
5829 case PREDEF_TYPE_CHAR32_ID: T = Context.Char32Ty; break;
5830 case PREDEF_TYPE_OBJC_ID: T = Context.ObjCBuiltinIdTy; break;
5831 case PREDEF_TYPE_OBJC_CLASS: T = Context.ObjCBuiltinClassTy; break;
5832 case PREDEF_TYPE_OBJC_SEL: T = Context.ObjCBuiltinSelTy; break;
Guy Benyeid8a08ea2012-12-18 14:38:23 +00005833 case PREDEF_TYPE_IMAGE1D_ID: T = Context.OCLImage1dTy; break;
5834 case PREDEF_TYPE_IMAGE1D_ARR_ID: T = Context.OCLImage1dArrayTy; break;
5835 case PREDEF_TYPE_IMAGE1D_BUFF_ID: T = Context.OCLImage1dBufferTy; break;
5836 case PREDEF_TYPE_IMAGE2D_ID: T = Context.OCLImage2dTy; break;
5837 case PREDEF_TYPE_IMAGE2D_ARR_ID: T = Context.OCLImage2dArrayTy; break;
5838 case PREDEF_TYPE_IMAGE3D_ID: T = Context.OCLImage3dTy; break;
Guy Benyei61054192013-02-07 10:55:47 +00005839 case PREDEF_TYPE_SAMPLER_ID: T = Context.OCLSamplerTy; break;
Guy Benyei1b4fb3e2013-01-20 12:31:11 +00005840 case PREDEF_TYPE_EVENT_ID: T = Context.OCLEventTy; break;
Guy Benyei11169dd2012-12-18 14:30:41 +00005841 case PREDEF_TYPE_AUTO_DEDUCT: T = Context.getAutoDeductType(); break;
5842
5843 case PREDEF_TYPE_AUTO_RREF_DEDUCT:
5844 T = Context.getAutoRRefDeductType();
5845 break;
5846
5847 case PREDEF_TYPE_ARC_UNBRIDGED_CAST:
5848 T = Context.ARCUnbridgedCastTy;
5849 break;
5850
5851 case PREDEF_TYPE_VA_LIST_TAG:
5852 T = Context.getVaListTagType();
5853 break;
5854
5855 case PREDEF_TYPE_BUILTIN_FN:
5856 T = Context.BuiltinFnTy;
5857 break;
5858 }
5859
5860 assert(!T.isNull() && "Unknown predefined type");
5861 return T.withFastQualifiers(FastQuals);
5862 }
5863
5864 Index -= NUM_PREDEF_TYPE_IDS;
5865 assert(Index < TypesLoaded.size() && "Type index out-of-range");
5866 if (TypesLoaded[Index].isNull()) {
5867 TypesLoaded[Index] = readTypeRecord(Index);
5868 if (TypesLoaded[Index].isNull())
5869 return QualType();
5870
5871 TypesLoaded[Index]->setFromAST();
5872 if (DeserializationListener)
5873 DeserializationListener->TypeRead(TypeIdx::fromTypeID(ID),
5874 TypesLoaded[Index]);
5875 }
5876
5877 return TypesLoaded[Index].withFastQualifiers(FastQuals);
5878}
5879
5880QualType ASTReader::getLocalType(ModuleFile &F, unsigned LocalID) {
5881 return GetType(getGlobalTypeID(F, LocalID));
5882}
5883
5884serialization::TypeID
5885ASTReader::getGlobalTypeID(ModuleFile &F, unsigned LocalID) const {
5886 unsigned FastQuals = LocalID & Qualifiers::FastMask;
5887 unsigned LocalIndex = LocalID >> Qualifiers::FastWidth;
5888
5889 if (LocalIndex < NUM_PREDEF_TYPE_IDS)
5890 return LocalID;
5891
5892 ContinuousRangeMap<uint32_t, int, 2>::iterator I
5893 = F.TypeRemap.find(LocalIndex - NUM_PREDEF_TYPE_IDS);
5894 assert(I != F.TypeRemap.end() && "Invalid index into type index remap");
5895
5896 unsigned GlobalIndex = LocalIndex + I->second;
5897 return (GlobalIndex << Qualifiers::FastWidth) | FastQuals;
5898}
5899
5900TemplateArgumentLocInfo
5901ASTReader::GetTemplateArgumentLocInfo(ModuleFile &F,
5902 TemplateArgument::ArgKind Kind,
5903 const RecordData &Record,
5904 unsigned &Index) {
5905 switch (Kind) {
5906 case TemplateArgument::Expression:
5907 return ReadExpr(F);
5908 case TemplateArgument::Type:
5909 return GetTypeSourceInfo(F, Record, Index);
5910 case TemplateArgument::Template: {
5911 NestedNameSpecifierLoc QualifierLoc = ReadNestedNameSpecifierLoc(F, Record,
5912 Index);
5913 SourceLocation TemplateNameLoc = ReadSourceLocation(F, Record, Index);
5914 return TemplateArgumentLocInfo(QualifierLoc, TemplateNameLoc,
5915 SourceLocation());
5916 }
5917 case TemplateArgument::TemplateExpansion: {
5918 NestedNameSpecifierLoc QualifierLoc = ReadNestedNameSpecifierLoc(F, Record,
5919 Index);
5920 SourceLocation TemplateNameLoc = ReadSourceLocation(F, Record, Index);
5921 SourceLocation EllipsisLoc = ReadSourceLocation(F, Record, Index);
5922 return TemplateArgumentLocInfo(QualifierLoc, TemplateNameLoc,
5923 EllipsisLoc);
5924 }
5925 case TemplateArgument::Null:
5926 case TemplateArgument::Integral:
5927 case TemplateArgument::Declaration:
5928 case TemplateArgument::NullPtr:
5929 case TemplateArgument::Pack:
5930 // FIXME: Is this right?
5931 return TemplateArgumentLocInfo();
5932 }
5933 llvm_unreachable("unexpected template argument loc");
5934}
5935
5936TemplateArgumentLoc
5937ASTReader::ReadTemplateArgumentLoc(ModuleFile &F,
5938 const RecordData &Record, unsigned &Index) {
5939 TemplateArgument Arg = ReadTemplateArgument(F, Record, Index);
5940
5941 if (Arg.getKind() == TemplateArgument::Expression) {
5942 if (Record[Index++]) // bool InfoHasSameExpr.
5943 return TemplateArgumentLoc(Arg, TemplateArgumentLocInfo(Arg.getAsExpr()));
5944 }
5945 return TemplateArgumentLoc(Arg, GetTemplateArgumentLocInfo(F, Arg.getKind(),
5946 Record, Index));
5947}
5948
Enea Zaffanella6dbe1872013-08-10 07:24:53 +00005949const ASTTemplateArgumentListInfo*
5950ASTReader::ReadASTTemplateArgumentListInfo(ModuleFile &F,
5951 const RecordData &Record,
5952 unsigned &Index) {
5953 SourceLocation LAngleLoc = ReadSourceLocation(F, Record, Index);
5954 SourceLocation RAngleLoc = ReadSourceLocation(F, Record, Index);
5955 unsigned NumArgsAsWritten = Record[Index++];
5956 TemplateArgumentListInfo TemplArgsInfo(LAngleLoc, RAngleLoc);
5957 for (unsigned i = 0; i != NumArgsAsWritten; ++i)
5958 TemplArgsInfo.addArgument(ReadTemplateArgumentLoc(F, Record, Index));
5959 return ASTTemplateArgumentListInfo::Create(getContext(), TemplArgsInfo);
5960}
5961
Guy Benyei11169dd2012-12-18 14:30:41 +00005962Decl *ASTReader::GetExternalDecl(uint32_t ID) {
5963 return GetDecl(ID);
5964}
5965
Richard Smith053f6c62014-05-16 23:01:30 +00005966void ASTReader::CompleteRedeclChain(const Decl *D) {
Richard Smith851072e2014-05-19 20:59:20 +00005967 if (NumCurrentElementsDeserializing) {
5968 // We arrange to not care about the complete redeclaration chain while we're
5969 // deserializing. Just remember that the AST has marked this one as complete
5970 // but that it's not actually complete yet, so we know we still need to
5971 // complete it later.
5972 PendingIncompleteDeclChains.push_back(const_cast<Decl*>(D));
5973 return;
5974 }
5975
Richard Smith053f6c62014-05-16 23:01:30 +00005976 const DeclContext *DC = D->getDeclContext()->getRedeclContext();
5977
5978 // Recursively ensure that the decl context itself is complete
5979 // (in particular, this matters if the decl context is a namespace).
5980 //
5981 // FIXME: This should be performed by lookup instead of here.
5982 cast<Decl>(DC)->getMostRecentDecl();
5983
5984 // If this is a named declaration, complete it by looking it up
5985 // within its context.
5986 //
5987 // FIXME: We don't currently handle the cases where we can't do this;
5988 // merging a class definition that contains unnamed entities should merge
5989 // those entities. Likewise, merging a function definition should merge
5990 // all mergeable entities within it.
5991 if (isa<TranslationUnitDecl>(DC) || isa<NamespaceDecl>(DC) ||
5992 isa<CXXRecordDecl>(DC) || isa<EnumDecl>(DC)) {
5993 if (DeclarationName Name = cast<NamedDecl>(D)->getDeclName()) {
5994 auto *II = Name.getAsIdentifierInfo();
5995 if (isa<TranslationUnitDecl>(DC) && II) {
5996 // Outside of C++, we don't have a lookup table for the TU, so update
5997 // the identifier instead. In C++, either way should work fine.
5998 if (II->isOutOfDate())
5999 updateOutOfDateIdentifier(*II);
6000 } else
6001 DC->lookup(Name);
6002 }
6003 }
6004}
6005
Richard Smithcd45dbc2014-04-19 03:48:30 +00006006uint64_t ASTReader::readCXXBaseSpecifiers(ModuleFile &M,
6007 const RecordData &Record,
6008 unsigned &Idx) {
6009 if (Idx >= Record.size() || Record[Idx] > M.LocalNumCXXBaseSpecifiers) {
6010 Error("malformed AST file: missing C++ base specifier");
Guy Benyei11169dd2012-12-18 14:30:41 +00006011 return 0;
Richard Smithcd45dbc2014-04-19 03:48:30 +00006012 }
6013
Guy Benyei11169dd2012-12-18 14:30:41 +00006014 unsigned LocalID = Record[Idx++];
6015 return getGlobalBitOffset(M, M.CXXBaseSpecifiersOffsets[LocalID - 1]);
6016}
6017
6018CXXBaseSpecifier *ASTReader::GetExternalCXXBaseSpecifiers(uint64_t Offset) {
6019 RecordLocation Loc = getLocalBitOffset(Offset);
Chris Lattner7fb3bef2013-01-20 00:56:42 +00006020 BitstreamCursor &Cursor = Loc.F->DeclsCursor;
Guy Benyei11169dd2012-12-18 14:30:41 +00006021 SavedStreamPosition SavedPosition(Cursor);
6022 Cursor.JumpToBit(Loc.Offset);
6023 ReadingKindTracker ReadingKind(Read_Decl, *this);
6024 RecordData Record;
6025 unsigned Code = Cursor.ReadCode();
Chris Lattner0e6c9402013-01-20 02:38:54 +00006026 unsigned RecCode = Cursor.readRecord(Code, Record);
Guy Benyei11169dd2012-12-18 14:30:41 +00006027 if (RecCode != DECL_CXX_BASE_SPECIFIERS) {
Richard Smithcd45dbc2014-04-19 03:48:30 +00006028 Error("malformed AST file: missing C++ base specifiers");
Craig Toppera13603a2014-05-22 05:54:18 +00006029 return nullptr;
Guy Benyei11169dd2012-12-18 14:30:41 +00006030 }
6031
6032 unsigned Idx = 0;
6033 unsigned NumBases = Record[Idx++];
6034 void *Mem = Context.Allocate(sizeof(CXXBaseSpecifier) * NumBases);
6035 CXXBaseSpecifier *Bases = new (Mem) CXXBaseSpecifier [NumBases];
6036 for (unsigned I = 0; I != NumBases; ++I)
6037 Bases[I] = ReadCXXBaseSpecifier(*Loc.F, Record, Idx);
6038 return Bases;
6039}
6040
6041serialization::DeclID
6042ASTReader::getGlobalDeclID(ModuleFile &F, LocalDeclID LocalID) const {
6043 if (LocalID < NUM_PREDEF_DECL_IDS)
6044 return LocalID;
6045
6046 ContinuousRangeMap<uint32_t, int, 2>::iterator I
6047 = F.DeclRemap.find(LocalID - NUM_PREDEF_DECL_IDS);
6048 assert(I != F.DeclRemap.end() && "Invalid index into decl index remap");
6049
6050 return LocalID + I->second;
6051}
6052
6053bool ASTReader::isDeclIDFromModule(serialization::GlobalDeclID ID,
6054 ModuleFile &M) const {
6055 GlobalDeclMapType::const_iterator I = GlobalDeclMap.find(ID);
6056 assert(I != GlobalDeclMap.end() && "Corrupted global declaration map");
6057 return &M == I->second;
6058}
6059
Douglas Gregor9f782892013-01-21 15:25:38 +00006060ModuleFile *ASTReader::getOwningModuleFile(const Decl *D) {
Guy Benyei11169dd2012-12-18 14:30:41 +00006061 if (!D->isFromASTFile())
Craig Toppera13603a2014-05-22 05:54:18 +00006062 return nullptr;
Guy Benyei11169dd2012-12-18 14:30:41 +00006063 GlobalDeclMapType::const_iterator I = GlobalDeclMap.find(D->getGlobalID());
6064 assert(I != GlobalDeclMap.end() && "Corrupted global declaration map");
6065 return I->second;
6066}
6067
6068SourceLocation ASTReader::getSourceLocationForDeclID(GlobalDeclID ID) {
6069 if (ID < NUM_PREDEF_DECL_IDS)
6070 return SourceLocation();
Richard Smithcd45dbc2014-04-19 03:48:30 +00006071
Guy Benyei11169dd2012-12-18 14:30:41 +00006072 unsigned Index = ID - NUM_PREDEF_DECL_IDS;
6073
6074 if (Index > DeclsLoaded.size()) {
6075 Error("declaration ID out-of-range for AST file");
6076 return SourceLocation();
6077 }
Richard Smithcd45dbc2014-04-19 03:48:30 +00006078
Guy Benyei11169dd2012-12-18 14:30:41 +00006079 if (Decl *D = DeclsLoaded[Index])
6080 return D->getLocation();
6081
6082 unsigned RawLocation = 0;
6083 RecordLocation Rec = DeclCursorForID(ID, RawLocation);
6084 return ReadSourceLocation(*Rec.F, RawLocation);
6085}
6086
Richard Smithcd45dbc2014-04-19 03:48:30 +00006087Decl *ASTReader::GetExistingDecl(DeclID ID) {
6088 if (ID < NUM_PREDEF_DECL_IDS) {
Guy Benyei11169dd2012-12-18 14:30:41 +00006089 switch ((PredefinedDeclIDs)ID) {
6090 case PREDEF_DECL_NULL_ID:
Craig Toppera13603a2014-05-22 05:54:18 +00006091 return nullptr;
Richard Smithcd45dbc2014-04-19 03:48:30 +00006092
Guy Benyei11169dd2012-12-18 14:30:41 +00006093 case PREDEF_DECL_TRANSLATION_UNIT_ID:
6094 return Context.getTranslationUnitDecl();
Richard Smithcd45dbc2014-04-19 03:48:30 +00006095
Guy Benyei11169dd2012-12-18 14:30:41 +00006096 case PREDEF_DECL_OBJC_ID_ID:
6097 return Context.getObjCIdDecl();
6098
6099 case PREDEF_DECL_OBJC_SEL_ID:
6100 return Context.getObjCSelDecl();
6101
6102 case PREDEF_DECL_OBJC_CLASS_ID:
6103 return Context.getObjCClassDecl();
Richard Smithcd45dbc2014-04-19 03:48:30 +00006104
Guy Benyei11169dd2012-12-18 14:30:41 +00006105 case PREDEF_DECL_OBJC_PROTOCOL_ID:
6106 return Context.getObjCProtocolDecl();
Richard Smithcd45dbc2014-04-19 03:48:30 +00006107
Guy Benyei11169dd2012-12-18 14:30:41 +00006108 case PREDEF_DECL_INT_128_ID:
6109 return Context.getInt128Decl();
6110
6111 case PREDEF_DECL_UNSIGNED_INT_128_ID:
6112 return Context.getUInt128Decl();
Richard Smithcd45dbc2014-04-19 03:48:30 +00006113
Guy Benyei11169dd2012-12-18 14:30:41 +00006114 case PREDEF_DECL_OBJC_INSTANCETYPE_ID:
6115 return Context.getObjCInstanceTypeDecl();
6116
6117 case PREDEF_DECL_BUILTIN_VA_LIST_ID:
6118 return Context.getBuiltinVaListDecl();
6119 }
6120 }
Richard Smithcd45dbc2014-04-19 03:48:30 +00006121
Guy Benyei11169dd2012-12-18 14:30:41 +00006122 unsigned Index = ID - NUM_PREDEF_DECL_IDS;
6123
6124 if (Index >= DeclsLoaded.size()) {
6125 assert(0 && "declaration ID out-of-range for AST file");
6126 Error("declaration ID out-of-range for AST file");
Craig Toppera13603a2014-05-22 05:54:18 +00006127 return nullptr;
Guy Benyei11169dd2012-12-18 14:30:41 +00006128 }
Richard Smithcd45dbc2014-04-19 03:48:30 +00006129
6130 return DeclsLoaded[Index];
6131}
6132
6133Decl *ASTReader::GetDecl(DeclID ID) {
6134 if (ID < NUM_PREDEF_DECL_IDS)
6135 return GetExistingDecl(ID);
6136
6137 unsigned Index = ID - NUM_PREDEF_DECL_IDS;
6138
6139 if (Index >= DeclsLoaded.size()) {
6140 assert(0 && "declaration ID out-of-range for AST file");
6141 Error("declaration ID out-of-range for AST file");
Craig Toppera13603a2014-05-22 05:54:18 +00006142 return nullptr;
Richard Smithcd45dbc2014-04-19 03:48:30 +00006143 }
6144
Guy Benyei11169dd2012-12-18 14:30:41 +00006145 if (!DeclsLoaded[Index]) {
6146 ReadDeclRecord(ID);
6147 if (DeserializationListener)
6148 DeserializationListener->DeclRead(ID, DeclsLoaded[Index]);
6149 }
6150
6151 return DeclsLoaded[Index];
6152}
6153
6154DeclID ASTReader::mapGlobalIDToModuleFileGlobalID(ModuleFile &M,
6155 DeclID GlobalID) {
6156 if (GlobalID < NUM_PREDEF_DECL_IDS)
6157 return GlobalID;
6158
6159 GlobalDeclMapType::const_iterator I = GlobalDeclMap.find(GlobalID);
6160 assert(I != GlobalDeclMap.end() && "Corrupted global declaration map");
6161 ModuleFile *Owner = I->second;
6162
6163 llvm::DenseMap<ModuleFile *, serialization::DeclID>::iterator Pos
6164 = M.GlobalToLocalDeclIDs.find(Owner);
6165 if (Pos == M.GlobalToLocalDeclIDs.end())
6166 return 0;
6167
6168 return GlobalID - Owner->BaseDeclID + Pos->second;
6169}
6170
6171serialization::DeclID ASTReader::ReadDeclID(ModuleFile &F,
6172 const RecordData &Record,
6173 unsigned &Idx) {
6174 if (Idx >= Record.size()) {
6175 Error("Corrupted AST file");
6176 return 0;
6177 }
6178
6179 return getGlobalDeclID(F, Record[Idx++]);
6180}
6181
6182/// \brief Resolve the offset of a statement into a statement.
6183///
6184/// This operation will read a new statement from the external
6185/// source each time it is called, and is meant to be used via a
6186/// LazyOffsetPtr (which is used by Decls for the body of functions, etc).
6187Stmt *ASTReader::GetExternalDeclStmt(uint64_t Offset) {
6188 // Switch case IDs are per Decl.
6189 ClearSwitchCaseIDs();
6190
6191 // Offset here is a global offset across the entire chain.
6192 RecordLocation Loc = getLocalBitOffset(Offset);
6193 Loc.F->DeclsCursor.JumpToBit(Loc.Offset);
6194 return ReadStmtFromStream(*Loc.F);
6195}
6196
6197namespace {
6198 class FindExternalLexicalDeclsVisitor {
6199 ASTReader &Reader;
6200 const DeclContext *DC;
6201 bool (*isKindWeWant)(Decl::Kind);
6202
6203 SmallVectorImpl<Decl*> &Decls;
6204 bool PredefsVisited[NUM_PREDEF_DECL_IDS];
6205
6206 public:
6207 FindExternalLexicalDeclsVisitor(ASTReader &Reader, const DeclContext *DC,
6208 bool (*isKindWeWant)(Decl::Kind),
6209 SmallVectorImpl<Decl*> &Decls)
6210 : Reader(Reader), DC(DC), isKindWeWant(isKindWeWant), Decls(Decls)
6211 {
6212 for (unsigned I = 0; I != NUM_PREDEF_DECL_IDS; ++I)
6213 PredefsVisited[I] = false;
6214 }
6215
6216 static bool visit(ModuleFile &M, bool Preorder, void *UserData) {
6217 if (Preorder)
6218 return false;
6219
6220 FindExternalLexicalDeclsVisitor *This
6221 = static_cast<FindExternalLexicalDeclsVisitor *>(UserData);
6222
6223 ModuleFile::DeclContextInfosMap::iterator Info
6224 = M.DeclContextInfos.find(This->DC);
6225 if (Info == M.DeclContextInfos.end() || !Info->second.LexicalDecls)
6226 return false;
6227
6228 // Load all of the declaration IDs
6229 for (const KindDeclIDPair *ID = Info->second.LexicalDecls,
6230 *IDE = ID + Info->second.NumLexicalDecls;
6231 ID != IDE; ++ID) {
6232 if (This->isKindWeWant && !This->isKindWeWant((Decl::Kind)ID->first))
6233 continue;
6234
6235 // Don't add predefined declarations to the lexical context more
6236 // than once.
6237 if (ID->second < NUM_PREDEF_DECL_IDS) {
6238 if (This->PredefsVisited[ID->second])
6239 continue;
6240
6241 This->PredefsVisited[ID->second] = true;
6242 }
6243
6244 if (Decl *D = This->Reader.GetLocalDecl(M, ID->second)) {
6245 if (!This->DC->isDeclInLexicalTraversal(D))
6246 This->Decls.push_back(D);
6247 }
6248 }
6249
6250 return false;
6251 }
6252 };
6253}
6254
6255ExternalLoadResult ASTReader::FindExternalLexicalDecls(const DeclContext *DC,
6256 bool (*isKindWeWant)(Decl::Kind),
6257 SmallVectorImpl<Decl*> &Decls) {
6258 // There might be lexical decls in multiple modules, for the TU at
6259 // least. Walk all of the modules in the order they were loaded.
6260 FindExternalLexicalDeclsVisitor Visitor(*this, DC, isKindWeWant, Decls);
6261 ModuleMgr.visitDepthFirst(&FindExternalLexicalDeclsVisitor::visit, &Visitor);
6262 ++NumLexicalDeclContextsRead;
6263 return ELR_Success;
6264}
6265
6266namespace {
6267
6268class DeclIDComp {
6269 ASTReader &Reader;
6270 ModuleFile &Mod;
6271
6272public:
6273 DeclIDComp(ASTReader &Reader, ModuleFile &M) : Reader(Reader), Mod(M) {}
6274
6275 bool operator()(LocalDeclID L, LocalDeclID R) const {
6276 SourceLocation LHS = getLocation(L);
6277 SourceLocation RHS = getLocation(R);
6278 return Reader.getSourceManager().isBeforeInTranslationUnit(LHS, RHS);
6279 }
6280
6281 bool operator()(SourceLocation LHS, LocalDeclID R) const {
6282 SourceLocation RHS = getLocation(R);
6283 return Reader.getSourceManager().isBeforeInTranslationUnit(LHS, RHS);
6284 }
6285
6286 bool operator()(LocalDeclID L, SourceLocation RHS) const {
6287 SourceLocation LHS = getLocation(L);
6288 return Reader.getSourceManager().isBeforeInTranslationUnit(LHS, RHS);
6289 }
6290
6291 SourceLocation getLocation(LocalDeclID ID) const {
6292 return Reader.getSourceManager().getFileLoc(
6293 Reader.getSourceLocationForDeclID(Reader.getGlobalDeclID(Mod, ID)));
6294 }
6295};
6296
6297}
6298
6299void ASTReader::FindFileRegionDecls(FileID File,
6300 unsigned Offset, unsigned Length,
6301 SmallVectorImpl<Decl *> &Decls) {
6302 SourceManager &SM = getSourceManager();
6303
6304 llvm::DenseMap<FileID, FileDeclsInfo>::iterator I = FileDeclIDs.find(File);
6305 if (I == FileDeclIDs.end())
6306 return;
6307
6308 FileDeclsInfo &DInfo = I->second;
6309 if (DInfo.Decls.empty())
6310 return;
6311
6312 SourceLocation
6313 BeginLoc = SM.getLocForStartOfFile(File).getLocWithOffset(Offset);
6314 SourceLocation EndLoc = BeginLoc.getLocWithOffset(Length);
6315
6316 DeclIDComp DIDComp(*this, *DInfo.Mod);
6317 ArrayRef<serialization::LocalDeclID>::iterator
6318 BeginIt = std::lower_bound(DInfo.Decls.begin(), DInfo.Decls.end(),
6319 BeginLoc, DIDComp);
6320 if (BeginIt != DInfo.Decls.begin())
6321 --BeginIt;
6322
6323 // If we are pointing at a top-level decl inside an objc container, we need
6324 // to backtrack until we find it otherwise we will fail to report that the
6325 // region overlaps with an objc container.
6326 while (BeginIt != DInfo.Decls.begin() &&
6327 GetDecl(getGlobalDeclID(*DInfo.Mod, *BeginIt))
6328 ->isTopLevelDeclInObjCContainer())
6329 --BeginIt;
6330
6331 ArrayRef<serialization::LocalDeclID>::iterator
6332 EndIt = std::upper_bound(DInfo.Decls.begin(), DInfo.Decls.end(),
6333 EndLoc, DIDComp);
6334 if (EndIt != DInfo.Decls.end())
6335 ++EndIt;
6336
6337 for (ArrayRef<serialization::LocalDeclID>::iterator
6338 DIt = BeginIt; DIt != EndIt; ++DIt)
6339 Decls.push_back(GetDecl(getGlobalDeclID(*DInfo.Mod, *DIt)));
6340}
6341
6342namespace {
6343 /// \brief ModuleFile visitor used to perform name lookup into a
6344 /// declaration context.
6345 class DeclContextNameLookupVisitor {
6346 ASTReader &Reader;
Dmitri Gribenkof8579502013-01-12 19:30:44 +00006347 SmallVectorImpl<const DeclContext *> &Contexts;
Guy Benyei11169dd2012-12-18 14:30:41 +00006348 DeclarationName Name;
6349 SmallVectorImpl<NamedDecl *> &Decls;
6350
6351 public:
6352 DeclContextNameLookupVisitor(ASTReader &Reader,
6353 SmallVectorImpl<const DeclContext *> &Contexts,
6354 DeclarationName Name,
6355 SmallVectorImpl<NamedDecl *> &Decls)
6356 : Reader(Reader), Contexts(Contexts), Name(Name), Decls(Decls) { }
6357
6358 static bool visit(ModuleFile &M, void *UserData) {
6359 DeclContextNameLookupVisitor *This
6360 = static_cast<DeclContextNameLookupVisitor *>(UserData);
6361
6362 // Check whether we have any visible declaration information for
6363 // this context in this module.
6364 ModuleFile::DeclContextInfosMap::iterator Info;
6365 bool FoundInfo = false;
6366 for (unsigned I = 0, N = This->Contexts.size(); I != N; ++I) {
6367 Info = M.DeclContextInfos.find(This->Contexts[I]);
6368 if (Info != M.DeclContextInfos.end() &&
6369 Info->second.NameLookupTableData) {
6370 FoundInfo = true;
6371 break;
6372 }
6373 }
6374
6375 if (!FoundInfo)
6376 return false;
6377
6378 // Look for this name within this module.
Richard Smith52e3fba2014-03-11 07:17:35 +00006379 ASTDeclContextNameLookupTable *LookupTable =
Guy Benyei11169dd2012-12-18 14:30:41 +00006380 Info->second.NameLookupTableData;
6381 ASTDeclContextNameLookupTable::iterator Pos
6382 = LookupTable->find(This->Name);
6383 if (Pos == LookupTable->end())
6384 return false;
6385
6386 bool FoundAnything = false;
6387 ASTDeclContextNameLookupTrait::data_type Data = *Pos;
6388 for (; Data.first != Data.second; ++Data.first) {
6389 NamedDecl *ND = This->Reader.GetLocalDeclAs<NamedDecl>(M, *Data.first);
6390 if (!ND)
6391 continue;
6392
6393 if (ND->getDeclName() != This->Name) {
6394 // A name might be null because the decl's redeclarable part is
6395 // currently read before reading its name. The lookup is triggered by
6396 // building that decl (likely indirectly), and so it is later in the
6397 // sense of "already existing" and can be ignored here.
6398 continue;
6399 }
6400
6401 // Record this declaration.
6402 FoundAnything = true;
6403 This->Decls.push_back(ND);
6404 }
6405
6406 return FoundAnything;
6407 }
6408 };
6409}
6410
Douglas Gregor9f782892013-01-21 15:25:38 +00006411/// \brief Retrieve the "definitive" module file for the definition of the
6412/// given declaration context, if there is one.
6413///
6414/// The "definitive" module file is the only place where we need to look to
6415/// find information about the declarations within the given declaration
6416/// context. For example, C++ and Objective-C classes, C structs/unions, and
6417/// Objective-C protocols, categories, and extensions are all defined in a
6418/// single place in the source code, so they have definitive module files
6419/// associated with them. C++ namespaces, on the other hand, can have
6420/// definitions in multiple different module files.
6421///
6422/// Note: this needs to be kept in sync with ASTWriter::AddedVisibleDecl's
6423/// NDEBUG checking.
6424static ModuleFile *getDefinitiveModuleFileFor(const DeclContext *DC,
6425 ASTReader &Reader) {
Douglas Gregor7a6e2002013-01-22 17:08:30 +00006426 if (const DeclContext *DefDC = getDefinitiveDeclContext(DC))
6427 return Reader.getOwningModuleFile(cast<Decl>(DefDC));
Douglas Gregor9f782892013-01-21 15:25:38 +00006428
Craig Toppera13603a2014-05-22 05:54:18 +00006429 return nullptr;
Douglas Gregor9f782892013-01-21 15:25:38 +00006430}
6431
Richard Smith9ce12e32013-02-07 03:30:24 +00006432bool
Guy Benyei11169dd2012-12-18 14:30:41 +00006433ASTReader::FindExternalVisibleDeclsByName(const DeclContext *DC,
6434 DeclarationName Name) {
6435 assert(DC->hasExternalVisibleStorage() &&
6436 "DeclContext has no visible decls in storage");
6437 if (!Name)
Richard Smith9ce12e32013-02-07 03:30:24 +00006438 return false;
Guy Benyei11169dd2012-12-18 14:30:41 +00006439
6440 SmallVector<NamedDecl *, 64> Decls;
6441
6442 // Compute the declaration contexts we need to look into. Multiple such
6443 // declaration contexts occur when two declaration contexts from disjoint
6444 // modules get merged, e.g., when two namespaces with the same name are
6445 // independently defined in separate modules.
6446 SmallVector<const DeclContext *, 2> Contexts;
6447 Contexts.push_back(DC);
6448
6449 if (DC->isNamespace()) {
Richard Smithcd45dbc2014-04-19 03:48:30 +00006450 auto Merged = MergedDecls.find(const_cast<Decl *>(cast<Decl>(DC)));
Guy Benyei11169dd2012-12-18 14:30:41 +00006451 if (Merged != MergedDecls.end()) {
6452 for (unsigned I = 0, N = Merged->second.size(); I != N; ++I)
6453 Contexts.push_back(cast<DeclContext>(GetDecl(Merged->second[I])));
6454 }
6455 }
Richard Smithcd45dbc2014-04-19 03:48:30 +00006456 if (isa<CXXRecordDecl>(DC)) {
6457 auto Merged = MergedLookups.find(DC);
6458 if (Merged != MergedLookups.end())
6459 Contexts.insert(Contexts.end(), Merged->second.begin(),
6460 Merged->second.end());
6461 }
6462
Guy Benyei11169dd2012-12-18 14:30:41 +00006463 DeclContextNameLookupVisitor Visitor(*this, Contexts, Name, Decls);
Douglas Gregor9f782892013-01-21 15:25:38 +00006464
6465 // If we can definitively determine which module file to look into,
6466 // only look there. Otherwise, look in all module files.
6467 ModuleFile *Definitive;
6468 if (Contexts.size() == 1 &&
6469 (Definitive = getDefinitiveModuleFileFor(DC, *this))) {
6470 DeclContextNameLookupVisitor::visit(*Definitive, &Visitor);
6471 } else {
6472 ModuleMgr.visit(&DeclContextNameLookupVisitor::visit, &Visitor);
6473 }
Guy Benyei11169dd2012-12-18 14:30:41 +00006474 ++NumVisibleDeclContextsRead;
6475 SetExternalVisibleDeclsForName(DC, Name, Decls);
Richard Smith9ce12e32013-02-07 03:30:24 +00006476 return !Decls.empty();
Guy Benyei11169dd2012-12-18 14:30:41 +00006477}
6478
6479namespace {
6480 /// \brief ModuleFile visitor used to retrieve all visible names in a
6481 /// declaration context.
6482 class DeclContextAllNamesVisitor {
6483 ASTReader &Reader;
Dmitri Gribenkof8579502013-01-12 19:30:44 +00006484 SmallVectorImpl<const DeclContext *> &Contexts;
Craig Topper3598eb72013-07-05 04:43:31 +00006485 DeclsMap &Decls;
Argyrios Kyrtzidis2810e9d2012-12-19 22:21:18 +00006486 bool VisitAll;
Guy Benyei11169dd2012-12-18 14:30:41 +00006487
6488 public:
6489 DeclContextAllNamesVisitor(ASTReader &Reader,
6490 SmallVectorImpl<const DeclContext *> &Contexts,
Craig Topper3598eb72013-07-05 04:43:31 +00006491 DeclsMap &Decls, bool VisitAll)
Argyrios Kyrtzidis2810e9d2012-12-19 22:21:18 +00006492 : Reader(Reader), Contexts(Contexts), Decls(Decls), VisitAll(VisitAll) { }
Guy Benyei11169dd2012-12-18 14:30:41 +00006493
6494 static bool visit(ModuleFile &M, void *UserData) {
6495 DeclContextAllNamesVisitor *This
6496 = static_cast<DeclContextAllNamesVisitor *>(UserData);
6497
6498 // Check whether we have any visible declaration information for
6499 // this context in this module.
6500 ModuleFile::DeclContextInfosMap::iterator Info;
6501 bool FoundInfo = false;
6502 for (unsigned I = 0, N = This->Contexts.size(); I != N; ++I) {
6503 Info = M.DeclContextInfos.find(This->Contexts[I]);
6504 if (Info != M.DeclContextInfos.end() &&
6505 Info->second.NameLookupTableData) {
6506 FoundInfo = true;
6507 break;
6508 }
6509 }
6510
6511 if (!FoundInfo)
6512 return false;
6513
Richard Smith52e3fba2014-03-11 07:17:35 +00006514 ASTDeclContextNameLookupTable *LookupTable =
Guy Benyei11169dd2012-12-18 14:30:41 +00006515 Info->second.NameLookupTableData;
6516 bool FoundAnything = false;
6517 for (ASTDeclContextNameLookupTable::data_iterator
Douglas Gregor5e306b12013-01-23 22:38:11 +00006518 I = LookupTable->data_begin(), E = LookupTable->data_end();
6519 I != E;
6520 ++I) {
Guy Benyei11169dd2012-12-18 14:30:41 +00006521 ASTDeclContextNameLookupTrait::data_type Data = *I;
6522 for (; Data.first != Data.second; ++Data.first) {
6523 NamedDecl *ND = This->Reader.GetLocalDeclAs<NamedDecl>(M,
6524 *Data.first);
6525 if (!ND)
6526 continue;
6527
6528 // Record this declaration.
6529 FoundAnything = true;
6530 This->Decls[ND->getDeclName()].push_back(ND);
6531 }
6532 }
6533
Argyrios Kyrtzidis2810e9d2012-12-19 22:21:18 +00006534 return FoundAnything && !This->VisitAll;
Guy Benyei11169dd2012-12-18 14:30:41 +00006535 }
6536 };
6537}
6538
6539void ASTReader::completeVisibleDeclsMap(const DeclContext *DC) {
6540 if (!DC->hasExternalVisibleStorage())
6541 return;
Craig Topper79be4cd2013-07-05 04:33:53 +00006542 DeclsMap Decls;
Guy Benyei11169dd2012-12-18 14:30:41 +00006543
6544 // Compute the declaration contexts we need to look into. Multiple such
6545 // declaration contexts occur when two declaration contexts from disjoint
6546 // modules get merged, e.g., when two namespaces with the same name are
6547 // independently defined in separate modules.
6548 SmallVector<const DeclContext *, 2> Contexts;
6549 Contexts.push_back(DC);
6550
6551 if (DC->isNamespace()) {
6552 MergedDeclsMap::iterator Merged
6553 = MergedDecls.find(const_cast<Decl *>(cast<Decl>(DC)));
6554 if (Merged != MergedDecls.end()) {
6555 for (unsigned I = 0, N = Merged->second.size(); I != N; ++I)
6556 Contexts.push_back(cast<DeclContext>(GetDecl(Merged->second[I])));
6557 }
6558 }
6559
Argyrios Kyrtzidis2810e9d2012-12-19 22:21:18 +00006560 DeclContextAllNamesVisitor Visitor(*this, Contexts, Decls,
6561 /*VisitAll=*/DC->isFileContext());
Guy Benyei11169dd2012-12-18 14:30:41 +00006562 ModuleMgr.visit(&DeclContextAllNamesVisitor::visit, &Visitor);
6563 ++NumVisibleDeclContextsRead;
6564
Craig Topper79be4cd2013-07-05 04:33:53 +00006565 for (DeclsMap::iterator I = Decls.begin(), E = Decls.end(); I != E; ++I) {
Guy Benyei11169dd2012-12-18 14:30:41 +00006566 SetExternalVisibleDeclsForName(DC, I->first, I->second);
6567 }
6568 const_cast<DeclContext *>(DC)->setHasExternalVisibleStorage(false);
6569}
6570
6571/// \brief Under non-PCH compilation the consumer receives the objc methods
6572/// before receiving the implementation, and codegen depends on this.
6573/// We simulate this by deserializing and passing to consumer the methods of the
6574/// implementation before passing the deserialized implementation decl.
6575static void PassObjCImplDeclToConsumer(ObjCImplDecl *ImplD,
6576 ASTConsumer *Consumer) {
6577 assert(ImplD && Consumer);
6578
Aaron Ballmanaff18c02014-03-13 19:03:34 +00006579 for (auto *I : ImplD->methods())
6580 Consumer->HandleInterestingDecl(DeclGroupRef(I));
Guy Benyei11169dd2012-12-18 14:30:41 +00006581
6582 Consumer->HandleInterestingDecl(DeclGroupRef(ImplD));
6583}
6584
6585void ASTReader::PassInterestingDeclsToConsumer() {
6586 assert(Consumer);
Richard Smith04d05b52014-03-23 00:27:18 +00006587
6588 if (PassingDeclsToConsumer)
6589 return;
6590
6591 // Guard variable to avoid recursively redoing the process of passing
6592 // decls to consumer.
6593 SaveAndRestore<bool> GuardPassingDeclsToConsumer(PassingDeclsToConsumer,
6594 true);
6595
Guy Benyei11169dd2012-12-18 14:30:41 +00006596 while (!InterestingDecls.empty()) {
6597 Decl *D = InterestingDecls.front();
6598 InterestingDecls.pop_front();
6599
6600 PassInterestingDeclToConsumer(D);
6601 }
6602}
6603
6604void ASTReader::PassInterestingDeclToConsumer(Decl *D) {
6605 if (ObjCImplDecl *ImplD = dyn_cast<ObjCImplDecl>(D))
6606 PassObjCImplDeclToConsumer(ImplD, Consumer);
6607 else
6608 Consumer->HandleInterestingDecl(DeclGroupRef(D));
6609}
6610
6611void ASTReader::StartTranslationUnit(ASTConsumer *Consumer) {
6612 this->Consumer = Consumer;
6613
6614 if (!Consumer)
6615 return;
6616
Ben Langmuir332aafe2014-01-31 01:06:56 +00006617 for (unsigned I = 0, N = EagerlyDeserializedDecls.size(); I != N; ++I) {
Guy Benyei11169dd2012-12-18 14:30:41 +00006618 // Force deserialization of this decl, which will cause it to be queued for
6619 // passing to the consumer.
Ben Langmuir332aafe2014-01-31 01:06:56 +00006620 GetDecl(EagerlyDeserializedDecls[I]);
Guy Benyei11169dd2012-12-18 14:30:41 +00006621 }
Ben Langmuir332aafe2014-01-31 01:06:56 +00006622 EagerlyDeserializedDecls.clear();
Guy Benyei11169dd2012-12-18 14:30:41 +00006623
6624 PassInterestingDeclsToConsumer();
6625}
6626
6627void ASTReader::PrintStats() {
6628 std::fprintf(stderr, "*** AST File Statistics:\n");
6629
6630 unsigned NumTypesLoaded
6631 = TypesLoaded.size() - std::count(TypesLoaded.begin(), TypesLoaded.end(),
6632 QualType());
6633 unsigned NumDeclsLoaded
6634 = DeclsLoaded.size() - std::count(DeclsLoaded.begin(), DeclsLoaded.end(),
Craig Toppera13603a2014-05-22 05:54:18 +00006635 (Decl *)nullptr);
Guy Benyei11169dd2012-12-18 14:30:41 +00006636 unsigned NumIdentifiersLoaded
6637 = IdentifiersLoaded.size() - std::count(IdentifiersLoaded.begin(),
6638 IdentifiersLoaded.end(),
Craig Toppera13603a2014-05-22 05:54:18 +00006639 (IdentifierInfo *)nullptr);
Guy Benyei11169dd2012-12-18 14:30:41 +00006640 unsigned NumMacrosLoaded
6641 = MacrosLoaded.size() - std::count(MacrosLoaded.begin(),
6642 MacrosLoaded.end(),
Craig Toppera13603a2014-05-22 05:54:18 +00006643 (MacroInfo *)nullptr);
Guy Benyei11169dd2012-12-18 14:30:41 +00006644 unsigned NumSelectorsLoaded
6645 = SelectorsLoaded.size() - std::count(SelectorsLoaded.begin(),
6646 SelectorsLoaded.end(),
6647 Selector());
6648
6649 if (unsigned TotalNumSLocEntries = getTotalNumSLocs())
6650 std::fprintf(stderr, " %u/%u source location entries read (%f%%)\n",
6651 NumSLocEntriesRead, TotalNumSLocEntries,
6652 ((float)NumSLocEntriesRead/TotalNumSLocEntries * 100));
6653 if (!TypesLoaded.empty())
6654 std::fprintf(stderr, " %u/%u types read (%f%%)\n",
6655 NumTypesLoaded, (unsigned)TypesLoaded.size(),
6656 ((float)NumTypesLoaded/TypesLoaded.size() * 100));
6657 if (!DeclsLoaded.empty())
6658 std::fprintf(stderr, " %u/%u declarations read (%f%%)\n",
6659 NumDeclsLoaded, (unsigned)DeclsLoaded.size(),
6660 ((float)NumDeclsLoaded/DeclsLoaded.size() * 100));
6661 if (!IdentifiersLoaded.empty())
6662 std::fprintf(stderr, " %u/%u identifiers read (%f%%)\n",
6663 NumIdentifiersLoaded, (unsigned)IdentifiersLoaded.size(),
6664 ((float)NumIdentifiersLoaded/IdentifiersLoaded.size() * 100));
6665 if (!MacrosLoaded.empty())
6666 std::fprintf(stderr, " %u/%u macros read (%f%%)\n",
6667 NumMacrosLoaded, (unsigned)MacrosLoaded.size(),
6668 ((float)NumMacrosLoaded/MacrosLoaded.size() * 100));
6669 if (!SelectorsLoaded.empty())
6670 std::fprintf(stderr, " %u/%u selectors read (%f%%)\n",
6671 NumSelectorsLoaded, (unsigned)SelectorsLoaded.size(),
6672 ((float)NumSelectorsLoaded/SelectorsLoaded.size() * 100));
6673 if (TotalNumStatements)
6674 std::fprintf(stderr, " %u/%u statements read (%f%%)\n",
6675 NumStatementsRead, TotalNumStatements,
6676 ((float)NumStatementsRead/TotalNumStatements * 100));
6677 if (TotalNumMacros)
6678 std::fprintf(stderr, " %u/%u macros read (%f%%)\n",
6679 NumMacrosRead, TotalNumMacros,
6680 ((float)NumMacrosRead/TotalNumMacros * 100));
6681 if (TotalLexicalDeclContexts)
6682 std::fprintf(stderr, " %u/%u lexical declcontexts read (%f%%)\n",
6683 NumLexicalDeclContextsRead, TotalLexicalDeclContexts,
6684 ((float)NumLexicalDeclContextsRead/TotalLexicalDeclContexts
6685 * 100));
6686 if (TotalVisibleDeclContexts)
6687 std::fprintf(stderr, " %u/%u visible declcontexts read (%f%%)\n",
6688 NumVisibleDeclContextsRead, TotalVisibleDeclContexts,
6689 ((float)NumVisibleDeclContextsRead/TotalVisibleDeclContexts
6690 * 100));
6691 if (TotalNumMethodPoolEntries) {
6692 std::fprintf(stderr, " %u/%u method pool entries read (%f%%)\n",
6693 NumMethodPoolEntriesRead, TotalNumMethodPoolEntries,
6694 ((float)NumMethodPoolEntriesRead/TotalNumMethodPoolEntries
6695 * 100));
Guy Benyei11169dd2012-12-18 14:30:41 +00006696 }
Douglas Gregorad2f7a52013-01-28 17:54:36 +00006697 if (NumMethodPoolLookups) {
6698 std::fprintf(stderr, " %u/%u method pool lookups succeeded (%f%%)\n",
6699 NumMethodPoolHits, NumMethodPoolLookups,
6700 ((float)NumMethodPoolHits/NumMethodPoolLookups * 100.0));
6701 }
6702 if (NumMethodPoolTableLookups) {
6703 std::fprintf(stderr, " %u/%u method pool table lookups succeeded (%f%%)\n",
6704 NumMethodPoolTableHits, NumMethodPoolTableLookups,
6705 ((float)NumMethodPoolTableHits/NumMethodPoolTableLookups
6706 * 100.0));
6707 }
6708
Douglas Gregor00a50f72013-01-25 00:38:33 +00006709 if (NumIdentifierLookupHits) {
6710 std::fprintf(stderr,
6711 " %u / %u identifier table lookups succeeded (%f%%)\n",
6712 NumIdentifierLookupHits, NumIdentifierLookups,
6713 (double)NumIdentifierLookupHits*100.0/NumIdentifierLookups);
6714 }
6715
Douglas Gregore060e572013-01-25 01:03:03 +00006716 if (GlobalIndex) {
6717 std::fprintf(stderr, "\n");
6718 GlobalIndex->printStats();
6719 }
6720
Guy Benyei11169dd2012-12-18 14:30:41 +00006721 std::fprintf(stderr, "\n");
6722 dump();
6723 std::fprintf(stderr, "\n");
6724}
6725
6726template<typename Key, typename ModuleFile, unsigned InitialCapacity>
6727static void
6728dumpModuleIDMap(StringRef Name,
6729 const ContinuousRangeMap<Key, ModuleFile *,
6730 InitialCapacity> &Map) {
6731 if (Map.begin() == Map.end())
6732 return;
6733
6734 typedef ContinuousRangeMap<Key, ModuleFile *, InitialCapacity> MapType;
6735 llvm::errs() << Name << ":\n";
6736 for (typename MapType::const_iterator I = Map.begin(), IEnd = Map.end();
6737 I != IEnd; ++I) {
6738 llvm::errs() << " " << I->first << " -> " << I->second->FileName
6739 << "\n";
6740 }
6741}
6742
6743void ASTReader::dump() {
6744 llvm::errs() << "*** PCH/ModuleFile Remappings:\n";
6745 dumpModuleIDMap("Global bit offset map", GlobalBitOffsetsMap);
6746 dumpModuleIDMap("Global source location entry map", GlobalSLocEntryMap);
6747 dumpModuleIDMap("Global type map", GlobalTypeMap);
6748 dumpModuleIDMap("Global declaration map", GlobalDeclMap);
6749 dumpModuleIDMap("Global identifier map", GlobalIdentifierMap);
6750 dumpModuleIDMap("Global macro map", GlobalMacroMap);
6751 dumpModuleIDMap("Global submodule map", GlobalSubmoduleMap);
6752 dumpModuleIDMap("Global selector map", GlobalSelectorMap);
6753 dumpModuleIDMap("Global preprocessed entity map",
6754 GlobalPreprocessedEntityMap);
6755
6756 llvm::errs() << "\n*** PCH/Modules Loaded:";
6757 for (ModuleManager::ModuleConstIterator M = ModuleMgr.begin(),
6758 MEnd = ModuleMgr.end();
6759 M != MEnd; ++M)
6760 (*M)->dump();
6761}
6762
6763/// Return the amount of memory used by memory buffers, breaking down
6764/// by heap-backed versus mmap'ed memory.
6765void ASTReader::getMemoryBufferSizes(MemoryBufferSizes &sizes) const {
6766 for (ModuleConstIterator I = ModuleMgr.begin(),
6767 E = ModuleMgr.end(); I != E; ++I) {
6768 if (llvm::MemoryBuffer *buf = (*I)->Buffer.get()) {
6769 size_t bytes = buf->getBufferSize();
6770 switch (buf->getBufferKind()) {
6771 case llvm::MemoryBuffer::MemoryBuffer_Malloc:
6772 sizes.malloc_bytes += bytes;
6773 break;
6774 case llvm::MemoryBuffer::MemoryBuffer_MMap:
6775 sizes.mmap_bytes += bytes;
6776 break;
6777 }
6778 }
6779 }
6780}
6781
6782void ASTReader::InitializeSema(Sema &S) {
6783 SemaObj = &S;
6784 S.addExternalSource(this);
6785
6786 // Makes sure any declarations that were deserialized "too early"
6787 // still get added to the identifier's declaration chains.
6788 for (unsigned I = 0, N = PreloadedDecls.size(); I != N; ++I) {
Argyrios Kyrtzidise5edbf92013-04-26 21:33:35 +00006789 pushExternalDeclIntoScope(PreloadedDecls[I],
6790 PreloadedDecls[I]->getDeclName());
Guy Benyei11169dd2012-12-18 14:30:41 +00006791 }
6792 PreloadedDecls.clear();
6793
Richard Smith3d8e97e2013-10-18 06:54:39 +00006794 // FIXME: What happens if these are changed by a module import?
Guy Benyei11169dd2012-12-18 14:30:41 +00006795 if (!FPPragmaOptions.empty()) {
6796 assert(FPPragmaOptions.size() == 1 && "Wrong number of FP_PRAGMA_OPTIONS");
6797 SemaObj->FPFeatures.fp_contract = FPPragmaOptions[0];
6798 }
6799
Richard Smith3d8e97e2013-10-18 06:54:39 +00006800 // FIXME: What happens if these are changed by a module import?
Guy Benyei11169dd2012-12-18 14:30:41 +00006801 if (!OpenCLExtensions.empty()) {
6802 unsigned I = 0;
6803#define OPENCLEXT(nm) SemaObj->OpenCLFeatures.nm = OpenCLExtensions[I++];
6804#include "clang/Basic/OpenCLExtensions.def"
6805
6806 assert(OpenCLExtensions.size() == I && "Wrong number of OPENCL_EXTENSIONS");
6807 }
Richard Smith3d8e97e2013-10-18 06:54:39 +00006808
6809 UpdateSema();
6810}
6811
6812void ASTReader::UpdateSema() {
6813 assert(SemaObj && "no Sema to update");
6814
6815 // Load the offsets of the declarations that Sema references.
6816 // They will be lazily deserialized when needed.
6817 if (!SemaDeclRefs.empty()) {
6818 assert(SemaDeclRefs.size() % 2 == 0);
6819 for (unsigned I = 0; I != SemaDeclRefs.size(); I += 2) {
6820 if (!SemaObj->StdNamespace)
6821 SemaObj->StdNamespace = SemaDeclRefs[I];
6822 if (!SemaObj->StdBadAlloc)
6823 SemaObj->StdBadAlloc = SemaDeclRefs[I+1];
6824 }
6825 SemaDeclRefs.clear();
6826 }
Dario Domizioli13a0a382014-05-23 12:13:25 +00006827
6828 // Update the state of 'pragma clang optimize'. Use the same API as if we had
6829 // encountered the pragma in the source.
6830 if(OptimizeOffPragmaLocation.isValid())
6831 SemaObj->ActOnPragmaOptimize(/* IsOn = */ false, OptimizeOffPragmaLocation);
Guy Benyei11169dd2012-12-18 14:30:41 +00006832}
6833
6834IdentifierInfo* ASTReader::get(const char *NameStart, const char *NameEnd) {
6835 // Note that we are loading an identifier.
6836 Deserializing AnIdentifier(this);
Douglas Gregore060e572013-01-25 01:03:03 +00006837 StringRef Name(NameStart, NameEnd - NameStart);
6838
6839 // If there is a global index, look there first to determine which modules
6840 // provably do not have any results for this identifier.
Douglas Gregor7211ac12013-01-25 23:32:03 +00006841 GlobalModuleIndex::HitSet Hits;
Craig Toppera13603a2014-05-22 05:54:18 +00006842 GlobalModuleIndex::HitSet *HitsPtr = nullptr;
Douglas Gregore060e572013-01-25 01:03:03 +00006843 if (!loadGlobalIndex()) {
Douglas Gregor7211ac12013-01-25 23:32:03 +00006844 if (GlobalIndex->lookupIdentifier(Name, Hits)) {
6845 HitsPtr = &Hits;
Douglas Gregore060e572013-01-25 01:03:03 +00006846 }
6847 }
Douglas Gregor7211ac12013-01-25 23:32:03 +00006848 IdentifierLookupVisitor Visitor(Name, /*PriorGeneration=*/0,
Douglas Gregor00a50f72013-01-25 00:38:33 +00006849 NumIdentifierLookups,
6850 NumIdentifierLookupHits);
Douglas Gregor7211ac12013-01-25 23:32:03 +00006851 ModuleMgr.visit(IdentifierLookupVisitor::visit, &Visitor, HitsPtr);
Guy Benyei11169dd2012-12-18 14:30:41 +00006852 IdentifierInfo *II = Visitor.getIdentifierInfo();
6853 markIdentifierUpToDate(II);
6854 return II;
6855}
6856
6857namespace clang {
6858 /// \brief An identifier-lookup iterator that enumerates all of the
6859 /// identifiers stored within a set of AST files.
6860 class ASTIdentifierIterator : public IdentifierIterator {
6861 /// \brief The AST reader whose identifiers are being enumerated.
6862 const ASTReader &Reader;
6863
6864 /// \brief The current index into the chain of AST files stored in
6865 /// the AST reader.
6866 unsigned Index;
6867
6868 /// \brief The current position within the identifier lookup table
6869 /// of the current AST file.
6870 ASTIdentifierLookupTable::key_iterator Current;
6871
6872 /// \brief The end position within the identifier lookup table of
6873 /// the current AST file.
6874 ASTIdentifierLookupTable::key_iterator End;
6875
6876 public:
6877 explicit ASTIdentifierIterator(const ASTReader &Reader);
6878
Craig Topper3e89dfe2014-03-13 02:13:41 +00006879 StringRef Next() override;
Guy Benyei11169dd2012-12-18 14:30:41 +00006880 };
6881}
6882
6883ASTIdentifierIterator::ASTIdentifierIterator(const ASTReader &Reader)
6884 : Reader(Reader), Index(Reader.ModuleMgr.size() - 1) {
6885 ASTIdentifierLookupTable *IdTable
6886 = (ASTIdentifierLookupTable *)Reader.ModuleMgr[Index].IdentifierLookupTable;
6887 Current = IdTable->key_begin();
6888 End = IdTable->key_end();
6889}
6890
6891StringRef ASTIdentifierIterator::Next() {
6892 while (Current == End) {
6893 // If we have exhausted all of our AST files, we're done.
6894 if (Index == 0)
6895 return StringRef();
6896
6897 --Index;
6898 ASTIdentifierLookupTable *IdTable
6899 = (ASTIdentifierLookupTable *)Reader.ModuleMgr[Index].
6900 IdentifierLookupTable;
6901 Current = IdTable->key_begin();
6902 End = IdTable->key_end();
6903 }
6904
6905 // We have any identifiers remaining in the current AST file; return
6906 // the next one.
Douglas Gregorbfd73d72013-01-23 18:53:14 +00006907 StringRef Result = *Current;
Guy Benyei11169dd2012-12-18 14:30:41 +00006908 ++Current;
Douglas Gregorbfd73d72013-01-23 18:53:14 +00006909 return Result;
Guy Benyei11169dd2012-12-18 14:30:41 +00006910}
6911
Argyrios Kyrtzidis9aca3c62013-04-17 22:10:55 +00006912IdentifierIterator *ASTReader::getIdentifiers() {
6913 if (!loadGlobalIndex())
6914 return GlobalIndex->createIdentifierIterator();
6915
Guy Benyei11169dd2012-12-18 14:30:41 +00006916 return new ASTIdentifierIterator(*this);
6917}
6918
6919namespace clang { namespace serialization {
6920 class ReadMethodPoolVisitor {
6921 ASTReader &Reader;
6922 Selector Sel;
6923 unsigned PriorGeneration;
Argyrios Kyrtzidisd3da6e02013-04-17 00:08:58 +00006924 unsigned InstanceBits;
6925 unsigned FactoryBits;
Dmitri Gribenkof8579502013-01-12 19:30:44 +00006926 SmallVector<ObjCMethodDecl *, 4> InstanceMethods;
6927 SmallVector<ObjCMethodDecl *, 4> FactoryMethods;
Guy Benyei11169dd2012-12-18 14:30:41 +00006928
6929 public:
6930 ReadMethodPoolVisitor(ASTReader &Reader, Selector Sel,
6931 unsigned PriorGeneration)
Argyrios Kyrtzidisd3da6e02013-04-17 00:08:58 +00006932 : Reader(Reader), Sel(Sel), PriorGeneration(PriorGeneration),
6933 InstanceBits(0), FactoryBits(0) { }
Guy Benyei11169dd2012-12-18 14:30:41 +00006934
6935 static bool visit(ModuleFile &M, void *UserData) {
6936 ReadMethodPoolVisitor *This
6937 = static_cast<ReadMethodPoolVisitor *>(UserData);
6938
6939 if (!M.SelectorLookupTable)
6940 return false;
6941
6942 // If we've already searched this module file, skip it now.
6943 if (M.Generation <= This->PriorGeneration)
6944 return true;
6945
Douglas Gregorad2f7a52013-01-28 17:54:36 +00006946 ++This->Reader.NumMethodPoolTableLookups;
Guy Benyei11169dd2012-12-18 14:30:41 +00006947 ASTSelectorLookupTable *PoolTable
6948 = (ASTSelectorLookupTable*)M.SelectorLookupTable;
6949 ASTSelectorLookupTable::iterator Pos = PoolTable->find(This->Sel);
6950 if (Pos == PoolTable->end())
6951 return false;
Douglas Gregorad2f7a52013-01-28 17:54:36 +00006952
6953 ++This->Reader.NumMethodPoolTableHits;
Guy Benyei11169dd2012-12-18 14:30:41 +00006954 ++This->Reader.NumSelectorsRead;
6955 // FIXME: Not quite happy with the statistics here. We probably should
6956 // disable this tracking when called via LoadSelector.
6957 // Also, should entries without methods count as misses?
6958 ++This->Reader.NumMethodPoolEntriesRead;
6959 ASTSelectorLookupTrait::data_type Data = *Pos;
6960 if (This->Reader.DeserializationListener)
6961 This->Reader.DeserializationListener->SelectorRead(Data.ID,
6962 This->Sel);
6963
6964 This->InstanceMethods.append(Data.Instance.begin(), Data.Instance.end());
6965 This->FactoryMethods.append(Data.Factory.begin(), Data.Factory.end());
Argyrios Kyrtzidisd3da6e02013-04-17 00:08:58 +00006966 This->InstanceBits = Data.InstanceBits;
6967 This->FactoryBits = Data.FactoryBits;
Guy Benyei11169dd2012-12-18 14:30:41 +00006968 return true;
6969 }
6970
6971 /// \brief Retrieve the instance methods found by this visitor.
6972 ArrayRef<ObjCMethodDecl *> getInstanceMethods() const {
6973 return InstanceMethods;
6974 }
6975
6976 /// \brief Retrieve the instance methods found by this visitor.
6977 ArrayRef<ObjCMethodDecl *> getFactoryMethods() const {
6978 return FactoryMethods;
6979 }
Argyrios Kyrtzidisd3da6e02013-04-17 00:08:58 +00006980
6981 unsigned getInstanceBits() const { return InstanceBits; }
6982 unsigned getFactoryBits() const { return FactoryBits; }
Guy Benyei11169dd2012-12-18 14:30:41 +00006983 };
6984} } // end namespace clang::serialization
6985
6986/// \brief Add the given set of methods to the method list.
6987static void addMethodsToPool(Sema &S, ArrayRef<ObjCMethodDecl *> Methods,
6988 ObjCMethodList &List) {
6989 for (unsigned I = 0, N = Methods.size(); I != N; ++I) {
6990 S.addMethodToGlobalList(&List, Methods[I]);
6991 }
6992}
6993
6994void ASTReader::ReadMethodPool(Selector Sel) {
6995 // Get the selector generation and update it to the current generation.
6996 unsigned &Generation = SelectorGeneration[Sel];
6997 unsigned PriorGeneration = Generation;
Richard Smith053f6c62014-05-16 23:01:30 +00006998 Generation = getGeneration();
Guy Benyei11169dd2012-12-18 14:30:41 +00006999
7000 // Search for methods defined with this selector.
Douglas Gregorad2f7a52013-01-28 17:54:36 +00007001 ++NumMethodPoolLookups;
Guy Benyei11169dd2012-12-18 14:30:41 +00007002 ReadMethodPoolVisitor Visitor(*this, Sel, PriorGeneration);
7003 ModuleMgr.visit(&ReadMethodPoolVisitor::visit, &Visitor);
7004
7005 if (Visitor.getInstanceMethods().empty() &&
Douglas Gregorad2f7a52013-01-28 17:54:36 +00007006 Visitor.getFactoryMethods().empty())
Guy Benyei11169dd2012-12-18 14:30:41 +00007007 return;
Douglas Gregorad2f7a52013-01-28 17:54:36 +00007008
7009 ++NumMethodPoolHits;
7010
Guy Benyei11169dd2012-12-18 14:30:41 +00007011 if (!getSema())
7012 return;
7013
7014 Sema &S = *getSema();
7015 Sema::GlobalMethodPool::iterator Pos
7016 = S.MethodPool.insert(std::make_pair(Sel, Sema::GlobalMethods())).first;
7017
7018 addMethodsToPool(S, Visitor.getInstanceMethods(), Pos->second.first);
7019 addMethodsToPool(S, Visitor.getFactoryMethods(), Pos->second.second);
Argyrios Kyrtzidisd3da6e02013-04-17 00:08:58 +00007020 Pos->second.first.setBits(Visitor.getInstanceBits());
7021 Pos->second.second.setBits(Visitor.getFactoryBits());
Guy Benyei11169dd2012-12-18 14:30:41 +00007022}
7023
7024void ASTReader::ReadKnownNamespaces(
7025 SmallVectorImpl<NamespaceDecl *> &Namespaces) {
7026 Namespaces.clear();
7027
7028 for (unsigned I = 0, N = KnownNamespaces.size(); I != N; ++I) {
7029 if (NamespaceDecl *Namespace
7030 = dyn_cast_or_null<NamespaceDecl>(GetDecl(KnownNamespaces[I])))
7031 Namespaces.push_back(Namespace);
7032 }
7033}
7034
Nick Lewycky9c7eb1d2013-02-01 08:13:20 +00007035void ASTReader::ReadUndefinedButUsed(
Nick Lewyckyf0f56162013-01-31 03:23:57 +00007036 llvm::DenseMap<NamedDecl*, SourceLocation> &Undefined) {
Nick Lewycky9c7eb1d2013-02-01 08:13:20 +00007037 for (unsigned Idx = 0, N = UndefinedButUsed.size(); Idx != N;) {
7038 NamedDecl *D = cast<NamedDecl>(GetDecl(UndefinedButUsed[Idx++]));
Nick Lewycky8334af82013-01-26 00:35:08 +00007039 SourceLocation Loc =
Nick Lewycky9c7eb1d2013-02-01 08:13:20 +00007040 SourceLocation::getFromRawEncoding(UndefinedButUsed[Idx++]);
Nick Lewycky8334af82013-01-26 00:35:08 +00007041 Undefined.insert(std::make_pair(D, Loc));
7042 }
7043}
Nick Lewycky8334af82013-01-26 00:35:08 +00007044
Guy Benyei11169dd2012-12-18 14:30:41 +00007045void ASTReader::ReadTentativeDefinitions(
7046 SmallVectorImpl<VarDecl *> &TentativeDefs) {
7047 for (unsigned I = 0, N = TentativeDefinitions.size(); I != N; ++I) {
7048 VarDecl *Var = dyn_cast_or_null<VarDecl>(GetDecl(TentativeDefinitions[I]));
7049 if (Var)
7050 TentativeDefs.push_back(Var);
7051 }
7052 TentativeDefinitions.clear();
7053}
7054
7055void ASTReader::ReadUnusedFileScopedDecls(
7056 SmallVectorImpl<const DeclaratorDecl *> &Decls) {
7057 for (unsigned I = 0, N = UnusedFileScopedDecls.size(); I != N; ++I) {
7058 DeclaratorDecl *D
7059 = dyn_cast_or_null<DeclaratorDecl>(GetDecl(UnusedFileScopedDecls[I]));
7060 if (D)
7061 Decls.push_back(D);
7062 }
7063 UnusedFileScopedDecls.clear();
7064}
7065
7066void ASTReader::ReadDelegatingConstructors(
7067 SmallVectorImpl<CXXConstructorDecl *> &Decls) {
7068 for (unsigned I = 0, N = DelegatingCtorDecls.size(); I != N; ++I) {
7069 CXXConstructorDecl *D
7070 = dyn_cast_or_null<CXXConstructorDecl>(GetDecl(DelegatingCtorDecls[I]));
7071 if (D)
7072 Decls.push_back(D);
7073 }
7074 DelegatingCtorDecls.clear();
7075}
7076
7077void ASTReader::ReadExtVectorDecls(SmallVectorImpl<TypedefNameDecl *> &Decls) {
7078 for (unsigned I = 0, N = ExtVectorDecls.size(); I != N; ++I) {
7079 TypedefNameDecl *D
7080 = dyn_cast_or_null<TypedefNameDecl>(GetDecl(ExtVectorDecls[I]));
7081 if (D)
7082 Decls.push_back(D);
7083 }
7084 ExtVectorDecls.clear();
7085}
7086
7087void ASTReader::ReadDynamicClasses(SmallVectorImpl<CXXRecordDecl *> &Decls) {
7088 for (unsigned I = 0, N = DynamicClasses.size(); I != N; ++I) {
7089 CXXRecordDecl *D
7090 = dyn_cast_or_null<CXXRecordDecl>(GetDecl(DynamicClasses[I]));
7091 if (D)
7092 Decls.push_back(D);
7093 }
7094 DynamicClasses.clear();
7095}
7096
7097void
Richard Smith78165b52013-01-10 23:43:47 +00007098ASTReader::ReadLocallyScopedExternCDecls(SmallVectorImpl<NamedDecl *> &Decls) {
7099 for (unsigned I = 0, N = LocallyScopedExternCDecls.size(); I != N; ++I) {
7100 NamedDecl *D
7101 = dyn_cast_or_null<NamedDecl>(GetDecl(LocallyScopedExternCDecls[I]));
Guy Benyei11169dd2012-12-18 14:30:41 +00007102 if (D)
7103 Decls.push_back(D);
7104 }
Richard Smith78165b52013-01-10 23:43:47 +00007105 LocallyScopedExternCDecls.clear();
Guy Benyei11169dd2012-12-18 14:30:41 +00007106}
7107
7108void ASTReader::ReadReferencedSelectors(
7109 SmallVectorImpl<std::pair<Selector, SourceLocation> > &Sels) {
7110 if (ReferencedSelectorsData.empty())
7111 return;
7112
7113 // If there are @selector references added them to its pool. This is for
7114 // implementation of -Wselector.
7115 unsigned int DataSize = ReferencedSelectorsData.size()-1;
7116 unsigned I = 0;
7117 while (I < DataSize) {
7118 Selector Sel = DecodeSelector(ReferencedSelectorsData[I++]);
7119 SourceLocation SelLoc
7120 = SourceLocation::getFromRawEncoding(ReferencedSelectorsData[I++]);
7121 Sels.push_back(std::make_pair(Sel, SelLoc));
7122 }
7123 ReferencedSelectorsData.clear();
7124}
7125
7126void ASTReader::ReadWeakUndeclaredIdentifiers(
7127 SmallVectorImpl<std::pair<IdentifierInfo *, WeakInfo> > &WeakIDs) {
7128 if (WeakUndeclaredIdentifiers.empty())
7129 return;
7130
7131 for (unsigned I = 0, N = WeakUndeclaredIdentifiers.size(); I < N; /*none*/) {
7132 IdentifierInfo *WeakId
7133 = DecodeIdentifierInfo(WeakUndeclaredIdentifiers[I++]);
7134 IdentifierInfo *AliasId
7135 = DecodeIdentifierInfo(WeakUndeclaredIdentifiers[I++]);
7136 SourceLocation Loc
7137 = SourceLocation::getFromRawEncoding(WeakUndeclaredIdentifiers[I++]);
7138 bool Used = WeakUndeclaredIdentifiers[I++];
7139 WeakInfo WI(AliasId, Loc);
7140 WI.setUsed(Used);
7141 WeakIDs.push_back(std::make_pair(WeakId, WI));
7142 }
7143 WeakUndeclaredIdentifiers.clear();
7144}
7145
7146void ASTReader::ReadUsedVTables(SmallVectorImpl<ExternalVTableUse> &VTables) {
7147 for (unsigned Idx = 0, N = VTableUses.size(); Idx < N; /* In loop */) {
7148 ExternalVTableUse VT;
7149 VT.Record = dyn_cast_or_null<CXXRecordDecl>(GetDecl(VTableUses[Idx++]));
7150 VT.Location = SourceLocation::getFromRawEncoding(VTableUses[Idx++]);
7151 VT.DefinitionRequired = VTableUses[Idx++];
7152 VTables.push_back(VT);
7153 }
7154
7155 VTableUses.clear();
7156}
7157
7158void ASTReader::ReadPendingInstantiations(
7159 SmallVectorImpl<std::pair<ValueDecl *, SourceLocation> > &Pending) {
7160 for (unsigned Idx = 0, N = PendingInstantiations.size(); Idx < N;) {
7161 ValueDecl *D = cast<ValueDecl>(GetDecl(PendingInstantiations[Idx++]));
7162 SourceLocation Loc
7163 = SourceLocation::getFromRawEncoding(PendingInstantiations[Idx++]);
7164
7165 Pending.push_back(std::make_pair(D, Loc));
7166 }
7167 PendingInstantiations.clear();
7168}
7169
Richard Smithe40f2ba2013-08-07 21:41:30 +00007170void ASTReader::ReadLateParsedTemplates(
7171 llvm::DenseMap<const FunctionDecl *, LateParsedTemplate *> &LPTMap) {
7172 for (unsigned Idx = 0, N = LateParsedTemplates.size(); Idx < N;
7173 /* In loop */) {
7174 FunctionDecl *FD = cast<FunctionDecl>(GetDecl(LateParsedTemplates[Idx++]));
7175
7176 LateParsedTemplate *LT = new LateParsedTemplate;
7177 LT->D = GetDecl(LateParsedTemplates[Idx++]);
7178
7179 ModuleFile *F = getOwningModuleFile(LT->D);
7180 assert(F && "No module");
7181
7182 unsigned TokN = LateParsedTemplates[Idx++];
7183 LT->Toks.reserve(TokN);
7184 for (unsigned T = 0; T < TokN; ++T)
7185 LT->Toks.push_back(ReadToken(*F, LateParsedTemplates, Idx));
7186
7187 LPTMap[FD] = LT;
7188 }
7189
7190 LateParsedTemplates.clear();
7191}
7192
Guy Benyei11169dd2012-12-18 14:30:41 +00007193void ASTReader::LoadSelector(Selector Sel) {
7194 // It would be complicated to avoid reading the methods anyway. So don't.
7195 ReadMethodPool(Sel);
7196}
7197
7198void ASTReader::SetIdentifierInfo(IdentifierID ID, IdentifierInfo *II) {
7199 assert(ID && "Non-zero identifier ID required");
7200 assert(ID <= IdentifiersLoaded.size() && "identifier ID out of range");
7201 IdentifiersLoaded[ID - 1] = II;
7202 if (DeserializationListener)
7203 DeserializationListener->IdentifierRead(ID, II);
7204}
7205
7206/// \brief Set the globally-visible declarations associated with the given
7207/// identifier.
7208///
7209/// If the AST reader is currently in a state where the given declaration IDs
7210/// cannot safely be resolved, they are queued until it is safe to resolve
7211/// them.
7212///
7213/// \param II an IdentifierInfo that refers to one or more globally-visible
7214/// declarations.
7215///
7216/// \param DeclIDs the set of declaration IDs with the name @p II that are
7217/// visible at global scope.
7218///
Douglas Gregor6168bd22013-02-18 15:53:43 +00007219/// \param Decls if non-null, this vector will be populated with the set of
7220/// deserialized declarations. These declarations will not be pushed into
7221/// scope.
Guy Benyei11169dd2012-12-18 14:30:41 +00007222void
7223ASTReader::SetGloballyVisibleDecls(IdentifierInfo *II,
7224 const SmallVectorImpl<uint32_t> &DeclIDs,
Douglas Gregor6168bd22013-02-18 15:53:43 +00007225 SmallVectorImpl<Decl *> *Decls) {
7226 if (NumCurrentElementsDeserializing && !Decls) {
7227 PendingIdentifierInfos[II].append(DeclIDs.begin(), DeclIDs.end());
Guy Benyei11169dd2012-12-18 14:30:41 +00007228 return;
7229 }
7230
7231 for (unsigned I = 0, N = DeclIDs.size(); I != N; ++I) {
7232 NamedDecl *D = cast<NamedDecl>(GetDecl(DeclIDs[I]));
7233 if (SemaObj) {
Douglas Gregor6168bd22013-02-18 15:53:43 +00007234 // If we're simply supposed to record the declarations, do so now.
7235 if (Decls) {
7236 Decls->push_back(D);
7237 continue;
7238 }
7239
Guy Benyei11169dd2012-12-18 14:30:41 +00007240 // Introduce this declaration into the translation-unit scope
7241 // and add it to the declaration chain for this identifier, so
7242 // that (unqualified) name lookup will find it.
Argyrios Kyrtzidise5edbf92013-04-26 21:33:35 +00007243 pushExternalDeclIntoScope(D, II);
Guy Benyei11169dd2012-12-18 14:30:41 +00007244 } else {
7245 // Queue this declaration so that it will be added to the
7246 // translation unit scope and identifier's declaration chain
7247 // once a Sema object is known.
7248 PreloadedDecls.push_back(D);
7249 }
7250 }
7251}
7252
Douglas Gregorc8a992f2013-01-21 16:52:34 +00007253IdentifierInfo *ASTReader::DecodeIdentifierInfo(IdentifierID ID) {
Guy Benyei11169dd2012-12-18 14:30:41 +00007254 if (ID == 0)
Craig Toppera13603a2014-05-22 05:54:18 +00007255 return nullptr;
Guy Benyei11169dd2012-12-18 14:30:41 +00007256
7257 if (IdentifiersLoaded.empty()) {
7258 Error("no identifier table in AST file");
Craig Toppera13603a2014-05-22 05:54:18 +00007259 return nullptr;
Guy Benyei11169dd2012-12-18 14:30:41 +00007260 }
7261
7262 ID -= 1;
7263 if (!IdentifiersLoaded[ID]) {
7264 GlobalIdentifierMapType::iterator I = GlobalIdentifierMap.find(ID + 1);
7265 assert(I != GlobalIdentifierMap.end() && "Corrupted global identifier map");
7266 ModuleFile *M = I->second;
7267 unsigned Index = ID - M->BaseIdentifierID;
7268 const char *Str = M->IdentifierTableData + M->IdentifierOffsets[Index];
7269
7270 // All of the strings in the AST file are preceded by a 16-bit length.
7271 // Extract that 16-bit length to avoid having to execute strlen().
7272 // NOTE: 'StrLenPtr' is an 'unsigned char*' so that we load bytes as
7273 // unsigned integers. This is important to avoid integer overflow when
7274 // we cast them to 'unsigned'.
7275 const unsigned char *StrLenPtr = (const unsigned char*) Str - 2;
7276 unsigned StrLen = (((unsigned) StrLenPtr[0])
7277 | (((unsigned) StrLenPtr[1]) << 8)) - 1;
Douglas Gregorc8a992f2013-01-21 16:52:34 +00007278 IdentifiersLoaded[ID]
7279 = &PP.getIdentifierTable().get(StringRef(Str, StrLen));
Guy Benyei11169dd2012-12-18 14:30:41 +00007280 if (DeserializationListener)
7281 DeserializationListener->IdentifierRead(ID + 1, IdentifiersLoaded[ID]);
7282 }
7283
7284 return IdentifiersLoaded[ID];
7285}
7286
Douglas Gregorc8a992f2013-01-21 16:52:34 +00007287IdentifierInfo *ASTReader::getLocalIdentifier(ModuleFile &M, unsigned LocalID) {
7288 return DecodeIdentifierInfo(getGlobalIdentifierID(M, LocalID));
Guy Benyei11169dd2012-12-18 14:30:41 +00007289}
7290
7291IdentifierID ASTReader::getGlobalIdentifierID(ModuleFile &M, unsigned LocalID) {
7292 if (LocalID < NUM_PREDEF_IDENT_IDS)
7293 return LocalID;
7294
7295 ContinuousRangeMap<uint32_t, int, 2>::iterator I
7296 = M.IdentifierRemap.find(LocalID - NUM_PREDEF_IDENT_IDS);
7297 assert(I != M.IdentifierRemap.end()
7298 && "Invalid index into identifier index remap");
7299
7300 return LocalID + I->second;
7301}
7302
Argyrios Kyrtzidiseb663da2013-03-22 21:12:57 +00007303MacroInfo *ASTReader::getMacro(MacroID ID) {
Guy Benyei11169dd2012-12-18 14:30:41 +00007304 if (ID == 0)
Craig Toppera13603a2014-05-22 05:54:18 +00007305 return nullptr;
Guy Benyei11169dd2012-12-18 14:30:41 +00007306
7307 if (MacrosLoaded.empty()) {
7308 Error("no macro table in AST file");
Craig Toppera13603a2014-05-22 05:54:18 +00007309 return nullptr;
Guy Benyei11169dd2012-12-18 14:30:41 +00007310 }
7311
7312 ID -= NUM_PREDEF_MACRO_IDS;
7313 if (!MacrosLoaded[ID]) {
7314 GlobalMacroMapType::iterator I
7315 = GlobalMacroMap.find(ID + NUM_PREDEF_MACRO_IDS);
7316 assert(I != GlobalMacroMap.end() && "Corrupted global macro map");
7317 ModuleFile *M = I->second;
7318 unsigned Index = ID - M->BaseMacroID;
Argyrios Kyrtzidiseb663da2013-03-22 21:12:57 +00007319 MacrosLoaded[ID] = ReadMacroRecord(*M, M->MacroOffsets[Index]);
7320
7321 if (DeserializationListener)
7322 DeserializationListener->MacroRead(ID + NUM_PREDEF_MACRO_IDS,
7323 MacrosLoaded[ID]);
Guy Benyei11169dd2012-12-18 14:30:41 +00007324 }
7325
7326 return MacrosLoaded[ID];
7327}
7328
7329MacroID ASTReader::getGlobalMacroID(ModuleFile &M, unsigned LocalID) {
7330 if (LocalID < NUM_PREDEF_MACRO_IDS)
7331 return LocalID;
7332
7333 ContinuousRangeMap<uint32_t, int, 2>::iterator I
7334 = M.MacroRemap.find(LocalID - NUM_PREDEF_MACRO_IDS);
7335 assert(I != M.MacroRemap.end() && "Invalid index into macro index remap");
7336
7337 return LocalID + I->second;
7338}
7339
7340serialization::SubmoduleID
7341ASTReader::getGlobalSubmoduleID(ModuleFile &M, unsigned LocalID) {
7342 if (LocalID < NUM_PREDEF_SUBMODULE_IDS)
7343 return LocalID;
7344
7345 ContinuousRangeMap<uint32_t, int, 2>::iterator I
7346 = M.SubmoduleRemap.find(LocalID - NUM_PREDEF_SUBMODULE_IDS);
7347 assert(I != M.SubmoduleRemap.end()
7348 && "Invalid index into submodule index remap");
7349
7350 return LocalID + I->second;
7351}
7352
7353Module *ASTReader::getSubmodule(SubmoduleID GlobalID) {
7354 if (GlobalID < NUM_PREDEF_SUBMODULE_IDS) {
7355 assert(GlobalID == 0 && "Unhandled global submodule ID");
Craig Toppera13603a2014-05-22 05:54:18 +00007356 return nullptr;
Guy Benyei11169dd2012-12-18 14:30:41 +00007357 }
7358
7359 if (GlobalID > SubmodulesLoaded.size()) {
7360 Error("submodule ID out of range in AST file");
Craig Toppera13603a2014-05-22 05:54:18 +00007361 return nullptr;
Guy Benyei11169dd2012-12-18 14:30:41 +00007362 }
7363
7364 return SubmodulesLoaded[GlobalID - NUM_PREDEF_SUBMODULE_IDS];
7365}
Douglas Gregorc147b0b2013-01-12 01:29:50 +00007366
7367Module *ASTReader::getModule(unsigned ID) {
7368 return getSubmodule(ID);
7369}
7370
Guy Benyei11169dd2012-12-18 14:30:41 +00007371Selector ASTReader::getLocalSelector(ModuleFile &M, unsigned LocalID) {
7372 return DecodeSelector(getGlobalSelectorID(M, LocalID));
7373}
7374
7375Selector ASTReader::DecodeSelector(serialization::SelectorID ID) {
7376 if (ID == 0)
7377 return Selector();
7378
7379 if (ID > SelectorsLoaded.size()) {
7380 Error("selector ID out of range in AST file");
7381 return Selector();
7382 }
7383
Craig Toppera13603a2014-05-22 05:54:18 +00007384 if (SelectorsLoaded[ID - 1].getAsOpaquePtr() == nullptr) {
Guy Benyei11169dd2012-12-18 14:30:41 +00007385 // Load this selector from the selector table.
7386 GlobalSelectorMapType::iterator I = GlobalSelectorMap.find(ID);
7387 assert(I != GlobalSelectorMap.end() && "Corrupted global selector map");
7388 ModuleFile &M = *I->second;
7389 ASTSelectorLookupTrait Trait(*this, M);
7390 unsigned Idx = ID - M.BaseSelectorID - NUM_PREDEF_SELECTOR_IDS;
7391 SelectorsLoaded[ID - 1] =
7392 Trait.ReadKey(M.SelectorLookupTableData + M.SelectorOffsets[Idx], 0);
7393 if (DeserializationListener)
7394 DeserializationListener->SelectorRead(ID, SelectorsLoaded[ID - 1]);
7395 }
7396
7397 return SelectorsLoaded[ID - 1];
7398}
7399
7400Selector ASTReader::GetExternalSelector(serialization::SelectorID ID) {
7401 return DecodeSelector(ID);
7402}
7403
7404uint32_t ASTReader::GetNumExternalSelectors() {
7405 // ID 0 (the null selector) is considered an external selector.
7406 return getTotalNumSelectors() + 1;
7407}
7408
7409serialization::SelectorID
7410ASTReader::getGlobalSelectorID(ModuleFile &M, unsigned LocalID) const {
7411 if (LocalID < NUM_PREDEF_SELECTOR_IDS)
7412 return LocalID;
7413
7414 ContinuousRangeMap<uint32_t, int, 2>::iterator I
7415 = M.SelectorRemap.find(LocalID - NUM_PREDEF_SELECTOR_IDS);
7416 assert(I != M.SelectorRemap.end()
7417 && "Invalid index into selector index remap");
7418
7419 return LocalID + I->second;
7420}
7421
7422DeclarationName
7423ASTReader::ReadDeclarationName(ModuleFile &F,
7424 const RecordData &Record, unsigned &Idx) {
7425 DeclarationName::NameKind Kind = (DeclarationName::NameKind)Record[Idx++];
7426 switch (Kind) {
7427 case DeclarationName::Identifier:
Douglas Gregorc8a992f2013-01-21 16:52:34 +00007428 return DeclarationName(GetIdentifierInfo(F, Record, Idx));
Guy Benyei11169dd2012-12-18 14:30:41 +00007429
7430 case DeclarationName::ObjCZeroArgSelector:
7431 case DeclarationName::ObjCOneArgSelector:
7432 case DeclarationName::ObjCMultiArgSelector:
7433 return DeclarationName(ReadSelector(F, Record, Idx));
7434
7435 case DeclarationName::CXXConstructorName:
7436 return Context.DeclarationNames.getCXXConstructorName(
7437 Context.getCanonicalType(readType(F, Record, Idx)));
7438
7439 case DeclarationName::CXXDestructorName:
7440 return Context.DeclarationNames.getCXXDestructorName(
7441 Context.getCanonicalType(readType(F, Record, Idx)));
7442
7443 case DeclarationName::CXXConversionFunctionName:
7444 return Context.DeclarationNames.getCXXConversionFunctionName(
7445 Context.getCanonicalType(readType(F, Record, Idx)));
7446
7447 case DeclarationName::CXXOperatorName:
7448 return Context.DeclarationNames.getCXXOperatorName(
7449 (OverloadedOperatorKind)Record[Idx++]);
7450
7451 case DeclarationName::CXXLiteralOperatorName:
7452 return Context.DeclarationNames.getCXXLiteralOperatorName(
7453 GetIdentifierInfo(F, Record, Idx));
7454
7455 case DeclarationName::CXXUsingDirective:
7456 return DeclarationName::getUsingDirectiveName();
7457 }
7458
7459 llvm_unreachable("Invalid NameKind!");
7460}
7461
7462void ASTReader::ReadDeclarationNameLoc(ModuleFile &F,
7463 DeclarationNameLoc &DNLoc,
7464 DeclarationName Name,
7465 const RecordData &Record, unsigned &Idx) {
7466 switch (Name.getNameKind()) {
7467 case DeclarationName::CXXConstructorName:
7468 case DeclarationName::CXXDestructorName:
7469 case DeclarationName::CXXConversionFunctionName:
7470 DNLoc.NamedType.TInfo = GetTypeSourceInfo(F, Record, Idx);
7471 break;
7472
7473 case DeclarationName::CXXOperatorName:
7474 DNLoc.CXXOperatorName.BeginOpNameLoc
7475 = ReadSourceLocation(F, Record, Idx).getRawEncoding();
7476 DNLoc.CXXOperatorName.EndOpNameLoc
7477 = ReadSourceLocation(F, Record, Idx).getRawEncoding();
7478 break;
7479
7480 case DeclarationName::CXXLiteralOperatorName:
7481 DNLoc.CXXLiteralOperatorName.OpNameLoc
7482 = ReadSourceLocation(F, Record, Idx).getRawEncoding();
7483 break;
7484
7485 case DeclarationName::Identifier:
7486 case DeclarationName::ObjCZeroArgSelector:
7487 case DeclarationName::ObjCOneArgSelector:
7488 case DeclarationName::ObjCMultiArgSelector:
7489 case DeclarationName::CXXUsingDirective:
7490 break;
7491 }
7492}
7493
7494void ASTReader::ReadDeclarationNameInfo(ModuleFile &F,
7495 DeclarationNameInfo &NameInfo,
7496 const RecordData &Record, unsigned &Idx) {
7497 NameInfo.setName(ReadDeclarationName(F, Record, Idx));
7498 NameInfo.setLoc(ReadSourceLocation(F, Record, Idx));
7499 DeclarationNameLoc DNLoc;
7500 ReadDeclarationNameLoc(F, DNLoc, NameInfo.getName(), Record, Idx);
7501 NameInfo.setInfo(DNLoc);
7502}
7503
7504void ASTReader::ReadQualifierInfo(ModuleFile &F, QualifierInfo &Info,
7505 const RecordData &Record, unsigned &Idx) {
7506 Info.QualifierLoc = ReadNestedNameSpecifierLoc(F, Record, Idx);
7507 unsigned NumTPLists = Record[Idx++];
7508 Info.NumTemplParamLists = NumTPLists;
7509 if (NumTPLists) {
7510 Info.TemplParamLists = new (Context) TemplateParameterList*[NumTPLists];
7511 for (unsigned i=0; i != NumTPLists; ++i)
7512 Info.TemplParamLists[i] = ReadTemplateParameterList(F, Record, Idx);
7513 }
7514}
7515
7516TemplateName
7517ASTReader::ReadTemplateName(ModuleFile &F, const RecordData &Record,
7518 unsigned &Idx) {
7519 TemplateName::NameKind Kind = (TemplateName::NameKind)Record[Idx++];
7520 switch (Kind) {
7521 case TemplateName::Template:
7522 return TemplateName(ReadDeclAs<TemplateDecl>(F, Record, Idx));
7523
7524 case TemplateName::OverloadedTemplate: {
7525 unsigned size = Record[Idx++];
7526 UnresolvedSet<8> Decls;
7527 while (size--)
7528 Decls.addDecl(ReadDeclAs<NamedDecl>(F, Record, Idx));
7529
7530 return Context.getOverloadedTemplateName(Decls.begin(), Decls.end());
7531 }
7532
7533 case TemplateName::QualifiedTemplate: {
7534 NestedNameSpecifier *NNS = ReadNestedNameSpecifier(F, Record, Idx);
7535 bool hasTemplKeyword = Record[Idx++];
7536 TemplateDecl *Template = ReadDeclAs<TemplateDecl>(F, Record, Idx);
7537 return Context.getQualifiedTemplateName(NNS, hasTemplKeyword, Template);
7538 }
7539
7540 case TemplateName::DependentTemplate: {
7541 NestedNameSpecifier *NNS = ReadNestedNameSpecifier(F, Record, Idx);
7542 if (Record[Idx++]) // isIdentifier
7543 return Context.getDependentTemplateName(NNS,
7544 GetIdentifierInfo(F, Record,
7545 Idx));
7546 return Context.getDependentTemplateName(NNS,
7547 (OverloadedOperatorKind)Record[Idx++]);
7548 }
7549
7550 case TemplateName::SubstTemplateTemplateParm: {
7551 TemplateTemplateParmDecl *param
7552 = ReadDeclAs<TemplateTemplateParmDecl>(F, Record, Idx);
7553 if (!param) return TemplateName();
7554 TemplateName replacement = ReadTemplateName(F, Record, Idx);
7555 return Context.getSubstTemplateTemplateParm(param, replacement);
7556 }
7557
7558 case TemplateName::SubstTemplateTemplateParmPack: {
7559 TemplateTemplateParmDecl *Param
7560 = ReadDeclAs<TemplateTemplateParmDecl>(F, Record, Idx);
7561 if (!Param)
7562 return TemplateName();
7563
7564 TemplateArgument ArgPack = ReadTemplateArgument(F, Record, Idx);
7565 if (ArgPack.getKind() != TemplateArgument::Pack)
7566 return TemplateName();
7567
7568 return Context.getSubstTemplateTemplateParmPack(Param, ArgPack);
7569 }
7570 }
7571
7572 llvm_unreachable("Unhandled template name kind!");
7573}
7574
7575TemplateArgument
7576ASTReader::ReadTemplateArgument(ModuleFile &F,
7577 const RecordData &Record, unsigned &Idx) {
7578 TemplateArgument::ArgKind Kind = (TemplateArgument::ArgKind)Record[Idx++];
7579 switch (Kind) {
7580 case TemplateArgument::Null:
7581 return TemplateArgument();
7582 case TemplateArgument::Type:
7583 return TemplateArgument(readType(F, Record, Idx));
7584 case TemplateArgument::Declaration: {
7585 ValueDecl *D = ReadDeclAs<ValueDecl>(F, Record, Idx);
7586 bool ForReferenceParam = Record[Idx++];
7587 return TemplateArgument(D, ForReferenceParam);
7588 }
7589 case TemplateArgument::NullPtr:
7590 return TemplateArgument(readType(F, Record, Idx), /*isNullPtr*/true);
7591 case TemplateArgument::Integral: {
7592 llvm::APSInt Value = ReadAPSInt(Record, Idx);
7593 QualType T = readType(F, Record, Idx);
7594 return TemplateArgument(Context, Value, T);
7595 }
7596 case TemplateArgument::Template:
7597 return TemplateArgument(ReadTemplateName(F, Record, Idx));
7598 case TemplateArgument::TemplateExpansion: {
7599 TemplateName Name = ReadTemplateName(F, Record, Idx);
David Blaikie05785d12013-02-20 22:23:23 +00007600 Optional<unsigned> NumTemplateExpansions;
Guy Benyei11169dd2012-12-18 14:30:41 +00007601 if (unsigned NumExpansions = Record[Idx++])
7602 NumTemplateExpansions = NumExpansions - 1;
7603 return TemplateArgument(Name, NumTemplateExpansions);
7604 }
7605 case TemplateArgument::Expression:
7606 return TemplateArgument(ReadExpr(F));
7607 case TemplateArgument::Pack: {
7608 unsigned NumArgs = Record[Idx++];
7609 TemplateArgument *Args = new (Context) TemplateArgument[NumArgs];
7610 for (unsigned I = 0; I != NumArgs; ++I)
7611 Args[I] = ReadTemplateArgument(F, Record, Idx);
7612 return TemplateArgument(Args, NumArgs);
7613 }
7614 }
7615
7616 llvm_unreachable("Unhandled template argument kind!");
7617}
7618
7619TemplateParameterList *
7620ASTReader::ReadTemplateParameterList(ModuleFile &F,
7621 const RecordData &Record, unsigned &Idx) {
7622 SourceLocation TemplateLoc = ReadSourceLocation(F, Record, Idx);
7623 SourceLocation LAngleLoc = ReadSourceLocation(F, Record, Idx);
7624 SourceLocation RAngleLoc = ReadSourceLocation(F, Record, Idx);
7625
7626 unsigned NumParams = Record[Idx++];
7627 SmallVector<NamedDecl *, 16> Params;
7628 Params.reserve(NumParams);
7629 while (NumParams--)
7630 Params.push_back(ReadDeclAs<NamedDecl>(F, Record, Idx));
7631
7632 TemplateParameterList* TemplateParams =
7633 TemplateParameterList::Create(Context, TemplateLoc, LAngleLoc,
7634 Params.data(), Params.size(), RAngleLoc);
7635 return TemplateParams;
7636}
7637
7638void
7639ASTReader::
Craig Topper5603df42013-07-05 19:34:19 +00007640ReadTemplateArgumentList(SmallVectorImpl<TemplateArgument> &TemplArgs,
Guy Benyei11169dd2012-12-18 14:30:41 +00007641 ModuleFile &F, const RecordData &Record,
7642 unsigned &Idx) {
7643 unsigned NumTemplateArgs = Record[Idx++];
7644 TemplArgs.reserve(NumTemplateArgs);
7645 while (NumTemplateArgs--)
7646 TemplArgs.push_back(ReadTemplateArgument(F, Record, Idx));
7647}
7648
7649/// \brief Read a UnresolvedSet structure.
Richard Smitha4ba74c2013-08-30 04:46:40 +00007650void ASTReader::ReadUnresolvedSet(ModuleFile &F, LazyASTUnresolvedSet &Set,
Guy Benyei11169dd2012-12-18 14:30:41 +00007651 const RecordData &Record, unsigned &Idx) {
7652 unsigned NumDecls = Record[Idx++];
7653 Set.reserve(Context, NumDecls);
7654 while (NumDecls--) {
Richard Smitha4ba74c2013-08-30 04:46:40 +00007655 DeclID ID = ReadDeclID(F, Record, Idx);
Guy Benyei11169dd2012-12-18 14:30:41 +00007656 AccessSpecifier AS = (AccessSpecifier)Record[Idx++];
Richard Smitha4ba74c2013-08-30 04:46:40 +00007657 Set.addLazyDecl(Context, ID, AS);
Guy Benyei11169dd2012-12-18 14:30:41 +00007658 }
7659}
7660
7661CXXBaseSpecifier
7662ASTReader::ReadCXXBaseSpecifier(ModuleFile &F,
7663 const RecordData &Record, unsigned &Idx) {
7664 bool isVirtual = static_cast<bool>(Record[Idx++]);
7665 bool isBaseOfClass = static_cast<bool>(Record[Idx++]);
7666 AccessSpecifier AS = static_cast<AccessSpecifier>(Record[Idx++]);
7667 bool inheritConstructors = static_cast<bool>(Record[Idx++]);
7668 TypeSourceInfo *TInfo = GetTypeSourceInfo(F, Record, Idx);
7669 SourceRange Range = ReadSourceRange(F, Record, Idx);
7670 SourceLocation EllipsisLoc = ReadSourceLocation(F, Record, Idx);
7671 CXXBaseSpecifier Result(Range, isVirtual, isBaseOfClass, AS, TInfo,
7672 EllipsisLoc);
7673 Result.setInheritConstructors(inheritConstructors);
7674 return Result;
7675}
7676
7677std::pair<CXXCtorInitializer **, unsigned>
7678ASTReader::ReadCXXCtorInitializers(ModuleFile &F, const RecordData &Record,
7679 unsigned &Idx) {
Craig Toppera13603a2014-05-22 05:54:18 +00007680 CXXCtorInitializer **CtorInitializers = nullptr;
Guy Benyei11169dd2012-12-18 14:30:41 +00007681 unsigned NumInitializers = Record[Idx++];
7682 if (NumInitializers) {
7683 CtorInitializers
7684 = new (Context) CXXCtorInitializer*[NumInitializers];
7685 for (unsigned i=0; i != NumInitializers; ++i) {
Craig Toppera13603a2014-05-22 05:54:18 +00007686 TypeSourceInfo *TInfo = nullptr;
Guy Benyei11169dd2012-12-18 14:30:41 +00007687 bool IsBaseVirtual = false;
Craig Toppera13603a2014-05-22 05:54:18 +00007688 FieldDecl *Member = nullptr;
7689 IndirectFieldDecl *IndirectMember = nullptr;
Guy Benyei11169dd2012-12-18 14:30:41 +00007690
7691 CtorInitializerType Type = (CtorInitializerType)Record[Idx++];
7692 switch (Type) {
7693 case CTOR_INITIALIZER_BASE:
7694 TInfo = GetTypeSourceInfo(F, Record, Idx);
7695 IsBaseVirtual = Record[Idx++];
7696 break;
7697
7698 case CTOR_INITIALIZER_DELEGATING:
7699 TInfo = GetTypeSourceInfo(F, Record, Idx);
7700 break;
7701
7702 case CTOR_INITIALIZER_MEMBER:
7703 Member = ReadDeclAs<FieldDecl>(F, Record, Idx);
7704 break;
7705
7706 case CTOR_INITIALIZER_INDIRECT_MEMBER:
7707 IndirectMember = ReadDeclAs<IndirectFieldDecl>(F, Record, Idx);
7708 break;
7709 }
7710
7711 SourceLocation MemberOrEllipsisLoc = ReadSourceLocation(F, Record, Idx);
7712 Expr *Init = ReadExpr(F);
7713 SourceLocation LParenLoc = ReadSourceLocation(F, Record, Idx);
7714 SourceLocation RParenLoc = ReadSourceLocation(F, Record, Idx);
7715 bool IsWritten = Record[Idx++];
7716 unsigned SourceOrderOrNumArrayIndices;
7717 SmallVector<VarDecl *, 8> Indices;
7718 if (IsWritten) {
7719 SourceOrderOrNumArrayIndices = Record[Idx++];
7720 } else {
7721 SourceOrderOrNumArrayIndices = Record[Idx++];
7722 Indices.reserve(SourceOrderOrNumArrayIndices);
7723 for (unsigned i=0; i != SourceOrderOrNumArrayIndices; ++i)
7724 Indices.push_back(ReadDeclAs<VarDecl>(F, Record, Idx));
7725 }
7726
7727 CXXCtorInitializer *BOMInit;
7728 if (Type == CTOR_INITIALIZER_BASE) {
7729 BOMInit = new (Context) CXXCtorInitializer(Context, TInfo, IsBaseVirtual,
7730 LParenLoc, Init, RParenLoc,
7731 MemberOrEllipsisLoc);
7732 } else if (Type == CTOR_INITIALIZER_DELEGATING) {
7733 BOMInit = new (Context) CXXCtorInitializer(Context, TInfo, LParenLoc,
7734 Init, RParenLoc);
7735 } else if (IsWritten) {
7736 if (Member)
7737 BOMInit = new (Context) CXXCtorInitializer(Context, Member, MemberOrEllipsisLoc,
7738 LParenLoc, Init, RParenLoc);
7739 else
7740 BOMInit = new (Context) CXXCtorInitializer(Context, IndirectMember,
7741 MemberOrEllipsisLoc, LParenLoc,
7742 Init, RParenLoc);
7743 } else {
Argyrios Kyrtzidis794671d2013-05-30 23:59:46 +00007744 if (IndirectMember) {
7745 assert(Indices.empty() && "Indirect field improperly initialized");
7746 BOMInit = new (Context) CXXCtorInitializer(Context, IndirectMember,
7747 MemberOrEllipsisLoc, LParenLoc,
7748 Init, RParenLoc);
7749 } else {
7750 BOMInit = CXXCtorInitializer::Create(Context, Member, MemberOrEllipsisLoc,
7751 LParenLoc, Init, RParenLoc,
7752 Indices.data(), Indices.size());
7753 }
Guy Benyei11169dd2012-12-18 14:30:41 +00007754 }
7755
7756 if (IsWritten)
7757 BOMInit->setSourceOrder(SourceOrderOrNumArrayIndices);
7758 CtorInitializers[i] = BOMInit;
7759 }
7760 }
7761
7762 return std::make_pair(CtorInitializers, NumInitializers);
7763}
7764
7765NestedNameSpecifier *
7766ASTReader::ReadNestedNameSpecifier(ModuleFile &F,
7767 const RecordData &Record, unsigned &Idx) {
7768 unsigned N = Record[Idx++];
Craig Toppera13603a2014-05-22 05:54:18 +00007769 NestedNameSpecifier *NNS = nullptr, *Prev = nullptr;
Guy Benyei11169dd2012-12-18 14:30:41 +00007770 for (unsigned I = 0; I != N; ++I) {
7771 NestedNameSpecifier::SpecifierKind Kind
7772 = (NestedNameSpecifier::SpecifierKind)Record[Idx++];
7773 switch (Kind) {
7774 case NestedNameSpecifier::Identifier: {
7775 IdentifierInfo *II = GetIdentifierInfo(F, Record, Idx);
7776 NNS = NestedNameSpecifier::Create(Context, Prev, II);
7777 break;
7778 }
7779
7780 case NestedNameSpecifier::Namespace: {
7781 NamespaceDecl *NS = ReadDeclAs<NamespaceDecl>(F, Record, Idx);
7782 NNS = NestedNameSpecifier::Create(Context, Prev, NS);
7783 break;
7784 }
7785
7786 case NestedNameSpecifier::NamespaceAlias: {
7787 NamespaceAliasDecl *Alias =ReadDeclAs<NamespaceAliasDecl>(F, Record, Idx);
7788 NNS = NestedNameSpecifier::Create(Context, Prev, Alias);
7789 break;
7790 }
7791
7792 case NestedNameSpecifier::TypeSpec:
7793 case NestedNameSpecifier::TypeSpecWithTemplate: {
7794 const Type *T = readType(F, Record, Idx).getTypePtrOrNull();
7795 if (!T)
Craig Toppera13603a2014-05-22 05:54:18 +00007796 return nullptr;
7797
Guy Benyei11169dd2012-12-18 14:30:41 +00007798 bool Template = Record[Idx++];
7799 NNS = NestedNameSpecifier::Create(Context, Prev, Template, T);
7800 break;
7801 }
7802
7803 case NestedNameSpecifier::Global: {
7804 NNS = NestedNameSpecifier::GlobalSpecifier(Context);
7805 // No associated value, and there can't be a prefix.
7806 break;
7807 }
7808 }
7809 Prev = NNS;
7810 }
7811 return NNS;
7812}
7813
7814NestedNameSpecifierLoc
7815ASTReader::ReadNestedNameSpecifierLoc(ModuleFile &F, const RecordData &Record,
7816 unsigned &Idx) {
7817 unsigned N = Record[Idx++];
7818 NestedNameSpecifierLocBuilder Builder;
7819 for (unsigned I = 0; I != N; ++I) {
7820 NestedNameSpecifier::SpecifierKind Kind
7821 = (NestedNameSpecifier::SpecifierKind)Record[Idx++];
7822 switch (Kind) {
7823 case NestedNameSpecifier::Identifier: {
7824 IdentifierInfo *II = GetIdentifierInfo(F, Record, Idx);
7825 SourceRange Range = ReadSourceRange(F, Record, Idx);
7826 Builder.Extend(Context, II, Range.getBegin(), Range.getEnd());
7827 break;
7828 }
7829
7830 case NestedNameSpecifier::Namespace: {
7831 NamespaceDecl *NS = ReadDeclAs<NamespaceDecl>(F, Record, Idx);
7832 SourceRange Range = ReadSourceRange(F, Record, Idx);
7833 Builder.Extend(Context, NS, Range.getBegin(), Range.getEnd());
7834 break;
7835 }
7836
7837 case NestedNameSpecifier::NamespaceAlias: {
7838 NamespaceAliasDecl *Alias =ReadDeclAs<NamespaceAliasDecl>(F, Record, Idx);
7839 SourceRange Range = ReadSourceRange(F, Record, Idx);
7840 Builder.Extend(Context, Alias, Range.getBegin(), Range.getEnd());
7841 break;
7842 }
7843
7844 case NestedNameSpecifier::TypeSpec:
7845 case NestedNameSpecifier::TypeSpecWithTemplate: {
7846 bool Template = Record[Idx++];
7847 TypeSourceInfo *T = GetTypeSourceInfo(F, Record, Idx);
7848 if (!T)
7849 return NestedNameSpecifierLoc();
7850 SourceLocation ColonColonLoc = ReadSourceLocation(F, Record, Idx);
7851
7852 // FIXME: 'template' keyword location not saved anywhere, so we fake it.
7853 Builder.Extend(Context,
7854 Template? T->getTypeLoc().getBeginLoc() : SourceLocation(),
7855 T->getTypeLoc(), ColonColonLoc);
7856 break;
7857 }
7858
7859 case NestedNameSpecifier::Global: {
7860 SourceLocation ColonColonLoc = ReadSourceLocation(F, Record, Idx);
7861 Builder.MakeGlobal(Context, ColonColonLoc);
7862 break;
7863 }
7864 }
7865 }
7866
7867 return Builder.getWithLocInContext(Context);
7868}
7869
7870SourceRange
7871ASTReader::ReadSourceRange(ModuleFile &F, const RecordData &Record,
7872 unsigned &Idx) {
7873 SourceLocation beg = ReadSourceLocation(F, Record, Idx);
7874 SourceLocation end = ReadSourceLocation(F, Record, Idx);
7875 return SourceRange(beg, end);
7876}
7877
7878/// \brief Read an integral value
7879llvm::APInt ASTReader::ReadAPInt(const RecordData &Record, unsigned &Idx) {
7880 unsigned BitWidth = Record[Idx++];
7881 unsigned NumWords = llvm::APInt::getNumWords(BitWidth);
7882 llvm::APInt Result(BitWidth, NumWords, &Record[Idx]);
7883 Idx += NumWords;
7884 return Result;
7885}
7886
7887/// \brief Read a signed integral value
7888llvm::APSInt ASTReader::ReadAPSInt(const RecordData &Record, unsigned &Idx) {
7889 bool isUnsigned = Record[Idx++];
7890 return llvm::APSInt(ReadAPInt(Record, Idx), isUnsigned);
7891}
7892
7893/// \brief Read a floating-point value
Tim Northover178723a2013-01-22 09:46:51 +00007894llvm::APFloat ASTReader::ReadAPFloat(const RecordData &Record,
7895 const llvm::fltSemantics &Sem,
7896 unsigned &Idx) {
7897 return llvm::APFloat(Sem, ReadAPInt(Record, Idx));
Guy Benyei11169dd2012-12-18 14:30:41 +00007898}
7899
7900// \brief Read a string
7901std::string ASTReader::ReadString(const RecordData &Record, unsigned &Idx) {
7902 unsigned Len = Record[Idx++];
7903 std::string Result(Record.data() + Idx, Record.data() + Idx + Len);
7904 Idx += Len;
7905 return Result;
7906}
7907
7908VersionTuple ASTReader::ReadVersionTuple(const RecordData &Record,
7909 unsigned &Idx) {
7910 unsigned Major = Record[Idx++];
7911 unsigned Minor = Record[Idx++];
7912 unsigned Subminor = Record[Idx++];
7913 if (Minor == 0)
7914 return VersionTuple(Major);
7915 if (Subminor == 0)
7916 return VersionTuple(Major, Minor - 1);
7917 return VersionTuple(Major, Minor - 1, Subminor - 1);
7918}
7919
7920CXXTemporary *ASTReader::ReadCXXTemporary(ModuleFile &F,
7921 const RecordData &Record,
7922 unsigned &Idx) {
7923 CXXDestructorDecl *Decl = ReadDeclAs<CXXDestructorDecl>(F, Record, Idx);
7924 return CXXTemporary::Create(Context, Decl);
7925}
7926
7927DiagnosticBuilder ASTReader::Diag(unsigned DiagID) {
Argyrios Kyrtzidisdc9fdaf2013-05-24 05:44:08 +00007928 return Diag(CurrentImportLoc, DiagID);
Guy Benyei11169dd2012-12-18 14:30:41 +00007929}
7930
7931DiagnosticBuilder ASTReader::Diag(SourceLocation Loc, unsigned DiagID) {
7932 return Diags.Report(Loc, DiagID);
7933}
7934
7935/// \brief Retrieve the identifier table associated with the
7936/// preprocessor.
7937IdentifierTable &ASTReader::getIdentifierTable() {
7938 return PP.getIdentifierTable();
7939}
7940
7941/// \brief Record that the given ID maps to the given switch-case
7942/// statement.
7943void ASTReader::RecordSwitchCaseID(SwitchCase *SC, unsigned ID) {
Craig Toppera13603a2014-05-22 05:54:18 +00007944 assert((*CurrSwitchCaseStmts)[ID] == nullptr &&
Guy Benyei11169dd2012-12-18 14:30:41 +00007945 "Already have a SwitchCase with this ID");
7946 (*CurrSwitchCaseStmts)[ID] = SC;
7947}
7948
7949/// \brief Retrieve the switch-case statement with the given ID.
7950SwitchCase *ASTReader::getSwitchCaseWithID(unsigned ID) {
Craig Toppera13603a2014-05-22 05:54:18 +00007951 assert((*CurrSwitchCaseStmts)[ID] != nullptr && "No SwitchCase with this ID");
Guy Benyei11169dd2012-12-18 14:30:41 +00007952 return (*CurrSwitchCaseStmts)[ID];
7953}
7954
7955void ASTReader::ClearSwitchCaseIDs() {
7956 CurrSwitchCaseStmts->clear();
7957}
7958
7959void ASTReader::ReadComments() {
7960 std::vector<RawComment *> Comments;
Chris Lattner7fb3bef2013-01-20 00:56:42 +00007961 for (SmallVectorImpl<std::pair<BitstreamCursor,
Guy Benyei11169dd2012-12-18 14:30:41 +00007962 serialization::ModuleFile *> >::iterator
7963 I = CommentsCursors.begin(),
7964 E = CommentsCursors.end();
7965 I != E; ++I) {
Dmitri Gribenko9ee0e302014-03-27 15:40:39 +00007966 Comments.clear();
Chris Lattner7fb3bef2013-01-20 00:56:42 +00007967 BitstreamCursor &Cursor = I->first;
Guy Benyei11169dd2012-12-18 14:30:41 +00007968 serialization::ModuleFile &F = *I->second;
7969 SavedStreamPosition SavedPosition(Cursor);
7970
7971 RecordData Record;
7972 while (true) {
Chris Lattner7fb3bef2013-01-20 00:56:42 +00007973 llvm::BitstreamEntry Entry =
7974 Cursor.advanceSkippingSubblocks(BitstreamCursor::AF_DontPopBlockAtEnd);
Dmitri Gribenko9ee0e302014-03-27 15:40:39 +00007975
Chris Lattner7fb3bef2013-01-20 00:56:42 +00007976 switch (Entry.Kind) {
7977 case llvm::BitstreamEntry::SubBlock: // Handled for us already.
7978 case llvm::BitstreamEntry::Error:
7979 Error("malformed block record in AST file");
7980 return;
7981 case llvm::BitstreamEntry::EndBlock:
7982 goto NextCursor;
7983 case llvm::BitstreamEntry::Record:
7984 // The interesting case.
Guy Benyei11169dd2012-12-18 14:30:41 +00007985 break;
Guy Benyei11169dd2012-12-18 14:30:41 +00007986 }
7987
7988 // Read a record.
7989 Record.clear();
Chris Lattner0e6c9402013-01-20 02:38:54 +00007990 switch ((CommentRecordTypes)Cursor.readRecord(Entry.ID, Record)) {
Guy Benyei11169dd2012-12-18 14:30:41 +00007991 case COMMENTS_RAW_COMMENT: {
7992 unsigned Idx = 0;
7993 SourceRange SR = ReadSourceRange(F, Record, Idx);
7994 RawComment::CommentKind Kind =
7995 (RawComment::CommentKind) Record[Idx++];
7996 bool IsTrailingComment = Record[Idx++];
7997 bool IsAlmostTrailingComment = Record[Idx++];
Dmitri Gribenkoa7d16ce2013-04-10 15:35:17 +00007998 Comments.push_back(new (Context) RawComment(
7999 SR, Kind, IsTrailingComment, IsAlmostTrailingComment,
8000 Context.getLangOpts().CommentOpts.ParseAllComments));
Guy Benyei11169dd2012-12-18 14:30:41 +00008001 break;
8002 }
8003 }
8004 }
Dmitri Gribenko9ee0e302014-03-27 15:40:39 +00008005 NextCursor:
8006 Context.Comments.addDeserializedComments(Comments);
Guy Benyei11169dd2012-12-18 14:30:41 +00008007 }
Guy Benyei11169dd2012-12-18 14:30:41 +00008008}
8009
Richard Smithcd45dbc2014-04-19 03:48:30 +00008010std::string ASTReader::getOwningModuleNameForDiagnostic(const Decl *D) {
8011 // If we know the owning module, use it.
8012 if (Module *M = D->getOwningModule())
8013 return M->getFullModuleName();
8014
8015 // Otherwise, use the name of the top-level module the decl is within.
8016 if (ModuleFile *M = getOwningModuleFile(D))
8017 return M->ModuleName;
8018
8019 // Not from a module.
8020 return "";
8021}
8022
Guy Benyei11169dd2012-12-18 14:30:41 +00008023void ASTReader::finishPendingActions() {
Richard Smith851072e2014-05-19 20:59:20 +00008024 while (!PendingIdentifierInfos.empty() ||
8025 !PendingIncompleteDeclChains.empty() || !PendingDeclChains.empty() ||
Richard Smith2b9e3e32013-10-18 06:05:18 +00008026 !PendingMacroIDs.empty() || !PendingDeclContextInfos.empty() ||
Richard Smith93914a92014-05-08 00:25:01 +00008027 !PendingUpdateRecords.empty() || !PendingOdrMergeChecks.empty()) {
Guy Benyei11169dd2012-12-18 14:30:41 +00008028 // If any identifiers with corresponding top-level declarations have
8029 // been loaded, load those declarations now.
Craig Topper79be4cd2013-07-05 04:33:53 +00008030 typedef llvm::DenseMap<IdentifierInfo *, SmallVector<Decl *, 2> >
8031 TopLevelDeclsMap;
8032 TopLevelDeclsMap TopLevelDecls;
8033
Guy Benyei11169dd2012-12-18 14:30:41 +00008034 while (!PendingIdentifierInfos.empty()) {
Douglas Gregor6168bd22013-02-18 15:53:43 +00008035 IdentifierInfo *II = PendingIdentifierInfos.back().first;
Richard Smithf0ae3c2d2014-03-28 17:31:23 +00008036 SmallVector<uint32_t, 4> DeclIDs =
8037 std::move(PendingIdentifierInfos.back().second);
Douglas Gregorcb15f082013-02-19 18:26:28 +00008038 PendingIdentifierInfos.pop_back();
Douglas Gregor6168bd22013-02-18 15:53:43 +00008039
8040 SetGloballyVisibleDecls(II, DeclIDs, &TopLevelDecls[II]);
Guy Benyei11169dd2012-12-18 14:30:41 +00008041 }
Richard Smithf0ae3c2d2014-03-28 17:31:23 +00008042
Richard Smith851072e2014-05-19 20:59:20 +00008043 // For each decl chain that we wanted to complete while deserializing, mark
8044 // it as "still needs to be completed".
8045 for (unsigned I = 0; I != PendingIncompleteDeclChains.size(); ++I) {
8046 markIncompleteDeclChain(PendingIncompleteDeclChains[I]);
8047 }
8048 PendingIncompleteDeclChains.clear();
8049
Guy Benyei11169dd2012-12-18 14:30:41 +00008050 // Load pending declaration chains.
8051 for (unsigned I = 0; I != PendingDeclChains.size(); ++I) {
8052 loadPendingDeclChain(PendingDeclChains[I]);
8053 PendingDeclChainsKnown.erase(PendingDeclChains[I]);
8054 }
8055 PendingDeclChains.clear();
8056
Douglas Gregor6168bd22013-02-18 15:53:43 +00008057 // Make the most recent of the top-level declarations visible.
Craig Topper79be4cd2013-07-05 04:33:53 +00008058 for (TopLevelDeclsMap::iterator TLD = TopLevelDecls.begin(),
8059 TLDEnd = TopLevelDecls.end(); TLD != TLDEnd; ++TLD) {
Douglas Gregor6168bd22013-02-18 15:53:43 +00008060 IdentifierInfo *II = TLD->first;
8061 for (unsigned I = 0, N = TLD->second.size(); I != N; ++I) {
Argyrios Kyrtzidise5edbf92013-04-26 21:33:35 +00008062 pushExternalDeclIntoScope(cast<NamedDecl>(TLD->second[I]), II);
Douglas Gregor6168bd22013-02-18 15:53:43 +00008063 }
8064 }
8065
Guy Benyei11169dd2012-12-18 14:30:41 +00008066 // Load any pending macro definitions.
8067 for (unsigned I = 0; I != PendingMacroIDs.size(); ++I) {
Argyrios Kyrtzidiseb663da2013-03-22 21:12:57 +00008068 IdentifierInfo *II = PendingMacroIDs.begin()[I].first;
8069 SmallVector<PendingMacroInfo, 2> GlobalIDs;
8070 GlobalIDs.swap(PendingMacroIDs.begin()[I].second);
8071 // Initialize the macro history from chained-PCHs ahead of module imports.
Richard Smith49f906a2014-03-01 00:08:04 +00008072 for (unsigned IDIdx = 0, NumIDs = GlobalIDs.size(); IDIdx != NumIDs;
Argyrios Kyrtzidis719736c2013-01-19 03:14:56 +00008073 ++IDIdx) {
Argyrios Kyrtzidiseb663da2013-03-22 21:12:57 +00008074 const PendingMacroInfo &Info = GlobalIDs[IDIdx];
8075 if (Info.M->Kind != MK_Module)
8076 resolvePendingMacro(II, Info);
8077 }
8078 // Handle module imports.
Richard Smith49f906a2014-03-01 00:08:04 +00008079 for (unsigned IDIdx = 0, NumIDs = GlobalIDs.size(); IDIdx != NumIDs;
Argyrios Kyrtzidiseb663da2013-03-22 21:12:57 +00008080 ++IDIdx) {
8081 const PendingMacroInfo &Info = GlobalIDs[IDIdx];
8082 if (Info.M->Kind == MK_Module)
8083 resolvePendingMacro(II, Info);
Guy Benyei11169dd2012-12-18 14:30:41 +00008084 }
8085 }
8086 PendingMacroIDs.clear();
Argyrios Kyrtzidis83a6e3b2013-02-16 00:48:59 +00008087
8088 // Wire up the DeclContexts for Decls that we delayed setting until
8089 // recursive loading is completed.
8090 while (!PendingDeclContextInfos.empty()) {
8091 PendingDeclContextInfo Info = PendingDeclContextInfos.front();
8092 PendingDeclContextInfos.pop_front();
8093 DeclContext *SemaDC = cast<DeclContext>(GetDecl(Info.SemaDC));
8094 DeclContext *LexicalDC = cast<DeclContext>(GetDecl(Info.LexicalDC));
8095 Info.D->setDeclContextsImpl(SemaDC, LexicalDC, getContext());
8096 }
Richard Smith2b9e3e32013-10-18 06:05:18 +00008097
Richard Smithd1c46742014-04-30 02:24:17 +00008098 // Perform any pending declaration updates.
Richard Smith675d2792014-06-16 20:26:19 +00008099 //
8100 // Don't do this if we have known-incomplete redecl chains: it relies on
8101 // being able to walk redeclaration chains.
8102 while (PendingDeclChains.empty() && !PendingUpdateRecords.empty()) {
Richard Smithd1c46742014-04-30 02:24:17 +00008103 auto Update = PendingUpdateRecords.pop_back_val();
8104 ReadingKindTracker ReadingKind(Read_Decl, *this);
8105 loadDeclUpdateRecords(Update.first, Update.second);
8106 }
8107
Richard Smithcd45dbc2014-04-19 03:48:30 +00008108 // Trigger the import of the full definition of each class that had any
8109 // odr-merging problems, so we can produce better diagnostics for them.
8110 for (auto &Merge : PendingOdrMergeFailures) {
8111 Merge.first->buildLookup();
8112 Merge.first->decls_begin();
8113 Merge.first->bases_begin();
8114 Merge.first->vbases_begin();
8115 for (auto *RD : Merge.second) {
8116 RD->decls_begin();
8117 RD->bases_begin();
8118 RD->vbases_begin();
8119 }
8120 }
8121
Richard Smith2b9e3e32013-10-18 06:05:18 +00008122 // For each declaration from a merged context, check that the canonical
8123 // definition of that context also contains a declaration of the same
8124 // entity.
8125 while (!PendingOdrMergeChecks.empty()) {
8126 NamedDecl *D = PendingOdrMergeChecks.pop_back_val();
8127
8128 // FIXME: Skip over implicit declarations for now. This matters for things
8129 // like implicitly-declared special member functions. This isn't entirely
8130 // correct; we can end up with multiple unmerged declarations of the same
8131 // implicit entity.
8132 if (D->isImplicit())
8133 continue;
8134
8135 DeclContext *CanonDef = D->getDeclContext();
8136 DeclContext::lookup_result R = CanonDef->lookup(D->getDeclName());
8137
8138 bool Found = false;
8139 const Decl *DCanon = D->getCanonicalDecl();
8140
8141 llvm::SmallVector<const NamedDecl*, 4> Candidates;
8142 for (DeclContext::lookup_iterator I = R.begin(), E = R.end();
8143 !Found && I != E; ++I) {
Aaron Ballman86c93902014-03-06 23:45:36 +00008144 for (auto RI : (*I)->redecls()) {
8145 if (RI->getLexicalDeclContext() == CanonDef) {
Richard Smith2b9e3e32013-10-18 06:05:18 +00008146 // This declaration is present in the canonical definition. If it's
8147 // in the same redecl chain, it's the one we're looking for.
Aaron Ballman86c93902014-03-06 23:45:36 +00008148 if (RI->getCanonicalDecl() == DCanon)
Richard Smith2b9e3e32013-10-18 06:05:18 +00008149 Found = true;
8150 else
Aaron Ballman86c93902014-03-06 23:45:36 +00008151 Candidates.push_back(cast<NamedDecl>(RI));
Richard Smith2b9e3e32013-10-18 06:05:18 +00008152 break;
8153 }
8154 }
8155 }
8156
8157 if (!Found) {
8158 D->setInvalidDecl();
8159
Richard Smithcd45dbc2014-04-19 03:48:30 +00008160 std::string CanonDefModule =
8161 getOwningModuleNameForDiagnostic(cast<Decl>(CanonDef));
Richard Smith2b9e3e32013-10-18 06:05:18 +00008162 Diag(D->getLocation(), diag::err_module_odr_violation_missing_decl)
Richard Smithcd45dbc2014-04-19 03:48:30 +00008163 << D << getOwningModuleNameForDiagnostic(D)
8164 << CanonDef << CanonDefModule.empty() << CanonDefModule;
Richard Smith2b9e3e32013-10-18 06:05:18 +00008165
8166 if (Candidates.empty())
8167 Diag(cast<Decl>(CanonDef)->getLocation(),
8168 diag::note_module_odr_violation_no_possible_decls) << D;
8169 else {
8170 for (unsigned I = 0, N = Candidates.size(); I != N; ++I)
8171 Diag(Candidates[I]->getLocation(),
8172 diag::note_module_odr_violation_possible_decl)
8173 << Candidates[I];
8174 }
Richard Smithcd45dbc2014-04-19 03:48:30 +00008175
8176 DiagnosedOdrMergeFailures.insert(CanonDef);
Richard Smith2b9e3e32013-10-18 06:05:18 +00008177 }
8178 }
Guy Benyei11169dd2012-12-18 14:30:41 +00008179 }
8180
8181 // If we deserialized any C++ or Objective-C class definitions, any
8182 // Objective-C protocol definitions, or any redeclarable templates, make sure
8183 // that all redeclarations point to the definitions. Note that this can only
8184 // happen now, after the redeclaration chains have been fully wired.
8185 for (llvm::SmallPtrSet<Decl *, 4>::iterator D = PendingDefinitions.begin(),
8186 DEnd = PendingDefinitions.end();
8187 D != DEnd; ++D) {
8188 if (TagDecl *TD = dyn_cast<TagDecl>(*D)) {
Richard Smith5b21db82014-04-23 18:20:42 +00008189 if (const TagType *TagT = dyn_cast<TagType>(TD->getTypeForDecl())) {
Guy Benyei11169dd2012-12-18 14:30:41 +00008190 // Make sure that the TagType points at the definition.
8191 const_cast<TagType*>(TagT)->decl = TD;
8192 }
8193
Aaron Ballman86c93902014-03-06 23:45:36 +00008194 if (auto RD = dyn_cast<CXXRecordDecl>(*D)) {
8195 for (auto R : RD->redecls())
8196 cast<CXXRecordDecl>(R)->DefinitionData = RD->DefinitionData;
Guy Benyei11169dd2012-12-18 14:30:41 +00008197 }
8198
8199 continue;
8200 }
8201
Aaron Ballman86c93902014-03-06 23:45:36 +00008202 if (auto ID = dyn_cast<ObjCInterfaceDecl>(*D)) {
Guy Benyei11169dd2012-12-18 14:30:41 +00008203 // Make sure that the ObjCInterfaceType points at the definition.
8204 const_cast<ObjCInterfaceType *>(cast<ObjCInterfaceType>(ID->TypeForDecl))
8205 ->Decl = ID;
8206
Aaron Ballman86c93902014-03-06 23:45:36 +00008207 for (auto R : ID->redecls())
Guy Benyei11169dd2012-12-18 14:30:41 +00008208 R->Data = ID->Data;
8209
8210 continue;
8211 }
8212
Aaron Ballman86c93902014-03-06 23:45:36 +00008213 if (auto PD = dyn_cast<ObjCProtocolDecl>(*D)) {
8214 for (auto R : PD->redecls())
Guy Benyei11169dd2012-12-18 14:30:41 +00008215 R->Data = PD->Data;
8216
8217 continue;
8218 }
8219
Aaron Ballman86c93902014-03-06 23:45:36 +00008220 auto RTD = cast<RedeclarableTemplateDecl>(*D)->getCanonicalDecl();
8221 for (auto R : RTD->redecls())
Guy Benyei11169dd2012-12-18 14:30:41 +00008222 R->Common = RTD->Common;
8223 }
8224 PendingDefinitions.clear();
8225
8226 // Load the bodies of any functions or methods we've encountered. We do
8227 // this now (delayed) so that we can be sure that the declaration chains
8228 // have been fully wired up.
8229 for (PendingBodiesMap::iterator PB = PendingBodies.begin(),
8230 PBEnd = PendingBodies.end();
8231 PB != PBEnd; ++PB) {
8232 if (FunctionDecl *FD = dyn_cast<FunctionDecl>(PB->first)) {
8233 // FIXME: Check for =delete/=default?
8234 // FIXME: Complain about ODR violations here?
8235 if (!getContext().getLangOpts().Modules || !FD->hasBody())
8236 FD->setLazyBody(PB->second);
8237 continue;
8238 }
8239
8240 ObjCMethodDecl *MD = cast<ObjCMethodDecl>(PB->first);
8241 if (!getContext().getLangOpts().Modules || !MD->hasBody())
8242 MD->setLazyBody(PB->second);
8243 }
8244 PendingBodies.clear();
Richard Smithcd45dbc2014-04-19 03:48:30 +00008245
8246 // Issue any pending ODR-failure diagnostics.
8247 for (auto &Merge : PendingOdrMergeFailures) {
8248 if (!DiagnosedOdrMergeFailures.insert(Merge.first))
8249 continue;
8250
8251 bool Diagnosed = false;
8252 for (auto *RD : Merge.second) {
8253 // Multiple different declarations got merged together; tell the user
8254 // where they came from.
8255 if (Merge.first != RD) {
8256 // FIXME: Walk the definition, figure out what's different,
8257 // and diagnose that.
8258 if (!Diagnosed) {
8259 std::string Module = getOwningModuleNameForDiagnostic(Merge.first);
8260 Diag(Merge.first->getLocation(),
8261 diag::err_module_odr_violation_different_definitions)
8262 << Merge.first << Module.empty() << Module;
8263 Diagnosed = true;
8264 }
8265
8266 Diag(RD->getLocation(),
8267 diag::note_module_odr_violation_different_definitions)
8268 << getOwningModuleNameForDiagnostic(RD);
8269 }
8270 }
8271
8272 if (!Diagnosed) {
8273 // All definitions are updates to the same declaration. This happens if a
8274 // module instantiates the declaration of a class template specialization
8275 // and two or more other modules instantiate its definition.
8276 //
8277 // FIXME: Indicate which modules had instantiations of this definition.
8278 // FIXME: How can this even happen?
8279 Diag(Merge.first->getLocation(),
8280 diag::err_module_odr_violation_different_instantiations)
8281 << Merge.first;
8282 }
8283 }
8284 PendingOdrMergeFailures.clear();
Guy Benyei11169dd2012-12-18 14:30:41 +00008285}
8286
8287void ASTReader::FinishedDeserializing() {
8288 assert(NumCurrentElementsDeserializing &&
8289 "FinishedDeserializing not paired with StartedDeserializing");
8290 if (NumCurrentElementsDeserializing == 1) {
8291 // We decrease NumCurrentElementsDeserializing only after pending actions
8292 // are finished, to avoid recursively re-calling finishPendingActions().
8293 finishPendingActions();
8294 }
8295 --NumCurrentElementsDeserializing;
8296
Richard Smith04d05b52014-03-23 00:27:18 +00008297 if (NumCurrentElementsDeserializing == 0 && Consumer) {
8298 // We are not in recursive loading, so it's safe to pass the "interesting"
8299 // decls to the consumer.
8300 PassInterestingDeclsToConsumer();
Guy Benyei11169dd2012-12-18 14:30:41 +00008301 }
8302}
8303
Argyrios Kyrtzidise5edbf92013-04-26 21:33:35 +00008304void ASTReader::pushExternalDeclIntoScope(NamedDecl *D, DeclarationName Name) {
Rafael Espindola7b56f6c2013-10-19 16:55:03 +00008305 D = D->getMostRecentDecl();
Argyrios Kyrtzidise5edbf92013-04-26 21:33:35 +00008306
8307 if (SemaObj->IdResolver.tryAddTopLevelDecl(D, Name) && SemaObj->TUScope) {
8308 SemaObj->TUScope->AddDecl(D);
8309 } else if (SemaObj->TUScope) {
8310 // Adding the decl to IdResolver may have failed because it was already in
8311 // (even though it was not added in scope). If it is already in, make sure
8312 // it gets in the scope as well.
8313 if (std::find(SemaObj->IdResolver.begin(Name),
8314 SemaObj->IdResolver.end(), D) != SemaObj->IdResolver.end())
8315 SemaObj->TUScope->AddDecl(D);
8316 }
8317}
8318
Nico Weber824285e2014-05-08 04:26:47 +00008319ASTReader::ASTReader(Preprocessor &PP, ASTContext &Context, StringRef isysroot,
8320 bool DisableValidation, bool AllowASTWithCompilerErrors,
8321 bool AllowConfigurationMismatch, bool ValidateSystemInputs,
Ben Langmuir2cb4a782014-02-05 22:21:15 +00008322 bool UseGlobalIndex)
Craig Toppera13603a2014-05-22 05:54:18 +00008323 : Listener(new PCHValidator(PP, *this)), DeserializationListener(nullptr),
Nico Weber824285e2014-05-08 04:26:47 +00008324 OwnsDeserializationListener(false), SourceMgr(PP.getSourceManager()),
Craig Toppera13603a2014-05-22 05:54:18 +00008325 FileMgr(PP.getFileManager()), Diags(PP.getDiagnostics()),
8326 SemaObj(nullptr), PP(PP), Context(Context), Consumer(nullptr),
8327 ModuleMgr(PP.getFileManager()), isysroot(isysroot),
8328 DisableValidation(DisableValidation),
Nico Weber824285e2014-05-08 04:26:47 +00008329 AllowASTWithCompilerErrors(AllowASTWithCompilerErrors),
8330 AllowConfigurationMismatch(AllowConfigurationMismatch),
8331 ValidateSystemInputs(ValidateSystemInputs),
8332 UseGlobalIndex(UseGlobalIndex), TriedLoadingGlobalIndex(false),
Richard Smith053f6c62014-05-16 23:01:30 +00008333 CurrSwitchCaseStmts(&SwitchCaseStmts),
Nico Weber824285e2014-05-08 04:26:47 +00008334 NumSLocEntriesRead(0), TotalNumSLocEntries(0), NumStatementsRead(0),
8335 TotalNumStatements(0), NumMacrosRead(0), TotalNumMacros(0),
8336 NumIdentifierLookups(0), NumIdentifierLookupHits(0), NumSelectorsRead(0),
8337 NumMethodPoolEntriesRead(0), NumMethodPoolLookups(0),
8338 NumMethodPoolHits(0), NumMethodPoolTableLookups(0),
8339 NumMethodPoolTableHits(0), TotalNumMethodPoolEntries(0),
8340 NumLexicalDeclContextsRead(0), TotalLexicalDeclContexts(0),
8341 NumVisibleDeclContextsRead(0), TotalVisibleDeclContexts(0),
8342 TotalModulesSizeInBits(0), NumCurrentElementsDeserializing(0),
8343 PassingDeclsToConsumer(false), NumCXXBaseSpecifiersLoaded(0),
8344 ReadingKind(Read_None) {
Guy Benyei11169dd2012-12-18 14:30:41 +00008345 SourceMgr.setExternalSLocEntrySource(this);
8346}
8347
8348ASTReader::~ASTReader() {
Nico Weber824285e2014-05-08 04:26:47 +00008349 if (OwnsDeserializationListener)
8350 delete DeserializationListener;
8351
Guy Benyei11169dd2012-12-18 14:30:41 +00008352 for (DeclContextVisibleUpdatesPending::iterator
8353 I = PendingVisibleUpdates.begin(),
8354 E = PendingVisibleUpdates.end();
8355 I != E; ++I) {
8356 for (DeclContextVisibleUpdates::iterator J = I->second.begin(),
8357 F = I->second.end();
8358 J != F; ++J)
8359 delete J->first;
8360 }
8361}