blob: bc7778adc6c52a863e7997c49b497f4399592dce [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 \"";
Manuel Klimek9af34ae2014-08-12 08:25:57 +0000546 SuggestedPredefines += File;
Guy Benyei11169dd2012-12-18 14:30:41 +0000547 SuggestedPredefines += "\"\n";
548 }
549
550 for (unsigned I = 0, N = ExistingPPOpts.MacroIncludes.size(); I != N; ++I) {
551 StringRef File = ExistingPPOpts.MacroIncludes[I];
552 if (std::find(PPOpts.MacroIncludes.begin(), PPOpts.MacroIncludes.end(),
553 File)
554 != PPOpts.MacroIncludes.end())
555 continue;
556
557 SuggestedPredefines += "#__include_macros \"";
Manuel Klimek9af34ae2014-08-12 08:25:57 +0000558 SuggestedPredefines += File;
Guy Benyei11169dd2012-12-18 14:30:41 +0000559 SuggestedPredefines += "\"\n##\n";
560 }
561
562 return false;
563}
564
565bool PCHValidator::ReadPreprocessorOptions(const PreprocessorOptions &PPOpts,
566 bool Complain,
567 std::string &SuggestedPredefines) {
568 const PreprocessorOptions &ExistingPPOpts = PP.getPreprocessorOpts();
569
570 return checkPreprocessorOptions(PPOpts, ExistingPPOpts,
Craig Toppera13603a2014-05-22 05:54:18 +0000571 Complain? &Reader.Diags : nullptr,
Guy Benyei11169dd2012-12-18 14:30:41 +0000572 PP.getFileManager(),
Argyrios Kyrtzidisd3afa0c2013-04-26 21:33:40 +0000573 SuggestedPredefines,
574 PP.getLangOpts());
Guy Benyei11169dd2012-12-18 14:30:41 +0000575}
576
Guy Benyei11169dd2012-12-18 14:30:41 +0000577void PCHValidator::ReadCounter(const ModuleFile &M, unsigned Value) {
578 PP.setCounterValue(Value);
579}
580
581//===----------------------------------------------------------------------===//
582// AST reader implementation
583//===----------------------------------------------------------------------===//
584
Nico Weber824285e2014-05-08 04:26:47 +0000585void ASTReader::setDeserializationListener(ASTDeserializationListener *Listener,
586 bool TakeOwnership) {
Guy Benyei11169dd2012-12-18 14:30:41 +0000587 DeserializationListener = Listener;
Nico Weber824285e2014-05-08 04:26:47 +0000588 OwnsDeserializationListener = TakeOwnership;
Guy Benyei11169dd2012-12-18 14:30:41 +0000589}
590
591
592
593unsigned ASTSelectorLookupTrait::ComputeHash(Selector Sel) {
594 return serialization::ComputeHash(Sel);
595}
596
597
598std::pair<unsigned, unsigned>
599ASTSelectorLookupTrait::ReadKeyDataLength(const unsigned char*& d) {
Justin Bogner57ba0b22014-03-28 22:03:24 +0000600 using namespace llvm::support;
601 unsigned KeyLen = endian::readNext<uint16_t, little, unaligned>(d);
602 unsigned DataLen = endian::readNext<uint16_t, little, unaligned>(d);
Guy Benyei11169dd2012-12-18 14:30:41 +0000603 return std::make_pair(KeyLen, DataLen);
604}
605
606ASTSelectorLookupTrait::internal_key_type
607ASTSelectorLookupTrait::ReadKey(const unsigned char* d, unsigned) {
Justin Bogner57ba0b22014-03-28 22:03:24 +0000608 using namespace llvm::support;
Guy Benyei11169dd2012-12-18 14:30:41 +0000609 SelectorTable &SelTable = Reader.getContext().Selectors;
Justin Bogner57ba0b22014-03-28 22:03:24 +0000610 unsigned N = endian::readNext<uint16_t, little, unaligned>(d);
611 IdentifierInfo *FirstII = Reader.getLocalIdentifier(
612 F, endian::readNext<uint32_t, little, unaligned>(d));
Guy Benyei11169dd2012-12-18 14:30:41 +0000613 if (N == 0)
614 return SelTable.getNullarySelector(FirstII);
615 else if (N == 1)
616 return SelTable.getUnarySelector(FirstII);
617
618 SmallVector<IdentifierInfo *, 16> Args;
619 Args.push_back(FirstII);
620 for (unsigned I = 1; I != N; ++I)
Justin Bogner57ba0b22014-03-28 22:03:24 +0000621 Args.push_back(Reader.getLocalIdentifier(
622 F, endian::readNext<uint32_t, little, unaligned>(d)));
Guy Benyei11169dd2012-12-18 14:30:41 +0000623
624 return SelTable.getSelector(N, Args.data());
625}
626
627ASTSelectorLookupTrait::data_type
628ASTSelectorLookupTrait::ReadData(Selector, const unsigned char* d,
629 unsigned DataLen) {
Justin Bogner57ba0b22014-03-28 22:03:24 +0000630 using namespace llvm::support;
Guy Benyei11169dd2012-12-18 14:30:41 +0000631
632 data_type Result;
633
Justin Bogner57ba0b22014-03-28 22:03:24 +0000634 Result.ID = Reader.getGlobalSelectorID(
635 F, endian::readNext<uint32_t, little, unaligned>(d));
636 unsigned NumInstanceMethodsAndBits =
637 endian::readNext<uint16_t, little, unaligned>(d);
638 unsigned NumFactoryMethodsAndBits =
639 endian::readNext<uint16_t, little, unaligned>(d);
Argyrios Kyrtzidisd3da6e02013-04-17 00:08:58 +0000640 Result.InstanceBits = NumInstanceMethodsAndBits & 0x3;
641 Result.FactoryBits = NumFactoryMethodsAndBits & 0x3;
642 unsigned NumInstanceMethods = NumInstanceMethodsAndBits >> 2;
643 unsigned NumFactoryMethods = NumFactoryMethodsAndBits >> 2;
Guy Benyei11169dd2012-12-18 14:30:41 +0000644
645 // Load instance methods
646 for (unsigned I = 0; I != NumInstanceMethods; ++I) {
Justin Bogner57ba0b22014-03-28 22:03:24 +0000647 if (ObjCMethodDecl *Method = Reader.GetLocalDeclAs<ObjCMethodDecl>(
648 F, endian::readNext<uint32_t, little, unaligned>(d)))
Guy Benyei11169dd2012-12-18 14:30:41 +0000649 Result.Instance.push_back(Method);
650 }
651
652 // Load factory methods
653 for (unsigned I = 0; I != NumFactoryMethods; ++I) {
Justin Bogner57ba0b22014-03-28 22:03:24 +0000654 if (ObjCMethodDecl *Method = Reader.GetLocalDeclAs<ObjCMethodDecl>(
655 F, endian::readNext<uint32_t, little, unaligned>(d)))
Guy Benyei11169dd2012-12-18 14:30:41 +0000656 Result.Factory.push_back(Method);
657 }
658
659 return Result;
660}
661
Douglas Gregorbfd73d72013-01-23 18:53:14 +0000662unsigned ASTIdentifierLookupTraitBase::ComputeHash(const internal_key_type& a) {
663 return llvm::HashString(a);
Guy Benyei11169dd2012-12-18 14:30:41 +0000664}
665
666std::pair<unsigned, unsigned>
Douglas Gregorbfd73d72013-01-23 18:53:14 +0000667ASTIdentifierLookupTraitBase::ReadKeyDataLength(const unsigned char*& d) {
Justin Bogner57ba0b22014-03-28 22:03:24 +0000668 using namespace llvm::support;
669 unsigned DataLen = endian::readNext<uint16_t, little, unaligned>(d);
670 unsigned KeyLen = endian::readNext<uint16_t, little, unaligned>(d);
Guy Benyei11169dd2012-12-18 14:30:41 +0000671 return std::make_pair(KeyLen, DataLen);
672}
673
Douglas Gregorbfd73d72013-01-23 18:53:14 +0000674ASTIdentifierLookupTraitBase::internal_key_type
675ASTIdentifierLookupTraitBase::ReadKey(const unsigned char* d, unsigned n) {
Guy Benyei11169dd2012-12-18 14:30:41 +0000676 assert(n >= 2 && d[n-1] == '\0');
Douglas Gregorbfd73d72013-01-23 18:53:14 +0000677 return StringRef((const char*) d, n-1);
Guy Benyei11169dd2012-12-18 14:30:41 +0000678}
679
Douglas Gregordcf25082013-02-11 18:16:18 +0000680/// \brief Whether the given identifier is "interesting".
681static bool isInterestingIdentifier(IdentifierInfo &II) {
682 return II.isPoisoned() ||
683 II.isExtensionToken() ||
684 II.getObjCOrBuiltinID() ||
685 II.hasRevertedTokenIDToIdentifier() ||
686 II.hadMacroDefinition() ||
687 II.getFETokenInfo<void>();
688}
689
Guy Benyei11169dd2012-12-18 14:30:41 +0000690IdentifierInfo *ASTIdentifierLookupTrait::ReadData(const internal_key_type& k,
691 const unsigned char* d,
692 unsigned DataLen) {
Justin Bogner57ba0b22014-03-28 22:03:24 +0000693 using namespace llvm::support;
694 unsigned RawID = endian::readNext<uint32_t, little, unaligned>(d);
Guy Benyei11169dd2012-12-18 14:30:41 +0000695 bool IsInteresting = RawID & 0x01;
696
697 // Wipe out the "is interesting" bit.
698 RawID = RawID >> 1;
699
700 IdentID ID = Reader.getGlobalIdentifierID(F, RawID);
701 if (!IsInteresting) {
702 // For uninteresting identifiers, just build the IdentifierInfo
703 // and associate it with the persistent ID.
704 IdentifierInfo *II = KnownII;
705 if (!II) {
Douglas Gregorbfd73d72013-01-23 18:53:14 +0000706 II = &Reader.getIdentifierTable().getOwn(k);
Guy Benyei11169dd2012-12-18 14:30:41 +0000707 KnownII = II;
708 }
709 Reader.SetIdentifierInfo(ID, II);
Douglas Gregordcf25082013-02-11 18:16:18 +0000710 if (!II->isFromAST()) {
711 bool WasInteresting = isInterestingIdentifier(*II);
712 II->setIsFromAST();
713 if (WasInteresting)
714 II->setChangedSinceDeserialization();
715 }
716 Reader.markIdentifierUpToDate(II);
Guy Benyei11169dd2012-12-18 14:30:41 +0000717 return II;
718 }
719
Justin Bogner57ba0b22014-03-28 22:03:24 +0000720 unsigned ObjCOrBuiltinID = endian::readNext<uint16_t, little, unaligned>(d);
721 unsigned Bits = endian::readNext<uint16_t, little, unaligned>(d);
Guy Benyei11169dd2012-12-18 14:30:41 +0000722 bool CPlusPlusOperatorKeyword = Bits & 0x01;
723 Bits >>= 1;
724 bool HasRevertedTokenIDToIdentifier = Bits & 0x01;
725 Bits >>= 1;
726 bool Poisoned = Bits & 0x01;
727 Bits >>= 1;
728 bool ExtensionToken = Bits & 0x01;
729 Bits >>= 1;
Argyrios Kyrtzidiseb663da2013-03-22 21:12:57 +0000730 bool hasSubmoduleMacros = Bits & 0x01;
731 Bits >>= 1;
Guy Benyei11169dd2012-12-18 14:30:41 +0000732 bool hadMacroDefinition = Bits & 0x01;
733 Bits >>= 1;
734
735 assert(Bits == 0 && "Extra bits in the identifier?");
736 DataLen -= 8;
737
738 // Build the IdentifierInfo itself and link the identifier ID with
739 // the new IdentifierInfo.
740 IdentifierInfo *II = KnownII;
741 if (!II) {
Douglas Gregorbfd73d72013-01-23 18:53:14 +0000742 II = &Reader.getIdentifierTable().getOwn(StringRef(k));
Guy Benyei11169dd2012-12-18 14:30:41 +0000743 KnownII = II;
744 }
745 Reader.markIdentifierUpToDate(II);
Douglas Gregordcf25082013-02-11 18:16:18 +0000746 if (!II->isFromAST()) {
747 bool WasInteresting = isInterestingIdentifier(*II);
748 II->setIsFromAST();
749 if (WasInteresting)
750 II->setChangedSinceDeserialization();
751 }
Guy Benyei11169dd2012-12-18 14:30:41 +0000752
753 // Set or check the various bits in the IdentifierInfo structure.
754 // Token IDs are read-only.
Argyrios Kyrtzidisddee8c92013-02-27 01:13:51 +0000755 if (HasRevertedTokenIDToIdentifier && II->getTokenID() != tok::identifier)
Guy Benyei11169dd2012-12-18 14:30:41 +0000756 II->RevertTokenIDToIdentifier();
757 II->setObjCOrBuiltinID(ObjCOrBuiltinID);
758 assert(II->isExtensionToken() == ExtensionToken &&
759 "Incorrect extension token flag");
760 (void)ExtensionToken;
761 if (Poisoned)
762 II->setIsPoisoned(true);
763 assert(II->isCPlusPlusOperatorKeyword() == CPlusPlusOperatorKeyword &&
764 "Incorrect C++ operator keyword flag");
765 (void)CPlusPlusOperatorKeyword;
766
767 // If this identifier is a macro, deserialize the macro
768 // definition.
769 if (hadMacroDefinition) {
Justin Bogner57ba0b22014-03-28 22:03:24 +0000770 uint32_t MacroDirectivesOffset =
771 endian::readNext<uint32_t, little, unaligned>(d);
Argyrios Kyrtzidiseb663da2013-03-22 21:12:57 +0000772 DataLen -= 4;
773 SmallVector<uint32_t, 8> LocalMacroIDs;
774 if (hasSubmoduleMacros) {
Richard Smithdaa69e02014-07-25 04:40:03 +0000775 while (true) {
776 uint32_t LocalMacroID =
777 endian::readNext<uint32_t, little, unaligned>(d);
Argyrios Kyrtzidiseb663da2013-03-22 21:12:57 +0000778 DataLen -= 4;
Richard Smithdaa69e02014-07-25 04:40:03 +0000779 if (LocalMacroID == 0xdeadbeef) break;
Argyrios Kyrtzidiseb663da2013-03-22 21:12:57 +0000780 LocalMacroIDs.push_back(LocalMacroID);
781 }
Argyrios Kyrtzidis719736c2013-01-19 03:14:56 +0000782 }
Argyrios Kyrtzidiseb663da2013-03-22 21:12:57 +0000783
784 if (F.Kind == MK_Module) {
Richard Smith49f906a2014-03-01 00:08:04 +0000785 // Macro definitions are stored from newest to oldest, so reverse them
786 // before registering them.
787 llvm::SmallVector<unsigned, 8> MacroSizes;
Argyrios Kyrtzidiseb663da2013-03-22 21:12:57 +0000788 for (SmallVectorImpl<uint32_t>::iterator
Richard Smith49f906a2014-03-01 00:08:04 +0000789 I = LocalMacroIDs.begin(), E = LocalMacroIDs.end(); I != E; /**/) {
790 unsigned Size = 1;
791
792 static const uint32_t HasOverridesFlag = 0x80000000U;
793 if (I + 1 != E && (I[1] & HasOverridesFlag))
794 Size += 1 + (I[1] & ~HasOverridesFlag);
795
796 MacroSizes.push_back(Size);
797 I += Size;
Argyrios Kyrtzidiseb663da2013-03-22 21:12:57 +0000798 }
Richard Smith49f906a2014-03-01 00:08:04 +0000799
800 SmallVectorImpl<uint32_t>::iterator I = LocalMacroIDs.end();
801 for (SmallVectorImpl<unsigned>::reverse_iterator SI = MacroSizes.rbegin(),
802 SE = MacroSizes.rend();
803 SI != SE; ++SI) {
804 I -= *SI;
805
806 uint32_t LocalMacroID = *I;
Craig Topper00bbdcf2014-06-28 23:22:23 +0000807 ArrayRef<uint32_t> Overrides;
Richard Smith49f906a2014-03-01 00:08:04 +0000808 if (*SI != 1)
809 Overrides = llvm::makeArrayRef(&I[2], *SI - 2);
810 Reader.addPendingMacroFromModule(II, &F, LocalMacroID, Overrides);
811 }
812 assert(I == LocalMacroIDs.begin());
Argyrios Kyrtzidiseb663da2013-03-22 21:12:57 +0000813 } else {
814 Reader.addPendingMacroFromPCH(II, &F, MacroDirectivesOffset);
815 }
Guy Benyei11169dd2012-12-18 14:30:41 +0000816 }
817
818 Reader.SetIdentifierInfo(ID, II);
819
820 // Read all of the declarations visible at global scope with this
821 // name.
822 if (DataLen > 0) {
823 SmallVector<uint32_t, 4> DeclIDs;
824 for (; DataLen > 0; DataLen -= 4)
Justin Bogner57ba0b22014-03-28 22:03:24 +0000825 DeclIDs.push_back(Reader.getGlobalDeclID(
826 F, endian::readNext<uint32_t, little, unaligned>(d)));
Guy Benyei11169dd2012-12-18 14:30:41 +0000827 Reader.SetGloballyVisibleDecls(II, DeclIDs);
828 }
829
830 return II;
831}
832
833unsigned
834ASTDeclContextNameLookupTrait::ComputeHash(const DeclNameKey &Key) const {
835 llvm::FoldingSetNodeID ID;
836 ID.AddInteger(Key.Kind);
837
838 switch (Key.Kind) {
839 case DeclarationName::Identifier:
840 case DeclarationName::CXXLiteralOperatorName:
841 ID.AddString(((IdentifierInfo*)Key.Data)->getName());
842 break;
843 case DeclarationName::ObjCZeroArgSelector:
844 case DeclarationName::ObjCOneArgSelector:
845 case DeclarationName::ObjCMultiArgSelector:
846 ID.AddInteger(serialization::ComputeHash(Selector(Key.Data)));
847 break;
848 case DeclarationName::CXXOperatorName:
849 ID.AddInteger((OverloadedOperatorKind)Key.Data);
850 break;
851 case DeclarationName::CXXConstructorName:
852 case DeclarationName::CXXDestructorName:
853 case DeclarationName::CXXConversionFunctionName:
854 case DeclarationName::CXXUsingDirective:
855 break;
856 }
857
858 return ID.ComputeHash();
859}
860
861ASTDeclContextNameLookupTrait::internal_key_type
862ASTDeclContextNameLookupTrait::GetInternalKey(
863 const external_key_type& Name) const {
864 DeclNameKey Key;
865 Key.Kind = Name.getNameKind();
866 switch (Name.getNameKind()) {
867 case DeclarationName::Identifier:
868 Key.Data = (uint64_t)Name.getAsIdentifierInfo();
869 break;
870 case DeclarationName::ObjCZeroArgSelector:
871 case DeclarationName::ObjCOneArgSelector:
872 case DeclarationName::ObjCMultiArgSelector:
873 Key.Data = (uint64_t)Name.getObjCSelector().getAsOpaquePtr();
874 break;
875 case DeclarationName::CXXOperatorName:
876 Key.Data = Name.getCXXOverloadedOperator();
877 break;
878 case DeclarationName::CXXLiteralOperatorName:
879 Key.Data = (uint64_t)Name.getCXXLiteralIdentifier();
880 break;
881 case DeclarationName::CXXConstructorName:
882 case DeclarationName::CXXDestructorName:
883 case DeclarationName::CXXConversionFunctionName:
884 case DeclarationName::CXXUsingDirective:
885 Key.Data = 0;
886 break;
887 }
888
889 return Key;
890}
891
892std::pair<unsigned, unsigned>
893ASTDeclContextNameLookupTrait::ReadKeyDataLength(const unsigned char*& d) {
Justin Bogner57ba0b22014-03-28 22:03:24 +0000894 using namespace llvm::support;
895 unsigned KeyLen = endian::readNext<uint16_t, little, unaligned>(d);
896 unsigned DataLen = endian::readNext<uint16_t, little, unaligned>(d);
Guy Benyei11169dd2012-12-18 14:30:41 +0000897 return std::make_pair(KeyLen, DataLen);
898}
899
900ASTDeclContextNameLookupTrait::internal_key_type
901ASTDeclContextNameLookupTrait::ReadKey(const unsigned char* d, unsigned) {
Justin Bogner57ba0b22014-03-28 22:03:24 +0000902 using namespace llvm::support;
Guy Benyei11169dd2012-12-18 14:30:41 +0000903
904 DeclNameKey Key;
905 Key.Kind = (DeclarationName::NameKind)*d++;
906 switch (Key.Kind) {
907 case DeclarationName::Identifier:
Justin Bogner57ba0b22014-03-28 22:03:24 +0000908 Key.Data = (uint64_t)Reader.getLocalIdentifier(
909 F, endian::readNext<uint32_t, little, unaligned>(d));
Guy Benyei11169dd2012-12-18 14:30:41 +0000910 break;
911 case DeclarationName::ObjCZeroArgSelector:
912 case DeclarationName::ObjCOneArgSelector:
913 case DeclarationName::ObjCMultiArgSelector:
914 Key.Data =
Justin Bogner57ba0b22014-03-28 22:03:24 +0000915 (uint64_t)Reader.getLocalSelector(
916 F, endian::readNext<uint32_t, little, unaligned>(
917 d)).getAsOpaquePtr();
Guy Benyei11169dd2012-12-18 14:30:41 +0000918 break;
919 case DeclarationName::CXXOperatorName:
920 Key.Data = *d++; // OverloadedOperatorKind
921 break;
922 case DeclarationName::CXXLiteralOperatorName:
Justin Bogner57ba0b22014-03-28 22:03:24 +0000923 Key.Data = (uint64_t)Reader.getLocalIdentifier(
924 F, endian::readNext<uint32_t, little, unaligned>(d));
Guy Benyei11169dd2012-12-18 14:30:41 +0000925 break;
926 case DeclarationName::CXXConstructorName:
927 case DeclarationName::CXXDestructorName:
928 case DeclarationName::CXXConversionFunctionName:
929 case DeclarationName::CXXUsingDirective:
930 Key.Data = 0;
931 break;
932 }
933
934 return Key;
935}
936
937ASTDeclContextNameLookupTrait::data_type
938ASTDeclContextNameLookupTrait::ReadData(internal_key_type,
939 const unsigned char* d,
940 unsigned DataLen) {
Justin Bogner57ba0b22014-03-28 22:03:24 +0000941 using namespace llvm::support;
942 unsigned NumDecls = endian::readNext<uint16_t, little, unaligned>(d);
Argyrios Kyrtzidisc57e5032013-01-11 22:29:49 +0000943 LE32DeclID *Start = reinterpret_cast<LE32DeclID *>(
944 const_cast<unsigned char *>(d));
Guy Benyei11169dd2012-12-18 14:30:41 +0000945 return std::make_pair(Start, Start + NumDecls);
946}
947
948bool ASTReader::ReadDeclContextStorage(ModuleFile &M,
Chris Lattner7fb3bef2013-01-20 00:56:42 +0000949 BitstreamCursor &Cursor,
Guy Benyei11169dd2012-12-18 14:30:41 +0000950 const std::pair<uint64_t, uint64_t> &Offsets,
951 DeclContextInfo &Info) {
952 SavedStreamPosition SavedPosition(Cursor);
953 // First the lexical decls.
954 if (Offsets.first != 0) {
955 Cursor.JumpToBit(Offsets.first);
956
957 RecordData Record;
Chris Lattner0e6c9402013-01-20 02:38:54 +0000958 StringRef Blob;
Guy Benyei11169dd2012-12-18 14:30:41 +0000959 unsigned Code = Cursor.ReadCode();
Chris Lattner0e6c9402013-01-20 02:38:54 +0000960 unsigned RecCode = Cursor.readRecord(Code, Record, &Blob);
Guy Benyei11169dd2012-12-18 14:30:41 +0000961 if (RecCode != DECL_CONTEXT_LEXICAL) {
962 Error("Expected lexical block");
963 return true;
964 }
965
Chris Lattner0e6c9402013-01-20 02:38:54 +0000966 Info.LexicalDecls = reinterpret_cast<const KindDeclIDPair*>(Blob.data());
967 Info.NumLexicalDecls = Blob.size() / sizeof(KindDeclIDPair);
Guy Benyei11169dd2012-12-18 14:30:41 +0000968 }
969
970 // Now the lookup table.
971 if (Offsets.second != 0) {
972 Cursor.JumpToBit(Offsets.second);
973
974 RecordData Record;
Chris Lattner0e6c9402013-01-20 02:38:54 +0000975 StringRef Blob;
Guy Benyei11169dd2012-12-18 14:30:41 +0000976 unsigned Code = Cursor.ReadCode();
Chris Lattner0e6c9402013-01-20 02:38:54 +0000977 unsigned RecCode = Cursor.readRecord(Code, Record, &Blob);
Guy Benyei11169dd2012-12-18 14:30:41 +0000978 if (RecCode != DECL_CONTEXT_VISIBLE) {
979 Error("Expected visible lookup table block");
980 return true;
981 }
Justin Bognerda4e6502014-04-14 16:34:29 +0000982 Info.NameLookupTableData = ASTDeclContextNameLookupTable::Create(
983 (const unsigned char *)Blob.data() + Record[0],
984 (const unsigned char *)Blob.data() + sizeof(uint32_t),
985 (const unsigned char *)Blob.data(),
986 ASTDeclContextNameLookupTrait(*this, M));
Guy Benyei11169dd2012-12-18 14:30:41 +0000987 }
988
989 return false;
990}
991
992void ASTReader::Error(StringRef Msg) {
993 Error(diag::err_fe_pch_malformed, Msg);
Douglas Gregor940e8052013-05-10 22:15:13 +0000994 if (Context.getLangOpts().Modules && !Diags.isDiagnosticInFlight()) {
995 Diag(diag::note_module_cache_path)
996 << PP.getHeaderSearchInfo().getModuleCachePath();
997 }
Guy Benyei11169dd2012-12-18 14:30:41 +0000998}
999
1000void ASTReader::Error(unsigned DiagID,
1001 StringRef Arg1, StringRef Arg2) {
1002 if (Diags.isDiagnosticInFlight())
1003 Diags.SetDelayedDiagnostic(DiagID, Arg1, Arg2);
1004 else
1005 Diag(DiagID) << Arg1 << Arg2;
1006}
1007
1008//===----------------------------------------------------------------------===//
1009// Source Manager Deserialization
1010//===----------------------------------------------------------------------===//
1011
1012/// \brief Read the line table in the source manager block.
1013/// \returns true if there was an error.
1014bool ASTReader::ParseLineTable(ModuleFile &F,
1015 SmallVectorImpl<uint64_t> &Record) {
1016 unsigned Idx = 0;
1017 LineTableInfo &LineTable = SourceMgr.getLineTable();
1018
1019 // Parse the file names
1020 std::map<int, int> FileIDs;
1021 for (int I = 0, N = Record[Idx++]; I != N; ++I) {
1022 // Extract the file name
1023 unsigned FilenameLen = Record[Idx++];
1024 std::string Filename(&Record[Idx], &Record[Idx] + FilenameLen);
1025 Idx += FilenameLen;
1026 MaybeAddSystemRootToFilename(F, Filename);
1027 FileIDs[I] = LineTable.getLineTableFilenameID(Filename);
1028 }
1029
1030 // Parse the line entries
1031 std::vector<LineEntry> Entries;
1032 while (Idx < Record.size()) {
1033 int FID = Record[Idx++];
1034 assert(FID >= 0 && "Serialized line entries for non-local file.");
1035 // Remap FileID from 1-based old view.
1036 FID += F.SLocEntryBaseID - 1;
1037
1038 // Extract the line entries
1039 unsigned NumEntries = Record[Idx++];
1040 assert(NumEntries && "Numentries is 00000");
1041 Entries.clear();
1042 Entries.reserve(NumEntries);
1043 for (unsigned I = 0; I != NumEntries; ++I) {
1044 unsigned FileOffset = Record[Idx++];
1045 unsigned LineNo = Record[Idx++];
1046 int FilenameID = FileIDs[Record[Idx++]];
1047 SrcMgr::CharacteristicKind FileKind
1048 = (SrcMgr::CharacteristicKind)Record[Idx++];
1049 unsigned IncludeOffset = Record[Idx++];
1050 Entries.push_back(LineEntry::get(FileOffset, LineNo, FilenameID,
1051 FileKind, IncludeOffset));
1052 }
1053 LineTable.AddEntry(FileID::get(FID), Entries);
1054 }
1055
1056 return false;
1057}
1058
1059/// \brief Read a source manager block
1060bool ASTReader::ReadSourceManagerBlock(ModuleFile &F) {
1061 using namespace SrcMgr;
1062
Chris Lattner7fb3bef2013-01-20 00:56:42 +00001063 BitstreamCursor &SLocEntryCursor = F.SLocEntryCursor;
Guy Benyei11169dd2012-12-18 14:30:41 +00001064
1065 // Set the source-location entry cursor to the current position in
1066 // the stream. This cursor will be used to read the contents of the
1067 // source manager block initially, and then lazily read
1068 // source-location entries as needed.
1069 SLocEntryCursor = F.Stream;
1070
1071 // The stream itself is going to skip over the source manager block.
1072 if (F.Stream.SkipBlock()) {
1073 Error("malformed block record in AST file");
1074 return true;
1075 }
1076
1077 // Enter the source manager block.
1078 if (SLocEntryCursor.EnterSubBlock(SOURCE_MANAGER_BLOCK_ID)) {
1079 Error("malformed source manager block record in AST file");
1080 return true;
1081 }
1082
1083 RecordData Record;
1084 while (true) {
Chris Lattnere7b154b2013-01-19 21:39:22 +00001085 llvm::BitstreamEntry E = SLocEntryCursor.advanceSkippingSubblocks();
1086
1087 switch (E.Kind) {
1088 case llvm::BitstreamEntry::SubBlock: // Handled for us already.
1089 case llvm::BitstreamEntry::Error:
1090 Error("malformed block record in AST file");
1091 return true;
1092 case llvm::BitstreamEntry::EndBlock:
Guy Benyei11169dd2012-12-18 14:30:41 +00001093 return false;
Chris Lattnere7b154b2013-01-19 21:39:22 +00001094 case llvm::BitstreamEntry::Record:
1095 // The interesting case.
1096 break;
Guy Benyei11169dd2012-12-18 14:30:41 +00001097 }
Chris Lattnere7b154b2013-01-19 21:39:22 +00001098
Guy Benyei11169dd2012-12-18 14:30:41 +00001099 // Read a record.
Guy Benyei11169dd2012-12-18 14:30:41 +00001100 Record.clear();
Chris Lattner15c3e7d2013-01-21 18:28:26 +00001101 StringRef Blob;
1102 switch (SLocEntryCursor.readRecord(E.ID, Record, &Blob)) {
Guy Benyei11169dd2012-12-18 14:30:41 +00001103 default: // Default behavior: ignore.
1104 break;
1105
1106 case SM_SLOC_FILE_ENTRY:
1107 case SM_SLOC_BUFFER_ENTRY:
1108 case SM_SLOC_EXPANSION_ENTRY:
1109 // Once we hit one of the source location entries, we're done.
1110 return false;
1111 }
1112 }
1113}
1114
1115/// \brief If a header file is not found at the path that we expect it to be
1116/// and the PCH file was moved from its original location, try to resolve the
1117/// file by assuming that header+PCH were moved together and the header is in
1118/// the same place relative to the PCH.
1119static std::string
1120resolveFileRelativeToOriginalDir(const std::string &Filename,
1121 const std::string &OriginalDir,
1122 const std::string &CurrDir) {
1123 assert(OriginalDir != CurrDir &&
1124 "No point trying to resolve the file if the PCH dir didn't change");
1125 using namespace llvm::sys;
1126 SmallString<128> filePath(Filename);
1127 fs::make_absolute(filePath);
1128 assert(path::is_absolute(OriginalDir));
1129 SmallString<128> currPCHPath(CurrDir);
1130
1131 path::const_iterator fileDirI = path::begin(path::parent_path(filePath)),
1132 fileDirE = path::end(path::parent_path(filePath));
1133 path::const_iterator origDirI = path::begin(OriginalDir),
1134 origDirE = path::end(OriginalDir);
1135 // Skip the common path components from filePath and OriginalDir.
1136 while (fileDirI != fileDirE && origDirI != origDirE &&
1137 *fileDirI == *origDirI) {
1138 ++fileDirI;
1139 ++origDirI;
1140 }
1141 for (; origDirI != origDirE; ++origDirI)
1142 path::append(currPCHPath, "..");
1143 path::append(currPCHPath, fileDirI, fileDirE);
1144 path::append(currPCHPath, path::filename(Filename));
1145 return currPCHPath.str();
1146}
1147
1148bool ASTReader::ReadSLocEntry(int ID) {
1149 if (ID == 0)
1150 return false;
1151
1152 if (unsigned(-ID) - 2 >= getTotalNumSLocs() || ID > 0) {
1153 Error("source location entry ID out-of-range for AST file");
1154 return true;
1155 }
1156
1157 ModuleFile *F = GlobalSLocEntryMap.find(-ID)->second;
1158 F->SLocEntryCursor.JumpToBit(F->SLocEntryOffsets[ID - F->SLocEntryBaseID]);
Chris Lattner7fb3bef2013-01-20 00:56:42 +00001159 BitstreamCursor &SLocEntryCursor = F->SLocEntryCursor;
Guy Benyei11169dd2012-12-18 14:30:41 +00001160 unsigned BaseOffset = F->SLocEntryBaseOffset;
1161
1162 ++NumSLocEntriesRead;
Chris Lattnere7b154b2013-01-19 21:39:22 +00001163 llvm::BitstreamEntry Entry = SLocEntryCursor.advance();
1164 if (Entry.Kind != llvm::BitstreamEntry::Record) {
Guy Benyei11169dd2012-12-18 14:30:41 +00001165 Error("incorrectly-formatted source location entry in AST file");
1166 return true;
1167 }
Chris Lattnere7b154b2013-01-19 21:39:22 +00001168
Guy Benyei11169dd2012-12-18 14:30:41 +00001169 RecordData Record;
Chris Lattner0e6c9402013-01-20 02:38:54 +00001170 StringRef Blob;
1171 switch (SLocEntryCursor.readRecord(Entry.ID, Record, &Blob)) {
Guy Benyei11169dd2012-12-18 14:30:41 +00001172 default:
1173 Error("incorrectly-formatted source location entry in AST file");
1174 return true;
1175
1176 case SM_SLOC_FILE_ENTRY: {
1177 // We will detect whether a file changed and return 'Failure' for it, but
1178 // we will also try to fail gracefully by setting up the SLocEntry.
1179 unsigned InputID = Record[4];
1180 InputFile IF = getInputFile(*F, InputID);
Argyrios Kyrtzidis61c3d872013-03-01 03:26:04 +00001181 const FileEntry *File = IF.getFile();
1182 bool OverriddenBuffer = IF.isOverridden();
Guy Benyei11169dd2012-12-18 14:30:41 +00001183
Argyrios Kyrtzidis61c3d872013-03-01 03:26:04 +00001184 // Note that we only check if a File was returned. If it was out-of-date
1185 // we have complained but we will continue creating a FileID to recover
1186 // gracefully.
1187 if (!File)
Guy Benyei11169dd2012-12-18 14:30:41 +00001188 return true;
1189
1190 SourceLocation IncludeLoc = ReadSourceLocation(*F, Record[1]);
1191 if (IncludeLoc.isInvalid() && F->Kind != MK_MainFile) {
1192 // This is the module's main file.
1193 IncludeLoc = getImportLocation(F);
1194 }
1195 SrcMgr::CharacteristicKind
1196 FileCharacter = (SrcMgr::CharacteristicKind)Record[2];
1197 FileID FID = SourceMgr.createFileID(File, IncludeLoc, FileCharacter,
1198 ID, BaseOffset + Record[0]);
1199 SrcMgr::FileInfo &FileInfo =
1200 const_cast<SrcMgr::FileInfo&>(SourceMgr.getSLocEntry(FID).getFile());
1201 FileInfo.NumCreatedFIDs = Record[5];
1202 if (Record[3])
1203 FileInfo.setHasLineDirectives();
1204
1205 const DeclID *FirstDecl = F->FileSortedDecls + Record[6];
1206 unsigned NumFileDecls = Record[7];
1207 if (NumFileDecls) {
1208 assert(F->FileSortedDecls && "FILE_SORTED_DECLS not encountered yet ?");
1209 FileDeclIDs[FID] = FileDeclsInfo(F, llvm::makeArrayRef(FirstDecl,
1210 NumFileDecls));
1211 }
1212
1213 const SrcMgr::ContentCache *ContentCache
1214 = SourceMgr.getOrCreateContentCache(File,
1215 /*isSystemFile=*/FileCharacter != SrcMgr::C_User);
1216 if (OverriddenBuffer && !ContentCache->BufferOverridden &&
1217 ContentCache->ContentsEntry == ContentCache->OrigEntry) {
1218 unsigned Code = SLocEntryCursor.ReadCode();
1219 Record.clear();
Chris Lattner0e6c9402013-01-20 02:38:54 +00001220 unsigned RecCode = SLocEntryCursor.readRecord(Code, Record, &Blob);
Guy Benyei11169dd2012-12-18 14:30:41 +00001221
1222 if (RecCode != SM_SLOC_BUFFER_BLOB) {
1223 Error("AST record has invalid code");
1224 return true;
1225 }
1226
1227 llvm::MemoryBuffer *Buffer
Chris Lattner0e6c9402013-01-20 02:38:54 +00001228 = llvm::MemoryBuffer::getMemBuffer(Blob.drop_back(1), File->getName());
Guy Benyei11169dd2012-12-18 14:30:41 +00001229 SourceMgr.overrideFileContents(File, Buffer);
1230 }
1231
1232 break;
1233 }
1234
1235 case SM_SLOC_BUFFER_ENTRY: {
Chris Lattner0e6c9402013-01-20 02:38:54 +00001236 const char *Name = Blob.data();
Guy Benyei11169dd2012-12-18 14:30:41 +00001237 unsigned Offset = Record[0];
1238 SrcMgr::CharacteristicKind
1239 FileCharacter = (SrcMgr::CharacteristicKind)Record[2];
1240 SourceLocation IncludeLoc = ReadSourceLocation(*F, Record[1]);
1241 if (IncludeLoc.isInvalid() && F->Kind == MK_Module) {
1242 IncludeLoc = getImportLocation(F);
1243 }
1244 unsigned Code = SLocEntryCursor.ReadCode();
1245 Record.clear();
1246 unsigned RecCode
Chris Lattner0e6c9402013-01-20 02:38:54 +00001247 = SLocEntryCursor.readRecord(Code, Record, &Blob);
Guy Benyei11169dd2012-12-18 14:30:41 +00001248
1249 if (RecCode != SM_SLOC_BUFFER_BLOB) {
1250 Error("AST record has invalid code");
1251 return true;
1252 }
1253
1254 llvm::MemoryBuffer *Buffer
Chris Lattner0e6c9402013-01-20 02:38:54 +00001255 = llvm::MemoryBuffer::getMemBuffer(Blob.drop_back(1), Name);
Alp Toker6ac2cd02014-05-16 17:23:01 +00001256 SourceMgr.createFileID(Buffer, FileCharacter, ID, BaseOffset + Offset,
1257 IncludeLoc);
Guy Benyei11169dd2012-12-18 14:30:41 +00001258 break;
1259 }
1260
1261 case SM_SLOC_EXPANSION_ENTRY: {
1262 SourceLocation SpellingLoc = ReadSourceLocation(*F, Record[1]);
1263 SourceMgr.createExpansionLoc(SpellingLoc,
1264 ReadSourceLocation(*F, Record[2]),
1265 ReadSourceLocation(*F, Record[3]),
1266 Record[4],
1267 ID,
1268 BaseOffset + Record[0]);
1269 break;
1270 }
1271 }
1272
1273 return false;
1274}
1275
1276std::pair<SourceLocation, StringRef> ASTReader::getModuleImportLoc(int ID) {
1277 if (ID == 0)
1278 return std::make_pair(SourceLocation(), "");
1279
1280 if (unsigned(-ID) - 2 >= getTotalNumSLocs() || ID > 0) {
1281 Error("source location entry ID out-of-range for AST file");
1282 return std::make_pair(SourceLocation(), "");
1283 }
1284
1285 // Find which module file this entry lands in.
1286 ModuleFile *M = GlobalSLocEntryMap.find(-ID)->second;
1287 if (M->Kind != MK_Module)
1288 return std::make_pair(SourceLocation(), "");
1289
1290 // FIXME: Can we map this down to a particular submodule? That would be
1291 // ideal.
Ben Langmuirbeee15e2014-04-14 18:00:01 +00001292 return std::make_pair(M->ImportLoc, StringRef(M->ModuleName));
Guy Benyei11169dd2012-12-18 14:30:41 +00001293}
1294
1295/// \brief Find the location where the module F is imported.
1296SourceLocation ASTReader::getImportLocation(ModuleFile *F) {
1297 if (F->ImportLoc.isValid())
1298 return F->ImportLoc;
1299
1300 // Otherwise we have a PCH. It's considered to be "imported" at the first
1301 // location of its includer.
1302 if (F->ImportedBy.empty() || !F->ImportedBy[0]) {
Ben Langmuirbeee15e2014-04-14 18:00:01 +00001303 // Main file is the importer.
1304 assert(!SourceMgr.getMainFileID().isInvalid() && "missing main file");
1305 return SourceMgr.getLocForStartOfFile(SourceMgr.getMainFileID());
Guy Benyei11169dd2012-12-18 14:30:41 +00001306 }
Guy Benyei11169dd2012-12-18 14:30:41 +00001307 return F->ImportedBy[0]->FirstLoc;
1308}
1309
1310/// ReadBlockAbbrevs - Enter a subblock of the specified BlockID with the
1311/// specified cursor. Read the abbreviations that are at the top of the block
1312/// and then leave the cursor pointing into the block.
Chris Lattner7fb3bef2013-01-20 00:56:42 +00001313bool ASTReader::ReadBlockAbbrevs(BitstreamCursor &Cursor, unsigned BlockID) {
Guy Benyei11169dd2012-12-18 14:30:41 +00001314 if (Cursor.EnterSubBlock(BlockID)) {
1315 Error("malformed block record in AST file");
1316 return Failure;
1317 }
1318
1319 while (true) {
1320 uint64_t Offset = Cursor.GetCurrentBitNo();
1321 unsigned Code = Cursor.ReadCode();
1322
1323 // We expect all abbrevs to be at the start of the block.
1324 if (Code != llvm::bitc::DEFINE_ABBREV) {
1325 Cursor.JumpToBit(Offset);
1326 return false;
1327 }
1328 Cursor.ReadAbbrevRecord();
1329 }
1330}
1331
Richard Smithe40f2ba2013-08-07 21:41:30 +00001332Token ASTReader::ReadToken(ModuleFile &F, const RecordDataImpl &Record,
John McCallf413f5e2013-05-03 00:10:13 +00001333 unsigned &Idx) {
1334 Token Tok;
1335 Tok.startToken();
1336 Tok.setLocation(ReadSourceLocation(F, Record, Idx));
1337 Tok.setLength(Record[Idx++]);
1338 if (IdentifierInfo *II = getLocalIdentifier(F, Record[Idx++]))
1339 Tok.setIdentifierInfo(II);
1340 Tok.setKind((tok::TokenKind)Record[Idx++]);
1341 Tok.setFlag((Token::TokenFlags)Record[Idx++]);
1342 return Tok;
1343}
1344
Argyrios Kyrtzidiseb663da2013-03-22 21:12:57 +00001345MacroInfo *ASTReader::ReadMacroRecord(ModuleFile &F, uint64_t Offset) {
Chris Lattner7fb3bef2013-01-20 00:56:42 +00001346 BitstreamCursor &Stream = F.MacroCursor;
Guy Benyei11169dd2012-12-18 14:30:41 +00001347
1348 // Keep track of where we are in the stream, then jump back there
1349 // after reading this macro.
1350 SavedStreamPosition SavedPosition(Stream);
1351
1352 Stream.JumpToBit(Offset);
1353 RecordData Record;
1354 SmallVector<IdentifierInfo*, 16> MacroArgs;
Craig Toppera13603a2014-05-22 05:54:18 +00001355 MacroInfo *Macro = nullptr;
Guy Benyei11169dd2012-12-18 14:30:41 +00001356
Guy Benyei11169dd2012-12-18 14:30:41 +00001357 while (true) {
Chris Lattnerefa77172013-01-20 00:00:22 +00001358 // Advance to the next record, but if we get to the end of the block, don't
1359 // pop it (removing all the abbreviations from the cursor) since we want to
1360 // be able to reseek within the block and read entries.
Chris Lattner7fb3bef2013-01-20 00:56:42 +00001361 unsigned Flags = BitstreamCursor::AF_DontPopBlockAtEnd;
Chris Lattnerefa77172013-01-20 00:00:22 +00001362 llvm::BitstreamEntry Entry = Stream.advanceSkippingSubblocks(Flags);
1363
1364 switch (Entry.Kind) {
1365 case llvm::BitstreamEntry::SubBlock: // Handled for us already.
1366 case llvm::BitstreamEntry::Error:
1367 Error("malformed block record in AST file");
Argyrios Kyrtzidiseb663da2013-03-22 21:12:57 +00001368 return Macro;
Chris Lattnerefa77172013-01-20 00:00:22 +00001369 case llvm::BitstreamEntry::EndBlock:
Argyrios Kyrtzidiseb663da2013-03-22 21:12:57 +00001370 return Macro;
Chris Lattnerefa77172013-01-20 00:00:22 +00001371 case llvm::BitstreamEntry::Record:
1372 // The interesting case.
1373 break;
Guy Benyei11169dd2012-12-18 14:30:41 +00001374 }
1375
1376 // Read a record.
Guy Benyei11169dd2012-12-18 14:30:41 +00001377 Record.clear();
1378 PreprocessorRecordTypes RecType =
Chris Lattner0e6c9402013-01-20 02:38:54 +00001379 (PreprocessorRecordTypes)Stream.readRecord(Entry.ID, Record);
Guy Benyei11169dd2012-12-18 14:30:41 +00001380 switch (RecType) {
Argyrios Kyrtzidiseb663da2013-03-22 21:12:57 +00001381 case PP_MACRO_DIRECTIVE_HISTORY:
1382 return Macro;
1383
Guy Benyei11169dd2012-12-18 14:30:41 +00001384 case PP_MACRO_OBJECT_LIKE:
1385 case PP_MACRO_FUNCTION_LIKE: {
1386 // If we already have a macro, that means that we've hit the end
1387 // of the definition of the macro we were looking for. We're
1388 // done.
1389 if (Macro)
Argyrios Kyrtzidiseb663da2013-03-22 21:12:57 +00001390 return Macro;
Guy Benyei11169dd2012-12-18 14:30:41 +00001391
Argyrios Kyrtzidiseb663da2013-03-22 21:12:57 +00001392 unsigned NextIndex = 1; // Skip identifier ID.
1393 SubmoduleID SubModID = getGlobalSubmoduleID(F, Record[NextIndex++]);
Guy Benyei11169dd2012-12-18 14:30:41 +00001394 SourceLocation Loc = ReadSourceLocation(F, Record, NextIndex);
Argyrios Kyrtzidiseb663da2013-03-22 21:12:57 +00001395 MacroInfo *MI = PP.AllocateDeserializedMacroInfo(Loc, SubModID);
Argyrios Kyrtzidis7572be22013-01-07 19:16:23 +00001396 MI->setDefinitionEndLoc(ReadSourceLocation(F, Record, NextIndex));
Guy Benyei11169dd2012-12-18 14:30:41 +00001397 MI->setIsUsed(Record[NextIndex++]);
Argyrios Kyrtzidis9ef53ce2014-04-09 18:21:23 +00001398 MI->setUsedForHeaderGuard(Record[NextIndex++]);
Guy Benyei11169dd2012-12-18 14:30:41 +00001399
Guy Benyei11169dd2012-12-18 14:30:41 +00001400 if (RecType == PP_MACRO_FUNCTION_LIKE) {
1401 // Decode function-like macro info.
1402 bool isC99VarArgs = Record[NextIndex++];
1403 bool isGNUVarArgs = Record[NextIndex++];
1404 bool hasCommaPasting = Record[NextIndex++];
1405 MacroArgs.clear();
1406 unsigned NumArgs = Record[NextIndex++];
1407 for (unsigned i = 0; i != NumArgs; ++i)
1408 MacroArgs.push_back(getLocalIdentifier(F, Record[NextIndex++]));
1409
1410 // Install function-like macro info.
1411 MI->setIsFunctionLike();
1412 if (isC99VarArgs) MI->setIsC99Varargs();
1413 if (isGNUVarArgs) MI->setIsGNUVarargs();
1414 if (hasCommaPasting) MI->setHasCommaPasting();
1415 MI->setArgumentList(MacroArgs.data(), MacroArgs.size(),
1416 PP.getPreprocessorAllocator());
1417 }
1418
Guy Benyei11169dd2012-12-18 14:30:41 +00001419 // Remember that we saw this macro last so that we add the tokens that
1420 // form its body to it.
1421 Macro = MI;
1422
1423 if (NextIndex + 1 == Record.size() && PP.getPreprocessingRecord() &&
1424 Record[NextIndex]) {
1425 // We have a macro definition. Register the association
1426 PreprocessedEntityID
1427 GlobalID = getGlobalPreprocessedEntityID(F, Record[NextIndex]);
1428 PreprocessingRecord &PPRec = *PP.getPreprocessingRecord();
Argyrios Kyrtzidis832de9f2013-02-22 18:35:59 +00001429 PreprocessingRecord::PPEntityID
1430 PPID = PPRec.getPPEntityID(GlobalID-1, /*isLoaded=*/true);
1431 MacroDefinition *PPDef =
1432 cast_or_null<MacroDefinition>(PPRec.getPreprocessedEntity(PPID));
1433 if (PPDef)
1434 PPRec.RegisterMacroDefinition(Macro, PPDef);
Guy Benyei11169dd2012-12-18 14:30:41 +00001435 }
1436
1437 ++NumMacrosRead;
1438 break;
1439 }
1440
1441 case PP_TOKEN: {
1442 // If we see a TOKEN before a PP_MACRO_*, then the file is
1443 // erroneous, just pretend we didn't see this.
Craig Toppera13603a2014-05-22 05:54:18 +00001444 if (!Macro) break;
Guy Benyei11169dd2012-12-18 14:30:41 +00001445
John McCallf413f5e2013-05-03 00:10:13 +00001446 unsigned Idx = 0;
1447 Token Tok = ReadToken(F, Record, Idx);
Guy Benyei11169dd2012-12-18 14:30:41 +00001448 Macro->AddTokenToBody(Tok);
1449 break;
1450 }
1451 }
1452 }
1453}
1454
1455PreprocessedEntityID
1456ASTReader::getGlobalPreprocessedEntityID(ModuleFile &M, unsigned LocalID) const {
1457 ContinuousRangeMap<uint32_t, int, 2>::const_iterator
1458 I = M.PreprocessedEntityRemap.find(LocalID - NUM_PREDEF_PP_ENTITY_IDS);
1459 assert(I != M.PreprocessedEntityRemap.end()
1460 && "Invalid index into preprocessed entity index remap");
1461
1462 return LocalID + I->second;
1463}
1464
Argyrios Kyrtzidis5c2a3452013-03-06 18:12:47 +00001465unsigned HeaderFileInfoTrait::ComputeHash(internal_key_ref ikey) {
1466 return llvm::hash_combine(ikey.Size, ikey.ModTime);
Guy Benyei11169dd2012-12-18 14:30:41 +00001467}
1468
1469HeaderFileInfoTrait::internal_key_type
Argyrios Kyrtzidis5c2a3452013-03-06 18:12:47 +00001470HeaderFileInfoTrait::GetInternalKey(const FileEntry *FE) {
1471 internal_key_type ikey = { FE->getSize(), FE->getModificationTime(),
1472 FE->getName() };
1473 return ikey;
1474}
Guy Benyei11169dd2012-12-18 14:30:41 +00001475
Argyrios Kyrtzidis5c2a3452013-03-06 18:12:47 +00001476bool HeaderFileInfoTrait::EqualKey(internal_key_ref a, internal_key_ref b) {
1477 if (a.Size != b.Size || a.ModTime != b.ModTime)
Guy Benyei11169dd2012-12-18 14:30:41 +00001478 return false;
1479
Argyrios Kyrtzidis5c2a3452013-03-06 18:12:47 +00001480 if (strcmp(a.Filename, b.Filename) == 0)
1481 return true;
1482
Guy Benyei11169dd2012-12-18 14:30:41 +00001483 // Determine whether the actual files are equivalent.
Argyrios Kyrtzidis2a513e82013-03-04 20:33:40 +00001484 FileManager &FileMgr = Reader.getFileManager();
Argyrios Kyrtzidis5c2a3452013-03-06 18:12:47 +00001485 const FileEntry *FEA = FileMgr.getFile(a.Filename);
1486 const FileEntry *FEB = FileMgr.getFile(b.Filename);
Argyrios Kyrtzidis2a513e82013-03-04 20:33:40 +00001487 return (FEA && FEA == FEB);
Guy Benyei11169dd2012-12-18 14:30:41 +00001488}
1489
1490std::pair<unsigned, unsigned>
1491HeaderFileInfoTrait::ReadKeyDataLength(const unsigned char*& d) {
Justin Bogner57ba0b22014-03-28 22:03:24 +00001492 using namespace llvm::support;
1493 unsigned KeyLen = (unsigned) endian::readNext<uint16_t, little, unaligned>(d);
Guy Benyei11169dd2012-12-18 14:30:41 +00001494 unsigned DataLen = (unsigned) *d++;
Argyrios Kyrtzidis5c2a3452013-03-06 18:12:47 +00001495 return std::make_pair(KeyLen, DataLen);
Guy Benyei11169dd2012-12-18 14:30:41 +00001496}
Argyrios Kyrtzidis5c2a3452013-03-06 18:12:47 +00001497
1498HeaderFileInfoTrait::internal_key_type
1499HeaderFileInfoTrait::ReadKey(const unsigned char *d, unsigned) {
Justin Bogner57ba0b22014-03-28 22:03:24 +00001500 using namespace llvm::support;
Argyrios Kyrtzidis5c2a3452013-03-06 18:12:47 +00001501 internal_key_type ikey;
Justin Bogner57ba0b22014-03-28 22:03:24 +00001502 ikey.Size = off_t(endian::readNext<uint64_t, little, unaligned>(d));
1503 ikey.ModTime = time_t(endian::readNext<uint64_t, little, unaligned>(d));
Argyrios Kyrtzidis5c2a3452013-03-06 18:12:47 +00001504 ikey.Filename = (const char *)d;
1505 return ikey;
1506}
1507
Guy Benyei11169dd2012-12-18 14:30:41 +00001508HeaderFileInfoTrait::data_type
Argyrios Kyrtzidisb146baa2013-03-13 21:13:51 +00001509HeaderFileInfoTrait::ReadData(internal_key_ref key, const unsigned char *d,
Guy Benyei11169dd2012-12-18 14:30:41 +00001510 unsigned DataLen) {
1511 const unsigned char *End = d + DataLen;
Justin Bogner57ba0b22014-03-28 22:03:24 +00001512 using namespace llvm::support;
Guy Benyei11169dd2012-12-18 14:30:41 +00001513 HeaderFileInfo HFI;
1514 unsigned Flags = *d++;
Lawrence Crowlb53e5482013-06-20 21:14:14 +00001515 HFI.HeaderRole = static_cast<ModuleMap::ModuleHeaderRole>
1516 ((Flags >> 6) & 0x03);
Guy Benyei11169dd2012-12-18 14:30:41 +00001517 HFI.isImport = (Flags >> 5) & 0x01;
1518 HFI.isPragmaOnce = (Flags >> 4) & 0x01;
1519 HFI.DirInfo = (Flags >> 2) & 0x03;
1520 HFI.Resolved = (Flags >> 1) & 0x01;
1521 HFI.IndexHeaderMapHeader = Flags & 0x01;
Justin Bogner57ba0b22014-03-28 22:03:24 +00001522 HFI.NumIncludes = endian::readNext<uint16_t, little, unaligned>(d);
1523 HFI.ControllingMacroID = Reader.getGlobalIdentifierID(
1524 M, endian::readNext<uint32_t, little, unaligned>(d));
1525 if (unsigned FrameworkOffset =
1526 endian::readNext<uint32_t, little, unaligned>(d)) {
Guy Benyei11169dd2012-12-18 14:30:41 +00001527 // The framework offset is 1 greater than the actual offset,
1528 // since 0 is used as an indicator for "no framework name".
1529 StringRef FrameworkName(FrameworkStrings + FrameworkOffset - 1);
1530 HFI.Framework = HS->getUniqueFrameworkName(FrameworkName);
1531 }
1532
Argyrios Kyrtzidisb146baa2013-03-13 21:13:51 +00001533 if (d != End) {
Justin Bogner57ba0b22014-03-28 22:03:24 +00001534 uint32_t LocalSMID = endian::readNext<uint32_t, little, unaligned>(d);
Argyrios Kyrtzidisb146baa2013-03-13 21:13:51 +00001535 if (LocalSMID) {
1536 // This header is part of a module. Associate it with the module to enable
1537 // implicit module import.
1538 SubmoduleID GlobalSMID = Reader.getGlobalSubmoduleID(M, LocalSMID);
1539 Module *Mod = Reader.getSubmodule(GlobalSMID);
1540 HFI.isModuleHeader = true;
1541 FileManager &FileMgr = Reader.getFileManager();
1542 ModuleMap &ModMap =
1543 Reader.getPreprocessor().getHeaderSearchInfo().getModuleMap();
Lawrence Crowlb53e5482013-06-20 21:14:14 +00001544 ModMap.addHeader(Mod, FileMgr.getFile(key.Filename), HFI.getHeaderRole());
Argyrios Kyrtzidisb146baa2013-03-13 21:13:51 +00001545 }
1546 }
1547
Guy Benyei11169dd2012-12-18 14:30:41 +00001548 assert(End == d && "Wrong data length in HeaderFileInfo deserialization");
1549 (void)End;
1550
1551 // This HeaderFileInfo was externally loaded.
1552 HFI.External = true;
1553 return HFI;
1554}
1555
Richard Smith49f906a2014-03-01 00:08:04 +00001556void
1557ASTReader::addPendingMacroFromModule(IdentifierInfo *II, ModuleFile *M,
1558 GlobalMacroID GMacID,
Craig Topper00bbdcf2014-06-28 23:22:23 +00001559 ArrayRef<SubmoduleID> Overrides) {
Guy Benyei11169dd2012-12-18 14:30:41 +00001560 assert(NumCurrentElementsDeserializing > 0 &&"Missing deserialization guard");
Craig Toppera13603a2014-05-22 05:54:18 +00001561 SubmoduleID *OverrideData = nullptr;
Richard Smith49f906a2014-03-01 00:08:04 +00001562 if (!Overrides.empty()) {
1563 OverrideData = new (Context) SubmoduleID[Overrides.size() + 1];
1564 OverrideData[0] = Overrides.size();
1565 for (unsigned I = 0; I != Overrides.size(); ++I)
1566 OverrideData[I + 1] = getGlobalSubmoduleID(*M, Overrides[I]);
1567 }
1568 PendingMacroIDs[II].push_back(PendingMacroInfo(M, GMacID, OverrideData));
Argyrios Kyrtzidiseb663da2013-03-22 21:12:57 +00001569}
1570
1571void ASTReader::addPendingMacroFromPCH(IdentifierInfo *II,
1572 ModuleFile *M,
1573 uint64_t MacroDirectivesOffset) {
1574 assert(NumCurrentElementsDeserializing > 0 &&"Missing deserialization guard");
1575 PendingMacroIDs[II].push_back(PendingMacroInfo(M, MacroDirectivesOffset));
Guy Benyei11169dd2012-12-18 14:30:41 +00001576}
1577
1578void ASTReader::ReadDefinedMacros() {
1579 // Note that we are loading defined macros.
1580 Deserializing Macros(this);
1581
1582 for (ModuleReverseIterator I = ModuleMgr.rbegin(),
1583 E = ModuleMgr.rend(); I != E; ++I) {
Chris Lattner7fb3bef2013-01-20 00:56:42 +00001584 BitstreamCursor &MacroCursor = (*I)->MacroCursor;
Guy Benyei11169dd2012-12-18 14:30:41 +00001585
1586 // If there was no preprocessor block, skip this file.
1587 if (!MacroCursor.getBitStreamReader())
1588 continue;
1589
Chris Lattner7fb3bef2013-01-20 00:56:42 +00001590 BitstreamCursor Cursor = MacroCursor;
Guy Benyei11169dd2012-12-18 14:30:41 +00001591 Cursor.JumpToBit((*I)->MacroStartOffset);
1592
1593 RecordData Record;
1594 while (true) {
Chris Lattnere7b154b2013-01-19 21:39:22 +00001595 llvm::BitstreamEntry E = Cursor.advanceSkippingSubblocks();
1596
1597 switch (E.Kind) {
1598 case llvm::BitstreamEntry::SubBlock: // Handled for us already.
1599 case llvm::BitstreamEntry::Error:
1600 Error("malformed block record in AST file");
1601 return;
1602 case llvm::BitstreamEntry::EndBlock:
1603 goto NextCursor;
1604
1605 case llvm::BitstreamEntry::Record:
Chris Lattnere7b154b2013-01-19 21:39:22 +00001606 Record.clear();
Chris Lattner0e6c9402013-01-20 02:38:54 +00001607 switch (Cursor.readRecord(E.ID, Record)) {
Chris Lattnere7b154b2013-01-19 21:39:22 +00001608 default: // Default behavior: ignore.
1609 break;
1610
1611 case PP_MACRO_OBJECT_LIKE:
1612 case PP_MACRO_FUNCTION_LIKE:
1613 getLocalIdentifier(**I, Record[0]);
1614 break;
1615
1616 case PP_TOKEN:
1617 // Ignore tokens.
1618 break;
Guy Benyei11169dd2012-12-18 14:30:41 +00001619 }
Guy Benyei11169dd2012-12-18 14:30:41 +00001620 break;
1621 }
1622 }
Chris Lattnere7b154b2013-01-19 21:39:22 +00001623 NextCursor: ;
Guy Benyei11169dd2012-12-18 14:30:41 +00001624 }
1625}
1626
1627namespace {
1628 /// \brief Visitor class used to look up identifirs in an AST file.
1629 class IdentifierLookupVisitor {
1630 StringRef Name;
1631 unsigned PriorGeneration;
Douglas Gregor00a50f72013-01-25 00:38:33 +00001632 unsigned &NumIdentifierLookups;
1633 unsigned &NumIdentifierLookupHits;
Guy Benyei11169dd2012-12-18 14:30:41 +00001634 IdentifierInfo *Found;
Douglas Gregor00a50f72013-01-25 00:38:33 +00001635
Guy Benyei11169dd2012-12-18 14:30:41 +00001636 public:
Douglas Gregor00a50f72013-01-25 00:38:33 +00001637 IdentifierLookupVisitor(StringRef Name, unsigned PriorGeneration,
1638 unsigned &NumIdentifierLookups,
1639 unsigned &NumIdentifierLookupHits)
Douglas Gregor7211ac12013-01-25 23:32:03 +00001640 : Name(Name), PriorGeneration(PriorGeneration),
Douglas Gregor00a50f72013-01-25 00:38:33 +00001641 NumIdentifierLookups(NumIdentifierLookups),
1642 NumIdentifierLookupHits(NumIdentifierLookupHits),
1643 Found()
1644 {
1645 }
Guy Benyei11169dd2012-12-18 14:30:41 +00001646
1647 static bool visit(ModuleFile &M, void *UserData) {
1648 IdentifierLookupVisitor *This
1649 = static_cast<IdentifierLookupVisitor *>(UserData);
1650
1651 // If we've already searched this module file, skip it now.
1652 if (M.Generation <= This->PriorGeneration)
1653 return true;
Douglas Gregore060e572013-01-25 01:03:03 +00001654
Guy Benyei11169dd2012-12-18 14:30:41 +00001655 ASTIdentifierLookupTable *IdTable
1656 = (ASTIdentifierLookupTable *)M.IdentifierLookupTable;
1657 if (!IdTable)
1658 return false;
1659
1660 ASTIdentifierLookupTrait Trait(IdTable->getInfoObj().getReader(),
1661 M, This->Found);
Douglas Gregor00a50f72013-01-25 00:38:33 +00001662 ++This->NumIdentifierLookups;
1663 ASTIdentifierLookupTable::iterator Pos = IdTable->find(This->Name,&Trait);
Guy Benyei11169dd2012-12-18 14:30:41 +00001664 if (Pos == IdTable->end())
1665 return false;
1666
1667 // Dereferencing the iterator has the effect of building the
1668 // IdentifierInfo node and populating it with the various
1669 // declarations it needs.
Douglas Gregor00a50f72013-01-25 00:38:33 +00001670 ++This->NumIdentifierLookupHits;
Guy Benyei11169dd2012-12-18 14:30:41 +00001671 This->Found = *Pos;
1672 return true;
1673 }
1674
1675 // \brief Retrieve the identifier info found within the module
1676 // files.
1677 IdentifierInfo *getIdentifierInfo() const { return Found; }
1678 };
1679}
1680
1681void ASTReader::updateOutOfDateIdentifier(IdentifierInfo &II) {
1682 // Note that we are loading an identifier.
1683 Deserializing AnIdentifier(this);
1684
1685 unsigned PriorGeneration = 0;
1686 if (getContext().getLangOpts().Modules)
1687 PriorGeneration = IdentifierGeneration[&II];
Douglas Gregore060e572013-01-25 01:03:03 +00001688
1689 // If there is a global index, look there first to determine which modules
1690 // provably do not have any results for this identifier.
Douglas Gregor7211ac12013-01-25 23:32:03 +00001691 GlobalModuleIndex::HitSet Hits;
Craig Toppera13603a2014-05-22 05:54:18 +00001692 GlobalModuleIndex::HitSet *HitsPtr = nullptr;
Douglas Gregore060e572013-01-25 01:03:03 +00001693 if (!loadGlobalIndex()) {
Douglas Gregor7211ac12013-01-25 23:32:03 +00001694 if (GlobalIndex->lookupIdentifier(II.getName(), Hits)) {
1695 HitsPtr = &Hits;
Douglas Gregore060e572013-01-25 01:03:03 +00001696 }
1697 }
1698
Douglas Gregor7211ac12013-01-25 23:32:03 +00001699 IdentifierLookupVisitor Visitor(II.getName(), PriorGeneration,
Douglas Gregor00a50f72013-01-25 00:38:33 +00001700 NumIdentifierLookups,
1701 NumIdentifierLookupHits);
Douglas Gregor7211ac12013-01-25 23:32:03 +00001702 ModuleMgr.visit(IdentifierLookupVisitor::visit, &Visitor, HitsPtr);
Guy Benyei11169dd2012-12-18 14:30:41 +00001703 markIdentifierUpToDate(&II);
1704}
1705
1706void ASTReader::markIdentifierUpToDate(IdentifierInfo *II) {
1707 if (!II)
1708 return;
1709
1710 II->setOutOfDate(false);
1711
1712 // Update the generation for this identifier.
1713 if (getContext().getLangOpts().Modules)
Richard Smith053f6c62014-05-16 23:01:30 +00001714 IdentifierGeneration[II] = getGeneration();
Guy Benyei11169dd2012-12-18 14:30:41 +00001715}
1716
Richard Smith49f906a2014-03-01 00:08:04 +00001717struct ASTReader::ModuleMacroInfo {
1718 SubmoduleID SubModID;
1719 MacroInfo *MI;
1720 SubmoduleID *Overrides;
1721 // FIXME: Remove this.
1722 ModuleFile *F;
1723
1724 bool isDefine() const { return MI; }
1725
1726 SubmoduleID getSubmoduleID() const { return SubModID; }
1727
Craig Topper00bbdcf2014-06-28 23:22:23 +00001728 ArrayRef<SubmoduleID> getOverriddenSubmodules() const {
Richard Smith49f906a2014-03-01 00:08:04 +00001729 if (!Overrides)
Craig Topper00bbdcf2014-06-28 23:22:23 +00001730 return None;
Richard Smith49f906a2014-03-01 00:08:04 +00001731 return llvm::makeArrayRef(Overrides + 1, *Overrides);
1732 }
1733
Richard Smithdaa69e02014-07-25 04:40:03 +00001734 MacroDirective *import(Preprocessor &PP, SourceLocation ImportLoc) const {
Richard Smith49f906a2014-03-01 00:08:04 +00001735 if (!MI)
Richard Smithdaa69e02014-07-25 04:40:03 +00001736 return PP.AllocateUndefMacroDirective(ImportLoc, SubModID,
1737 getOverriddenSubmodules());
1738 return PP.AllocateDefMacroDirective(MI, ImportLoc, SubModID,
1739 getOverriddenSubmodules());
Richard Smith49f906a2014-03-01 00:08:04 +00001740 }
1741};
1742
1743ASTReader::ModuleMacroInfo *
1744ASTReader::getModuleMacro(const PendingMacroInfo &PMInfo) {
1745 ModuleMacroInfo Info;
1746
1747 uint32_t ID = PMInfo.ModuleMacroData.MacID;
1748 if (ID & 1) {
1749 // Macro undefinition.
1750 Info.SubModID = getGlobalSubmoduleID(*PMInfo.M, ID >> 1);
Craig Toppera13603a2014-05-22 05:54:18 +00001751 Info.MI = nullptr;
Richard Smith49f906a2014-03-01 00:08:04 +00001752 } else {
1753 // Macro definition.
1754 GlobalMacroID GMacID = getGlobalMacroID(*PMInfo.M, ID >> 1);
1755 assert(GMacID);
1756
1757 // If this macro has already been loaded, don't do so again.
1758 // FIXME: This is highly dubious. Multiple macro definitions can have the
1759 // same MacroInfo (and hence the same GMacID) due to #pragma push_macro etc.
1760 if (MacrosLoaded[GMacID - NUM_PREDEF_MACRO_IDS])
Craig Toppera13603a2014-05-22 05:54:18 +00001761 return nullptr;
Richard Smith49f906a2014-03-01 00:08:04 +00001762
1763 Info.MI = getMacro(GMacID);
1764 Info.SubModID = Info.MI->getOwningModuleID();
1765 }
1766 Info.Overrides = PMInfo.ModuleMacroData.Overrides;
1767 Info.F = PMInfo.M;
1768
1769 return new (Context) ModuleMacroInfo(Info);
1770}
1771
Argyrios Kyrtzidiseb663da2013-03-22 21:12:57 +00001772void ASTReader::resolvePendingMacro(IdentifierInfo *II,
1773 const PendingMacroInfo &PMInfo) {
1774 assert(II);
1775
1776 if (PMInfo.M->Kind != MK_Module) {
1777 installPCHMacroDirectives(II, *PMInfo.M,
1778 PMInfo.PCHMacroData.MacroDirectivesOffset);
1779 return;
1780 }
Richard Smith49f906a2014-03-01 00:08:04 +00001781
Argyrios Kyrtzidiseb663da2013-03-22 21:12:57 +00001782 // Module Macro.
1783
Richard Smith49f906a2014-03-01 00:08:04 +00001784 ModuleMacroInfo *MMI = getModuleMacro(PMInfo);
1785 if (!MMI)
Argyrios Kyrtzidiseb663da2013-03-22 21:12:57 +00001786 return;
1787
Richard Smith49f906a2014-03-01 00:08:04 +00001788 Module *Owner = getSubmodule(MMI->getSubmoduleID());
1789 if (Owner && Owner->NameVisibility == Module::Hidden) {
1790 // Macros in the owning module are hidden. Just remember this macro to
1791 // install if we make this module visible.
1792 HiddenNamesMap[Owner].HiddenMacros.insert(std::make_pair(II, MMI));
1793 } else {
Richard Smithdaa69e02014-07-25 04:40:03 +00001794 installImportedMacro(II, MMI, Owner);
Argyrios Kyrtzidiseb663da2013-03-22 21:12:57 +00001795 }
Argyrios Kyrtzidiseb663da2013-03-22 21:12:57 +00001796}
1797
1798void ASTReader::installPCHMacroDirectives(IdentifierInfo *II,
1799 ModuleFile &M, uint64_t Offset) {
1800 assert(M.Kind != MK_Module);
1801
1802 BitstreamCursor &Cursor = M.MacroCursor;
1803 SavedStreamPosition SavedPosition(Cursor);
1804 Cursor.JumpToBit(Offset);
1805
1806 llvm::BitstreamEntry Entry =
1807 Cursor.advance(BitstreamCursor::AF_DontPopBlockAtEnd);
1808 if (Entry.Kind != llvm::BitstreamEntry::Record) {
1809 Error("malformed block record in AST file");
1810 return;
1811 }
1812
1813 RecordData Record;
1814 PreprocessorRecordTypes RecType =
1815 (PreprocessorRecordTypes)Cursor.readRecord(Entry.ID, Record);
1816 if (RecType != PP_MACRO_DIRECTIVE_HISTORY) {
1817 Error("malformed block record in AST file");
1818 return;
1819 }
1820
1821 // Deserialize the macro directives history in reverse source-order.
Craig Toppera13603a2014-05-22 05:54:18 +00001822 MacroDirective *Latest = nullptr, *Earliest = nullptr;
Argyrios Kyrtzidiseb663da2013-03-22 21:12:57 +00001823 unsigned Idx = 0, N = Record.size();
1824 while (Idx < N) {
Craig Toppera13603a2014-05-22 05:54:18 +00001825 MacroDirective *MD = nullptr;
Argyrios Kyrtzidiseb663da2013-03-22 21:12:57 +00001826 SourceLocation Loc = ReadSourceLocation(M, Record, Idx);
Argyrios Kyrtzidisb6210df2013-03-26 17:17:01 +00001827 MacroDirective::Kind K = (MacroDirective::Kind)Record[Idx++];
1828 switch (K) {
1829 case MacroDirective::MD_Define: {
1830 GlobalMacroID GMacID = getGlobalMacroID(M, Record[Idx++]);
1831 MacroInfo *MI = getMacro(GMacID);
Richard Smithdaa69e02014-07-25 04:40:03 +00001832 SubmoduleID ImportedFrom = Record[Idx++];
1833 bool IsAmbiguous = Record[Idx++];
1834 llvm::SmallVector<unsigned, 4> Overrides;
1835 if (ImportedFrom) {
1836 Overrides.insert(Overrides.end(),
1837 &Record[Idx] + 1, &Record[Idx] + 1 + Record[Idx]);
1838 Idx += Overrides.size() + 1;
1839 }
Argyrios Kyrtzidisb6210df2013-03-26 17:17:01 +00001840 DefMacroDirective *DefMD =
Richard Smithdaa69e02014-07-25 04:40:03 +00001841 PP.AllocateDefMacroDirective(MI, Loc, ImportedFrom, Overrides);
1842 DefMD->setAmbiguous(IsAmbiguous);
Argyrios Kyrtzidisb6210df2013-03-26 17:17:01 +00001843 MD = DefMD;
1844 break;
1845 }
Richard Smithdaa69e02014-07-25 04:40:03 +00001846 case MacroDirective::MD_Undefine: {
1847 SubmoduleID ImportedFrom = Record[Idx++];
1848 llvm::SmallVector<unsigned, 4> Overrides;
1849 if (ImportedFrom) {
1850 Overrides.insert(Overrides.end(),
1851 &Record[Idx] + 1, &Record[Idx] + 1 + Record[Idx]);
1852 Idx += Overrides.size() + 1;
1853 }
1854 MD = PP.AllocateUndefMacroDirective(Loc, ImportedFrom, Overrides);
Argyrios Kyrtzidisb6210df2013-03-26 17:17:01 +00001855 break;
Richard Smithdaa69e02014-07-25 04:40:03 +00001856 }
1857 case MacroDirective::MD_Visibility:
Argyrios Kyrtzidisb6210df2013-03-26 17:17:01 +00001858 bool isPublic = Record[Idx++];
1859 MD = PP.AllocateVisibilityMacroDirective(Loc, isPublic);
1860 break;
1861 }
Argyrios Kyrtzidiseb663da2013-03-22 21:12:57 +00001862
1863 if (!Latest)
1864 Latest = MD;
1865 if (Earliest)
1866 Earliest->setPrevious(MD);
1867 Earliest = MD;
1868 }
1869
1870 PP.setLoadedMacroDirective(II, Latest);
1871}
1872
Argyrios Kyrtzidis3a9c42c2013-03-27 01:25:34 +00001873/// \brief For the given macro definitions, check if they are both in system
Douglas Gregor0b202052013-04-12 21:00:54 +00001874/// modules.
1875static bool areDefinedInSystemModules(MacroInfo *PrevMI, MacroInfo *NewMI,
Douglas Gregor5e461192013-06-07 22:56:11 +00001876 Module *NewOwner, ASTReader &Reader) {
Argyrios Kyrtzidis3a9c42c2013-03-27 01:25:34 +00001877 assert(PrevMI && NewMI);
Craig Toppera13603a2014-05-22 05:54:18 +00001878 Module *PrevOwner = nullptr;
Argyrios Kyrtzidis3a9c42c2013-03-27 01:25:34 +00001879 if (SubmoduleID PrevModID = PrevMI->getOwningModuleID())
1880 PrevOwner = Reader.getSubmodule(PrevModID);
Douglas Gregor5e461192013-06-07 22:56:11 +00001881 SourceManager &SrcMgr = Reader.getSourceManager();
1882 bool PrevInSystem
1883 = PrevOwner? PrevOwner->IsSystem
1884 : SrcMgr.isInSystemHeader(PrevMI->getDefinitionLoc());
1885 bool NewInSystem
1886 = NewOwner? NewOwner->IsSystem
1887 : SrcMgr.isInSystemHeader(NewMI->getDefinitionLoc());
1888 if (PrevOwner && PrevOwner == NewOwner)
Argyrios Kyrtzidis3a9c42c2013-03-27 01:25:34 +00001889 return false;
Douglas Gregor5e461192013-06-07 22:56:11 +00001890 return PrevInSystem && NewInSystem;
Argyrios Kyrtzidis3a9c42c2013-03-27 01:25:34 +00001891}
1892
Richard Smith49f906a2014-03-01 00:08:04 +00001893void ASTReader::removeOverriddenMacros(IdentifierInfo *II,
Richard Smithdaa69e02014-07-25 04:40:03 +00001894 SourceLocation ImportLoc,
Richard Smith49f906a2014-03-01 00:08:04 +00001895 AmbiguousMacros &Ambig,
Craig Topper00bbdcf2014-06-28 23:22:23 +00001896 ArrayRef<SubmoduleID> Overrides) {
Richard Smith49f906a2014-03-01 00:08:04 +00001897 for (unsigned OI = 0, ON = Overrides.size(); OI != ON; ++OI) {
1898 SubmoduleID OwnerID = Overrides[OI];
Argyrios Kyrtzidiseb663da2013-03-22 21:12:57 +00001899
Richard Smith49f906a2014-03-01 00:08:04 +00001900 // If this macro is not yet visible, remove it from the hidden names list.
1901 Module *Owner = getSubmodule(OwnerID);
1902 HiddenNames &Hidden = HiddenNamesMap[Owner];
1903 HiddenMacrosMap::iterator HI = Hidden.HiddenMacros.find(II);
1904 if (HI != Hidden.HiddenMacros.end()) {
Richard Smithdaa69e02014-07-25 04:40:03 +00001905 // Register the macro now so we don't lose it when we re-export.
1906 PP.appendMacroDirective(II, HI->second->import(PP, ImportLoc));
1907
Richard Smith9d100862014-03-06 03:16:27 +00001908 auto SubOverrides = HI->second->getOverriddenSubmodules();
Richard Smith49f906a2014-03-01 00:08:04 +00001909 Hidden.HiddenMacros.erase(HI);
Richard Smithdaa69e02014-07-25 04:40:03 +00001910 removeOverriddenMacros(II, ImportLoc, Ambig, SubOverrides);
Richard Smith49f906a2014-03-01 00:08:04 +00001911 }
1912
1913 // If this macro is already in our list of conflicts, remove it from there.
Richard Smithbb29e512014-03-06 00:33:23 +00001914 Ambig.erase(
1915 std::remove_if(Ambig.begin(), Ambig.end(), [&](DefMacroDirective *MD) {
1916 return MD->getInfo()->getOwningModuleID() == OwnerID;
1917 }),
1918 Ambig.end());
Richard Smith49f906a2014-03-01 00:08:04 +00001919 }
1920}
1921
1922ASTReader::AmbiguousMacros *
1923ASTReader::removeOverriddenMacros(IdentifierInfo *II,
Richard Smithdaa69e02014-07-25 04:40:03 +00001924 SourceLocation ImportLoc,
Craig Topper00bbdcf2014-06-28 23:22:23 +00001925 ArrayRef<SubmoduleID> Overrides) {
Argyrios Kyrtzidiseb663da2013-03-22 21:12:57 +00001926 MacroDirective *Prev = PP.getMacroDirective(II);
Richard Smith49f906a2014-03-01 00:08:04 +00001927 if (!Prev && Overrides.empty())
Craig Toppera13603a2014-05-22 05:54:18 +00001928 return nullptr;
Richard Smith49f906a2014-03-01 00:08:04 +00001929
Craig Toppera13603a2014-05-22 05:54:18 +00001930 DefMacroDirective *PrevDef = Prev ? Prev->getDefinition().getDirective()
1931 : nullptr;
Richard Smith49f906a2014-03-01 00:08:04 +00001932 if (PrevDef && PrevDef->isAmbiguous()) {
1933 // We had a prior ambiguity. Check whether we resolve it (or make it worse).
1934 AmbiguousMacros &Ambig = AmbiguousMacroDefs[II];
1935 Ambig.push_back(PrevDef);
1936
Richard Smithdaa69e02014-07-25 04:40:03 +00001937 removeOverriddenMacros(II, ImportLoc, Ambig, Overrides);
Richard Smith49f906a2014-03-01 00:08:04 +00001938
1939 if (!Ambig.empty())
1940 return &Ambig;
1941
1942 AmbiguousMacroDefs.erase(II);
1943 } else {
1944 // There's no ambiguity yet. Maybe we're introducing one.
Benjamin Kramer834652a2014-05-03 18:44:26 +00001945 AmbiguousMacros Ambig;
Richard Smith49f906a2014-03-01 00:08:04 +00001946 if (PrevDef)
1947 Ambig.push_back(PrevDef);
1948
Richard Smithdaa69e02014-07-25 04:40:03 +00001949 removeOverriddenMacros(II, ImportLoc, Ambig, Overrides);
Richard Smith49f906a2014-03-01 00:08:04 +00001950
1951 if (!Ambig.empty()) {
1952 AmbiguousMacros &Result = AmbiguousMacroDefs[II];
Benjamin Kramer834652a2014-05-03 18:44:26 +00001953 std::swap(Result, Ambig);
Richard Smith49f906a2014-03-01 00:08:04 +00001954 return &Result;
Argyrios Kyrtzidisb6210df2013-03-26 17:17:01 +00001955 }
Argyrios Kyrtzidiseb663da2013-03-22 21:12:57 +00001956 }
Richard Smith49f906a2014-03-01 00:08:04 +00001957
1958 // We ended up with no ambiguity.
Craig Toppera13603a2014-05-22 05:54:18 +00001959 return nullptr;
Richard Smith49f906a2014-03-01 00:08:04 +00001960}
1961
1962void ASTReader::installImportedMacro(IdentifierInfo *II, ModuleMacroInfo *MMI,
Richard Smithdaa69e02014-07-25 04:40:03 +00001963 Module *Owner) {
Richard Smith49f906a2014-03-01 00:08:04 +00001964 assert(II && Owner);
1965
1966 SourceLocation ImportLoc = Owner->MacroVisibilityLoc;
Richard Smithdaa69e02014-07-25 04:40:03 +00001967 if (ImportLoc.isInvalid()) {
Richard Smith49f906a2014-03-01 00:08:04 +00001968 // FIXME: If we made macros from this module visible but didn't provide a
1969 // source location for the import, we don't have a location for the macro.
1970 // Use the location at which the containing module file was first imported
1971 // for now.
1972 ImportLoc = MMI->F->DirectImportLoc;
Richard Smith56be7542014-03-21 00:33:59 +00001973 assert(ImportLoc.isValid() && "no import location for a visible macro?");
Richard Smith49f906a2014-03-01 00:08:04 +00001974 }
1975
Benjamin Kramer834652a2014-05-03 18:44:26 +00001976 AmbiguousMacros *Prev =
Richard Smithdaa69e02014-07-25 04:40:03 +00001977 removeOverriddenMacros(II, ImportLoc, MMI->getOverriddenSubmodules());
Richard Smith49f906a2014-03-01 00:08:04 +00001978
Richard Smith49f906a2014-03-01 00:08:04 +00001979 // Create a synthetic macro definition corresponding to the import (or null
1980 // if this was an undefinition of the macro).
Richard Smithdaa69e02014-07-25 04:40:03 +00001981 MacroDirective *Imported = MMI->import(PP, ImportLoc);
1982 DefMacroDirective *MD = dyn_cast<DefMacroDirective>(Imported);
Richard Smith49f906a2014-03-01 00:08:04 +00001983
1984 // If there's no ambiguity, just install the macro.
1985 if (!Prev) {
Richard Smithdaa69e02014-07-25 04:40:03 +00001986 PP.appendMacroDirective(II, Imported);
Richard Smith49f906a2014-03-01 00:08:04 +00001987 return;
1988 }
1989 assert(!Prev->empty());
1990
1991 if (!MD) {
1992 // We imported a #undef that didn't remove all prior definitions. The most
1993 // recent prior definition remains, and we install it in the place of the
Richard Smithdaa69e02014-07-25 04:40:03 +00001994 // imported directive, as if by a local #pragma pop_macro.
Richard Smith49f906a2014-03-01 00:08:04 +00001995 MacroInfo *NewMI = Prev->back()->getInfo();
1996 Prev->pop_back();
Richard Smithdaa69e02014-07-25 04:40:03 +00001997 MD = PP.AllocateDefMacroDirective(NewMI, ImportLoc);
1998
1999 // Install our #undef first so that we don't lose track of it. We'll replace
2000 // this with whichever macro definition ends up winning.
2001 PP.appendMacroDirective(II, Imported);
Richard Smith49f906a2014-03-01 00:08:04 +00002002 }
2003
2004 // We're introducing a macro definition that creates or adds to an ambiguity.
2005 // We can resolve that ambiguity if this macro is token-for-token identical to
2006 // all of the existing definitions.
2007 MacroInfo *NewMI = MD->getInfo();
2008 assert(NewMI && "macro definition with no MacroInfo?");
2009 while (!Prev->empty()) {
2010 MacroInfo *PrevMI = Prev->back()->getInfo();
2011 assert(PrevMI && "macro definition with no MacroInfo?");
2012
2013 // Before marking the macros as ambiguous, check if this is a case where
2014 // both macros are in system headers. If so, we trust that the system
2015 // did not get it wrong. This also handles cases where Clang's own
2016 // headers have a different spelling of certain system macros:
2017 // #define LONG_MAX __LONG_MAX__ (clang's limits.h)
2018 // #define LONG_MAX 0x7fffffffffffffffL (system's limits.h)
2019 //
2020 // FIXME: Remove the defined-in-system-headers check. clang's limits.h
2021 // overrides the system limits.h's macros, so there's no conflict here.
2022 if (NewMI != PrevMI &&
2023 !PrevMI->isIdenticalTo(*NewMI, PP, /*Syntactically=*/true) &&
2024 !areDefinedInSystemModules(PrevMI, NewMI, Owner, *this))
2025 break;
2026
2027 // The previous definition is the same as this one (or both are defined in
2028 // system modules so we can assume they're equivalent); we don't need to
2029 // track it any more.
2030 Prev->pop_back();
2031 }
2032
2033 if (!Prev->empty())
2034 MD->setAmbiguous(true);
2035
Argyrios Kyrtzidisb6210df2013-03-26 17:17:01 +00002036 PP.appendMacroDirective(II, MD);
Argyrios Kyrtzidiseb663da2013-03-22 21:12:57 +00002037}
2038
Argyrios Kyrtzidisce9b49e2014-03-14 02:26:27 +00002039ASTReader::InputFileInfo
2040ASTReader::readInputFileInfo(ModuleFile &F, unsigned ID) {
Ben Langmuir198c1682014-03-07 07:27:49 +00002041 // Go find this input file.
2042 BitstreamCursor &Cursor = F.InputFilesCursor;
2043 SavedStreamPosition SavedPosition(Cursor);
2044 Cursor.JumpToBit(F.InputFileOffsets[ID-1]);
2045
2046 unsigned Code = Cursor.ReadCode();
2047 RecordData Record;
2048 StringRef Blob;
2049
2050 unsigned Result = Cursor.readRecord(Code, Record, &Blob);
2051 assert(static_cast<InputFileRecordTypes>(Result) == INPUT_FILE &&
2052 "invalid record type for input file");
2053 (void)Result;
2054
Argyrios Kyrtzidisce9b49e2014-03-14 02:26:27 +00002055 std::string Filename;
2056 off_t StoredSize;
2057 time_t StoredTime;
2058 bool Overridden;
2059
Ben Langmuir198c1682014-03-07 07:27:49 +00002060 assert(Record[0] == ID && "Bogus stored ID or offset");
2061 StoredSize = static_cast<off_t>(Record[1]);
2062 StoredTime = static_cast<time_t>(Record[2]);
2063 Overridden = static_cast<bool>(Record[3]);
2064 Filename = Blob;
2065 MaybeAddSystemRootToFilename(F, Filename);
Argyrios Kyrtzidisce9b49e2014-03-14 02:26:27 +00002066
Hans Wennborg73945142014-03-14 17:45:06 +00002067 InputFileInfo R = { std::move(Filename), StoredSize, StoredTime, Overridden };
2068 return R;
Ben Langmuir198c1682014-03-07 07:27:49 +00002069}
2070
2071std::string ASTReader::getInputFileName(ModuleFile &F, unsigned int ID) {
Argyrios Kyrtzidisce9b49e2014-03-14 02:26:27 +00002072 return readInputFileInfo(F, ID).Filename;
Ben Langmuir198c1682014-03-07 07:27:49 +00002073}
2074
Argyrios Kyrtzidis61c3d872013-03-01 03:26:04 +00002075InputFile ASTReader::getInputFile(ModuleFile &F, unsigned ID, bool Complain) {
Guy Benyei11169dd2012-12-18 14:30:41 +00002076 // If this ID is bogus, just return an empty input file.
2077 if (ID == 0 || ID > F.InputFilesLoaded.size())
2078 return InputFile();
2079
2080 // If we've already loaded this input file, return it.
Argyrios Kyrtzidis61c3d872013-03-01 03:26:04 +00002081 if (F.InputFilesLoaded[ID-1].getFile())
Guy Benyei11169dd2012-12-18 14:30:41 +00002082 return F.InputFilesLoaded[ID-1];
2083
Argyrios Kyrtzidis9308f0a2014-01-08 19:13:34 +00002084 if (F.InputFilesLoaded[ID-1].isNotFound())
2085 return InputFile();
2086
Guy Benyei11169dd2012-12-18 14:30:41 +00002087 // Go find this input file.
Chris Lattner7fb3bef2013-01-20 00:56:42 +00002088 BitstreamCursor &Cursor = F.InputFilesCursor;
Guy Benyei11169dd2012-12-18 14:30:41 +00002089 SavedStreamPosition SavedPosition(Cursor);
2090 Cursor.JumpToBit(F.InputFileOffsets[ID-1]);
2091
Argyrios Kyrtzidisce9b49e2014-03-14 02:26:27 +00002092 InputFileInfo FI = readInputFileInfo(F, ID);
2093 off_t StoredSize = FI.StoredSize;
2094 time_t StoredTime = FI.StoredTime;
2095 bool Overridden = FI.Overridden;
2096 StringRef Filename = FI.Filename;
Argyrios Kyrtzidis61c3d872013-03-01 03:26:04 +00002097
Ben Langmuir198c1682014-03-07 07:27:49 +00002098 const FileEntry *File
2099 = Overridden? FileMgr.getVirtualFile(Filename, StoredSize, StoredTime)
2100 : FileMgr.getFile(Filename, /*OpenFile=*/false);
2101
2102 // If we didn't find the file, resolve it relative to the
2103 // original directory from which this AST file was created.
Craig Toppera13603a2014-05-22 05:54:18 +00002104 if (File == nullptr && !F.OriginalDir.empty() && !CurrentDir.empty() &&
Ben Langmuir198c1682014-03-07 07:27:49 +00002105 F.OriginalDir != CurrentDir) {
2106 std::string Resolved = resolveFileRelativeToOriginalDir(Filename,
2107 F.OriginalDir,
2108 CurrentDir);
2109 if (!Resolved.empty())
2110 File = FileMgr.getFile(Resolved);
2111 }
2112
2113 // For an overridden file, create a virtual file with the stored
2114 // size/timestamp.
Craig Toppera13603a2014-05-22 05:54:18 +00002115 if (Overridden && File == nullptr) {
Ben Langmuir198c1682014-03-07 07:27:49 +00002116 File = FileMgr.getVirtualFile(Filename, StoredSize, StoredTime);
2117 }
2118
Craig Toppera13603a2014-05-22 05:54:18 +00002119 if (File == nullptr) {
Ben Langmuir198c1682014-03-07 07:27:49 +00002120 if (Complain) {
2121 std::string ErrorStr = "could not find file '";
2122 ErrorStr += Filename;
2123 ErrorStr += "' referenced by AST file";
2124 Error(ErrorStr.c_str());
Guy Benyei11169dd2012-12-18 14:30:41 +00002125 }
Ben Langmuir198c1682014-03-07 07:27:49 +00002126 // Record that we didn't find the file.
2127 F.InputFilesLoaded[ID-1] = InputFile::getNotFound();
2128 return InputFile();
2129 }
Guy Benyei11169dd2012-12-18 14:30:41 +00002130
Ben Langmuir198c1682014-03-07 07:27:49 +00002131 // Check if there was a request to override the contents of the file
2132 // that was part of the precompiled header. Overridding such a file
2133 // can lead to problems when lexing using the source locations from the
2134 // PCH.
2135 SourceManager &SM = getSourceManager();
2136 if (!Overridden && SM.isFileOverridden(File)) {
2137 if (Complain)
2138 Error(diag::err_fe_pch_file_overridden, Filename);
2139 // After emitting the diagnostic, recover by disabling the override so
2140 // that the original file will be used.
2141 SM.disableFileContentsOverride(File);
2142 // The FileEntry is a virtual file entry with the size of the contents
2143 // that would override the original contents. Set it to the original's
2144 // size/time.
2145 FileMgr.modifyFileEntry(const_cast<FileEntry*>(File),
2146 StoredSize, StoredTime);
2147 }
Guy Benyei11169dd2012-12-18 14:30:41 +00002148
Ben Langmuir198c1682014-03-07 07:27:49 +00002149 bool IsOutOfDate = false;
2150
2151 // For an overridden file, there is nothing to validate.
2152 if (!Overridden && (StoredSize != File->getSize()
Guy Benyei11169dd2012-12-18 14:30:41 +00002153#if !defined(LLVM_ON_WIN32)
Ben Langmuir198c1682014-03-07 07:27:49 +00002154 // In our regression testing, the Windows file system seems to
2155 // have inconsistent modification times that sometimes
2156 // erroneously trigger this error-handling path.
2157 || StoredTime != File->getModificationTime()
Guy Benyei11169dd2012-12-18 14:30:41 +00002158#endif
Ben Langmuir198c1682014-03-07 07:27:49 +00002159 )) {
2160 if (Complain) {
2161 // Build a list of the PCH imports that got us here (in reverse).
2162 SmallVector<ModuleFile *, 4> ImportStack(1, &F);
2163 while (ImportStack.back()->ImportedBy.size() > 0)
2164 ImportStack.push_back(ImportStack.back()->ImportedBy[0]);
Ben Langmuire82630d2014-01-17 00:19:09 +00002165
Ben Langmuir198c1682014-03-07 07:27:49 +00002166 // The top-level PCH is stale.
2167 StringRef TopLevelPCHName(ImportStack.back()->FileName);
2168 Error(diag::err_fe_pch_file_modified, Filename, TopLevelPCHName);
Ben Langmuire82630d2014-01-17 00:19:09 +00002169
Ben Langmuir198c1682014-03-07 07:27:49 +00002170 // Print the import stack.
2171 if (ImportStack.size() > 1 && !Diags.isDiagnosticInFlight()) {
2172 Diag(diag::note_pch_required_by)
2173 << Filename << ImportStack[0]->FileName;
2174 for (unsigned I = 1; I < ImportStack.size(); ++I)
Ben Langmuire82630d2014-01-17 00:19:09 +00002175 Diag(diag::note_pch_required_by)
Ben Langmuir198c1682014-03-07 07:27:49 +00002176 << ImportStack[I-1]->FileName << ImportStack[I]->FileName;
Douglas Gregor7029ce12013-03-19 00:28:20 +00002177 }
2178
Ben Langmuir198c1682014-03-07 07:27:49 +00002179 if (!Diags.isDiagnosticInFlight())
2180 Diag(diag::note_pch_rebuild_required) << TopLevelPCHName;
Guy Benyei11169dd2012-12-18 14:30:41 +00002181 }
2182
Ben Langmuir198c1682014-03-07 07:27:49 +00002183 IsOutOfDate = true;
Guy Benyei11169dd2012-12-18 14:30:41 +00002184 }
2185
Ben Langmuir198c1682014-03-07 07:27:49 +00002186 InputFile IF = InputFile(File, Overridden, IsOutOfDate);
2187
2188 // Note that we've loaded this input file.
2189 F.InputFilesLoaded[ID-1] = IF;
2190 return IF;
Guy Benyei11169dd2012-12-18 14:30:41 +00002191}
2192
2193const FileEntry *ASTReader::getFileEntry(StringRef filenameStrRef) {
2194 ModuleFile &M = ModuleMgr.getPrimaryModule();
2195 std::string Filename = filenameStrRef;
2196 MaybeAddSystemRootToFilename(M, Filename);
2197 const FileEntry *File = FileMgr.getFile(Filename);
Craig Toppera13603a2014-05-22 05:54:18 +00002198 if (File == nullptr && !M.OriginalDir.empty() && !CurrentDir.empty() &&
Guy Benyei11169dd2012-12-18 14:30:41 +00002199 M.OriginalDir != CurrentDir) {
2200 std::string resolved = resolveFileRelativeToOriginalDir(Filename,
2201 M.OriginalDir,
2202 CurrentDir);
2203 if (!resolved.empty())
2204 File = FileMgr.getFile(resolved);
2205 }
2206
2207 return File;
2208}
2209
2210/// \brief If we are loading a relocatable PCH file, and the filename is
2211/// not an absolute path, add the system root to the beginning of the file
2212/// name.
2213void ASTReader::MaybeAddSystemRootToFilename(ModuleFile &M,
2214 std::string &Filename) {
2215 // If this is not a relocatable PCH file, there's nothing to do.
2216 if (!M.RelocatablePCH)
2217 return;
2218
2219 if (Filename.empty() || llvm::sys::path::is_absolute(Filename))
2220 return;
2221
2222 if (isysroot.empty()) {
2223 // If no system root was given, default to '/'
2224 Filename.insert(Filename.begin(), '/');
2225 return;
2226 }
2227
2228 unsigned Length = isysroot.size();
2229 if (isysroot[Length - 1] != '/')
2230 Filename.insert(Filename.begin(), '/');
2231
2232 Filename.insert(Filename.begin(), isysroot.begin(), isysroot.end());
2233}
2234
2235ASTReader::ASTReadResult
2236ASTReader::ReadControlBlock(ModuleFile &F,
Dmitri Gribenkof8579502013-01-12 19:30:44 +00002237 SmallVectorImpl<ImportedModule> &Loaded,
Ben Langmuirbeee15e2014-04-14 18:00:01 +00002238 const ModuleFile *ImportedBy,
Guy Benyei11169dd2012-12-18 14:30:41 +00002239 unsigned ClientLoadCapabilities) {
Chris Lattner7fb3bef2013-01-20 00:56:42 +00002240 BitstreamCursor &Stream = F.Stream;
Guy Benyei11169dd2012-12-18 14:30:41 +00002241
2242 if (Stream.EnterSubBlock(CONTROL_BLOCK_ID)) {
2243 Error("malformed block record in AST file");
2244 return Failure;
2245 }
2246
2247 // Read all of the records and blocks in the control block.
2248 RecordData Record;
Chris Lattnere7b154b2013-01-19 21:39:22 +00002249 while (1) {
2250 llvm::BitstreamEntry Entry = Stream.advance();
2251
2252 switch (Entry.Kind) {
2253 case llvm::BitstreamEntry::Error:
2254 Error("malformed block record in AST file");
2255 return Failure;
Dmitri Gribenkof430da42014-02-12 10:33:14 +00002256 case llvm::BitstreamEntry::EndBlock: {
2257 // Validate input files.
2258 const HeaderSearchOptions &HSOpts =
2259 PP.getHeaderSearchInfo().getHeaderSearchOpts();
Ben Langmuircb69b572014-03-07 06:40:32 +00002260
2261 // All user input files reside at the index range [0, Record[1]), and
2262 // system input files reside at [Record[1], Record[0]).
2263 // Record is the one from INPUT_FILE_OFFSETS.
2264 unsigned NumInputs = Record[0];
2265 unsigned NumUserInputs = Record[1];
2266
Dmitri Gribenkof430da42014-02-12 10:33:14 +00002267 if (!DisableValidation &&
Ben Langmuir1e258222014-04-08 15:36:28 +00002268 (ValidateSystemInputs || !HSOpts.ModulesValidateOncePerBuildSession ||
Dmitri Gribenkof430da42014-02-12 10:33:14 +00002269 F.InputFilesValidationTimestamp <= HSOpts.BuildSessionTimestamp)) {
Guy Benyei11169dd2012-12-18 14:30:41 +00002270 bool Complain = (ClientLoadCapabilities & ARR_OutOfDate) == 0;
Ben Langmuircb69b572014-03-07 06:40:32 +00002271
Dmitri Gribenkof430da42014-02-12 10:33:14 +00002272 // If we are reading a module, we will create a verification timestamp,
2273 // so we verify all input files. Otherwise, verify only user input
2274 // files.
Ben Langmuircb69b572014-03-07 06:40:32 +00002275
2276 unsigned N = NumUserInputs;
2277 if (ValidateSystemInputs ||
Ben Langmuircb69b572014-03-07 06:40:32 +00002278 (HSOpts.ModulesValidateOncePerBuildSession && F.Kind == MK_Module))
2279 N = NumInputs;
2280
Ben Langmuir3d4417c2014-02-07 17:31:11 +00002281 for (unsigned I = 0; I < N; ++I) {
Argyrios Kyrtzidis61c3d872013-03-01 03:26:04 +00002282 InputFile IF = getInputFile(F, I+1, Complain);
2283 if (!IF.getFile() || IF.isOutOfDate())
Guy Benyei11169dd2012-12-18 14:30:41 +00002284 return OutOfDate;
Argyrios Kyrtzidis61c3d872013-03-01 03:26:04 +00002285 }
Guy Benyei11169dd2012-12-18 14:30:41 +00002286 }
Ben Langmuircb69b572014-03-07 06:40:32 +00002287
Argyrios Kyrtzidis6d0753d2014-03-14 03:07:38 +00002288 if (Listener)
2289 Listener->visitModuleFile(F.FileName);
2290
Ben Langmuircb69b572014-03-07 06:40:32 +00002291 if (Listener && Listener->needsInputFileVisitation()) {
2292 unsigned N = Listener->needsSystemInputFileVisitation() ? NumInputs
2293 : NumUserInputs;
Argyrios Kyrtzidis68ccbe02014-03-14 02:26:31 +00002294 for (unsigned I = 0; I < N; ++I) {
2295 bool IsSystem = I >= NumUserInputs;
2296 InputFileInfo FI = readInputFileInfo(F, I+1);
2297 Listener->visitInputFile(FI.Filename, IsSystem, FI.Overridden);
2298 }
Ben Langmuircb69b572014-03-07 06:40:32 +00002299 }
2300
Guy Benyei11169dd2012-12-18 14:30:41 +00002301 return Success;
Dmitri Gribenkof430da42014-02-12 10:33:14 +00002302 }
2303
Chris Lattnere7b154b2013-01-19 21:39:22 +00002304 case llvm::BitstreamEntry::SubBlock:
2305 switch (Entry.ID) {
Guy Benyei11169dd2012-12-18 14:30:41 +00002306 case INPUT_FILES_BLOCK_ID:
2307 F.InputFilesCursor = Stream;
2308 if (Stream.SkipBlock() || // Skip with the main cursor
2309 // Read the abbreviations
2310 ReadBlockAbbrevs(F.InputFilesCursor, INPUT_FILES_BLOCK_ID)) {
2311 Error("malformed block record in AST file");
2312 return Failure;
2313 }
2314 continue;
Chris Lattnere7b154b2013-01-19 21:39:22 +00002315
Guy Benyei11169dd2012-12-18 14:30:41 +00002316 default:
Chris Lattnere7b154b2013-01-19 21:39:22 +00002317 if (Stream.SkipBlock()) {
2318 Error("malformed block record in AST file");
2319 return Failure;
2320 }
2321 continue;
Guy Benyei11169dd2012-12-18 14:30:41 +00002322 }
Chris Lattnere7b154b2013-01-19 21:39:22 +00002323
2324 case llvm::BitstreamEntry::Record:
2325 // The interesting case.
2326 break;
Guy Benyei11169dd2012-12-18 14:30:41 +00002327 }
2328
2329 // Read and process a record.
2330 Record.clear();
Chris Lattner0e6c9402013-01-20 02:38:54 +00002331 StringRef Blob;
2332 switch ((ControlRecordTypes)Stream.readRecord(Entry.ID, Record, &Blob)) {
Guy Benyei11169dd2012-12-18 14:30:41 +00002333 case METADATA: {
2334 if (Record[0] != VERSION_MAJOR && !DisableValidation) {
2335 if ((ClientLoadCapabilities & ARR_VersionMismatch) == 0)
Dmitri Gribenko2228cd32014-02-11 15:40:09 +00002336 Diag(Record[0] < VERSION_MAJOR? diag::err_pch_version_too_old
2337 : diag::err_pch_version_too_new);
Guy Benyei11169dd2012-12-18 14:30:41 +00002338 return VersionMismatch;
2339 }
2340
2341 bool hasErrors = Record[5];
2342 if (hasErrors && !DisableValidation && !AllowASTWithCompilerErrors) {
2343 Diag(diag::err_pch_with_compiler_errors);
2344 return HadErrors;
2345 }
2346
2347 F.RelocatablePCH = Record[4];
2348
2349 const std::string &CurBranch = getClangFullRepositoryVersion();
Chris Lattner0e6c9402013-01-20 02:38:54 +00002350 StringRef ASTBranch = Blob;
Guy Benyei11169dd2012-12-18 14:30:41 +00002351 if (StringRef(CurBranch) != ASTBranch && !DisableValidation) {
2352 if ((ClientLoadCapabilities & ARR_VersionMismatch) == 0)
Dmitri Gribenko2228cd32014-02-11 15:40:09 +00002353 Diag(diag::err_pch_different_branch) << ASTBranch << CurBranch;
Guy Benyei11169dd2012-12-18 14:30:41 +00002354 return VersionMismatch;
2355 }
2356 break;
2357 }
2358
2359 case IMPORTS: {
2360 // Load each of the imported PCH files.
2361 unsigned Idx = 0, N = Record.size();
2362 while (Idx < N) {
2363 // Read information about the AST file.
2364 ModuleKind ImportedKind = (ModuleKind)Record[Idx++];
2365 // The import location will be the local one for now; we will adjust
2366 // all import locations of module imports after the global source
2367 // location info are setup.
2368 SourceLocation ImportLoc =
2369 SourceLocation::getFromRawEncoding(Record[Idx++]);
Douglas Gregor7029ce12013-03-19 00:28:20 +00002370 off_t StoredSize = (off_t)Record[Idx++];
2371 time_t StoredModTime = (time_t)Record[Idx++];
Guy Benyei11169dd2012-12-18 14:30:41 +00002372 unsigned Length = Record[Idx++];
2373 SmallString<128> ImportedFile(Record.begin() + Idx,
2374 Record.begin() + Idx + Length);
2375 Idx += Length;
2376
2377 // Load the AST file.
2378 switch(ReadASTCore(ImportedFile, ImportedKind, ImportLoc, &F, Loaded,
Douglas Gregor7029ce12013-03-19 00:28:20 +00002379 StoredSize, StoredModTime,
Guy Benyei11169dd2012-12-18 14:30:41 +00002380 ClientLoadCapabilities)) {
2381 case Failure: return Failure;
2382 // If we have to ignore the dependency, we'll have to ignore this too.
Douglas Gregor2f1806e2013-03-19 00:38:50 +00002383 case Missing:
Guy Benyei11169dd2012-12-18 14:30:41 +00002384 case OutOfDate: return OutOfDate;
2385 case VersionMismatch: return VersionMismatch;
2386 case ConfigurationMismatch: return ConfigurationMismatch;
2387 case HadErrors: return HadErrors;
2388 case Success: break;
2389 }
2390 }
2391 break;
2392 }
2393
2394 case LANGUAGE_OPTIONS: {
2395 bool Complain = (ClientLoadCapabilities & ARR_ConfigurationMismatch) == 0;
2396 if (Listener && &F == *ModuleMgr.begin() &&
2397 ParseLanguageOptions(Record, Complain, *Listener) &&
Ben Langmuir2cb4a782014-02-05 22:21:15 +00002398 !DisableValidation && !AllowConfigurationMismatch)
Guy Benyei11169dd2012-12-18 14:30:41 +00002399 return ConfigurationMismatch;
2400 break;
2401 }
2402
2403 case TARGET_OPTIONS: {
2404 bool Complain = (ClientLoadCapabilities & ARR_ConfigurationMismatch)==0;
2405 if (Listener && &F == *ModuleMgr.begin() &&
2406 ParseTargetOptions(Record, Complain, *Listener) &&
Ben Langmuir2cb4a782014-02-05 22:21:15 +00002407 !DisableValidation && !AllowConfigurationMismatch)
Guy Benyei11169dd2012-12-18 14:30:41 +00002408 return ConfigurationMismatch;
2409 break;
2410 }
2411
2412 case DIAGNOSTIC_OPTIONS: {
Ben Langmuirb92de022014-04-29 16:25:26 +00002413 bool Complain = (ClientLoadCapabilities & ARR_OutOfDate)==0;
Guy Benyei11169dd2012-12-18 14:30:41 +00002414 if (Listener && &F == *ModuleMgr.begin() &&
2415 ParseDiagnosticOptions(Record, Complain, *Listener) &&
Ben Langmuirb92de022014-04-29 16:25:26 +00002416 !DisableValidation)
2417 return OutOfDate;
Guy Benyei11169dd2012-12-18 14:30:41 +00002418 break;
2419 }
2420
2421 case FILE_SYSTEM_OPTIONS: {
2422 bool Complain = (ClientLoadCapabilities & ARR_ConfigurationMismatch)==0;
2423 if (Listener && &F == *ModuleMgr.begin() &&
2424 ParseFileSystemOptions(Record, Complain, *Listener) &&
Ben Langmuir2cb4a782014-02-05 22:21:15 +00002425 !DisableValidation && !AllowConfigurationMismatch)
Guy Benyei11169dd2012-12-18 14:30:41 +00002426 return ConfigurationMismatch;
2427 break;
2428 }
2429
2430 case HEADER_SEARCH_OPTIONS: {
2431 bool Complain = (ClientLoadCapabilities & ARR_ConfigurationMismatch)==0;
2432 if (Listener && &F == *ModuleMgr.begin() &&
2433 ParseHeaderSearchOptions(Record, Complain, *Listener) &&
Ben Langmuir2cb4a782014-02-05 22:21:15 +00002434 !DisableValidation && !AllowConfigurationMismatch)
Guy Benyei11169dd2012-12-18 14:30:41 +00002435 return ConfigurationMismatch;
2436 break;
2437 }
2438
2439 case PREPROCESSOR_OPTIONS: {
2440 bool Complain = (ClientLoadCapabilities & ARR_ConfigurationMismatch)==0;
2441 if (Listener && &F == *ModuleMgr.begin() &&
2442 ParsePreprocessorOptions(Record, Complain, *Listener,
2443 SuggestedPredefines) &&
Ben Langmuir2cb4a782014-02-05 22:21:15 +00002444 !DisableValidation && !AllowConfigurationMismatch)
Guy Benyei11169dd2012-12-18 14:30:41 +00002445 return ConfigurationMismatch;
2446 break;
2447 }
2448
2449 case ORIGINAL_FILE:
2450 F.OriginalSourceFileID = FileID::get(Record[0]);
Chris Lattner0e6c9402013-01-20 02:38:54 +00002451 F.ActualOriginalSourceFileName = Blob;
Guy Benyei11169dd2012-12-18 14:30:41 +00002452 F.OriginalSourceFileName = F.ActualOriginalSourceFileName;
2453 MaybeAddSystemRootToFilename(F, F.OriginalSourceFileName);
2454 break;
2455
2456 case ORIGINAL_FILE_ID:
2457 F.OriginalSourceFileID = FileID::get(Record[0]);
2458 break;
2459
2460 case ORIGINAL_PCH_DIR:
Chris Lattner0e6c9402013-01-20 02:38:54 +00002461 F.OriginalDir = Blob;
Guy Benyei11169dd2012-12-18 14:30:41 +00002462 break;
2463
Ben Langmuirbeee15e2014-04-14 18:00:01 +00002464 case MODULE_NAME:
2465 F.ModuleName = Blob;
Ben Langmuir4f5212a2014-04-14 22:12:44 +00002466 if (Listener)
2467 Listener->ReadModuleName(F.ModuleName);
Ben Langmuirbeee15e2014-04-14 18:00:01 +00002468 break;
2469
2470 case MODULE_MAP_FILE:
2471 F.ModuleMapPath = Blob;
2472
2473 // Try to resolve ModuleName in the current header search context and
2474 // verify that it is found in the same module map file as we saved. If the
2475 // top-level AST file is a main file, skip this check because there is no
2476 // usable header search context.
2477 assert(!F.ModuleName.empty() &&
2478 "MODULE_NAME should come before MOUDLE_MAP_FILE");
2479 if (F.Kind == MK_Module &&
2480 (*ModuleMgr.begin())->Kind != MK_MainFile) {
2481 Module *M = PP.getHeaderSearchInfo().lookupModule(F.ModuleName);
2482 if (!M) {
2483 assert(ImportedBy && "top-level import should be verified");
2484 if ((ClientLoadCapabilities & ARR_Missing) == 0)
2485 Diag(diag::err_imported_module_not_found)
2486 << F.ModuleName << ImportedBy->FileName;
2487 return Missing;
2488 }
2489
Ben Langmuir9d6448b2014-08-09 00:57:23 +00002490 HeaderSearch &HS = PP.getHeaderSearchInfo();
Ben Langmuirbeee15e2014-04-14 18:00:01 +00002491 const FileEntry *StoredModMap = FileMgr.getFile(F.ModuleMapPath);
Ben Langmuir9d6448b2014-08-09 00:57:23 +00002492 const FileEntry *ModMap =
2493 HS.getModuleMap().getModuleMapFileForUniquing(M);
2494 if (StoredModMap == nullptr || StoredModMap != ModMap) {
2495 assert(ModMap && "found module is missing module map file");
Ben Langmuirbeee15e2014-04-14 18:00:01 +00002496 assert(M->Name == F.ModuleName && "found module with different name");
2497 assert(ImportedBy && "top-level import should be verified");
2498 if ((ClientLoadCapabilities & ARR_OutOfDate) == 0)
2499 Diag(diag::err_imported_module_modmap_changed)
2500 << F.ModuleName << ImportedBy->FileName
Ben Langmuir9d6448b2014-08-09 00:57:23 +00002501 << ModMap->getName() << F.ModuleMapPath;
Ben Langmuirbeee15e2014-04-14 18:00:01 +00002502 return OutOfDate;
2503 }
2504 }
Ben Langmuir4f5212a2014-04-14 22:12:44 +00002505
2506 if (Listener)
2507 Listener->ReadModuleMapFile(F.ModuleMapPath);
Ben Langmuirbeee15e2014-04-14 18:00:01 +00002508 break;
2509
Guy Benyei11169dd2012-12-18 14:30:41 +00002510 case INPUT_FILE_OFFSETS:
Chris Lattner0e6c9402013-01-20 02:38:54 +00002511 F.InputFileOffsets = (const uint32_t *)Blob.data();
Guy Benyei11169dd2012-12-18 14:30:41 +00002512 F.InputFilesLoaded.resize(Record[0]);
2513 break;
2514 }
2515 }
Guy Benyei11169dd2012-12-18 14:30:41 +00002516}
2517
Ben Langmuir2c9af442014-04-10 17:57:43 +00002518ASTReader::ASTReadResult
2519ASTReader::ReadASTBlock(ModuleFile &F, unsigned ClientLoadCapabilities) {
Chris Lattner7fb3bef2013-01-20 00:56:42 +00002520 BitstreamCursor &Stream = F.Stream;
Guy Benyei11169dd2012-12-18 14:30:41 +00002521
2522 if (Stream.EnterSubBlock(AST_BLOCK_ID)) {
2523 Error("malformed block record in AST file");
Ben Langmuir2c9af442014-04-10 17:57:43 +00002524 return Failure;
Guy Benyei11169dd2012-12-18 14:30:41 +00002525 }
2526
2527 // Read all of the records and blocks for the AST file.
2528 RecordData Record;
Chris Lattnere7b154b2013-01-19 21:39:22 +00002529 while (1) {
2530 llvm::BitstreamEntry Entry = Stream.advance();
2531
2532 switch (Entry.Kind) {
2533 case llvm::BitstreamEntry::Error:
2534 Error("error at end of module block in AST file");
Ben Langmuir2c9af442014-04-10 17:57:43 +00002535 return Failure;
Chris Lattnere7b154b2013-01-19 21:39:22 +00002536 case llvm::BitstreamEntry::EndBlock: {
Richard Smithc0fbba72013-04-03 22:49:41 +00002537 // Outside of C++, we do not store a lookup map for the translation unit.
2538 // Instead, mark it as needing a lookup map to be built if this module
2539 // contains any declarations lexically within it (which it always does!).
2540 // This usually has no cost, since we very rarely need the lookup map for
2541 // the translation unit outside C++.
Guy Benyei11169dd2012-12-18 14:30:41 +00002542 DeclContext *DC = Context.getTranslationUnitDecl();
Richard Smithc0fbba72013-04-03 22:49:41 +00002543 if (DC->hasExternalLexicalStorage() &&
2544 !getContext().getLangOpts().CPlusPlus)
Guy Benyei11169dd2012-12-18 14:30:41 +00002545 DC->setMustBuildLookupTable();
Chris Lattnere7b154b2013-01-19 21:39:22 +00002546
Ben Langmuir2c9af442014-04-10 17:57:43 +00002547 return Success;
Guy Benyei11169dd2012-12-18 14:30:41 +00002548 }
Chris Lattnere7b154b2013-01-19 21:39:22 +00002549 case llvm::BitstreamEntry::SubBlock:
2550 switch (Entry.ID) {
Guy Benyei11169dd2012-12-18 14:30:41 +00002551 case DECLTYPES_BLOCK_ID:
2552 // We lazily load the decls block, but we want to set up the
2553 // DeclsCursor cursor to point into it. Clone our current bitcode
2554 // cursor to it, enter the block and read the abbrevs in that block.
2555 // With the main cursor, we just skip over it.
2556 F.DeclsCursor = Stream;
2557 if (Stream.SkipBlock() || // Skip with the main cursor.
2558 // Read the abbrevs.
2559 ReadBlockAbbrevs(F.DeclsCursor, DECLTYPES_BLOCK_ID)) {
2560 Error("malformed block record in AST file");
Ben Langmuir2c9af442014-04-10 17:57:43 +00002561 return Failure;
Guy Benyei11169dd2012-12-18 14:30:41 +00002562 }
2563 break;
Richard Smithb9eab6d2014-03-20 19:44:17 +00002564
Guy Benyei11169dd2012-12-18 14:30:41 +00002565 case PREPROCESSOR_BLOCK_ID:
2566 F.MacroCursor = Stream;
2567 if (!PP.getExternalSource())
2568 PP.setExternalSource(this);
Chris Lattnere7b154b2013-01-19 21:39:22 +00002569
Guy Benyei11169dd2012-12-18 14:30:41 +00002570 if (Stream.SkipBlock() ||
2571 ReadBlockAbbrevs(F.MacroCursor, PREPROCESSOR_BLOCK_ID)) {
2572 Error("malformed block record in AST file");
Ben Langmuir2c9af442014-04-10 17:57:43 +00002573 return Failure;
Guy Benyei11169dd2012-12-18 14:30:41 +00002574 }
2575 F.MacroStartOffset = F.MacroCursor.GetCurrentBitNo();
2576 break;
Chris Lattnere7b154b2013-01-19 21:39:22 +00002577
Guy Benyei11169dd2012-12-18 14:30:41 +00002578 case PREPROCESSOR_DETAIL_BLOCK_ID:
2579 F.PreprocessorDetailCursor = Stream;
2580 if (Stream.SkipBlock() ||
Chris Lattnere7b154b2013-01-19 21:39:22 +00002581 ReadBlockAbbrevs(F.PreprocessorDetailCursor,
Guy Benyei11169dd2012-12-18 14:30:41 +00002582 PREPROCESSOR_DETAIL_BLOCK_ID)) {
Chris Lattnere7b154b2013-01-19 21:39:22 +00002583 Error("malformed preprocessor detail record in AST file");
Ben Langmuir2c9af442014-04-10 17:57:43 +00002584 return Failure;
Chris Lattnere7b154b2013-01-19 21:39:22 +00002585 }
Guy Benyei11169dd2012-12-18 14:30:41 +00002586 F.PreprocessorDetailStartOffset
Chris Lattnere7b154b2013-01-19 21:39:22 +00002587 = F.PreprocessorDetailCursor.GetCurrentBitNo();
2588
Guy Benyei11169dd2012-12-18 14:30:41 +00002589 if (!PP.getPreprocessingRecord())
2590 PP.createPreprocessingRecord();
2591 if (!PP.getPreprocessingRecord()->getExternalSource())
2592 PP.getPreprocessingRecord()->SetExternalSource(*this);
2593 break;
2594
2595 case SOURCE_MANAGER_BLOCK_ID:
2596 if (ReadSourceManagerBlock(F))
Ben Langmuir2c9af442014-04-10 17:57:43 +00002597 return Failure;
Guy Benyei11169dd2012-12-18 14:30:41 +00002598 break;
Chris Lattnere7b154b2013-01-19 21:39:22 +00002599
Guy Benyei11169dd2012-12-18 14:30:41 +00002600 case SUBMODULE_BLOCK_ID:
Ben Langmuir2c9af442014-04-10 17:57:43 +00002601 if (ASTReadResult Result = ReadSubmoduleBlock(F, ClientLoadCapabilities))
2602 return Result;
Guy Benyei11169dd2012-12-18 14:30:41 +00002603 break;
Chris Lattnere7b154b2013-01-19 21:39:22 +00002604
Guy Benyei11169dd2012-12-18 14:30:41 +00002605 case COMMENTS_BLOCK_ID: {
Chris Lattner7fb3bef2013-01-20 00:56:42 +00002606 BitstreamCursor C = Stream;
Guy Benyei11169dd2012-12-18 14:30:41 +00002607 if (Stream.SkipBlock() ||
2608 ReadBlockAbbrevs(C, COMMENTS_BLOCK_ID)) {
2609 Error("malformed comments block in AST file");
Ben Langmuir2c9af442014-04-10 17:57:43 +00002610 return Failure;
Guy Benyei11169dd2012-12-18 14:30:41 +00002611 }
2612 CommentsCursors.push_back(std::make_pair(C, &F));
2613 break;
2614 }
Chris Lattnere7b154b2013-01-19 21:39:22 +00002615
Guy Benyei11169dd2012-12-18 14:30:41 +00002616 default:
Chris Lattnere7b154b2013-01-19 21:39:22 +00002617 if (Stream.SkipBlock()) {
2618 Error("malformed block record in AST file");
Ben Langmuir2c9af442014-04-10 17:57:43 +00002619 return Failure;
Chris Lattnere7b154b2013-01-19 21:39:22 +00002620 }
2621 break;
Guy Benyei11169dd2012-12-18 14:30:41 +00002622 }
2623 continue;
Chris Lattnere7b154b2013-01-19 21:39:22 +00002624
2625 case llvm::BitstreamEntry::Record:
2626 // The interesting case.
2627 break;
Guy Benyei11169dd2012-12-18 14:30:41 +00002628 }
2629
2630 // Read and process a record.
2631 Record.clear();
Chris Lattner0e6c9402013-01-20 02:38:54 +00002632 StringRef Blob;
2633 switch ((ASTRecordTypes)Stream.readRecord(Entry.ID, Record, &Blob)) {
Guy Benyei11169dd2012-12-18 14:30:41 +00002634 default: // Default behavior: ignore.
2635 break;
2636
2637 case TYPE_OFFSET: {
2638 if (F.LocalNumTypes != 0) {
2639 Error("duplicate TYPE_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.TypeOffsets = (const uint32_t *)Blob.data();
Guy Benyei11169dd2012-12-18 14:30:41 +00002643 F.LocalNumTypes = Record[0];
2644 unsigned LocalBaseTypeIndex = Record[1];
2645 F.BaseTypeIndex = getTotalNumTypes();
2646
2647 if (F.LocalNumTypes > 0) {
2648 // Introduce the global -> local mapping for types within this module.
2649 GlobalTypeMap.insert(std::make_pair(getTotalNumTypes(), &F));
2650
2651 // Introduce the local -> global mapping for types within this module.
2652 F.TypeRemap.insertOrReplace(
2653 std::make_pair(LocalBaseTypeIndex,
2654 F.BaseTypeIndex - LocalBaseTypeIndex));
2655
2656 TypesLoaded.resize(TypesLoaded.size() + F.LocalNumTypes);
2657 }
2658 break;
2659 }
2660
2661 case DECL_OFFSET: {
2662 if (F.LocalNumDecls != 0) {
2663 Error("duplicate DECL_OFFSET record in AST file");
Ben Langmuir2c9af442014-04-10 17:57:43 +00002664 return Failure;
Guy Benyei11169dd2012-12-18 14:30:41 +00002665 }
Chris Lattner0e6c9402013-01-20 02:38:54 +00002666 F.DeclOffsets = (const DeclOffset *)Blob.data();
Guy Benyei11169dd2012-12-18 14:30:41 +00002667 F.LocalNumDecls = Record[0];
2668 unsigned LocalBaseDeclID = Record[1];
2669 F.BaseDeclID = getTotalNumDecls();
2670
2671 if (F.LocalNumDecls > 0) {
2672 // Introduce the global -> local mapping for declarations within this
2673 // module.
2674 GlobalDeclMap.insert(
2675 std::make_pair(getTotalNumDecls() + NUM_PREDEF_DECL_IDS, &F));
2676
2677 // Introduce the local -> global mapping for declarations within this
2678 // module.
2679 F.DeclRemap.insertOrReplace(
2680 std::make_pair(LocalBaseDeclID, F.BaseDeclID - LocalBaseDeclID));
2681
2682 // Introduce the global -> local mapping for declarations within this
2683 // module.
2684 F.GlobalToLocalDeclIDs[&F] = LocalBaseDeclID;
2685
2686 DeclsLoaded.resize(DeclsLoaded.size() + F.LocalNumDecls);
2687 }
2688 break;
2689 }
2690
2691 case TU_UPDATE_LEXICAL: {
2692 DeclContext *TU = Context.getTranslationUnitDecl();
2693 DeclContextInfo &Info = F.DeclContextInfos[TU];
Chris Lattner0e6c9402013-01-20 02:38:54 +00002694 Info.LexicalDecls = reinterpret_cast<const KindDeclIDPair *>(Blob.data());
Guy Benyei11169dd2012-12-18 14:30:41 +00002695 Info.NumLexicalDecls
Chris Lattner0e6c9402013-01-20 02:38:54 +00002696 = static_cast<unsigned int>(Blob.size() / sizeof(KindDeclIDPair));
Guy Benyei11169dd2012-12-18 14:30:41 +00002697 TU->setHasExternalLexicalStorage(true);
2698 break;
2699 }
2700
2701 case UPDATE_VISIBLE: {
2702 unsigned Idx = 0;
2703 serialization::DeclID ID = ReadDeclID(F, Record, Idx);
2704 ASTDeclContextNameLookupTable *Table =
Justin Bognerda4e6502014-04-14 16:34:29 +00002705 ASTDeclContextNameLookupTable::Create(
2706 (const unsigned char *)Blob.data() + Record[Idx++],
2707 (const unsigned char *)Blob.data() + sizeof(uint32_t),
2708 (const unsigned char *)Blob.data(),
2709 ASTDeclContextNameLookupTrait(*this, F));
Richard Smithcd45dbc2014-04-19 03:48:30 +00002710 if (Decl *D = GetExistingDecl(ID)) {
Richard Smithd9174792014-03-11 03:10:46 +00002711 auto *DC = cast<DeclContext>(D);
2712 DC->getPrimaryContext()->setHasExternalVisibleStorage(true);
Richard Smith52e3fba2014-03-11 07:17:35 +00002713 auto *&LookupTable = F.DeclContextInfos[DC].NameLookupTableData;
Richard Smithcd45dbc2014-04-19 03:48:30 +00002714 // FIXME: There should never be an existing lookup table.
Richard Smith52e3fba2014-03-11 07:17:35 +00002715 delete LookupTable;
2716 LookupTable = Table;
Guy Benyei11169dd2012-12-18 14:30:41 +00002717 } else
2718 PendingVisibleUpdates[ID].push_back(std::make_pair(Table, &F));
2719 break;
2720 }
2721
2722 case IDENTIFIER_TABLE:
Chris Lattner0e6c9402013-01-20 02:38:54 +00002723 F.IdentifierTableData = Blob.data();
Guy Benyei11169dd2012-12-18 14:30:41 +00002724 if (Record[0]) {
Justin Bognerda4e6502014-04-14 16:34:29 +00002725 F.IdentifierLookupTable = ASTIdentifierLookupTable::Create(
2726 (const unsigned char *)F.IdentifierTableData + Record[0],
2727 (const unsigned char *)F.IdentifierTableData + sizeof(uint32_t),
2728 (const unsigned char *)F.IdentifierTableData,
2729 ASTIdentifierLookupTrait(*this, F));
Guy Benyei11169dd2012-12-18 14:30:41 +00002730
2731 PP.getIdentifierTable().setExternalIdentifierLookup(this);
2732 }
2733 break;
2734
2735 case IDENTIFIER_OFFSET: {
2736 if (F.LocalNumIdentifiers != 0) {
2737 Error("duplicate IDENTIFIER_OFFSET record in AST file");
Ben Langmuir2c9af442014-04-10 17:57:43 +00002738 return Failure;
Guy Benyei11169dd2012-12-18 14:30:41 +00002739 }
Chris Lattner0e6c9402013-01-20 02:38:54 +00002740 F.IdentifierOffsets = (const uint32_t *)Blob.data();
Guy Benyei11169dd2012-12-18 14:30:41 +00002741 F.LocalNumIdentifiers = Record[0];
2742 unsigned LocalBaseIdentifierID = Record[1];
2743 F.BaseIdentifierID = getTotalNumIdentifiers();
2744
2745 if (F.LocalNumIdentifiers > 0) {
2746 // Introduce the global -> local mapping for identifiers within this
2747 // module.
2748 GlobalIdentifierMap.insert(std::make_pair(getTotalNumIdentifiers() + 1,
2749 &F));
2750
2751 // Introduce the local -> global mapping for identifiers within this
2752 // module.
2753 F.IdentifierRemap.insertOrReplace(
2754 std::make_pair(LocalBaseIdentifierID,
2755 F.BaseIdentifierID - LocalBaseIdentifierID));
2756
2757 IdentifiersLoaded.resize(IdentifiersLoaded.size()
2758 + F.LocalNumIdentifiers);
2759 }
2760 break;
2761 }
2762
Ben Langmuir332aafe2014-01-31 01:06:56 +00002763 case EAGERLY_DESERIALIZED_DECLS:
Guy Benyei11169dd2012-12-18 14:30:41 +00002764 for (unsigned I = 0, N = Record.size(); I != N; ++I)
Ben Langmuir332aafe2014-01-31 01:06:56 +00002765 EagerlyDeserializedDecls.push_back(getGlobalDeclID(F, Record[I]));
Guy Benyei11169dd2012-12-18 14:30:41 +00002766 break;
2767
2768 case SPECIAL_TYPES:
Douglas Gregor44180f82013-02-01 23:45:03 +00002769 if (SpecialTypes.empty()) {
2770 for (unsigned I = 0, N = Record.size(); I != N; ++I)
2771 SpecialTypes.push_back(getGlobalTypeID(F, Record[I]));
2772 break;
2773 }
2774
2775 if (SpecialTypes.size() != Record.size()) {
2776 Error("invalid special-types record");
Ben Langmuir2c9af442014-04-10 17:57:43 +00002777 return Failure;
Douglas Gregor44180f82013-02-01 23:45:03 +00002778 }
2779
2780 for (unsigned I = 0, N = Record.size(); I != N; ++I) {
2781 serialization::TypeID ID = getGlobalTypeID(F, Record[I]);
2782 if (!SpecialTypes[I])
2783 SpecialTypes[I] = ID;
2784 // FIXME: If ID && SpecialTypes[I] != ID, do we need a separate
2785 // merge step?
2786 }
Guy Benyei11169dd2012-12-18 14:30:41 +00002787 break;
2788
2789 case STATISTICS:
2790 TotalNumStatements += Record[0];
2791 TotalNumMacros += Record[1];
2792 TotalLexicalDeclContexts += Record[2];
2793 TotalVisibleDeclContexts += Record[3];
2794 break;
2795
2796 case UNUSED_FILESCOPED_DECLS:
2797 for (unsigned I = 0, N = Record.size(); I != N; ++I)
2798 UnusedFileScopedDecls.push_back(getGlobalDeclID(F, Record[I]));
2799 break;
2800
2801 case DELEGATING_CTORS:
2802 for (unsigned I = 0, N = Record.size(); I != N; ++I)
2803 DelegatingCtorDecls.push_back(getGlobalDeclID(F, Record[I]));
2804 break;
2805
2806 case WEAK_UNDECLARED_IDENTIFIERS:
2807 if (Record.size() % 4 != 0) {
2808 Error("invalid weak identifiers record");
Ben Langmuir2c9af442014-04-10 17:57:43 +00002809 return Failure;
Guy Benyei11169dd2012-12-18 14:30:41 +00002810 }
2811
2812 // FIXME: Ignore weak undeclared identifiers from non-original PCH
2813 // files. This isn't the way to do it :)
2814 WeakUndeclaredIdentifiers.clear();
2815
2816 // Translate the weak, undeclared identifiers into global IDs.
2817 for (unsigned I = 0, N = Record.size(); I < N; /* in loop */) {
2818 WeakUndeclaredIdentifiers.push_back(
2819 getGlobalIdentifierID(F, Record[I++]));
2820 WeakUndeclaredIdentifiers.push_back(
2821 getGlobalIdentifierID(F, Record[I++]));
2822 WeakUndeclaredIdentifiers.push_back(
2823 ReadSourceLocation(F, Record, I).getRawEncoding());
2824 WeakUndeclaredIdentifiers.push_back(Record[I++]);
2825 }
2826 break;
2827
Richard Smith78165b52013-01-10 23:43:47 +00002828 case LOCALLY_SCOPED_EXTERN_C_DECLS:
Guy Benyei11169dd2012-12-18 14:30:41 +00002829 for (unsigned I = 0, N = Record.size(); I != N; ++I)
Richard Smith78165b52013-01-10 23:43:47 +00002830 LocallyScopedExternCDecls.push_back(getGlobalDeclID(F, Record[I]));
Guy Benyei11169dd2012-12-18 14:30:41 +00002831 break;
2832
2833 case SELECTOR_OFFSETS: {
Chris Lattner0e6c9402013-01-20 02:38:54 +00002834 F.SelectorOffsets = (const uint32_t *)Blob.data();
Guy Benyei11169dd2012-12-18 14:30:41 +00002835 F.LocalNumSelectors = Record[0];
2836 unsigned LocalBaseSelectorID = Record[1];
2837 F.BaseSelectorID = getTotalNumSelectors();
2838
2839 if (F.LocalNumSelectors > 0) {
2840 // Introduce the global -> local mapping for selectors within this
2841 // module.
2842 GlobalSelectorMap.insert(std::make_pair(getTotalNumSelectors()+1, &F));
2843
2844 // Introduce the local -> global mapping for selectors within this
2845 // module.
2846 F.SelectorRemap.insertOrReplace(
2847 std::make_pair(LocalBaseSelectorID,
2848 F.BaseSelectorID - LocalBaseSelectorID));
2849
2850 SelectorsLoaded.resize(SelectorsLoaded.size() + F.LocalNumSelectors);
2851 }
2852 break;
2853 }
2854
2855 case METHOD_POOL:
Chris Lattner0e6c9402013-01-20 02:38:54 +00002856 F.SelectorLookupTableData = (const unsigned char *)Blob.data();
Guy Benyei11169dd2012-12-18 14:30:41 +00002857 if (Record[0])
2858 F.SelectorLookupTable
2859 = ASTSelectorLookupTable::Create(
2860 F.SelectorLookupTableData + Record[0],
2861 F.SelectorLookupTableData,
2862 ASTSelectorLookupTrait(*this, F));
2863 TotalNumMethodPoolEntries += Record[1];
2864 break;
2865
2866 case REFERENCED_SELECTOR_POOL:
2867 if (!Record.empty()) {
2868 for (unsigned Idx = 0, N = Record.size() - 1; Idx < N; /* in loop */) {
2869 ReferencedSelectorsData.push_back(getGlobalSelectorID(F,
2870 Record[Idx++]));
2871 ReferencedSelectorsData.push_back(ReadSourceLocation(F, Record, Idx).
2872 getRawEncoding());
2873 }
2874 }
2875 break;
2876
2877 case PP_COUNTER_VALUE:
2878 if (!Record.empty() && Listener)
2879 Listener->ReadCounter(F, Record[0]);
2880 break;
2881
2882 case FILE_SORTED_DECLS:
Chris Lattner0e6c9402013-01-20 02:38:54 +00002883 F.FileSortedDecls = (const DeclID *)Blob.data();
Guy Benyei11169dd2012-12-18 14:30:41 +00002884 F.NumFileSortedDecls = Record[0];
2885 break;
2886
2887 case SOURCE_LOCATION_OFFSETS: {
Chris Lattner0e6c9402013-01-20 02:38:54 +00002888 F.SLocEntryOffsets = (const uint32_t *)Blob.data();
Guy Benyei11169dd2012-12-18 14:30:41 +00002889 F.LocalNumSLocEntries = Record[0];
2890 unsigned SLocSpaceSize = Record[1];
Benjamin Kramer867ea1d2014-03-02 13:01:17 +00002891 std::tie(F.SLocEntryBaseID, F.SLocEntryBaseOffset) =
Guy Benyei11169dd2012-12-18 14:30:41 +00002892 SourceMgr.AllocateLoadedSLocEntries(F.LocalNumSLocEntries,
2893 SLocSpaceSize);
2894 // Make our entry in the range map. BaseID is negative and growing, so
2895 // we invert it. Because we invert it, though, we need the other end of
2896 // the range.
2897 unsigned RangeStart =
2898 unsigned(-F.SLocEntryBaseID) - F.LocalNumSLocEntries + 1;
2899 GlobalSLocEntryMap.insert(std::make_pair(RangeStart, &F));
2900 F.FirstLoc = SourceLocation::getFromRawEncoding(F.SLocEntryBaseOffset);
2901
2902 // SLocEntryBaseOffset is lower than MaxLoadedOffset and decreasing.
2903 assert((F.SLocEntryBaseOffset & (1U << 31U)) == 0);
2904 GlobalSLocOffsetMap.insert(
2905 std::make_pair(SourceManager::MaxLoadedOffset - F.SLocEntryBaseOffset
2906 - SLocSpaceSize,&F));
2907
2908 // Initialize the remapping table.
2909 // Invalid stays invalid.
Richard Smithb9eab6d2014-03-20 19:44:17 +00002910 F.SLocRemap.insertOrReplace(std::make_pair(0U, 0));
Guy Benyei11169dd2012-12-18 14:30:41 +00002911 // This module. Base was 2 when being compiled.
Richard Smithb9eab6d2014-03-20 19:44:17 +00002912 F.SLocRemap.insertOrReplace(std::make_pair(2U,
Guy Benyei11169dd2012-12-18 14:30:41 +00002913 static_cast<int>(F.SLocEntryBaseOffset - 2)));
2914
2915 TotalNumSLocEntries += F.LocalNumSLocEntries;
2916 break;
2917 }
2918
2919 case MODULE_OFFSET_MAP: {
2920 // Additional remapping information.
Chris Lattner0e6c9402013-01-20 02:38:54 +00002921 const unsigned char *Data = (const unsigned char*)Blob.data();
2922 const unsigned char *DataEnd = Data + Blob.size();
Richard Smithb9eab6d2014-03-20 19:44:17 +00002923
2924 // If we see this entry before SOURCE_LOCATION_OFFSETS, add placeholders.
2925 if (F.SLocRemap.find(0) == F.SLocRemap.end()) {
2926 F.SLocRemap.insert(std::make_pair(0U, 0));
2927 F.SLocRemap.insert(std::make_pair(2U, 1));
2928 }
2929
Guy Benyei11169dd2012-12-18 14:30:41 +00002930 // Continuous range maps we may be updating in our module.
2931 ContinuousRangeMap<uint32_t, int, 2>::Builder SLocRemap(F.SLocRemap);
2932 ContinuousRangeMap<uint32_t, int, 2>::Builder
2933 IdentifierRemap(F.IdentifierRemap);
2934 ContinuousRangeMap<uint32_t, int, 2>::Builder
2935 MacroRemap(F.MacroRemap);
2936 ContinuousRangeMap<uint32_t, int, 2>::Builder
2937 PreprocessedEntityRemap(F.PreprocessedEntityRemap);
2938 ContinuousRangeMap<uint32_t, int, 2>::Builder
2939 SubmoduleRemap(F.SubmoduleRemap);
2940 ContinuousRangeMap<uint32_t, int, 2>::Builder
2941 SelectorRemap(F.SelectorRemap);
2942 ContinuousRangeMap<uint32_t, int, 2>::Builder DeclRemap(F.DeclRemap);
2943 ContinuousRangeMap<uint32_t, int, 2>::Builder TypeRemap(F.TypeRemap);
2944
2945 while(Data < DataEnd) {
Justin Bogner57ba0b22014-03-28 22:03:24 +00002946 using namespace llvm::support;
2947 uint16_t Len = endian::readNext<uint16_t, little, unaligned>(Data);
Guy Benyei11169dd2012-12-18 14:30:41 +00002948 StringRef Name = StringRef((const char*)Data, Len);
2949 Data += Len;
2950 ModuleFile *OM = ModuleMgr.lookup(Name);
2951 if (!OM) {
2952 Error("SourceLocation remap refers to unknown module");
Ben Langmuir2c9af442014-04-10 17:57:43 +00002953 return Failure;
Guy Benyei11169dd2012-12-18 14:30:41 +00002954 }
2955
Justin Bogner57ba0b22014-03-28 22:03:24 +00002956 uint32_t SLocOffset =
2957 endian::readNext<uint32_t, little, unaligned>(Data);
2958 uint32_t IdentifierIDOffset =
2959 endian::readNext<uint32_t, little, unaligned>(Data);
2960 uint32_t MacroIDOffset =
2961 endian::readNext<uint32_t, little, unaligned>(Data);
2962 uint32_t PreprocessedEntityIDOffset =
2963 endian::readNext<uint32_t, little, unaligned>(Data);
2964 uint32_t SubmoduleIDOffset =
2965 endian::readNext<uint32_t, little, unaligned>(Data);
2966 uint32_t SelectorIDOffset =
2967 endian::readNext<uint32_t, little, unaligned>(Data);
2968 uint32_t DeclIDOffset =
2969 endian::readNext<uint32_t, little, unaligned>(Data);
2970 uint32_t TypeIndexOffset =
2971 endian::readNext<uint32_t, little, unaligned>(Data);
2972
Guy Benyei11169dd2012-12-18 14:30:41 +00002973 // Source location offset is mapped to OM->SLocEntryBaseOffset.
2974 SLocRemap.insert(std::make_pair(SLocOffset,
2975 static_cast<int>(OM->SLocEntryBaseOffset - SLocOffset)));
2976 IdentifierRemap.insert(
2977 std::make_pair(IdentifierIDOffset,
2978 OM->BaseIdentifierID - IdentifierIDOffset));
2979 MacroRemap.insert(std::make_pair(MacroIDOffset,
2980 OM->BaseMacroID - MacroIDOffset));
2981 PreprocessedEntityRemap.insert(
2982 std::make_pair(PreprocessedEntityIDOffset,
2983 OM->BasePreprocessedEntityID - PreprocessedEntityIDOffset));
2984 SubmoduleRemap.insert(std::make_pair(SubmoduleIDOffset,
2985 OM->BaseSubmoduleID - SubmoduleIDOffset));
2986 SelectorRemap.insert(std::make_pair(SelectorIDOffset,
2987 OM->BaseSelectorID - SelectorIDOffset));
2988 DeclRemap.insert(std::make_pair(DeclIDOffset,
2989 OM->BaseDeclID - DeclIDOffset));
2990
2991 TypeRemap.insert(std::make_pair(TypeIndexOffset,
2992 OM->BaseTypeIndex - TypeIndexOffset));
2993
2994 // Global -> local mappings.
2995 F.GlobalToLocalDeclIDs[OM] = DeclIDOffset;
2996 }
2997 break;
2998 }
2999
3000 case SOURCE_MANAGER_LINE_TABLE:
3001 if (ParseLineTable(F, Record))
Ben Langmuir2c9af442014-04-10 17:57:43 +00003002 return Failure;
Guy Benyei11169dd2012-12-18 14:30:41 +00003003 break;
3004
3005 case SOURCE_LOCATION_PRELOADS: {
3006 // Need to transform from the local view (1-based IDs) to the global view,
3007 // which is based off F.SLocEntryBaseID.
3008 if (!F.PreloadSLocEntries.empty()) {
3009 Error("Multiple SOURCE_LOCATION_PRELOADS records in AST file");
Ben Langmuir2c9af442014-04-10 17:57:43 +00003010 return Failure;
Guy Benyei11169dd2012-12-18 14:30:41 +00003011 }
3012
3013 F.PreloadSLocEntries.swap(Record);
3014 break;
3015 }
3016
3017 case EXT_VECTOR_DECLS:
3018 for (unsigned I = 0, N = Record.size(); I != N; ++I)
3019 ExtVectorDecls.push_back(getGlobalDeclID(F, Record[I]));
3020 break;
3021
3022 case VTABLE_USES:
3023 if (Record.size() % 3 != 0) {
3024 Error("Invalid VTABLE_USES record");
Ben Langmuir2c9af442014-04-10 17:57:43 +00003025 return Failure;
Guy Benyei11169dd2012-12-18 14:30:41 +00003026 }
3027
3028 // Later tables overwrite earlier ones.
3029 // FIXME: Modules will have some trouble with this. This is clearly not
3030 // the right way to do this.
3031 VTableUses.clear();
3032
3033 for (unsigned Idx = 0, N = Record.size(); Idx != N; /* In loop */) {
3034 VTableUses.push_back(getGlobalDeclID(F, Record[Idx++]));
3035 VTableUses.push_back(
3036 ReadSourceLocation(F, Record, Idx).getRawEncoding());
3037 VTableUses.push_back(Record[Idx++]);
3038 }
3039 break;
3040
3041 case DYNAMIC_CLASSES:
3042 for (unsigned I = 0, N = Record.size(); I != N; ++I)
3043 DynamicClasses.push_back(getGlobalDeclID(F, Record[I]));
3044 break;
3045
3046 case PENDING_IMPLICIT_INSTANTIATIONS:
3047 if (PendingInstantiations.size() % 2 != 0) {
3048 Error("Invalid existing PendingInstantiations");
Ben Langmuir2c9af442014-04-10 17:57:43 +00003049 return Failure;
Guy Benyei11169dd2012-12-18 14:30:41 +00003050 }
3051
3052 if (Record.size() % 2 != 0) {
3053 Error("Invalid PENDING_IMPLICIT_INSTANTIATIONS block");
Ben Langmuir2c9af442014-04-10 17:57:43 +00003054 return Failure;
Guy Benyei11169dd2012-12-18 14:30:41 +00003055 }
3056
3057 for (unsigned I = 0, N = Record.size(); I != N; /* in loop */) {
3058 PendingInstantiations.push_back(getGlobalDeclID(F, Record[I++]));
3059 PendingInstantiations.push_back(
3060 ReadSourceLocation(F, Record, I).getRawEncoding());
3061 }
3062 break;
3063
3064 case SEMA_DECL_REFS:
Richard Smith3d8e97e2013-10-18 06:54:39 +00003065 if (Record.size() != 2) {
3066 Error("Invalid SEMA_DECL_REFS block");
Ben Langmuir2c9af442014-04-10 17:57:43 +00003067 return Failure;
Richard Smith3d8e97e2013-10-18 06:54:39 +00003068 }
Guy Benyei11169dd2012-12-18 14:30:41 +00003069 for (unsigned I = 0, N = Record.size(); I != N; ++I)
3070 SemaDeclRefs.push_back(getGlobalDeclID(F, Record[I]));
3071 break;
3072
3073 case PPD_ENTITIES_OFFSETS: {
Chris Lattner0e6c9402013-01-20 02:38:54 +00003074 F.PreprocessedEntityOffsets = (const PPEntityOffset *)Blob.data();
3075 assert(Blob.size() % sizeof(PPEntityOffset) == 0);
3076 F.NumPreprocessedEntities = Blob.size() / sizeof(PPEntityOffset);
Guy Benyei11169dd2012-12-18 14:30:41 +00003077
3078 unsigned LocalBasePreprocessedEntityID = Record[0];
3079
3080 unsigned StartingID;
3081 if (!PP.getPreprocessingRecord())
3082 PP.createPreprocessingRecord();
3083 if (!PP.getPreprocessingRecord()->getExternalSource())
3084 PP.getPreprocessingRecord()->SetExternalSource(*this);
3085 StartingID
3086 = PP.getPreprocessingRecord()
3087 ->allocateLoadedEntities(F.NumPreprocessedEntities);
3088 F.BasePreprocessedEntityID = StartingID;
3089
3090 if (F.NumPreprocessedEntities > 0) {
3091 // Introduce the global -> local mapping for preprocessed entities in
3092 // this module.
3093 GlobalPreprocessedEntityMap.insert(std::make_pair(StartingID, &F));
3094
3095 // Introduce the local -> global mapping for preprocessed entities in
3096 // this module.
3097 F.PreprocessedEntityRemap.insertOrReplace(
3098 std::make_pair(LocalBasePreprocessedEntityID,
3099 F.BasePreprocessedEntityID - LocalBasePreprocessedEntityID));
3100 }
3101
3102 break;
3103 }
3104
3105 case DECL_UPDATE_OFFSETS: {
3106 if (Record.size() % 2 != 0) {
3107 Error("invalid DECL_UPDATE_OFFSETS block in AST file");
Ben Langmuir2c9af442014-04-10 17:57:43 +00003108 return Failure;
Guy Benyei11169dd2012-12-18 14:30:41 +00003109 }
Richard Smithcd45dbc2014-04-19 03:48:30 +00003110 for (unsigned I = 0, N = Record.size(); I != N; I += 2) {
3111 GlobalDeclID ID = getGlobalDeclID(F, Record[I]);
3112 DeclUpdateOffsets[ID].push_back(std::make_pair(&F, Record[I + 1]));
3113
3114 // If we've already loaded the decl, perform the updates when we finish
3115 // loading this block.
3116 if (Decl *D = GetExistingDecl(ID))
3117 PendingUpdateRecords.push_back(std::make_pair(ID, D));
3118 }
Guy Benyei11169dd2012-12-18 14:30:41 +00003119 break;
3120 }
3121
3122 case DECL_REPLACEMENTS: {
3123 if (Record.size() % 3 != 0) {
3124 Error("invalid DECL_REPLACEMENTS block in AST file");
Ben Langmuir2c9af442014-04-10 17:57:43 +00003125 return Failure;
Guy Benyei11169dd2012-12-18 14:30:41 +00003126 }
3127 for (unsigned I = 0, N = Record.size(); I != N; I += 3)
3128 ReplacedDecls[getGlobalDeclID(F, Record[I])]
3129 = ReplacedDeclInfo(&F, Record[I+1], Record[I+2]);
3130 break;
3131 }
3132
3133 case OBJC_CATEGORIES_MAP: {
3134 if (F.LocalNumObjCCategoriesInMap != 0) {
3135 Error("duplicate OBJC_CATEGORIES_MAP record in AST file");
Ben Langmuir2c9af442014-04-10 17:57:43 +00003136 return Failure;
Guy Benyei11169dd2012-12-18 14:30:41 +00003137 }
3138
3139 F.LocalNumObjCCategoriesInMap = Record[0];
Chris Lattner0e6c9402013-01-20 02:38:54 +00003140 F.ObjCCategoriesMap = (const ObjCCategoriesInfo *)Blob.data();
Guy Benyei11169dd2012-12-18 14:30:41 +00003141 break;
3142 }
3143
3144 case OBJC_CATEGORIES:
3145 F.ObjCCategories.swap(Record);
3146 break;
3147
3148 case CXX_BASE_SPECIFIER_OFFSETS: {
3149 if (F.LocalNumCXXBaseSpecifiers != 0) {
3150 Error("duplicate CXX_BASE_SPECIFIER_OFFSETS record in AST file");
Ben Langmuir2c9af442014-04-10 17:57:43 +00003151 return Failure;
Guy Benyei11169dd2012-12-18 14:30:41 +00003152 }
3153
3154 F.LocalNumCXXBaseSpecifiers = Record[0];
Chris Lattner0e6c9402013-01-20 02:38:54 +00003155 F.CXXBaseSpecifiersOffsets = (const uint32_t *)Blob.data();
Guy Benyei11169dd2012-12-18 14:30:41 +00003156 NumCXXBaseSpecifiersLoaded += F.LocalNumCXXBaseSpecifiers;
3157 break;
3158 }
3159
3160 case DIAG_PRAGMA_MAPPINGS:
3161 if (F.PragmaDiagMappings.empty())
3162 F.PragmaDiagMappings.swap(Record);
3163 else
3164 F.PragmaDiagMappings.insert(F.PragmaDiagMappings.end(),
3165 Record.begin(), Record.end());
3166 break;
3167
3168 case CUDA_SPECIAL_DECL_REFS:
3169 // Later tables overwrite earlier ones.
3170 // FIXME: Modules will have trouble with this.
3171 CUDASpecialDeclRefs.clear();
3172 for (unsigned I = 0, N = Record.size(); I != N; ++I)
3173 CUDASpecialDeclRefs.push_back(getGlobalDeclID(F, Record[I]));
3174 break;
3175
3176 case HEADER_SEARCH_TABLE: {
Chris Lattner0e6c9402013-01-20 02:38:54 +00003177 F.HeaderFileInfoTableData = Blob.data();
Guy Benyei11169dd2012-12-18 14:30:41 +00003178 F.LocalNumHeaderFileInfos = Record[1];
Guy Benyei11169dd2012-12-18 14:30:41 +00003179 if (Record[0]) {
3180 F.HeaderFileInfoTable
3181 = HeaderFileInfoLookupTable::Create(
3182 (const unsigned char *)F.HeaderFileInfoTableData + Record[0],
3183 (const unsigned char *)F.HeaderFileInfoTableData,
3184 HeaderFileInfoTrait(*this, F,
3185 &PP.getHeaderSearchInfo(),
Chris Lattner0e6c9402013-01-20 02:38:54 +00003186 Blob.data() + Record[2]));
Guy Benyei11169dd2012-12-18 14:30:41 +00003187
3188 PP.getHeaderSearchInfo().SetExternalSource(this);
3189 if (!PP.getHeaderSearchInfo().getExternalLookup())
3190 PP.getHeaderSearchInfo().SetExternalLookup(this);
3191 }
3192 break;
3193 }
3194
3195 case FP_PRAGMA_OPTIONS:
3196 // Later tables overwrite earlier ones.
3197 FPPragmaOptions.swap(Record);
3198 break;
3199
3200 case OPENCL_EXTENSIONS:
3201 // Later tables overwrite earlier ones.
3202 OpenCLExtensions.swap(Record);
3203 break;
3204
3205 case TENTATIVE_DEFINITIONS:
3206 for (unsigned I = 0, N = Record.size(); I != N; ++I)
3207 TentativeDefinitions.push_back(getGlobalDeclID(F, Record[I]));
3208 break;
3209
3210 case KNOWN_NAMESPACES:
3211 for (unsigned I = 0, N = Record.size(); I != N; ++I)
3212 KnownNamespaces.push_back(getGlobalDeclID(F, Record[I]));
3213 break;
Nick Lewycky8334af82013-01-26 00:35:08 +00003214
Nick Lewycky9c7eb1d2013-02-01 08:13:20 +00003215 case UNDEFINED_BUT_USED:
3216 if (UndefinedButUsed.size() % 2 != 0) {
3217 Error("Invalid existing UndefinedButUsed");
Ben Langmuir2c9af442014-04-10 17:57:43 +00003218 return Failure;
Nick Lewycky8334af82013-01-26 00:35:08 +00003219 }
3220
3221 if (Record.size() % 2 != 0) {
Nick Lewycky9c7eb1d2013-02-01 08:13:20 +00003222 Error("invalid undefined-but-used record");
Ben Langmuir2c9af442014-04-10 17:57:43 +00003223 return Failure;
Nick Lewycky8334af82013-01-26 00:35:08 +00003224 }
3225 for (unsigned I = 0, N = Record.size(); I != N; /* in loop */) {
Nick Lewycky9c7eb1d2013-02-01 08:13:20 +00003226 UndefinedButUsed.push_back(getGlobalDeclID(F, Record[I++]));
3227 UndefinedButUsed.push_back(
Nick Lewycky8334af82013-01-26 00:35:08 +00003228 ReadSourceLocation(F, Record, I).getRawEncoding());
3229 }
3230 break;
3231
Guy Benyei11169dd2012-12-18 14:30:41 +00003232 case IMPORTED_MODULES: {
3233 if (F.Kind != MK_Module) {
3234 // If we aren't loading a module (which has its own exports), make
3235 // all of the imported modules visible.
3236 // FIXME: Deal with macros-only imports.
Richard Smith56be7542014-03-21 00:33:59 +00003237 for (unsigned I = 0, N = Record.size(); I != N; /**/) {
3238 unsigned GlobalID = getGlobalSubmoduleID(F, Record[I++]);
3239 SourceLocation Loc = ReadSourceLocation(F, Record, I);
3240 if (GlobalID)
Aaron Ballman4f45b712014-03-21 15:22:56 +00003241 ImportedModules.push_back(ImportedSubmodule(GlobalID, Loc));
Guy Benyei11169dd2012-12-18 14:30:41 +00003242 }
3243 }
3244 break;
3245 }
3246
3247 case LOCAL_REDECLARATIONS: {
3248 F.RedeclarationChains.swap(Record);
3249 break;
3250 }
3251
3252 case LOCAL_REDECLARATIONS_MAP: {
3253 if (F.LocalNumRedeclarationsInMap != 0) {
3254 Error("duplicate LOCAL_REDECLARATIONS_MAP record in AST file");
Ben Langmuir2c9af442014-04-10 17:57:43 +00003255 return Failure;
Guy Benyei11169dd2012-12-18 14:30:41 +00003256 }
3257
3258 F.LocalNumRedeclarationsInMap = Record[0];
Chris Lattner0e6c9402013-01-20 02:38:54 +00003259 F.RedeclarationsMap = (const LocalRedeclarationsInfo *)Blob.data();
Guy Benyei11169dd2012-12-18 14:30:41 +00003260 break;
3261 }
3262
3263 case MERGED_DECLARATIONS: {
3264 for (unsigned Idx = 0; Idx < Record.size(); /* increment in loop */) {
3265 GlobalDeclID CanonID = getGlobalDeclID(F, Record[Idx++]);
3266 SmallVectorImpl<GlobalDeclID> &Decls = StoredMergedDecls[CanonID];
3267 for (unsigned N = Record[Idx++]; N > 0; --N)
3268 Decls.push_back(getGlobalDeclID(F, Record[Idx++]));
3269 }
3270 break;
3271 }
3272
3273 case MACRO_OFFSET: {
3274 if (F.LocalNumMacros != 0) {
3275 Error("duplicate MACRO_OFFSET record in AST file");
Ben Langmuir2c9af442014-04-10 17:57:43 +00003276 return Failure;
Guy Benyei11169dd2012-12-18 14:30:41 +00003277 }
Chris Lattner0e6c9402013-01-20 02:38:54 +00003278 F.MacroOffsets = (const uint32_t *)Blob.data();
Guy Benyei11169dd2012-12-18 14:30:41 +00003279 F.LocalNumMacros = Record[0];
3280 unsigned LocalBaseMacroID = Record[1];
3281 F.BaseMacroID = getTotalNumMacros();
3282
3283 if (F.LocalNumMacros > 0) {
3284 // Introduce the global -> local mapping for macros within this module.
3285 GlobalMacroMap.insert(std::make_pair(getTotalNumMacros() + 1, &F));
3286
3287 // Introduce the local -> global mapping for macros within this module.
3288 F.MacroRemap.insertOrReplace(
3289 std::make_pair(LocalBaseMacroID,
3290 F.BaseMacroID - LocalBaseMacroID));
3291
3292 MacrosLoaded.resize(MacrosLoaded.size() + F.LocalNumMacros);
3293 }
3294 break;
3295 }
3296
Argyrios Kyrtzidiseb663da2013-03-22 21:12:57 +00003297 case MACRO_TABLE: {
3298 // FIXME: Not used yet.
Guy Benyei11169dd2012-12-18 14:30:41 +00003299 break;
3300 }
Richard Smithe40f2ba2013-08-07 21:41:30 +00003301
3302 case LATE_PARSED_TEMPLATE: {
3303 LateParsedTemplates.append(Record.begin(), Record.end());
3304 break;
3305 }
Dario Domizioli13a0a382014-05-23 12:13:25 +00003306
3307 case OPTIMIZE_PRAGMA_OPTIONS:
3308 if (Record.size() != 1) {
3309 Error("invalid pragma optimize record");
3310 return Failure;
3311 }
3312 OptimizeOffPragmaLocation = ReadSourceLocation(F, Record[0]);
3313 break;
Guy Benyei11169dd2012-12-18 14:30:41 +00003314 }
3315 }
Guy Benyei11169dd2012-12-18 14:30:41 +00003316}
3317
Douglas Gregorc1489562013-02-12 23:36:21 +00003318/// \brief Move the given method to the back of the global list of methods.
3319static void moveMethodToBackOfGlobalList(Sema &S, ObjCMethodDecl *Method) {
3320 // Find the entry for this selector in the method pool.
3321 Sema::GlobalMethodPool::iterator Known
3322 = S.MethodPool.find(Method->getSelector());
3323 if (Known == S.MethodPool.end())
3324 return;
3325
3326 // Retrieve the appropriate method list.
3327 ObjCMethodList &Start = Method->isInstanceMethod()? Known->second.first
3328 : Known->second.second;
3329 bool Found = false;
Argyrios Kyrtzidisd3da6e02013-04-17 00:08:58 +00003330 for (ObjCMethodList *List = &Start; List; List = List->getNext()) {
Douglas Gregorc1489562013-02-12 23:36:21 +00003331 if (!Found) {
3332 if (List->Method == Method) {
3333 Found = true;
3334 } else {
3335 // Keep searching.
3336 continue;
3337 }
3338 }
3339
Argyrios Kyrtzidisd3da6e02013-04-17 00:08:58 +00003340 if (List->getNext())
3341 List->Method = List->getNext()->Method;
Douglas Gregorc1489562013-02-12 23:36:21 +00003342 else
3343 List->Method = Method;
3344 }
3345}
3346
Richard Smithe657bbd2014-07-18 22:13:40 +00003347void ASTReader::makeNamesVisible(const HiddenNames &Names, Module *Owner,
3348 bool FromFinalization) {
3349 // FIXME: Only do this if Owner->NameVisibility == AllVisible.
Richard Smith57721ac2014-07-21 04:10:40 +00003350 for (Decl *D : Names.HiddenDecls) {
Richard Smith49f906a2014-03-01 00:08:04 +00003351 bool wasHidden = D->Hidden;
3352 D->Hidden = false;
Guy Benyei11169dd2012-12-18 14:30:41 +00003353
Richard Smith49f906a2014-03-01 00:08:04 +00003354 if (wasHidden && SemaObj) {
3355 if (ObjCMethodDecl *Method = dyn_cast<ObjCMethodDecl>(D)) {
3356 moveMethodToBackOfGlobalList(*SemaObj, Method);
Douglas Gregorc1489562013-02-12 23:36:21 +00003357 }
Guy Benyei11169dd2012-12-18 14:30:41 +00003358 }
3359 }
Richard Smith49f906a2014-03-01 00:08:04 +00003360
Richard Smithe657bbd2014-07-18 22:13:40 +00003361 assert((FromFinalization || Owner->NameVisibility >= Module::MacrosVisible) &&
3362 "nothing to make visible?");
Richard Smithdaa69e02014-07-25 04:40:03 +00003363 for (const auto &Macro : Names.HiddenMacros) {
3364 if (FromFinalization)
3365 PP.appendMacroDirective(Macro.first,
3366 Macro.second->import(PP, SourceLocation()));
3367 else
3368 installImportedMacro(Macro.first, Macro.second, Owner);
3369 }
Guy Benyei11169dd2012-12-18 14:30:41 +00003370}
3371
Richard Smith49f906a2014-03-01 00:08:04 +00003372void ASTReader::makeModuleVisible(Module *Mod,
Argyrios Kyrtzidis125df052013-02-01 16:36:12 +00003373 Module::NameVisibilityKind NameVisibility,
Douglas Gregorfb912652013-03-20 21:10:35 +00003374 SourceLocation ImportLoc,
3375 bool Complain) {
Guy Benyei11169dd2012-12-18 14:30:41 +00003376 llvm::SmallPtrSet<Module *, 4> Visited;
Dmitri Gribenkof8579502013-01-12 19:30:44 +00003377 SmallVector<Module *, 4> Stack;
Robert Wilhelm25284cc2013-08-23 16:11:15 +00003378 Stack.push_back(Mod);
Guy Benyei11169dd2012-12-18 14:30:41 +00003379 while (!Stack.empty()) {
Robert Wilhelm25284cc2013-08-23 16:11:15 +00003380 Mod = Stack.pop_back_val();
Guy Benyei11169dd2012-12-18 14:30:41 +00003381
3382 if (NameVisibility <= Mod->NameVisibility) {
Robert Wilhelm25284cc2013-08-23 16:11:15 +00003383 // This module already has this level of visibility (or greater), so
Guy Benyei11169dd2012-12-18 14:30:41 +00003384 // there is nothing more to do.
3385 continue;
3386 }
Richard Smith49f906a2014-03-01 00:08:04 +00003387
Guy Benyei11169dd2012-12-18 14:30:41 +00003388 if (!Mod->isAvailable()) {
3389 // Modules that aren't available cannot be made visible.
3390 continue;
3391 }
3392
3393 // Update the module's name visibility.
Richard Smith49f906a2014-03-01 00:08:04 +00003394 if (NameVisibility >= Module::MacrosVisible &&
3395 Mod->NameVisibility < Module::MacrosVisible)
3396 Mod->MacroVisibilityLoc = ImportLoc;
Guy Benyei11169dd2012-12-18 14:30:41 +00003397 Mod->NameVisibility = NameVisibility;
Richard Smith49f906a2014-03-01 00:08:04 +00003398
Guy Benyei11169dd2012-12-18 14:30:41 +00003399 // If we've already deserialized any names from this module,
3400 // mark them as visible.
3401 HiddenNamesMapType::iterator Hidden = HiddenNamesMap.find(Mod);
3402 if (Hidden != HiddenNamesMap.end()) {
Richard Smith57721ac2014-07-21 04:10:40 +00003403 auto HiddenNames = std::move(*Hidden);
Guy Benyei11169dd2012-12-18 14:30:41 +00003404 HiddenNamesMap.erase(Hidden);
Richard Smith57721ac2014-07-21 04:10:40 +00003405 makeNamesVisible(HiddenNames.second, HiddenNames.first,
3406 /*FromFinalization*/false);
3407 assert(HiddenNamesMap.find(Mod) == HiddenNamesMap.end() &&
3408 "making names visible added hidden names");
Guy Benyei11169dd2012-12-18 14:30:41 +00003409 }
Dmitri Gribenkoe9bcf5b2013-11-04 21:51:33 +00003410
Guy Benyei11169dd2012-12-18 14:30:41 +00003411 // Push any exported modules onto the stack to be marked as visible.
Argyrios Kyrtzidis8739f7b2013-02-19 19:34:40 +00003412 SmallVector<Module *, 16> Exports;
3413 Mod->getExportedModules(Exports);
3414 for (SmallVectorImpl<Module *>::iterator
3415 I = Exports.begin(), E = Exports.end(); I != E; ++I) {
3416 Module *Exported = *I;
3417 if (Visited.insert(Exported))
3418 Stack.push_back(Exported);
Guy Benyei11169dd2012-12-18 14:30:41 +00003419 }
Douglas Gregorfb912652013-03-20 21:10:35 +00003420
3421 // Detect any conflicts.
3422 if (Complain) {
3423 assert(ImportLoc.isValid() && "Missing import location");
3424 for (unsigned I = 0, N = Mod->Conflicts.size(); I != N; ++I) {
3425 if (Mod->Conflicts[I].Other->NameVisibility >= NameVisibility) {
3426 Diag(ImportLoc, diag::warn_module_conflict)
3427 << Mod->getFullModuleName()
3428 << Mod->Conflicts[I].Other->getFullModuleName()
3429 << Mod->Conflicts[I].Message;
3430 // FIXME: Need note where the other module was imported.
3431 }
3432 }
3433 }
Guy Benyei11169dd2012-12-18 14:30:41 +00003434 }
3435}
3436
Douglas Gregore060e572013-01-25 01:03:03 +00003437bool ASTReader::loadGlobalIndex() {
3438 if (GlobalIndex)
3439 return false;
3440
3441 if (TriedLoadingGlobalIndex || !UseGlobalIndex ||
3442 !Context.getLangOpts().Modules)
3443 return true;
3444
3445 // Try to load the global index.
3446 TriedLoadingGlobalIndex = true;
3447 StringRef ModuleCachePath
3448 = getPreprocessor().getHeaderSearchInfo().getModuleCachePath();
3449 std::pair<GlobalModuleIndex *, GlobalModuleIndex::ErrorCode> Result
Douglas Gregor7029ce12013-03-19 00:28:20 +00003450 = GlobalModuleIndex::readIndex(ModuleCachePath);
Douglas Gregore060e572013-01-25 01:03:03 +00003451 if (!Result.first)
3452 return true;
3453
3454 GlobalIndex.reset(Result.first);
Douglas Gregor7211ac12013-01-25 23:32:03 +00003455 ModuleMgr.setGlobalIndex(GlobalIndex.get());
Douglas Gregore060e572013-01-25 01:03:03 +00003456 return false;
3457}
3458
3459bool ASTReader::isGlobalIndexUnavailable() const {
3460 return Context.getLangOpts().Modules && UseGlobalIndex &&
3461 !hasGlobalIndex() && TriedLoadingGlobalIndex;
3462}
3463
Dmitri Gribenkof430da42014-02-12 10:33:14 +00003464static void updateModuleTimestamp(ModuleFile &MF) {
3465 // Overwrite the timestamp file contents so that file's mtime changes.
3466 std::string TimestampFilename = MF.getTimestampFilename();
3467 std::string ErrorInfo;
Rafael Espindola04a13be2014-02-24 15:06:52 +00003468 llvm::raw_fd_ostream OS(TimestampFilename.c_str(), ErrorInfo,
Rafael Espindola4fbd3732014-02-24 18:20:21 +00003469 llvm::sys::fs::F_Text);
Dmitri Gribenkof430da42014-02-12 10:33:14 +00003470 if (!ErrorInfo.empty())
3471 return;
3472 OS << "Timestamp file\n";
3473}
3474
Guy Benyei11169dd2012-12-18 14:30:41 +00003475ASTReader::ASTReadResult ASTReader::ReadAST(const std::string &FileName,
3476 ModuleKind Type,
3477 SourceLocation ImportLoc,
3478 unsigned ClientLoadCapabilities) {
Argyrios Kyrtzidisdc9fdaf2013-05-24 05:44:08 +00003479 llvm::SaveAndRestore<SourceLocation>
3480 SetCurImportLocRAII(CurrentImportLoc, ImportLoc);
3481
Richard Smithd1c46742014-04-30 02:24:17 +00003482 // Defer any pending actions until we get to the end of reading the AST file.
3483 Deserializing AnASTFile(this);
3484
Guy Benyei11169dd2012-12-18 14:30:41 +00003485 // Bump the generation number.
Richard Smith053f6c62014-05-16 23:01:30 +00003486 unsigned PreviousGeneration = incrementGeneration(Context);
Guy Benyei11169dd2012-12-18 14:30:41 +00003487
3488 unsigned NumModules = ModuleMgr.size();
Dmitri Gribenkof8579502013-01-12 19:30:44 +00003489 SmallVector<ImportedModule, 4> Loaded;
Guy Benyei11169dd2012-12-18 14:30:41 +00003490 switch(ASTReadResult ReadResult = ReadASTCore(FileName, Type, ImportLoc,
Craig Toppera13603a2014-05-22 05:54:18 +00003491 /*ImportedBy=*/nullptr, Loaded,
Douglas Gregor7029ce12013-03-19 00:28:20 +00003492 0, 0,
Guy Benyei11169dd2012-12-18 14:30:41 +00003493 ClientLoadCapabilities)) {
3494 case Failure:
Douglas Gregor7029ce12013-03-19 00:28:20 +00003495 case Missing:
Guy Benyei11169dd2012-12-18 14:30:41 +00003496 case OutOfDate:
3497 case VersionMismatch:
3498 case ConfigurationMismatch:
Ben Langmuir9801b252014-06-20 00:24:56 +00003499 case HadErrors: {
3500 llvm::SmallPtrSet<ModuleFile *, 4> LoadedSet;
3501 for (const ImportedModule &IM : Loaded)
3502 LoadedSet.insert(IM.Mod);
3503
Douglas Gregor7029ce12013-03-19 00:28:20 +00003504 ModuleMgr.removeModules(ModuleMgr.begin() + NumModules, ModuleMgr.end(),
Ben Langmuir9801b252014-06-20 00:24:56 +00003505 LoadedSet,
Douglas Gregor7029ce12013-03-19 00:28:20 +00003506 Context.getLangOpts().Modules
3507 ? &PP.getHeaderSearchInfo().getModuleMap()
Craig Toppera13603a2014-05-22 05:54:18 +00003508 : nullptr);
Douglas Gregore060e572013-01-25 01:03:03 +00003509
3510 // If we find that any modules are unusable, the global index is going
3511 // to be out-of-date. Just remove it.
3512 GlobalIndex.reset();
Craig Toppera13603a2014-05-22 05:54:18 +00003513 ModuleMgr.setGlobalIndex(nullptr);
Guy Benyei11169dd2012-12-18 14:30:41 +00003514 return ReadResult;
Ben Langmuir9801b252014-06-20 00:24:56 +00003515 }
Guy Benyei11169dd2012-12-18 14:30:41 +00003516 case Success:
3517 break;
3518 }
3519
3520 // Here comes stuff that we only do once the entire chain is loaded.
3521
3522 // Load the AST blocks of all of the modules that we loaded.
Dmitri Gribenkof8579502013-01-12 19:30:44 +00003523 for (SmallVectorImpl<ImportedModule>::iterator M = Loaded.begin(),
3524 MEnd = Loaded.end();
Guy Benyei11169dd2012-12-18 14:30:41 +00003525 M != MEnd; ++M) {
3526 ModuleFile &F = *M->Mod;
3527
3528 // Read the AST block.
Ben Langmuir2c9af442014-04-10 17:57:43 +00003529 if (ASTReadResult Result = ReadASTBlock(F, ClientLoadCapabilities))
3530 return Result;
Guy Benyei11169dd2012-12-18 14:30:41 +00003531
3532 // Once read, set the ModuleFile bit base offset and update the size in
3533 // bits of all files we've seen.
3534 F.GlobalBitOffset = TotalModulesSizeInBits;
3535 TotalModulesSizeInBits += F.SizeInBits;
3536 GlobalBitOffsetsMap.insert(std::make_pair(F.GlobalBitOffset, &F));
3537
3538 // Preload SLocEntries.
3539 for (unsigned I = 0, N = F.PreloadSLocEntries.size(); I != N; ++I) {
3540 int Index = int(F.PreloadSLocEntries[I] - 1) + F.SLocEntryBaseID;
3541 // Load it through the SourceManager and don't call ReadSLocEntry()
3542 // directly because the entry may have already been loaded in which case
3543 // calling ReadSLocEntry() directly would trigger an assertion in
3544 // SourceManager.
3545 SourceMgr.getLoadedSLocEntryByID(Index);
3546 }
3547 }
3548
Douglas Gregor603cd862013-03-22 18:50:14 +00003549 // Setup the import locations and notify the module manager that we've
3550 // committed to these module files.
Dmitri Gribenkof8579502013-01-12 19:30:44 +00003551 for (SmallVectorImpl<ImportedModule>::iterator M = Loaded.begin(),
3552 MEnd = Loaded.end();
Guy Benyei11169dd2012-12-18 14:30:41 +00003553 M != MEnd; ++M) {
3554 ModuleFile &F = *M->Mod;
Douglas Gregor603cd862013-03-22 18:50:14 +00003555
3556 ModuleMgr.moduleFileAccepted(&F);
3557
3558 // Set the import location.
Argyrios Kyrtzidis71c1af82013-02-01 16:36:14 +00003559 F.DirectImportLoc = ImportLoc;
Guy Benyei11169dd2012-12-18 14:30:41 +00003560 if (!M->ImportedBy)
3561 F.ImportLoc = M->ImportLoc;
3562 else
3563 F.ImportLoc = ReadSourceLocation(*M->ImportedBy,
3564 M->ImportLoc.getRawEncoding());
3565 }
3566
3567 // Mark all of the identifiers in the identifier table as being out of date,
3568 // so that various accessors know to check the loaded modules when the
3569 // identifier is used.
3570 for (IdentifierTable::iterator Id = PP.getIdentifierTable().begin(),
3571 IdEnd = PP.getIdentifierTable().end();
3572 Id != IdEnd; ++Id)
3573 Id->second->setOutOfDate(true);
3574
3575 // Resolve any unresolved module exports.
Douglas Gregorfb912652013-03-20 21:10:35 +00003576 for (unsigned I = 0, N = UnresolvedModuleRefs.size(); I != N; ++I) {
3577 UnresolvedModuleRef &Unresolved = UnresolvedModuleRefs[I];
Guy Benyei11169dd2012-12-18 14:30:41 +00003578 SubmoduleID GlobalID = getGlobalSubmoduleID(*Unresolved.File,Unresolved.ID);
3579 Module *ResolvedMod = getSubmodule(GlobalID);
Douglas Gregorfb912652013-03-20 21:10:35 +00003580
3581 switch (Unresolved.Kind) {
3582 case UnresolvedModuleRef::Conflict:
3583 if (ResolvedMod) {
3584 Module::Conflict Conflict;
3585 Conflict.Other = ResolvedMod;
3586 Conflict.Message = Unresolved.String.str();
3587 Unresolved.Mod->Conflicts.push_back(Conflict);
3588 }
3589 continue;
3590
3591 case UnresolvedModuleRef::Import:
Guy Benyei11169dd2012-12-18 14:30:41 +00003592 if (ResolvedMod)
3593 Unresolved.Mod->Imports.push_back(ResolvedMod);
3594 continue;
Guy Benyei11169dd2012-12-18 14:30:41 +00003595
Douglas Gregorfb912652013-03-20 21:10:35 +00003596 case UnresolvedModuleRef::Export:
3597 if (ResolvedMod || Unresolved.IsWildcard)
3598 Unresolved.Mod->Exports.push_back(
3599 Module::ExportDecl(ResolvedMod, Unresolved.IsWildcard));
3600 continue;
3601 }
Guy Benyei11169dd2012-12-18 14:30:41 +00003602 }
Douglas Gregorfb912652013-03-20 21:10:35 +00003603 UnresolvedModuleRefs.clear();
Daniel Jasperba7f2f72013-09-24 09:14:14 +00003604
3605 // FIXME: How do we load the 'use'd modules? They may not be submodules.
3606 // Might be unnecessary as use declarations are only used to build the
3607 // module itself.
Guy Benyei11169dd2012-12-18 14:30:41 +00003608
3609 InitializeContext();
3610
Richard Smith3d8e97e2013-10-18 06:54:39 +00003611 if (SemaObj)
3612 UpdateSema();
3613
Guy Benyei11169dd2012-12-18 14:30:41 +00003614 if (DeserializationListener)
3615 DeserializationListener->ReaderInitialized(this);
3616
3617 ModuleFile &PrimaryModule = ModuleMgr.getPrimaryModule();
3618 if (!PrimaryModule.OriginalSourceFileID.isInvalid()) {
3619 PrimaryModule.OriginalSourceFileID
3620 = FileID::get(PrimaryModule.SLocEntryBaseID
3621 + PrimaryModule.OriginalSourceFileID.getOpaqueValue() - 1);
3622
3623 // If this AST file is a precompiled preamble, then set the
3624 // preamble file ID of the source manager to the file source file
3625 // from which the preamble was built.
3626 if (Type == MK_Preamble) {
3627 SourceMgr.setPreambleFileID(PrimaryModule.OriginalSourceFileID);
3628 } else if (Type == MK_MainFile) {
3629 SourceMgr.setMainFileID(PrimaryModule.OriginalSourceFileID);
3630 }
3631 }
3632
3633 // For any Objective-C class definitions we have already loaded, make sure
3634 // that we load any additional categories.
3635 for (unsigned I = 0, N = ObjCClassesLoaded.size(); I != N; ++I) {
3636 loadObjCCategories(ObjCClassesLoaded[I]->getGlobalID(),
3637 ObjCClassesLoaded[I],
3638 PreviousGeneration);
3639 }
Douglas Gregore060e572013-01-25 01:03:03 +00003640
Dmitri Gribenkof430da42014-02-12 10:33:14 +00003641 if (PP.getHeaderSearchInfo()
3642 .getHeaderSearchOpts()
3643 .ModulesValidateOncePerBuildSession) {
3644 // Now we are certain that the module and all modules it depends on are
3645 // up to date. Create or update timestamp files for modules that are
3646 // located in the module cache (not for PCH files that could be anywhere
3647 // in the filesystem).
3648 for (unsigned I = 0, N = Loaded.size(); I != N; ++I) {
3649 ImportedModule &M = Loaded[I];
3650 if (M.Mod->Kind == MK_Module) {
3651 updateModuleTimestamp(*M.Mod);
3652 }
3653 }
3654 }
3655
Guy Benyei11169dd2012-12-18 14:30:41 +00003656 return Success;
3657}
3658
3659ASTReader::ASTReadResult
3660ASTReader::ReadASTCore(StringRef FileName,
3661 ModuleKind Type,
3662 SourceLocation ImportLoc,
3663 ModuleFile *ImportedBy,
Dmitri Gribenkof8579502013-01-12 19:30:44 +00003664 SmallVectorImpl<ImportedModule> &Loaded,
Douglas Gregor7029ce12013-03-19 00:28:20 +00003665 off_t ExpectedSize, time_t ExpectedModTime,
Guy Benyei11169dd2012-12-18 14:30:41 +00003666 unsigned ClientLoadCapabilities) {
3667 ModuleFile *M;
Guy Benyei11169dd2012-12-18 14:30:41 +00003668 std::string ErrorStr;
Douglas Gregor7029ce12013-03-19 00:28:20 +00003669 ModuleManager::AddModuleResult AddResult
3670 = ModuleMgr.addModule(FileName, Type, ImportLoc, ImportedBy,
Richard Smith053f6c62014-05-16 23:01:30 +00003671 getGeneration(), ExpectedSize, ExpectedModTime,
Douglas Gregor7029ce12013-03-19 00:28:20 +00003672 M, ErrorStr);
Guy Benyei11169dd2012-12-18 14:30:41 +00003673
Douglas Gregor7029ce12013-03-19 00:28:20 +00003674 switch (AddResult) {
3675 case ModuleManager::AlreadyLoaded:
3676 return Success;
3677
3678 case ModuleManager::NewlyLoaded:
3679 // Load module file below.
3680 break;
3681
3682 case ModuleManager::Missing:
3683 // The module file was missing; if the client handle handle, that, return
3684 // it.
3685 if (ClientLoadCapabilities & ARR_Missing)
3686 return Missing;
3687
3688 // Otherwise, return an error.
3689 {
3690 std::string Msg = "Unable to load module \"" + FileName.str() + "\": "
3691 + ErrorStr;
3692 Error(Msg);
3693 }
3694 return Failure;
3695
3696 case ModuleManager::OutOfDate:
3697 // We couldn't load the module file because it is out-of-date. If the
3698 // client can handle out-of-date, return it.
3699 if (ClientLoadCapabilities & ARR_OutOfDate)
3700 return OutOfDate;
3701
3702 // Otherwise, return an error.
3703 {
3704 std::string Msg = "Unable to load module \"" + FileName.str() + "\": "
3705 + ErrorStr;
3706 Error(Msg);
3707 }
Guy Benyei11169dd2012-12-18 14:30:41 +00003708 return Failure;
3709 }
3710
Douglas Gregor7029ce12013-03-19 00:28:20 +00003711 assert(M && "Missing module file");
Guy Benyei11169dd2012-12-18 14:30:41 +00003712
3713 // FIXME: This seems rather a hack. Should CurrentDir be part of the
3714 // module?
3715 if (FileName != "-") {
3716 CurrentDir = llvm::sys::path::parent_path(FileName);
3717 if (CurrentDir.empty()) CurrentDir = ".";
3718 }
3719
3720 ModuleFile &F = *M;
Chris Lattner7fb3bef2013-01-20 00:56:42 +00003721 BitstreamCursor &Stream = F.Stream;
Guy Benyei11169dd2012-12-18 14:30:41 +00003722 Stream.init(F.StreamFile);
3723 F.SizeInBits = F.Buffer->getBufferSize() * 8;
3724
3725 // Sniff for the signature.
3726 if (Stream.Read(8) != 'C' ||
3727 Stream.Read(8) != 'P' ||
3728 Stream.Read(8) != 'C' ||
3729 Stream.Read(8) != 'H') {
3730 Diag(diag::err_not_a_pch_file) << FileName;
3731 return Failure;
3732 }
3733
3734 // This is used for compatibility with older PCH formats.
3735 bool HaveReadControlBlock = false;
3736
Chris Lattnerefa77172013-01-20 00:00:22 +00003737 while (1) {
3738 llvm::BitstreamEntry Entry = Stream.advance();
3739
3740 switch (Entry.Kind) {
3741 case llvm::BitstreamEntry::Error:
3742 case llvm::BitstreamEntry::EndBlock:
3743 case llvm::BitstreamEntry::Record:
Guy Benyei11169dd2012-12-18 14:30:41 +00003744 Error("invalid record at top-level of AST file");
3745 return Failure;
Chris Lattnerefa77172013-01-20 00:00:22 +00003746
3747 case llvm::BitstreamEntry::SubBlock:
3748 break;
Guy Benyei11169dd2012-12-18 14:30:41 +00003749 }
3750
Guy Benyei11169dd2012-12-18 14:30:41 +00003751 // We only know the control subblock ID.
Chris Lattnerefa77172013-01-20 00:00:22 +00003752 switch (Entry.ID) {
Guy Benyei11169dd2012-12-18 14:30:41 +00003753 case llvm::bitc::BLOCKINFO_BLOCK_ID:
3754 if (Stream.ReadBlockInfoBlock()) {
3755 Error("malformed BlockInfoBlock in AST file");
3756 return Failure;
3757 }
3758 break;
3759 case CONTROL_BLOCK_ID:
3760 HaveReadControlBlock = true;
Ben Langmuirbeee15e2014-04-14 18:00:01 +00003761 switch (ReadControlBlock(F, Loaded, ImportedBy, ClientLoadCapabilities)) {
Guy Benyei11169dd2012-12-18 14:30:41 +00003762 case Success:
3763 break;
3764
3765 case Failure: return Failure;
Douglas Gregor7029ce12013-03-19 00:28:20 +00003766 case Missing: return Missing;
Guy Benyei11169dd2012-12-18 14:30:41 +00003767 case OutOfDate: return OutOfDate;
3768 case VersionMismatch: return VersionMismatch;
3769 case ConfigurationMismatch: return ConfigurationMismatch;
3770 case HadErrors: return HadErrors;
3771 }
3772 break;
3773 case AST_BLOCK_ID:
3774 if (!HaveReadControlBlock) {
3775 if ((ClientLoadCapabilities & ARR_VersionMismatch) == 0)
Dmitri Gribenko2228cd32014-02-11 15:40:09 +00003776 Diag(diag::err_pch_version_too_old);
Guy Benyei11169dd2012-12-18 14:30:41 +00003777 return VersionMismatch;
3778 }
3779
3780 // Record that we've loaded this module.
3781 Loaded.push_back(ImportedModule(M, ImportedBy, ImportLoc));
3782 return Success;
3783
3784 default:
3785 if (Stream.SkipBlock()) {
3786 Error("malformed block record in AST file");
3787 return Failure;
3788 }
3789 break;
3790 }
3791 }
3792
3793 return Success;
3794}
3795
3796void ASTReader::InitializeContext() {
3797 // If there's a listener, notify them that we "read" the translation unit.
3798 if (DeserializationListener)
3799 DeserializationListener->DeclRead(PREDEF_DECL_TRANSLATION_UNIT_ID,
3800 Context.getTranslationUnitDecl());
3801
Guy Benyei11169dd2012-12-18 14:30:41 +00003802 // FIXME: Find a better way to deal with collisions between these
3803 // built-in types. Right now, we just ignore the problem.
3804
3805 // Load the special types.
3806 if (SpecialTypes.size() >= NumSpecialTypeIDs) {
3807 if (unsigned String = SpecialTypes[SPECIAL_TYPE_CF_CONSTANT_STRING]) {
3808 if (!Context.CFConstantStringTypeDecl)
3809 Context.setCFConstantStringType(GetType(String));
3810 }
3811
3812 if (unsigned File = SpecialTypes[SPECIAL_TYPE_FILE]) {
3813 QualType FileType = GetType(File);
3814 if (FileType.isNull()) {
3815 Error("FILE type is NULL");
3816 return;
3817 }
3818
3819 if (!Context.FILEDecl) {
3820 if (const TypedefType *Typedef = FileType->getAs<TypedefType>())
3821 Context.setFILEDecl(Typedef->getDecl());
3822 else {
3823 const TagType *Tag = FileType->getAs<TagType>();
3824 if (!Tag) {
3825 Error("Invalid FILE type in AST file");
3826 return;
3827 }
3828 Context.setFILEDecl(Tag->getDecl());
3829 }
3830 }
3831 }
3832
3833 if (unsigned Jmp_buf = SpecialTypes[SPECIAL_TYPE_JMP_BUF]) {
3834 QualType Jmp_bufType = GetType(Jmp_buf);
3835 if (Jmp_bufType.isNull()) {
3836 Error("jmp_buf type is NULL");
3837 return;
3838 }
3839
3840 if (!Context.jmp_bufDecl) {
3841 if (const TypedefType *Typedef = Jmp_bufType->getAs<TypedefType>())
3842 Context.setjmp_bufDecl(Typedef->getDecl());
3843 else {
3844 const TagType *Tag = Jmp_bufType->getAs<TagType>();
3845 if (!Tag) {
3846 Error("Invalid jmp_buf type in AST file");
3847 return;
3848 }
3849 Context.setjmp_bufDecl(Tag->getDecl());
3850 }
3851 }
3852 }
3853
3854 if (unsigned Sigjmp_buf = SpecialTypes[SPECIAL_TYPE_SIGJMP_BUF]) {
3855 QualType Sigjmp_bufType = GetType(Sigjmp_buf);
3856 if (Sigjmp_bufType.isNull()) {
3857 Error("sigjmp_buf type is NULL");
3858 return;
3859 }
3860
3861 if (!Context.sigjmp_bufDecl) {
3862 if (const TypedefType *Typedef = Sigjmp_bufType->getAs<TypedefType>())
3863 Context.setsigjmp_bufDecl(Typedef->getDecl());
3864 else {
3865 const TagType *Tag = Sigjmp_bufType->getAs<TagType>();
3866 assert(Tag && "Invalid sigjmp_buf type in AST file");
3867 Context.setsigjmp_bufDecl(Tag->getDecl());
3868 }
3869 }
3870 }
3871
3872 if (unsigned ObjCIdRedef
3873 = SpecialTypes[SPECIAL_TYPE_OBJC_ID_REDEFINITION]) {
3874 if (Context.ObjCIdRedefinitionType.isNull())
3875 Context.ObjCIdRedefinitionType = GetType(ObjCIdRedef);
3876 }
3877
3878 if (unsigned ObjCClassRedef
3879 = SpecialTypes[SPECIAL_TYPE_OBJC_CLASS_REDEFINITION]) {
3880 if (Context.ObjCClassRedefinitionType.isNull())
3881 Context.ObjCClassRedefinitionType = GetType(ObjCClassRedef);
3882 }
3883
3884 if (unsigned ObjCSelRedef
3885 = SpecialTypes[SPECIAL_TYPE_OBJC_SEL_REDEFINITION]) {
3886 if (Context.ObjCSelRedefinitionType.isNull())
3887 Context.ObjCSelRedefinitionType = GetType(ObjCSelRedef);
3888 }
3889
3890 if (unsigned Ucontext_t = SpecialTypes[SPECIAL_TYPE_UCONTEXT_T]) {
3891 QualType Ucontext_tType = GetType(Ucontext_t);
3892 if (Ucontext_tType.isNull()) {
3893 Error("ucontext_t type is NULL");
3894 return;
3895 }
3896
3897 if (!Context.ucontext_tDecl) {
3898 if (const TypedefType *Typedef = Ucontext_tType->getAs<TypedefType>())
3899 Context.setucontext_tDecl(Typedef->getDecl());
3900 else {
3901 const TagType *Tag = Ucontext_tType->getAs<TagType>();
3902 assert(Tag && "Invalid ucontext_t type in AST file");
3903 Context.setucontext_tDecl(Tag->getDecl());
3904 }
3905 }
3906 }
3907 }
3908
3909 ReadPragmaDiagnosticMappings(Context.getDiagnostics());
3910
3911 // If there were any CUDA special declarations, deserialize them.
3912 if (!CUDASpecialDeclRefs.empty()) {
3913 assert(CUDASpecialDeclRefs.size() == 1 && "More decl refs than expected!");
3914 Context.setcudaConfigureCallDecl(
3915 cast<FunctionDecl>(GetDecl(CUDASpecialDeclRefs[0])));
3916 }
Richard Smith56be7542014-03-21 00:33:59 +00003917
Guy Benyei11169dd2012-12-18 14:30:41 +00003918 // Re-export any modules that were imported by a non-module AST file.
Richard Smith56be7542014-03-21 00:33:59 +00003919 // FIXME: This does not make macro-only imports visible again. It also doesn't
3920 // make #includes mapped to module imports visible.
3921 for (auto &Import : ImportedModules) {
3922 if (Module *Imported = getSubmodule(Import.ID))
Argyrios Kyrtzidis125df052013-02-01 16:36:12 +00003923 makeModuleVisible(Imported, Module::AllVisible,
Richard Smith56be7542014-03-21 00:33:59 +00003924 /*ImportLoc=*/Import.ImportLoc,
Douglas Gregorfb912652013-03-20 21:10:35 +00003925 /*Complain=*/false);
Guy Benyei11169dd2012-12-18 14:30:41 +00003926 }
3927 ImportedModules.clear();
3928}
3929
3930void ASTReader::finalizeForWriting() {
Richard Smith57721ac2014-07-21 04:10:40 +00003931 while (!HiddenNamesMap.empty()) {
3932 auto HiddenNames = std::move(*HiddenNamesMap.begin());
3933 HiddenNamesMap.erase(HiddenNamesMap.begin());
3934 makeNamesVisible(HiddenNames.second, HiddenNames.first,
3935 /*FromFinalization*/true);
Guy Benyei11169dd2012-12-18 14:30:41 +00003936 }
Guy Benyei11169dd2012-12-18 14:30:41 +00003937}
3938
Argyrios Kyrtzidisc4cd2c42013-05-06 19:23:40 +00003939/// \brief Given a cursor at the start of an AST file, scan ahead and drop the
3940/// cursor into the start of the given block ID, returning false on success and
3941/// true on failure.
3942static bool SkipCursorToBlock(BitstreamCursor &Cursor, unsigned BlockID) {
Chris Lattner7fb3bef2013-01-20 00:56:42 +00003943 while (1) {
3944 llvm::BitstreamEntry Entry = Cursor.advance();
3945 switch (Entry.Kind) {
3946 case llvm::BitstreamEntry::Error:
3947 case llvm::BitstreamEntry::EndBlock:
3948 return true;
3949
3950 case llvm::BitstreamEntry::Record:
3951 // Ignore top-level records.
3952 Cursor.skipRecord(Entry.ID);
3953 break;
3954
3955 case llvm::BitstreamEntry::SubBlock:
Argyrios Kyrtzidisc4cd2c42013-05-06 19:23:40 +00003956 if (Entry.ID == BlockID) {
3957 if (Cursor.EnterSubBlock(BlockID))
Chris Lattner7fb3bef2013-01-20 00:56:42 +00003958 return true;
3959 // Found it!
3960 return false;
3961 }
3962
3963 if (Cursor.SkipBlock())
3964 return true;
3965 }
3966 }
3967}
3968
Guy Benyei11169dd2012-12-18 14:30:41 +00003969/// \brief Retrieve the name of the original source file name
3970/// directly from the AST file, without actually loading the AST
3971/// file.
3972std::string ASTReader::getOriginalSourceFile(const std::string &ASTFileName,
3973 FileManager &FileMgr,
3974 DiagnosticsEngine &Diags) {
3975 // Open the AST file.
3976 std::string ErrStr;
Ahmed Charlesb8984322014-03-07 20:03:18 +00003977 std::unique_ptr<llvm::MemoryBuffer> Buffer;
Guy Benyei11169dd2012-12-18 14:30:41 +00003978 Buffer.reset(FileMgr.getBufferForFile(ASTFileName, &ErrStr));
3979 if (!Buffer) {
3980 Diags.Report(diag::err_fe_unable_to_read_pch_file) << ASTFileName << ErrStr;
3981 return std::string();
3982 }
3983
3984 // Initialize the stream
3985 llvm::BitstreamReader StreamFile;
Chris Lattner7fb3bef2013-01-20 00:56:42 +00003986 BitstreamCursor Stream;
Guy Benyei11169dd2012-12-18 14:30:41 +00003987 StreamFile.init((const unsigned char *)Buffer->getBufferStart(),
3988 (const unsigned char *)Buffer->getBufferEnd());
3989 Stream.init(StreamFile);
3990
3991 // Sniff for the signature.
3992 if (Stream.Read(8) != 'C' ||
3993 Stream.Read(8) != 'P' ||
3994 Stream.Read(8) != 'C' ||
3995 Stream.Read(8) != 'H') {
3996 Diags.Report(diag::err_fe_not_a_pch_file) << ASTFileName;
3997 return std::string();
3998 }
Chris Lattner7fb3bef2013-01-20 00:56:42 +00003999
Chris Lattnere7b154b2013-01-19 21:39:22 +00004000 // Scan for the CONTROL_BLOCK_ID block.
Argyrios Kyrtzidisc4cd2c42013-05-06 19:23:40 +00004001 if (SkipCursorToBlock(Stream, CONTROL_BLOCK_ID)) {
Chris Lattner7fb3bef2013-01-20 00:56:42 +00004002 Diags.Report(diag::err_fe_pch_malformed_block) << ASTFileName;
4003 return std::string();
Chris Lattnere7b154b2013-01-19 21:39:22 +00004004 }
Guy Benyei11169dd2012-12-18 14:30:41 +00004005
Chris Lattner7fb3bef2013-01-20 00:56:42 +00004006 // Scan for ORIGINAL_FILE inside the control block.
4007 RecordData Record;
Chris Lattnere7b154b2013-01-19 21:39:22 +00004008 while (1) {
Chris Lattner7fb3bef2013-01-20 00:56:42 +00004009 llvm::BitstreamEntry Entry = Stream.advanceSkippingSubblocks();
Chris Lattnere7b154b2013-01-19 21:39:22 +00004010 if (Entry.Kind == llvm::BitstreamEntry::EndBlock)
4011 return std::string();
4012
4013 if (Entry.Kind != llvm::BitstreamEntry::Record) {
4014 Diags.Report(diag::err_fe_pch_malformed_block) << ASTFileName;
4015 return std::string();
Guy Benyei11169dd2012-12-18 14:30:41 +00004016 }
Chris Lattnere7b154b2013-01-19 21:39:22 +00004017
Guy Benyei11169dd2012-12-18 14:30:41 +00004018 Record.clear();
Chris Lattner0e6c9402013-01-20 02:38:54 +00004019 StringRef Blob;
4020 if (Stream.readRecord(Entry.ID, Record, &Blob) == ORIGINAL_FILE)
4021 return Blob.str();
Guy Benyei11169dd2012-12-18 14:30:41 +00004022 }
Guy Benyei11169dd2012-12-18 14:30:41 +00004023}
4024
4025namespace {
4026 class SimplePCHValidator : public ASTReaderListener {
4027 const LangOptions &ExistingLangOpts;
4028 const TargetOptions &ExistingTargetOpts;
4029 const PreprocessorOptions &ExistingPPOpts;
4030 FileManager &FileMgr;
4031
4032 public:
4033 SimplePCHValidator(const LangOptions &ExistingLangOpts,
4034 const TargetOptions &ExistingTargetOpts,
4035 const PreprocessorOptions &ExistingPPOpts,
4036 FileManager &FileMgr)
4037 : ExistingLangOpts(ExistingLangOpts),
4038 ExistingTargetOpts(ExistingTargetOpts),
4039 ExistingPPOpts(ExistingPPOpts),
4040 FileMgr(FileMgr)
4041 {
4042 }
4043
Craig Topper3e89dfe2014-03-13 02:13:41 +00004044 bool ReadLanguageOptions(const LangOptions &LangOpts,
4045 bool Complain) override {
Craig Toppera13603a2014-05-22 05:54:18 +00004046 return checkLanguageOptions(ExistingLangOpts, LangOpts, nullptr);
Guy Benyei11169dd2012-12-18 14:30:41 +00004047 }
Craig Topper3e89dfe2014-03-13 02:13:41 +00004048 bool ReadTargetOptions(const TargetOptions &TargetOpts,
4049 bool Complain) override {
Craig Toppera13603a2014-05-22 05:54:18 +00004050 return checkTargetOptions(ExistingTargetOpts, TargetOpts, nullptr);
Guy Benyei11169dd2012-12-18 14:30:41 +00004051 }
Craig Topper3e89dfe2014-03-13 02:13:41 +00004052 bool ReadPreprocessorOptions(const PreprocessorOptions &PPOpts,
4053 bool Complain,
4054 std::string &SuggestedPredefines) override {
Craig Toppera13603a2014-05-22 05:54:18 +00004055 return checkPreprocessorOptions(ExistingPPOpts, PPOpts, nullptr, FileMgr,
Argyrios Kyrtzidisd3afa0c2013-04-26 21:33:40 +00004056 SuggestedPredefines, ExistingLangOpts);
Guy Benyei11169dd2012-12-18 14:30:41 +00004057 }
4058 };
4059}
4060
4061bool ASTReader::readASTFileControlBlock(StringRef Filename,
4062 FileManager &FileMgr,
4063 ASTReaderListener &Listener) {
4064 // Open the AST file.
4065 std::string ErrStr;
Ahmed Charlesb8984322014-03-07 20:03:18 +00004066 std::unique_ptr<llvm::MemoryBuffer> Buffer;
Guy Benyei11169dd2012-12-18 14:30:41 +00004067 Buffer.reset(FileMgr.getBufferForFile(Filename, &ErrStr));
4068 if (!Buffer) {
4069 return true;
4070 }
4071
4072 // Initialize the stream
4073 llvm::BitstreamReader StreamFile;
Chris Lattner7fb3bef2013-01-20 00:56:42 +00004074 BitstreamCursor Stream;
Guy Benyei11169dd2012-12-18 14:30:41 +00004075 StreamFile.init((const unsigned char *)Buffer->getBufferStart(),
4076 (const unsigned char *)Buffer->getBufferEnd());
4077 Stream.init(StreamFile);
4078
4079 // Sniff for the signature.
4080 if (Stream.Read(8) != 'C' ||
4081 Stream.Read(8) != 'P' ||
4082 Stream.Read(8) != 'C' ||
4083 Stream.Read(8) != 'H') {
4084 return true;
4085 }
4086
Chris Lattner7fb3bef2013-01-20 00:56:42 +00004087 // Scan for the CONTROL_BLOCK_ID block.
Argyrios Kyrtzidisc4cd2c42013-05-06 19:23:40 +00004088 if (SkipCursorToBlock(Stream, CONTROL_BLOCK_ID))
Chris Lattner7fb3bef2013-01-20 00:56:42 +00004089 return true;
Argyrios Kyrtzidisc4cd2c42013-05-06 19:23:40 +00004090
4091 bool NeedsInputFiles = Listener.needsInputFileVisitation();
Ben Langmuircb69b572014-03-07 06:40:32 +00004092 bool NeedsSystemInputFiles = Listener.needsSystemInputFileVisitation();
Argyrios Kyrtzidisc4cd2c42013-05-06 19:23:40 +00004093 BitstreamCursor InputFilesCursor;
4094 if (NeedsInputFiles) {
4095 InputFilesCursor = Stream;
4096 if (SkipCursorToBlock(InputFilesCursor, INPUT_FILES_BLOCK_ID))
4097 return true;
4098
4099 // Read the abbreviations
4100 while (true) {
4101 uint64_t Offset = InputFilesCursor.GetCurrentBitNo();
4102 unsigned Code = InputFilesCursor.ReadCode();
4103
4104 // We expect all abbrevs to be at the start of the block.
4105 if (Code != llvm::bitc::DEFINE_ABBREV) {
4106 InputFilesCursor.JumpToBit(Offset);
4107 break;
4108 }
4109 InputFilesCursor.ReadAbbrevRecord();
4110 }
4111 }
Chris Lattner7fb3bef2013-01-20 00:56:42 +00004112
4113 // Scan for ORIGINAL_FILE inside the control block.
Guy Benyei11169dd2012-12-18 14:30:41 +00004114 RecordData Record;
Chris Lattner7fb3bef2013-01-20 00:56:42 +00004115 while (1) {
4116 llvm::BitstreamEntry Entry = Stream.advanceSkippingSubblocks();
4117 if (Entry.Kind == llvm::BitstreamEntry::EndBlock)
4118 return false;
4119
4120 if (Entry.Kind != llvm::BitstreamEntry::Record)
4121 return true;
4122
Guy Benyei11169dd2012-12-18 14:30:41 +00004123 Record.clear();
Chris Lattner0e6c9402013-01-20 02:38:54 +00004124 StringRef Blob;
4125 unsigned RecCode = Stream.readRecord(Entry.ID, Record, &Blob);
Chris Lattner7fb3bef2013-01-20 00:56:42 +00004126 switch ((ControlRecordTypes)RecCode) {
4127 case METADATA: {
4128 if (Record[0] != VERSION_MAJOR)
4129 return true;
Guy Benyei11169dd2012-12-18 14:30:41 +00004130
Douglas Gregorbf7fc9c2013-03-27 16:47:18 +00004131 if (Listener.ReadFullVersionInformation(Blob))
Chris Lattner7fb3bef2013-01-20 00:56:42 +00004132 return true;
Douglas Gregorbf7fc9c2013-03-27 16:47:18 +00004133
Chris Lattner7fb3bef2013-01-20 00:56:42 +00004134 break;
4135 }
Ben Langmuir4f5212a2014-04-14 22:12:44 +00004136 case MODULE_NAME:
4137 Listener.ReadModuleName(Blob);
4138 break;
4139 case MODULE_MAP_FILE:
4140 Listener.ReadModuleMapFile(Blob);
4141 break;
Chris Lattner7fb3bef2013-01-20 00:56:42 +00004142 case LANGUAGE_OPTIONS:
4143 if (ParseLanguageOptions(Record, false, Listener))
4144 return true;
4145 break;
Guy Benyei11169dd2012-12-18 14:30:41 +00004146
Chris Lattner7fb3bef2013-01-20 00:56:42 +00004147 case TARGET_OPTIONS:
4148 if (ParseTargetOptions(Record, false, Listener))
4149 return true;
4150 break;
Guy Benyei11169dd2012-12-18 14:30:41 +00004151
Chris Lattner7fb3bef2013-01-20 00:56:42 +00004152 case DIAGNOSTIC_OPTIONS:
4153 if (ParseDiagnosticOptions(Record, false, Listener))
4154 return true;
4155 break;
Guy Benyei11169dd2012-12-18 14:30:41 +00004156
Chris Lattner7fb3bef2013-01-20 00:56:42 +00004157 case FILE_SYSTEM_OPTIONS:
4158 if (ParseFileSystemOptions(Record, false, Listener))
4159 return true;
4160 break;
Guy Benyei11169dd2012-12-18 14:30:41 +00004161
Chris Lattner7fb3bef2013-01-20 00:56:42 +00004162 case HEADER_SEARCH_OPTIONS:
4163 if (ParseHeaderSearchOptions(Record, false, Listener))
4164 return true;
4165 break;
Guy Benyei11169dd2012-12-18 14:30:41 +00004166
Chris Lattner7fb3bef2013-01-20 00:56:42 +00004167 case PREPROCESSOR_OPTIONS: {
4168 std::string IgnoredSuggestedPredefines;
4169 if (ParsePreprocessorOptions(Record, false, Listener,
4170 IgnoredSuggestedPredefines))
4171 return true;
4172 break;
4173 }
Guy Benyei11169dd2012-12-18 14:30:41 +00004174
Argyrios Kyrtzidisc4cd2c42013-05-06 19:23:40 +00004175 case INPUT_FILE_OFFSETS: {
4176 if (!NeedsInputFiles)
4177 break;
4178
4179 unsigned NumInputFiles = Record[0];
4180 unsigned NumUserFiles = Record[1];
4181 const uint32_t *InputFileOffs = (const uint32_t *)Blob.data();
4182 for (unsigned I = 0; I != NumInputFiles; ++I) {
4183 // Go find this input file.
4184 bool isSystemFile = I >= NumUserFiles;
Ben Langmuircb69b572014-03-07 06:40:32 +00004185
4186 if (isSystemFile && !NeedsSystemInputFiles)
4187 break; // the rest are system input files
4188
Argyrios Kyrtzidisc4cd2c42013-05-06 19:23:40 +00004189 BitstreamCursor &Cursor = InputFilesCursor;
4190 SavedStreamPosition SavedPosition(Cursor);
4191 Cursor.JumpToBit(InputFileOffs[I]);
4192
4193 unsigned Code = Cursor.ReadCode();
4194 RecordData Record;
4195 StringRef Blob;
4196 bool shouldContinue = false;
4197 switch ((InputFileRecordTypes)Cursor.readRecord(Code, Record, &Blob)) {
4198 case INPUT_FILE:
Argyrios Kyrtzidis68ccbe02014-03-14 02:26:31 +00004199 bool Overridden = static_cast<bool>(Record[3]);
4200 shouldContinue = Listener.visitInputFile(Blob, isSystemFile, Overridden);
Argyrios Kyrtzidisc4cd2c42013-05-06 19:23:40 +00004201 break;
4202 }
4203 if (!shouldContinue)
4204 break;
4205 }
4206 break;
4207 }
4208
Chris Lattner7fb3bef2013-01-20 00:56:42 +00004209 default:
4210 // No other validation to perform.
4211 break;
Guy Benyei11169dd2012-12-18 14:30:41 +00004212 }
4213 }
Guy Benyei11169dd2012-12-18 14:30:41 +00004214}
4215
4216
4217bool ASTReader::isAcceptableASTFile(StringRef Filename,
4218 FileManager &FileMgr,
4219 const LangOptions &LangOpts,
4220 const TargetOptions &TargetOpts,
4221 const PreprocessorOptions &PPOpts) {
4222 SimplePCHValidator validator(LangOpts, TargetOpts, PPOpts, FileMgr);
4223 return !readASTFileControlBlock(Filename, FileMgr, validator);
4224}
4225
Ben Langmuir2c9af442014-04-10 17:57:43 +00004226ASTReader::ASTReadResult
4227ASTReader::ReadSubmoduleBlock(ModuleFile &F, unsigned ClientLoadCapabilities) {
Guy Benyei11169dd2012-12-18 14:30:41 +00004228 // Enter the submodule block.
4229 if (F.Stream.EnterSubBlock(SUBMODULE_BLOCK_ID)) {
4230 Error("malformed submodule block record in AST file");
Ben Langmuir2c9af442014-04-10 17:57:43 +00004231 return Failure;
Guy Benyei11169dd2012-12-18 14:30:41 +00004232 }
4233
4234 ModuleMap &ModMap = PP.getHeaderSearchInfo().getModuleMap();
4235 bool First = true;
Craig Toppera13603a2014-05-22 05:54:18 +00004236 Module *CurrentModule = nullptr;
Guy Benyei11169dd2012-12-18 14:30:41 +00004237 RecordData Record;
4238 while (true) {
Chris Lattner7fb3bef2013-01-20 00:56:42 +00004239 llvm::BitstreamEntry Entry = F.Stream.advanceSkippingSubblocks();
4240
4241 switch (Entry.Kind) {
4242 case llvm::BitstreamEntry::SubBlock: // Handled for us already.
4243 case llvm::BitstreamEntry::Error:
4244 Error("malformed block record in AST file");
Ben Langmuir2c9af442014-04-10 17:57:43 +00004245 return Failure;
Chris Lattner7fb3bef2013-01-20 00:56:42 +00004246 case llvm::BitstreamEntry::EndBlock:
Ben Langmuir2c9af442014-04-10 17:57:43 +00004247 return Success;
Chris Lattner7fb3bef2013-01-20 00:56:42 +00004248 case llvm::BitstreamEntry::Record:
4249 // The interesting case.
4250 break;
Guy Benyei11169dd2012-12-18 14:30:41 +00004251 }
Chris Lattner7fb3bef2013-01-20 00:56:42 +00004252
Guy Benyei11169dd2012-12-18 14:30:41 +00004253 // Read a record.
Chris Lattner0e6c9402013-01-20 02:38:54 +00004254 StringRef Blob;
Guy Benyei11169dd2012-12-18 14:30:41 +00004255 Record.clear();
Chris Lattner0e6c9402013-01-20 02:38:54 +00004256 switch (F.Stream.readRecord(Entry.ID, Record, &Blob)) {
Guy Benyei11169dd2012-12-18 14:30:41 +00004257 default: // Default behavior: ignore.
4258 break;
4259
4260 case SUBMODULE_DEFINITION: {
4261 if (First) {
4262 Error("missing submodule metadata record at beginning of block");
Ben Langmuir2c9af442014-04-10 17:57:43 +00004263 return Failure;
Guy Benyei11169dd2012-12-18 14:30:41 +00004264 }
4265
Douglas Gregor8d932422013-03-20 03:59:18 +00004266 if (Record.size() < 8) {
Guy Benyei11169dd2012-12-18 14:30:41 +00004267 Error("malformed module definition");
Ben Langmuir2c9af442014-04-10 17:57:43 +00004268 return Failure;
Guy Benyei11169dd2012-12-18 14:30:41 +00004269 }
4270
Chris Lattner0e6c9402013-01-20 02:38:54 +00004271 StringRef Name = Blob;
Richard Smith9bca2982014-03-08 00:03:56 +00004272 unsigned Idx = 0;
4273 SubmoduleID GlobalID = getGlobalSubmoduleID(F, Record[Idx++]);
4274 SubmoduleID Parent = getGlobalSubmoduleID(F, Record[Idx++]);
4275 bool IsFramework = Record[Idx++];
4276 bool IsExplicit = Record[Idx++];
4277 bool IsSystem = Record[Idx++];
4278 bool IsExternC = Record[Idx++];
4279 bool InferSubmodules = Record[Idx++];
4280 bool InferExplicitSubmodules = Record[Idx++];
4281 bool InferExportWildcard = Record[Idx++];
4282 bool ConfigMacrosExhaustive = Record[Idx++];
Douglas Gregor8d932422013-03-20 03:59:18 +00004283
Ben Langmuirbeee15e2014-04-14 18:00:01 +00004284 Module *ParentModule = nullptr;
Ben Langmuir9d6448b2014-08-09 00:57:23 +00004285 if (Parent)
Guy Benyei11169dd2012-12-18 14:30:41 +00004286 ParentModule = getSubmodule(Parent);
Ben Langmuirbeee15e2014-04-14 18:00:01 +00004287
Guy Benyei11169dd2012-12-18 14:30:41 +00004288 // Retrieve this (sub)module from the module map, creating it if
4289 // necessary.
Ben Langmuir9d6448b2014-08-09 00:57:23 +00004290 CurrentModule = ModMap.findOrCreateModule(Name, ParentModule, IsFramework,
Guy Benyei11169dd2012-12-18 14:30:41 +00004291 IsExplicit).first;
Ben Langmuir9d6448b2014-08-09 00:57:23 +00004292
4293 // FIXME: set the definition loc for CurrentModule, or call
4294 // ModMap.setInferredModuleAllowedBy()
4295
Guy Benyei11169dd2012-12-18 14:30:41 +00004296 SubmoduleID GlobalIndex = GlobalID - NUM_PREDEF_SUBMODULE_IDS;
4297 if (GlobalIndex >= SubmodulesLoaded.size() ||
4298 SubmodulesLoaded[GlobalIndex]) {
4299 Error("too many submodules");
Ben Langmuir2c9af442014-04-10 17:57:43 +00004300 return Failure;
Guy Benyei11169dd2012-12-18 14:30:41 +00004301 }
Douglas Gregor8a114ab2013-02-06 22:40:31 +00004302
Douglas Gregor7029ce12013-03-19 00:28:20 +00004303 if (!ParentModule) {
4304 if (const FileEntry *CurFile = CurrentModule->getASTFile()) {
4305 if (CurFile != F.File) {
4306 if (!Diags.isDiagnosticInFlight()) {
4307 Diag(diag::err_module_file_conflict)
4308 << CurrentModule->getTopLevelModuleName()
4309 << CurFile->getName()
4310 << F.File->getName();
4311 }
Ben Langmuir2c9af442014-04-10 17:57:43 +00004312 return Failure;
Douglas Gregor8a114ab2013-02-06 22:40:31 +00004313 }
Douglas Gregor8a114ab2013-02-06 22:40:31 +00004314 }
Douglas Gregor7029ce12013-03-19 00:28:20 +00004315
4316 CurrentModule->setASTFile(F.File);
Douglas Gregor8a114ab2013-02-06 22:40:31 +00004317 }
Ben Langmuirbeee15e2014-04-14 18:00:01 +00004318
Guy Benyei11169dd2012-12-18 14:30:41 +00004319 CurrentModule->IsFromModuleFile = true;
4320 CurrentModule->IsSystem = IsSystem || CurrentModule->IsSystem;
Richard Smith9bca2982014-03-08 00:03:56 +00004321 CurrentModule->IsExternC = IsExternC;
Guy Benyei11169dd2012-12-18 14:30:41 +00004322 CurrentModule->InferSubmodules = InferSubmodules;
4323 CurrentModule->InferExplicitSubmodules = InferExplicitSubmodules;
4324 CurrentModule->InferExportWildcard = InferExportWildcard;
Douglas Gregor8d932422013-03-20 03:59:18 +00004325 CurrentModule->ConfigMacrosExhaustive = ConfigMacrosExhaustive;
Guy Benyei11169dd2012-12-18 14:30:41 +00004326 if (DeserializationListener)
4327 DeserializationListener->ModuleRead(GlobalID, CurrentModule);
4328
4329 SubmodulesLoaded[GlobalIndex] = CurrentModule;
Douglas Gregor6ddfca92013-01-14 17:21:00 +00004330
Douglas Gregorfb912652013-03-20 21:10:35 +00004331 // Clear out data that will be replaced by what is the module file.
Douglas Gregor6ddfca92013-01-14 17:21:00 +00004332 CurrentModule->LinkLibraries.clear();
Douglas Gregor8d932422013-03-20 03:59:18 +00004333 CurrentModule->ConfigMacros.clear();
Douglas Gregorfb912652013-03-20 21:10:35 +00004334 CurrentModule->UnresolvedConflicts.clear();
4335 CurrentModule->Conflicts.clear();
Guy Benyei11169dd2012-12-18 14:30:41 +00004336 break;
4337 }
4338
4339 case SUBMODULE_UMBRELLA_HEADER: {
4340 if (First) {
4341 Error("missing submodule metadata record at beginning of block");
Ben Langmuir2c9af442014-04-10 17:57:43 +00004342 return Failure;
Guy Benyei11169dd2012-12-18 14:30:41 +00004343 }
4344
4345 if (!CurrentModule)
4346 break;
4347
Chris Lattner0e6c9402013-01-20 02:38:54 +00004348 if (const FileEntry *Umbrella = PP.getFileManager().getFile(Blob)) {
Guy Benyei11169dd2012-12-18 14:30:41 +00004349 if (!CurrentModule->getUmbrellaHeader())
4350 ModMap.setUmbrellaHeader(CurrentModule, Umbrella);
4351 else if (CurrentModule->getUmbrellaHeader() != Umbrella) {
Ben Langmuir2c9af442014-04-10 17:57:43 +00004352 if ((ClientLoadCapabilities & ARR_OutOfDate) == 0)
4353 Error("mismatched umbrella headers in submodule");
4354 return OutOfDate;
Guy Benyei11169dd2012-12-18 14:30:41 +00004355 }
4356 }
4357 break;
4358 }
4359
4360 case SUBMODULE_HEADER: {
4361 if (First) {
4362 Error("missing submodule metadata record at beginning of block");
Ben Langmuir2c9af442014-04-10 17:57:43 +00004363 return Failure;
Guy Benyei11169dd2012-12-18 14:30:41 +00004364 }
4365
4366 if (!CurrentModule)
4367 break;
4368
Argyrios Kyrtzidisb146baa2013-03-13 21:13:51 +00004369 // We lazily associate headers with their modules via the HeaderInfoTable.
4370 // FIXME: Re-evaluate this section; maybe only store InputFile IDs instead
4371 // of complete filenames or remove it entirely.
Guy Benyei11169dd2012-12-18 14:30:41 +00004372 break;
4373 }
4374
4375 case SUBMODULE_EXCLUDED_HEADER: {
4376 if (First) {
4377 Error("missing submodule metadata record at beginning of block");
Ben Langmuir2c9af442014-04-10 17:57:43 +00004378 return Failure;
Guy Benyei11169dd2012-12-18 14:30:41 +00004379 }
4380
4381 if (!CurrentModule)
4382 break;
4383
Argyrios Kyrtzidisb146baa2013-03-13 21:13:51 +00004384 // We lazily associate headers with their modules via the HeaderInfoTable.
4385 // FIXME: Re-evaluate this section; maybe only store InputFile IDs instead
4386 // of complete filenames or remove it entirely.
Guy Benyei11169dd2012-12-18 14:30:41 +00004387 break;
4388 }
4389
Lawrence Crowlb53e5482013-06-20 21:14:14 +00004390 case SUBMODULE_PRIVATE_HEADER: {
4391 if (First) {
4392 Error("missing submodule metadata record at beginning of block");
Ben Langmuir2c9af442014-04-10 17:57:43 +00004393 return Failure;
Lawrence Crowlb53e5482013-06-20 21:14:14 +00004394 }
4395
4396 if (!CurrentModule)
4397 break;
4398
4399 // We lazily associate headers with their modules via the HeaderInfoTable.
4400 // FIXME: Re-evaluate this section; maybe only store InputFile IDs instead
4401 // of complete filenames or remove it entirely.
4402 break;
4403 }
4404
Guy Benyei11169dd2012-12-18 14:30:41 +00004405 case SUBMODULE_TOPHEADER: {
4406 if (First) {
4407 Error("missing submodule metadata record at beginning of block");
Ben Langmuir2c9af442014-04-10 17:57:43 +00004408 return Failure;
Guy Benyei11169dd2012-12-18 14:30:41 +00004409 }
4410
4411 if (!CurrentModule)
4412 break;
4413
Argyrios Kyrtzidis3c5305c2013-03-13 21:13:43 +00004414 CurrentModule->addTopHeaderFilename(Blob);
Guy Benyei11169dd2012-12-18 14:30:41 +00004415 break;
4416 }
4417
4418 case SUBMODULE_UMBRELLA_DIR: {
4419 if (First) {
4420 Error("missing submodule metadata record at beginning of block");
Ben Langmuir2c9af442014-04-10 17:57:43 +00004421 return Failure;
Guy Benyei11169dd2012-12-18 14:30:41 +00004422 }
4423
4424 if (!CurrentModule)
4425 break;
4426
Guy Benyei11169dd2012-12-18 14:30:41 +00004427 if (const DirectoryEntry *Umbrella
Chris Lattner0e6c9402013-01-20 02:38:54 +00004428 = PP.getFileManager().getDirectory(Blob)) {
Guy Benyei11169dd2012-12-18 14:30:41 +00004429 if (!CurrentModule->getUmbrellaDir())
4430 ModMap.setUmbrellaDir(CurrentModule, Umbrella);
4431 else if (CurrentModule->getUmbrellaDir() != Umbrella) {
Ben Langmuir2c9af442014-04-10 17:57:43 +00004432 if ((ClientLoadCapabilities & ARR_OutOfDate) == 0)
4433 Error("mismatched umbrella directories in submodule");
4434 return OutOfDate;
Guy Benyei11169dd2012-12-18 14:30:41 +00004435 }
4436 }
4437 break;
4438 }
4439
4440 case SUBMODULE_METADATA: {
4441 if (!First) {
4442 Error("submodule metadata record not at beginning of block");
Ben Langmuir2c9af442014-04-10 17:57:43 +00004443 return Failure;
Guy Benyei11169dd2012-12-18 14:30:41 +00004444 }
4445 First = false;
4446
4447 F.BaseSubmoduleID = getTotalNumSubmodules();
4448 F.LocalNumSubmodules = Record[0];
4449 unsigned LocalBaseSubmoduleID = Record[1];
4450 if (F.LocalNumSubmodules > 0) {
4451 // Introduce the global -> local mapping for submodules within this
4452 // module.
4453 GlobalSubmoduleMap.insert(std::make_pair(getTotalNumSubmodules()+1,&F));
4454
4455 // Introduce the local -> global mapping for submodules within this
4456 // module.
4457 F.SubmoduleRemap.insertOrReplace(
4458 std::make_pair(LocalBaseSubmoduleID,
4459 F.BaseSubmoduleID - LocalBaseSubmoduleID));
4460
4461 SubmodulesLoaded.resize(SubmodulesLoaded.size() + F.LocalNumSubmodules);
4462 }
4463 break;
4464 }
4465
4466 case SUBMODULE_IMPORTS: {
4467 if (First) {
4468 Error("missing submodule metadata record at beginning of block");
Ben Langmuir2c9af442014-04-10 17:57:43 +00004469 return Failure;
Guy Benyei11169dd2012-12-18 14:30:41 +00004470 }
4471
4472 if (!CurrentModule)
4473 break;
4474
4475 for (unsigned Idx = 0; Idx != Record.size(); ++Idx) {
Douglas Gregorfb912652013-03-20 21:10:35 +00004476 UnresolvedModuleRef Unresolved;
Guy Benyei11169dd2012-12-18 14:30:41 +00004477 Unresolved.File = &F;
4478 Unresolved.Mod = CurrentModule;
4479 Unresolved.ID = Record[Idx];
Douglas Gregorfb912652013-03-20 21:10:35 +00004480 Unresolved.Kind = UnresolvedModuleRef::Import;
Guy Benyei11169dd2012-12-18 14:30:41 +00004481 Unresolved.IsWildcard = false;
Douglas Gregorfb912652013-03-20 21:10:35 +00004482 UnresolvedModuleRefs.push_back(Unresolved);
Guy Benyei11169dd2012-12-18 14:30:41 +00004483 }
4484 break;
4485 }
4486
4487 case SUBMODULE_EXPORTS: {
4488 if (First) {
4489 Error("missing submodule metadata record at beginning of block");
Ben Langmuir2c9af442014-04-10 17:57:43 +00004490 return Failure;
Guy Benyei11169dd2012-12-18 14:30:41 +00004491 }
4492
4493 if (!CurrentModule)
4494 break;
4495
4496 for (unsigned Idx = 0; Idx + 1 < Record.size(); Idx += 2) {
Douglas Gregorfb912652013-03-20 21:10:35 +00004497 UnresolvedModuleRef Unresolved;
Guy Benyei11169dd2012-12-18 14:30:41 +00004498 Unresolved.File = &F;
4499 Unresolved.Mod = CurrentModule;
4500 Unresolved.ID = Record[Idx];
Douglas Gregorfb912652013-03-20 21:10:35 +00004501 Unresolved.Kind = UnresolvedModuleRef::Export;
Guy Benyei11169dd2012-12-18 14:30:41 +00004502 Unresolved.IsWildcard = Record[Idx + 1];
Douglas Gregorfb912652013-03-20 21:10:35 +00004503 UnresolvedModuleRefs.push_back(Unresolved);
Guy Benyei11169dd2012-12-18 14:30:41 +00004504 }
4505
4506 // Once we've loaded the set of exports, there's no reason to keep
4507 // the parsed, unresolved exports around.
4508 CurrentModule->UnresolvedExports.clear();
4509 break;
4510 }
4511 case SUBMODULE_REQUIRES: {
4512 if (First) {
4513 Error("missing submodule metadata record at beginning of block");
Ben Langmuir2c9af442014-04-10 17:57:43 +00004514 return Failure;
Guy Benyei11169dd2012-12-18 14:30:41 +00004515 }
4516
4517 if (!CurrentModule)
4518 break;
4519
Richard Smitha3feee22013-10-28 22:18:19 +00004520 CurrentModule->addRequirement(Blob, Record[0], Context.getLangOpts(),
Guy Benyei11169dd2012-12-18 14:30:41 +00004521 Context.getTargetInfo());
4522 break;
4523 }
Douglas Gregor6ddfca92013-01-14 17:21:00 +00004524
4525 case SUBMODULE_LINK_LIBRARY:
4526 if (First) {
4527 Error("missing submodule metadata record at beginning of block");
Ben Langmuir2c9af442014-04-10 17:57:43 +00004528 return Failure;
Douglas Gregor6ddfca92013-01-14 17:21:00 +00004529 }
4530
4531 if (!CurrentModule)
4532 break;
4533
4534 CurrentModule->LinkLibraries.push_back(
Chris Lattner0e6c9402013-01-20 02:38:54 +00004535 Module::LinkLibrary(Blob, Record[0]));
Douglas Gregor6ddfca92013-01-14 17:21:00 +00004536 break;
Douglas Gregor35b13ec2013-03-20 00:22:05 +00004537
4538 case SUBMODULE_CONFIG_MACRO:
4539 if (First) {
4540 Error("missing submodule metadata record at beginning of block");
Ben Langmuir2c9af442014-04-10 17:57:43 +00004541 return Failure;
Douglas Gregor35b13ec2013-03-20 00:22:05 +00004542 }
4543
4544 if (!CurrentModule)
4545 break;
4546
4547 CurrentModule->ConfigMacros.push_back(Blob.str());
4548 break;
Douglas Gregorfb912652013-03-20 21:10:35 +00004549
4550 case SUBMODULE_CONFLICT: {
4551 if (First) {
4552 Error("missing submodule metadata record at beginning of block");
Ben Langmuir2c9af442014-04-10 17:57:43 +00004553 return Failure;
Douglas Gregorfb912652013-03-20 21:10:35 +00004554 }
4555
4556 if (!CurrentModule)
4557 break;
4558
4559 UnresolvedModuleRef Unresolved;
4560 Unresolved.File = &F;
4561 Unresolved.Mod = CurrentModule;
4562 Unresolved.ID = Record[0];
4563 Unresolved.Kind = UnresolvedModuleRef::Conflict;
4564 Unresolved.IsWildcard = false;
4565 Unresolved.String = Blob;
4566 UnresolvedModuleRefs.push_back(Unresolved);
4567 break;
4568 }
Guy Benyei11169dd2012-12-18 14:30:41 +00004569 }
4570 }
4571}
4572
4573/// \brief Parse the record that corresponds to a LangOptions data
4574/// structure.
4575///
4576/// This routine parses the language options from the AST file and then gives
4577/// them to the AST listener if one is set.
4578///
4579/// \returns true if the listener deems the file unacceptable, false otherwise.
4580bool ASTReader::ParseLanguageOptions(const RecordData &Record,
4581 bool Complain,
4582 ASTReaderListener &Listener) {
4583 LangOptions LangOpts;
4584 unsigned Idx = 0;
4585#define LANGOPT(Name, Bits, Default, Description) \
4586 LangOpts.Name = Record[Idx++];
4587#define ENUM_LANGOPT(Name, Type, Bits, Default, Description) \
4588 LangOpts.set##Name(static_cast<LangOptions::Type>(Record[Idx++]));
4589#include "clang/Basic/LangOptions.def"
Will Dietzf54319c2013-01-18 11:30:38 +00004590#define SANITIZER(NAME, ID) LangOpts.Sanitize.ID = Record[Idx++];
4591#include "clang/Basic/Sanitizers.def"
Guy Benyei11169dd2012-12-18 14:30:41 +00004592
4593 ObjCRuntime::Kind runtimeKind = (ObjCRuntime::Kind) Record[Idx++];
4594 VersionTuple runtimeVersion = ReadVersionTuple(Record, Idx);
4595 LangOpts.ObjCRuntime = ObjCRuntime(runtimeKind, runtimeVersion);
4596
4597 unsigned Length = Record[Idx++];
4598 LangOpts.CurrentModule.assign(Record.begin() + Idx,
4599 Record.begin() + Idx + Length);
Dmitri Gribenkoacf2e782013-02-22 14:21:27 +00004600
4601 Idx += Length;
4602
4603 // Comment options.
4604 for (unsigned N = Record[Idx++]; N; --N) {
4605 LangOpts.CommentOpts.BlockCommandNames.push_back(
4606 ReadString(Record, Idx));
4607 }
Dmitri Gribenkoa7d16ce2013-04-10 15:35:17 +00004608 LangOpts.CommentOpts.ParseAllComments = Record[Idx++];
Dmitri Gribenkoacf2e782013-02-22 14:21:27 +00004609
Guy Benyei11169dd2012-12-18 14:30:41 +00004610 return Listener.ReadLanguageOptions(LangOpts, Complain);
4611}
4612
4613bool ASTReader::ParseTargetOptions(const RecordData &Record,
4614 bool Complain,
4615 ASTReaderListener &Listener) {
4616 unsigned Idx = 0;
4617 TargetOptions TargetOpts;
4618 TargetOpts.Triple = ReadString(Record, Idx);
4619 TargetOpts.CPU = ReadString(Record, Idx);
4620 TargetOpts.ABI = ReadString(Record, Idx);
Guy Benyei11169dd2012-12-18 14:30:41 +00004621 for (unsigned N = Record[Idx++]; N; --N) {
4622 TargetOpts.FeaturesAsWritten.push_back(ReadString(Record, Idx));
4623 }
4624 for (unsigned N = Record[Idx++]; N; --N) {
4625 TargetOpts.Features.push_back(ReadString(Record, Idx));
4626 }
4627
4628 return Listener.ReadTargetOptions(TargetOpts, Complain);
4629}
4630
4631bool ASTReader::ParseDiagnosticOptions(const RecordData &Record, bool Complain,
4632 ASTReaderListener &Listener) {
Ben Langmuirb92de022014-04-29 16:25:26 +00004633 IntrusiveRefCntPtr<DiagnosticOptions> DiagOpts(new DiagnosticOptions);
Guy Benyei11169dd2012-12-18 14:30:41 +00004634 unsigned Idx = 0;
Ben Langmuirb92de022014-04-29 16:25:26 +00004635#define DIAGOPT(Name, Bits, Default) DiagOpts->Name = Record[Idx++];
Guy Benyei11169dd2012-12-18 14:30:41 +00004636#define ENUM_DIAGOPT(Name, Type, Bits, Default) \
Ben Langmuirb92de022014-04-29 16:25:26 +00004637 DiagOpts->set##Name(static_cast<Type>(Record[Idx++]));
Guy Benyei11169dd2012-12-18 14:30:41 +00004638#include "clang/Basic/DiagnosticOptions.def"
4639
Richard Smith3be1cb22014-08-07 00:24:21 +00004640 for (unsigned N = Record[Idx++]; N; --N)
Ben Langmuirb92de022014-04-29 16:25:26 +00004641 DiagOpts->Warnings.push_back(ReadString(Record, Idx));
Richard Smith3be1cb22014-08-07 00:24:21 +00004642 for (unsigned N = Record[Idx++]; N; --N)
4643 DiagOpts->Remarks.push_back(ReadString(Record, Idx));
Guy Benyei11169dd2012-12-18 14:30:41 +00004644
4645 return Listener.ReadDiagnosticOptions(DiagOpts, Complain);
4646}
4647
4648bool ASTReader::ParseFileSystemOptions(const RecordData &Record, bool Complain,
4649 ASTReaderListener &Listener) {
4650 FileSystemOptions FSOpts;
4651 unsigned Idx = 0;
4652 FSOpts.WorkingDir = ReadString(Record, Idx);
4653 return Listener.ReadFileSystemOptions(FSOpts, Complain);
4654}
4655
4656bool ASTReader::ParseHeaderSearchOptions(const RecordData &Record,
4657 bool Complain,
4658 ASTReaderListener &Listener) {
4659 HeaderSearchOptions HSOpts;
4660 unsigned Idx = 0;
4661 HSOpts.Sysroot = ReadString(Record, Idx);
4662
4663 // Include entries.
4664 for (unsigned N = Record[Idx++]; N; --N) {
4665 std::string Path = ReadString(Record, Idx);
4666 frontend::IncludeDirGroup Group
4667 = static_cast<frontend::IncludeDirGroup>(Record[Idx++]);
Guy Benyei11169dd2012-12-18 14:30:41 +00004668 bool IsFramework = Record[Idx++];
4669 bool IgnoreSysRoot = Record[Idx++];
Guy Benyei11169dd2012-12-18 14:30:41 +00004670 HSOpts.UserEntries.push_back(
Daniel Dunbar53681732013-01-30 00:34:26 +00004671 HeaderSearchOptions::Entry(Path, Group, IsFramework, IgnoreSysRoot));
Guy Benyei11169dd2012-12-18 14:30:41 +00004672 }
4673
4674 // System header prefixes.
4675 for (unsigned N = Record[Idx++]; N; --N) {
4676 std::string Prefix = ReadString(Record, Idx);
4677 bool IsSystemHeader = Record[Idx++];
4678 HSOpts.SystemHeaderPrefixes.push_back(
4679 HeaderSearchOptions::SystemHeaderPrefix(Prefix, IsSystemHeader));
4680 }
4681
4682 HSOpts.ResourceDir = ReadString(Record, Idx);
4683 HSOpts.ModuleCachePath = ReadString(Record, Idx);
Argyrios Kyrtzidis1594c152014-03-03 08:12:05 +00004684 HSOpts.ModuleUserBuildPath = ReadString(Record, Idx);
Guy Benyei11169dd2012-12-18 14:30:41 +00004685 HSOpts.DisableModuleHash = Record[Idx++];
4686 HSOpts.UseBuiltinIncludes = Record[Idx++];
4687 HSOpts.UseStandardSystemIncludes = Record[Idx++];
4688 HSOpts.UseStandardCXXIncludes = Record[Idx++];
4689 HSOpts.UseLibcxx = Record[Idx++];
4690
4691 return Listener.ReadHeaderSearchOptions(HSOpts, Complain);
4692}
4693
4694bool ASTReader::ParsePreprocessorOptions(const RecordData &Record,
4695 bool Complain,
4696 ASTReaderListener &Listener,
4697 std::string &SuggestedPredefines) {
4698 PreprocessorOptions PPOpts;
4699 unsigned Idx = 0;
4700
4701 // Macro definitions/undefs
4702 for (unsigned N = Record[Idx++]; N; --N) {
4703 std::string Macro = ReadString(Record, Idx);
4704 bool IsUndef = Record[Idx++];
4705 PPOpts.Macros.push_back(std::make_pair(Macro, IsUndef));
4706 }
4707
4708 // Includes
4709 for (unsigned N = Record[Idx++]; N; --N) {
4710 PPOpts.Includes.push_back(ReadString(Record, Idx));
4711 }
4712
4713 // Macro Includes
4714 for (unsigned N = Record[Idx++]; N; --N) {
4715 PPOpts.MacroIncludes.push_back(ReadString(Record, Idx));
4716 }
4717
4718 PPOpts.UsePredefines = Record[Idx++];
Argyrios Kyrtzidisd3afa0c2013-04-26 21:33:40 +00004719 PPOpts.DetailedRecord = Record[Idx++];
Guy Benyei11169dd2012-12-18 14:30:41 +00004720 PPOpts.ImplicitPCHInclude = ReadString(Record, Idx);
4721 PPOpts.ImplicitPTHInclude = ReadString(Record, Idx);
4722 PPOpts.ObjCXXARCStandardLibrary =
4723 static_cast<ObjCXXARCStandardLibraryKind>(Record[Idx++]);
4724 SuggestedPredefines.clear();
4725 return Listener.ReadPreprocessorOptions(PPOpts, Complain,
4726 SuggestedPredefines);
4727}
4728
4729std::pair<ModuleFile *, unsigned>
4730ASTReader::getModulePreprocessedEntity(unsigned GlobalIndex) {
4731 GlobalPreprocessedEntityMapType::iterator
4732 I = GlobalPreprocessedEntityMap.find(GlobalIndex);
4733 assert(I != GlobalPreprocessedEntityMap.end() &&
4734 "Corrupted global preprocessed entity map");
4735 ModuleFile *M = I->second;
4736 unsigned LocalIndex = GlobalIndex - M->BasePreprocessedEntityID;
4737 return std::make_pair(M, LocalIndex);
4738}
4739
4740std::pair<PreprocessingRecord::iterator, PreprocessingRecord::iterator>
4741ASTReader::getModulePreprocessedEntities(ModuleFile &Mod) const {
4742 if (PreprocessingRecord *PPRec = PP.getPreprocessingRecord())
4743 return PPRec->getIteratorsForLoadedRange(Mod.BasePreprocessedEntityID,
4744 Mod.NumPreprocessedEntities);
4745
4746 return std::make_pair(PreprocessingRecord::iterator(),
4747 PreprocessingRecord::iterator());
4748}
4749
4750std::pair<ASTReader::ModuleDeclIterator, ASTReader::ModuleDeclIterator>
4751ASTReader::getModuleFileLevelDecls(ModuleFile &Mod) {
4752 return std::make_pair(ModuleDeclIterator(this, &Mod, Mod.FileSortedDecls),
4753 ModuleDeclIterator(this, &Mod,
4754 Mod.FileSortedDecls + Mod.NumFileSortedDecls));
4755}
4756
4757PreprocessedEntity *ASTReader::ReadPreprocessedEntity(unsigned Index) {
4758 PreprocessedEntityID PPID = Index+1;
4759 std::pair<ModuleFile *, unsigned> PPInfo = getModulePreprocessedEntity(Index);
4760 ModuleFile &M = *PPInfo.first;
4761 unsigned LocalIndex = PPInfo.second;
4762 const PPEntityOffset &PPOffs = M.PreprocessedEntityOffsets[LocalIndex];
4763
Guy Benyei11169dd2012-12-18 14:30:41 +00004764 if (!PP.getPreprocessingRecord()) {
4765 Error("no preprocessing record");
Craig Toppera13603a2014-05-22 05:54:18 +00004766 return nullptr;
Guy Benyei11169dd2012-12-18 14:30:41 +00004767 }
4768
Chris Lattner7fb3bef2013-01-20 00:56:42 +00004769 SavedStreamPosition SavedPosition(M.PreprocessorDetailCursor);
4770 M.PreprocessorDetailCursor.JumpToBit(PPOffs.BitOffset);
4771
4772 llvm::BitstreamEntry Entry =
4773 M.PreprocessorDetailCursor.advance(BitstreamCursor::AF_DontPopBlockAtEnd);
4774 if (Entry.Kind != llvm::BitstreamEntry::Record)
Craig Toppera13603a2014-05-22 05:54:18 +00004775 return nullptr;
Chris Lattner7fb3bef2013-01-20 00:56:42 +00004776
Guy Benyei11169dd2012-12-18 14:30:41 +00004777 // Read the record.
4778 SourceRange Range(ReadSourceLocation(M, PPOffs.Begin),
4779 ReadSourceLocation(M, PPOffs.End));
4780 PreprocessingRecord &PPRec = *PP.getPreprocessingRecord();
Chris Lattner0e6c9402013-01-20 02:38:54 +00004781 StringRef Blob;
Guy Benyei11169dd2012-12-18 14:30:41 +00004782 RecordData Record;
4783 PreprocessorDetailRecordTypes RecType =
Chris Lattner0e6c9402013-01-20 02:38:54 +00004784 (PreprocessorDetailRecordTypes)M.PreprocessorDetailCursor.readRecord(
4785 Entry.ID, Record, &Blob);
Guy Benyei11169dd2012-12-18 14:30:41 +00004786 switch (RecType) {
4787 case PPD_MACRO_EXPANSION: {
4788 bool isBuiltin = Record[0];
Craig Toppera13603a2014-05-22 05:54:18 +00004789 IdentifierInfo *Name = nullptr;
4790 MacroDefinition *Def = nullptr;
Guy Benyei11169dd2012-12-18 14:30:41 +00004791 if (isBuiltin)
4792 Name = getLocalIdentifier(M, Record[1]);
4793 else {
4794 PreprocessedEntityID
4795 GlobalID = getGlobalPreprocessedEntityID(M, Record[1]);
4796 Def =cast<MacroDefinition>(PPRec.getLoadedPreprocessedEntity(GlobalID-1));
4797 }
4798
4799 MacroExpansion *ME;
4800 if (isBuiltin)
4801 ME = new (PPRec) MacroExpansion(Name, Range);
4802 else
4803 ME = new (PPRec) MacroExpansion(Def, Range);
4804
4805 return ME;
4806 }
4807
4808 case PPD_MACRO_DEFINITION: {
4809 // Decode the identifier info and then check again; if the macro is
4810 // still defined and associated with the identifier,
4811 IdentifierInfo *II = getLocalIdentifier(M, Record[0]);
4812 MacroDefinition *MD
4813 = new (PPRec) MacroDefinition(II, Range);
4814
4815 if (DeserializationListener)
4816 DeserializationListener->MacroDefinitionRead(PPID, MD);
4817
4818 return MD;
4819 }
4820
4821 case PPD_INCLUSION_DIRECTIVE: {
Chris Lattner0e6c9402013-01-20 02:38:54 +00004822 const char *FullFileNameStart = Blob.data() + Record[0];
4823 StringRef FullFileName(FullFileNameStart, Blob.size() - Record[0]);
Craig Toppera13603a2014-05-22 05:54:18 +00004824 const FileEntry *File = nullptr;
Guy Benyei11169dd2012-12-18 14:30:41 +00004825 if (!FullFileName.empty())
4826 File = PP.getFileManager().getFile(FullFileName);
4827
4828 // FIXME: Stable encoding
4829 InclusionDirective::InclusionKind Kind
4830 = static_cast<InclusionDirective::InclusionKind>(Record[2]);
4831 InclusionDirective *ID
4832 = new (PPRec) InclusionDirective(PPRec, Kind,
Chris Lattner0e6c9402013-01-20 02:38:54 +00004833 StringRef(Blob.data(), Record[0]),
Guy Benyei11169dd2012-12-18 14:30:41 +00004834 Record[1], Record[3],
4835 File,
4836 Range);
4837 return ID;
4838 }
4839 }
4840
4841 llvm_unreachable("Invalid PreprocessorDetailRecordTypes");
4842}
4843
4844/// \brief \arg SLocMapI points at a chunk of a module that contains no
4845/// preprocessed entities or the entities it contains are not the ones we are
4846/// looking for. Find the next module that contains entities and return the ID
4847/// of the first entry.
4848PreprocessedEntityID ASTReader::findNextPreprocessedEntity(
4849 GlobalSLocOffsetMapType::const_iterator SLocMapI) const {
4850 ++SLocMapI;
4851 for (GlobalSLocOffsetMapType::const_iterator
4852 EndI = GlobalSLocOffsetMap.end(); SLocMapI != EndI; ++SLocMapI) {
4853 ModuleFile &M = *SLocMapI->second;
4854 if (M.NumPreprocessedEntities)
4855 return M.BasePreprocessedEntityID;
4856 }
4857
4858 return getTotalNumPreprocessedEntities();
4859}
4860
4861namespace {
4862
4863template <unsigned PPEntityOffset::*PPLoc>
4864struct PPEntityComp {
4865 const ASTReader &Reader;
4866 ModuleFile &M;
4867
4868 PPEntityComp(const ASTReader &Reader, ModuleFile &M) : Reader(Reader), M(M) { }
4869
4870 bool operator()(const PPEntityOffset &L, const PPEntityOffset &R) const {
4871 SourceLocation LHS = getLoc(L);
4872 SourceLocation RHS = getLoc(R);
4873 return Reader.getSourceManager().isBeforeInTranslationUnit(LHS, RHS);
4874 }
4875
4876 bool operator()(const PPEntityOffset &L, SourceLocation RHS) const {
4877 SourceLocation LHS = getLoc(L);
4878 return Reader.getSourceManager().isBeforeInTranslationUnit(LHS, RHS);
4879 }
4880
4881 bool operator()(SourceLocation LHS, const PPEntityOffset &R) const {
4882 SourceLocation RHS = getLoc(R);
4883 return Reader.getSourceManager().isBeforeInTranslationUnit(LHS, RHS);
4884 }
4885
4886 SourceLocation getLoc(const PPEntityOffset &PPE) const {
4887 return Reader.ReadSourceLocation(M, PPE.*PPLoc);
4888 }
4889};
4890
4891}
4892
Alp Toker2e9ce4c2014-05-16 18:59:21 +00004893PreprocessedEntityID ASTReader::findPreprocessedEntity(SourceLocation Loc,
4894 bool EndsAfter) const {
4895 if (SourceMgr.isLocalSourceLocation(Loc))
Guy Benyei11169dd2012-12-18 14:30:41 +00004896 return getTotalNumPreprocessedEntities();
4897
Alp Toker2e9ce4c2014-05-16 18:59:21 +00004898 GlobalSLocOffsetMapType::const_iterator SLocMapI = GlobalSLocOffsetMap.find(
4899 SourceManager::MaxLoadedOffset - Loc.getOffset() - 1);
Guy Benyei11169dd2012-12-18 14:30:41 +00004900 assert(SLocMapI != GlobalSLocOffsetMap.end() &&
4901 "Corrupted global sloc offset map");
4902
4903 if (SLocMapI->second->NumPreprocessedEntities == 0)
4904 return findNextPreprocessedEntity(SLocMapI);
4905
4906 ModuleFile &M = *SLocMapI->second;
4907 typedef const PPEntityOffset *pp_iterator;
4908 pp_iterator pp_begin = M.PreprocessedEntityOffsets;
4909 pp_iterator pp_end = pp_begin + M.NumPreprocessedEntities;
4910
4911 size_t Count = M.NumPreprocessedEntities;
4912 size_t Half;
4913 pp_iterator First = pp_begin;
4914 pp_iterator PPI;
4915
Alp Toker2e9ce4c2014-05-16 18:59:21 +00004916 if (EndsAfter) {
4917 PPI = std::upper_bound(pp_begin, pp_end, Loc,
4918 PPEntityComp<&PPEntityOffset::Begin>(*this, M));
4919 } else {
4920 // Do a binary search manually instead of using std::lower_bound because
4921 // The end locations of entities may be unordered (when a macro expansion
4922 // is inside another macro argument), but for this case it is not important
4923 // whether we get the first macro expansion or its containing macro.
4924 while (Count > 0) {
4925 Half = Count / 2;
4926 PPI = First;
4927 std::advance(PPI, Half);
4928 if (SourceMgr.isBeforeInTranslationUnit(ReadSourceLocation(M, PPI->End),
4929 Loc)) {
4930 First = PPI;
4931 ++First;
4932 Count = Count - Half - 1;
4933 } else
4934 Count = Half;
4935 }
Guy Benyei11169dd2012-12-18 14:30:41 +00004936 }
4937
4938 if (PPI == pp_end)
4939 return findNextPreprocessedEntity(SLocMapI);
4940
4941 return M.BasePreprocessedEntityID + (PPI - pp_begin);
4942}
4943
Guy Benyei11169dd2012-12-18 14:30:41 +00004944/// \brief Returns a pair of [Begin, End) indices of preallocated
4945/// preprocessed entities that \arg Range encompasses.
4946std::pair<unsigned, unsigned>
4947 ASTReader::findPreprocessedEntitiesInRange(SourceRange Range) {
4948 if (Range.isInvalid())
4949 return std::make_pair(0,0);
4950 assert(!SourceMgr.isBeforeInTranslationUnit(Range.getEnd(),Range.getBegin()));
4951
Alp Toker2e9ce4c2014-05-16 18:59:21 +00004952 PreprocessedEntityID BeginID =
4953 findPreprocessedEntity(Range.getBegin(), false);
4954 PreprocessedEntityID EndID = findPreprocessedEntity(Range.getEnd(), true);
Guy Benyei11169dd2012-12-18 14:30:41 +00004955 return std::make_pair(BeginID, EndID);
4956}
4957
4958/// \brief Optionally returns true or false if the preallocated preprocessed
4959/// entity with index \arg Index came from file \arg FID.
David Blaikie05785d12013-02-20 22:23:23 +00004960Optional<bool> ASTReader::isPreprocessedEntityInFileID(unsigned Index,
Guy Benyei11169dd2012-12-18 14:30:41 +00004961 FileID FID) {
4962 if (FID.isInvalid())
4963 return false;
4964
4965 std::pair<ModuleFile *, unsigned> PPInfo = getModulePreprocessedEntity(Index);
4966 ModuleFile &M = *PPInfo.first;
4967 unsigned LocalIndex = PPInfo.second;
4968 const PPEntityOffset &PPOffs = M.PreprocessedEntityOffsets[LocalIndex];
4969
4970 SourceLocation Loc = ReadSourceLocation(M, PPOffs.Begin);
4971 if (Loc.isInvalid())
4972 return false;
4973
4974 if (SourceMgr.isInFileID(SourceMgr.getFileLoc(Loc), FID))
4975 return true;
4976 else
4977 return false;
4978}
4979
4980namespace {
4981 /// \brief Visitor used to search for information about a header file.
4982 class HeaderFileInfoVisitor {
Guy Benyei11169dd2012-12-18 14:30:41 +00004983 const FileEntry *FE;
4984
David Blaikie05785d12013-02-20 22:23:23 +00004985 Optional<HeaderFileInfo> HFI;
Guy Benyei11169dd2012-12-18 14:30:41 +00004986
4987 public:
Argyrios Kyrtzidis61a38962013-03-06 18:12:44 +00004988 explicit HeaderFileInfoVisitor(const FileEntry *FE)
4989 : FE(FE) { }
Guy Benyei11169dd2012-12-18 14:30:41 +00004990
4991 static bool visit(ModuleFile &M, void *UserData) {
4992 HeaderFileInfoVisitor *This
4993 = static_cast<HeaderFileInfoVisitor *>(UserData);
4994
Guy Benyei11169dd2012-12-18 14:30:41 +00004995 HeaderFileInfoLookupTable *Table
4996 = static_cast<HeaderFileInfoLookupTable *>(M.HeaderFileInfoTable);
4997 if (!Table)
4998 return false;
4999
5000 // Look in the on-disk hash table for an entry for this file name.
Argyrios Kyrtzidis5c2a3452013-03-06 18:12:47 +00005001 HeaderFileInfoLookupTable::iterator Pos = Table->find(This->FE);
Guy Benyei11169dd2012-12-18 14:30:41 +00005002 if (Pos == Table->end())
5003 return false;
5004
5005 This->HFI = *Pos;
5006 return true;
5007 }
5008
David Blaikie05785d12013-02-20 22:23:23 +00005009 Optional<HeaderFileInfo> getHeaderFileInfo() const { return HFI; }
Guy Benyei11169dd2012-12-18 14:30:41 +00005010 };
5011}
5012
5013HeaderFileInfo ASTReader::GetHeaderFileInfo(const FileEntry *FE) {
Argyrios Kyrtzidis61a38962013-03-06 18:12:44 +00005014 HeaderFileInfoVisitor Visitor(FE);
Guy Benyei11169dd2012-12-18 14:30:41 +00005015 ModuleMgr.visit(&HeaderFileInfoVisitor::visit, &Visitor);
Argyrios Kyrtzidis1054bbf2013-05-08 23:46:55 +00005016 if (Optional<HeaderFileInfo> HFI = Visitor.getHeaderFileInfo())
Guy Benyei11169dd2012-12-18 14:30:41 +00005017 return *HFI;
Guy Benyei11169dd2012-12-18 14:30:41 +00005018
5019 return HeaderFileInfo();
5020}
5021
5022void ASTReader::ReadPragmaDiagnosticMappings(DiagnosticsEngine &Diag) {
5023 // FIXME: Make it work properly with modules.
Dmitri Gribenkof8579502013-01-12 19:30:44 +00005024 SmallVector<DiagnosticsEngine::DiagState *, 32> DiagStates;
Guy Benyei11169dd2012-12-18 14:30:41 +00005025 for (ModuleIterator I = ModuleMgr.begin(), E = ModuleMgr.end(); I != E; ++I) {
5026 ModuleFile &F = *(*I);
5027 unsigned Idx = 0;
5028 DiagStates.clear();
5029 assert(!Diag.DiagStates.empty());
5030 DiagStates.push_back(&Diag.DiagStates.front()); // the command-line one.
5031 while (Idx < F.PragmaDiagMappings.size()) {
5032 SourceLocation Loc = ReadSourceLocation(F, F.PragmaDiagMappings[Idx++]);
5033 unsigned DiagStateID = F.PragmaDiagMappings[Idx++];
5034 if (DiagStateID != 0) {
5035 Diag.DiagStatePoints.push_back(
5036 DiagnosticsEngine::DiagStatePoint(DiagStates[DiagStateID-1],
5037 FullSourceLoc(Loc, SourceMgr)));
5038 continue;
5039 }
5040
5041 assert(DiagStateID == 0);
5042 // A new DiagState was created here.
5043 Diag.DiagStates.push_back(*Diag.GetCurDiagState());
5044 DiagnosticsEngine::DiagState *NewState = &Diag.DiagStates.back();
5045 DiagStates.push_back(NewState);
5046 Diag.DiagStatePoints.push_back(
5047 DiagnosticsEngine::DiagStatePoint(NewState,
5048 FullSourceLoc(Loc, SourceMgr)));
5049 while (1) {
5050 assert(Idx < F.PragmaDiagMappings.size() &&
5051 "Invalid data, didn't find '-1' marking end of diag/map pairs");
5052 if (Idx >= F.PragmaDiagMappings.size()) {
5053 break; // Something is messed up but at least avoid infinite loop in
5054 // release build.
5055 }
5056 unsigned DiagID = F.PragmaDiagMappings[Idx++];
5057 if (DiagID == (unsigned)-1) {
5058 break; // no more diag/map pairs for this location.
5059 }
Alp Tokerc726c362014-06-10 09:31:37 +00005060 diag::Severity Map = (diag::Severity)F.PragmaDiagMappings[Idx++];
5061 DiagnosticMapping Mapping = Diag.makeUserMapping(Map, Loc);
5062 Diag.GetCurDiagState()->setMapping(DiagID, Mapping);
Guy Benyei11169dd2012-12-18 14:30:41 +00005063 }
5064 }
5065 }
5066}
5067
5068/// \brief Get the correct cursor and offset for loading a type.
5069ASTReader::RecordLocation ASTReader::TypeCursorForIndex(unsigned Index) {
5070 GlobalTypeMapType::iterator I = GlobalTypeMap.find(Index);
5071 assert(I != GlobalTypeMap.end() && "Corrupted global type map");
5072 ModuleFile *M = I->second;
5073 return RecordLocation(M, M->TypeOffsets[Index - M->BaseTypeIndex]);
5074}
5075
5076/// \brief Read and return the type with the given index..
5077///
5078/// The index is the type ID, shifted and minus the number of predefs. This
5079/// routine actually reads the record corresponding to the type at the given
5080/// location. It is a helper routine for GetType, which deals with reading type
5081/// IDs.
5082QualType ASTReader::readTypeRecord(unsigned Index) {
5083 RecordLocation Loc = TypeCursorForIndex(Index);
Chris Lattner7fb3bef2013-01-20 00:56:42 +00005084 BitstreamCursor &DeclsCursor = Loc.F->DeclsCursor;
Guy Benyei11169dd2012-12-18 14:30:41 +00005085
5086 // Keep track of where we are in the stream, then jump back there
5087 // after reading this type.
5088 SavedStreamPosition SavedPosition(DeclsCursor);
5089
5090 ReadingKindTracker ReadingKind(Read_Type, *this);
5091
5092 // Note that we are loading a type record.
5093 Deserializing AType(this);
5094
5095 unsigned Idx = 0;
5096 DeclsCursor.JumpToBit(Loc.Offset);
5097 RecordData Record;
5098 unsigned Code = DeclsCursor.ReadCode();
Chris Lattner0e6c9402013-01-20 02:38:54 +00005099 switch ((TypeCode)DeclsCursor.readRecord(Code, Record)) {
Guy Benyei11169dd2012-12-18 14:30:41 +00005100 case TYPE_EXT_QUAL: {
5101 if (Record.size() != 2) {
5102 Error("Incorrect encoding of extended qualifier type");
5103 return QualType();
5104 }
5105 QualType Base = readType(*Loc.F, Record, Idx);
5106 Qualifiers Quals = Qualifiers::fromOpaqueValue(Record[Idx++]);
5107 return Context.getQualifiedType(Base, Quals);
5108 }
5109
5110 case TYPE_COMPLEX: {
5111 if (Record.size() != 1) {
5112 Error("Incorrect encoding of complex type");
5113 return QualType();
5114 }
5115 QualType ElemType = readType(*Loc.F, Record, Idx);
5116 return Context.getComplexType(ElemType);
5117 }
5118
5119 case TYPE_POINTER: {
5120 if (Record.size() != 1) {
5121 Error("Incorrect encoding of pointer type");
5122 return QualType();
5123 }
5124 QualType PointeeType = readType(*Loc.F, Record, Idx);
5125 return Context.getPointerType(PointeeType);
5126 }
5127
Reid Kleckner8a365022013-06-24 17:51:48 +00005128 case TYPE_DECAYED: {
5129 if (Record.size() != 1) {
5130 Error("Incorrect encoding of decayed type");
5131 return QualType();
5132 }
5133 QualType OriginalType = readType(*Loc.F, Record, Idx);
5134 QualType DT = Context.getAdjustedParameterType(OriginalType);
5135 if (!isa<DecayedType>(DT))
5136 Error("Decayed type does not decay");
5137 return DT;
5138 }
5139
Reid Kleckner0503a872013-12-05 01:23:43 +00005140 case TYPE_ADJUSTED: {
5141 if (Record.size() != 2) {
5142 Error("Incorrect encoding of adjusted type");
5143 return QualType();
5144 }
5145 QualType OriginalTy = readType(*Loc.F, Record, Idx);
5146 QualType AdjustedTy = readType(*Loc.F, Record, Idx);
5147 return Context.getAdjustedType(OriginalTy, AdjustedTy);
5148 }
5149
Guy Benyei11169dd2012-12-18 14:30:41 +00005150 case TYPE_BLOCK_POINTER: {
5151 if (Record.size() != 1) {
5152 Error("Incorrect encoding of block pointer type");
5153 return QualType();
5154 }
5155 QualType PointeeType = readType(*Loc.F, Record, Idx);
5156 return Context.getBlockPointerType(PointeeType);
5157 }
5158
5159 case TYPE_LVALUE_REFERENCE: {
5160 if (Record.size() != 2) {
5161 Error("Incorrect encoding of lvalue reference type");
5162 return QualType();
5163 }
5164 QualType PointeeType = readType(*Loc.F, Record, Idx);
5165 return Context.getLValueReferenceType(PointeeType, Record[1]);
5166 }
5167
5168 case TYPE_RVALUE_REFERENCE: {
5169 if (Record.size() != 1) {
5170 Error("Incorrect encoding of rvalue reference type");
5171 return QualType();
5172 }
5173 QualType PointeeType = readType(*Loc.F, Record, Idx);
5174 return Context.getRValueReferenceType(PointeeType);
5175 }
5176
5177 case TYPE_MEMBER_POINTER: {
5178 if (Record.size() != 2) {
5179 Error("Incorrect encoding of member pointer type");
5180 return QualType();
5181 }
5182 QualType PointeeType = readType(*Loc.F, Record, Idx);
5183 QualType ClassType = readType(*Loc.F, Record, Idx);
5184 if (PointeeType.isNull() || ClassType.isNull())
5185 return QualType();
5186
5187 return Context.getMemberPointerType(PointeeType, ClassType.getTypePtr());
5188 }
5189
5190 case TYPE_CONSTANT_ARRAY: {
5191 QualType ElementType = readType(*Loc.F, Record, Idx);
5192 ArrayType::ArraySizeModifier ASM = (ArrayType::ArraySizeModifier)Record[1];
5193 unsigned IndexTypeQuals = Record[2];
5194 unsigned Idx = 3;
5195 llvm::APInt Size = ReadAPInt(Record, Idx);
5196 return Context.getConstantArrayType(ElementType, Size,
5197 ASM, IndexTypeQuals);
5198 }
5199
5200 case TYPE_INCOMPLETE_ARRAY: {
5201 QualType ElementType = readType(*Loc.F, Record, Idx);
5202 ArrayType::ArraySizeModifier ASM = (ArrayType::ArraySizeModifier)Record[1];
5203 unsigned IndexTypeQuals = Record[2];
5204 return Context.getIncompleteArrayType(ElementType, ASM, IndexTypeQuals);
5205 }
5206
5207 case TYPE_VARIABLE_ARRAY: {
5208 QualType ElementType = readType(*Loc.F, Record, Idx);
5209 ArrayType::ArraySizeModifier ASM = (ArrayType::ArraySizeModifier)Record[1];
5210 unsigned IndexTypeQuals = Record[2];
5211 SourceLocation LBLoc = ReadSourceLocation(*Loc.F, Record[3]);
5212 SourceLocation RBLoc = ReadSourceLocation(*Loc.F, Record[4]);
5213 return Context.getVariableArrayType(ElementType, ReadExpr(*Loc.F),
5214 ASM, IndexTypeQuals,
5215 SourceRange(LBLoc, RBLoc));
5216 }
5217
5218 case TYPE_VECTOR: {
5219 if (Record.size() != 3) {
5220 Error("incorrect encoding of vector type in AST file");
5221 return QualType();
5222 }
5223
5224 QualType ElementType = readType(*Loc.F, Record, Idx);
5225 unsigned NumElements = Record[1];
5226 unsigned VecKind = Record[2];
5227 return Context.getVectorType(ElementType, NumElements,
5228 (VectorType::VectorKind)VecKind);
5229 }
5230
5231 case TYPE_EXT_VECTOR: {
5232 if (Record.size() != 3) {
5233 Error("incorrect encoding of extended vector type in AST file");
5234 return QualType();
5235 }
5236
5237 QualType ElementType = readType(*Loc.F, Record, Idx);
5238 unsigned NumElements = Record[1];
5239 return Context.getExtVectorType(ElementType, NumElements);
5240 }
5241
5242 case TYPE_FUNCTION_NO_PROTO: {
5243 if (Record.size() != 6) {
5244 Error("incorrect encoding of no-proto function type");
5245 return QualType();
5246 }
5247 QualType ResultType = readType(*Loc.F, Record, Idx);
5248 FunctionType::ExtInfo Info(Record[1], Record[2], Record[3],
5249 (CallingConv)Record[4], Record[5]);
5250 return Context.getFunctionNoProtoType(ResultType, Info);
5251 }
5252
5253 case TYPE_FUNCTION_PROTO: {
5254 QualType ResultType = readType(*Loc.F, Record, Idx);
5255
5256 FunctionProtoType::ExtProtoInfo EPI;
5257 EPI.ExtInfo = FunctionType::ExtInfo(/*noreturn*/ Record[1],
5258 /*hasregparm*/ Record[2],
5259 /*regparm*/ Record[3],
5260 static_cast<CallingConv>(Record[4]),
5261 /*produces*/ Record[5]);
5262
5263 unsigned Idx = 6;
Guy Benyei11169dd2012-12-18 14:30:41 +00005264
5265 EPI.Variadic = Record[Idx++];
5266 EPI.HasTrailingReturn = Record[Idx++];
5267 EPI.TypeQuals = Record[Idx++];
5268 EPI.RefQualifier = static_cast<RefQualifierKind>(Record[Idx++]);
Richard Smith564417a2014-03-20 21:47:22 +00005269 SmallVector<QualType, 8> ExceptionStorage;
Richard Smith8acb4282014-07-31 21:57:55 +00005270 readExceptionSpec(*Loc.F, ExceptionStorage, EPI.ExceptionSpec, Record, Idx);
Richard Smith01b2cb42014-07-26 06:37:51 +00005271
5272 unsigned NumParams = Record[Idx++];
5273 SmallVector<QualType, 16> ParamTypes;
5274 for (unsigned I = 0; I != NumParams; ++I)
5275 ParamTypes.push_back(readType(*Loc.F, Record, Idx));
5276
Jordan Rose5c382722013-03-08 21:51:21 +00005277 return Context.getFunctionType(ResultType, ParamTypes, EPI);
Guy Benyei11169dd2012-12-18 14:30:41 +00005278 }
5279
5280 case TYPE_UNRESOLVED_USING: {
5281 unsigned Idx = 0;
5282 return Context.getTypeDeclType(
5283 ReadDeclAs<UnresolvedUsingTypenameDecl>(*Loc.F, Record, Idx));
5284 }
5285
5286 case TYPE_TYPEDEF: {
5287 if (Record.size() != 2) {
5288 Error("incorrect encoding of typedef type");
5289 return QualType();
5290 }
5291 unsigned Idx = 0;
5292 TypedefNameDecl *Decl = ReadDeclAs<TypedefNameDecl>(*Loc.F, Record, Idx);
5293 QualType Canonical = readType(*Loc.F, Record, Idx);
5294 if (!Canonical.isNull())
5295 Canonical = Context.getCanonicalType(Canonical);
5296 return Context.getTypedefType(Decl, Canonical);
5297 }
5298
5299 case TYPE_TYPEOF_EXPR:
5300 return Context.getTypeOfExprType(ReadExpr(*Loc.F));
5301
5302 case TYPE_TYPEOF: {
5303 if (Record.size() != 1) {
5304 Error("incorrect encoding of typeof(type) in AST file");
5305 return QualType();
5306 }
5307 QualType UnderlyingType = readType(*Loc.F, Record, Idx);
5308 return Context.getTypeOfType(UnderlyingType);
5309 }
5310
5311 case TYPE_DECLTYPE: {
5312 QualType UnderlyingType = readType(*Loc.F, Record, Idx);
5313 return Context.getDecltypeType(ReadExpr(*Loc.F), UnderlyingType);
5314 }
5315
5316 case TYPE_UNARY_TRANSFORM: {
5317 QualType BaseType = readType(*Loc.F, Record, Idx);
5318 QualType UnderlyingType = readType(*Loc.F, Record, Idx);
5319 UnaryTransformType::UTTKind UKind = (UnaryTransformType::UTTKind)Record[2];
5320 return Context.getUnaryTransformType(BaseType, UnderlyingType, UKind);
5321 }
5322
Richard Smith74aeef52013-04-26 16:15:35 +00005323 case TYPE_AUTO: {
5324 QualType Deduced = readType(*Loc.F, Record, Idx);
5325 bool IsDecltypeAuto = Record[Idx++];
Richard Smith27d807c2013-04-30 13:56:41 +00005326 bool IsDependent = Deduced.isNull() ? Record[Idx++] : false;
Manuel Klimek2fdbea22013-08-22 12:12:24 +00005327 return Context.getAutoType(Deduced, IsDecltypeAuto, IsDependent);
Richard Smith74aeef52013-04-26 16:15:35 +00005328 }
Guy Benyei11169dd2012-12-18 14:30:41 +00005329
5330 case TYPE_RECORD: {
5331 if (Record.size() != 2) {
5332 Error("incorrect encoding of record type");
5333 return QualType();
5334 }
5335 unsigned Idx = 0;
5336 bool IsDependent = Record[Idx++];
5337 RecordDecl *RD = ReadDeclAs<RecordDecl>(*Loc.F, Record, Idx);
5338 RD = cast_or_null<RecordDecl>(RD->getCanonicalDecl());
5339 QualType T = Context.getRecordType(RD);
5340 const_cast<Type*>(T.getTypePtr())->setDependent(IsDependent);
5341 return T;
5342 }
5343
5344 case TYPE_ENUM: {
5345 if (Record.size() != 2) {
5346 Error("incorrect encoding of enum type");
5347 return QualType();
5348 }
5349 unsigned Idx = 0;
5350 bool IsDependent = Record[Idx++];
5351 QualType T
5352 = Context.getEnumType(ReadDeclAs<EnumDecl>(*Loc.F, Record, Idx));
5353 const_cast<Type*>(T.getTypePtr())->setDependent(IsDependent);
5354 return T;
5355 }
5356
5357 case TYPE_ATTRIBUTED: {
5358 if (Record.size() != 3) {
5359 Error("incorrect encoding of attributed type");
5360 return QualType();
5361 }
5362 QualType modifiedType = readType(*Loc.F, Record, Idx);
5363 QualType equivalentType = readType(*Loc.F, Record, Idx);
5364 AttributedType::Kind kind = static_cast<AttributedType::Kind>(Record[2]);
5365 return Context.getAttributedType(kind, modifiedType, equivalentType);
5366 }
5367
5368 case TYPE_PAREN: {
5369 if (Record.size() != 1) {
5370 Error("incorrect encoding of paren type");
5371 return QualType();
5372 }
5373 QualType InnerType = readType(*Loc.F, Record, Idx);
5374 return Context.getParenType(InnerType);
5375 }
5376
5377 case TYPE_PACK_EXPANSION: {
5378 if (Record.size() != 2) {
5379 Error("incorrect encoding of pack expansion type");
5380 return QualType();
5381 }
5382 QualType Pattern = readType(*Loc.F, Record, Idx);
5383 if (Pattern.isNull())
5384 return QualType();
David Blaikie05785d12013-02-20 22:23:23 +00005385 Optional<unsigned> NumExpansions;
Guy Benyei11169dd2012-12-18 14:30:41 +00005386 if (Record[1])
5387 NumExpansions = Record[1] - 1;
5388 return Context.getPackExpansionType(Pattern, NumExpansions);
5389 }
5390
5391 case TYPE_ELABORATED: {
5392 unsigned Idx = 0;
5393 ElaboratedTypeKeyword Keyword = (ElaboratedTypeKeyword)Record[Idx++];
5394 NestedNameSpecifier *NNS = ReadNestedNameSpecifier(*Loc.F, Record, Idx);
5395 QualType NamedType = readType(*Loc.F, Record, Idx);
5396 return Context.getElaboratedType(Keyword, NNS, NamedType);
5397 }
5398
5399 case TYPE_OBJC_INTERFACE: {
5400 unsigned Idx = 0;
5401 ObjCInterfaceDecl *ItfD
5402 = ReadDeclAs<ObjCInterfaceDecl>(*Loc.F, Record, Idx);
5403 return Context.getObjCInterfaceType(ItfD->getCanonicalDecl());
5404 }
5405
5406 case TYPE_OBJC_OBJECT: {
5407 unsigned Idx = 0;
5408 QualType Base = readType(*Loc.F, Record, Idx);
5409 unsigned NumProtos = Record[Idx++];
5410 SmallVector<ObjCProtocolDecl*, 4> Protos;
5411 for (unsigned I = 0; I != NumProtos; ++I)
5412 Protos.push_back(ReadDeclAs<ObjCProtocolDecl>(*Loc.F, Record, Idx));
5413 return Context.getObjCObjectType(Base, Protos.data(), NumProtos);
5414 }
5415
5416 case TYPE_OBJC_OBJECT_POINTER: {
5417 unsigned Idx = 0;
5418 QualType Pointee = readType(*Loc.F, Record, Idx);
5419 return Context.getObjCObjectPointerType(Pointee);
5420 }
5421
5422 case TYPE_SUBST_TEMPLATE_TYPE_PARM: {
5423 unsigned Idx = 0;
5424 QualType Parm = readType(*Loc.F, Record, Idx);
5425 QualType Replacement = readType(*Loc.F, Record, Idx);
Stephan Tolksdorfe96f8b32014-03-15 10:23:27 +00005426 return Context.getSubstTemplateTypeParmType(
5427 cast<TemplateTypeParmType>(Parm),
5428 Context.getCanonicalType(Replacement));
Guy Benyei11169dd2012-12-18 14:30:41 +00005429 }
5430
5431 case TYPE_SUBST_TEMPLATE_TYPE_PARM_PACK: {
5432 unsigned Idx = 0;
5433 QualType Parm = readType(*Loc.F, Record, Idx);
5434 TemplateArgument ArgPack = ReadTemplateArgument(*Loc.F, Record, Idx);
5435 return Context.getSubstTemplateTypeParmPackType(
5436 cast<TemplateTypeParmType>(Parm),
5437 ArgPack);
5438 }
5439
5440 case TYPE_INJECTED_CLASS_NAME: {
5441 CXXRecordDecl *D = ReadDeclAs<CXXRecordDecl>(*Loc.F, Record, Idx);
5442 QualType TST = readType(*Loc.F, Record, Idx); // probably derivable
5443 // FIXME: ASTContext::getInjectedClassNameType is not currently suitable
5444 // for AST reading, too much interdependencies.
Richard Smithf17fdbd2014-04-24 02:25:27 +00005445 const Type *T;
5446 if (const Type *Existing = D->getTypeForDecl())
5447 T = Existing;
5448 else if (auto *Prev = D->getPreviousDecl())
5449 T = Prev->getTypeForDecl();
5450 else
5451 T = new (Context, TypeAlignment) InjectedClassNameType(D, TST);
5452 return QualType(T, 0);
Guy Benyei11169dd2012-12-18 14:30:41 +00005453 }
5454
5455 case TYPE_TEMPLATE_TYPE_PARM: {
5456 unsigned Idx = 0;
5457 unsigned Depth = Record[Idx++];
5458 unsigned Index = Record[Idx++];
5459 bool Pack = Record[Idx++];
5460 TemplateTypeParmDecl *D
5461 = ReadDeclAs<TemplateTypeParmDecl>(*Loc.F, Record, Idx);
5462 return Context.getTemplateTypeParmType(Depth, Index, Pack, D);
5463 }
5464
5465 case TYPE_DEPENDENT_NAME: {
5466 unsigned Idx = 0;
5467 ElaboratedTypeKeyword Keyword = (ElaboratedTypeKeyword)Record[Idx++];
5468 NestedNameSpecifier *NNS = ReadNestedNameSpecifier(*Loc.F, Record, Idx);
5469 const IdentifierInfo *Name = this->GetIdentifierInfo(*Loc.F, Record, Idx);
5470 QualType Canon = readType(*Loc.F, Record, Idx);
5471 if (!Canon.isNull())
5472 Canon = Context.getCanonicalType(Canon);
5473 return Context.getDependentNameType(Keyword, NNS, Name, Canon);
5474 }
5475
5476 case TYPE_DEPENDENT_TEMPLATE_SPECIALIZATION: {
5477 unsigned Idx = 0;
5478 ElaboratedTypeKeyword Keyword = (ElaboratedTypeKeyword)Record[Idx++];
5479 NestedNameSpecifier *NNS = ReadNestedNameSpecifier(*Loc.F, Record, Idx);
5480 const IdentifierInfo *Name = this->GetIdentifierInfo(*Loc.F, Record, Idx);
5481 unsigned NumArgs = Record[Idx++];
5482 SmallVector<TemplateArgument, 8> Args;
5483 Args.reserve(NumArgs);
5484 while (NumArgs--)
5485 Args.push_back(ReadTemplateArgument(*Loc.F, Record, Idx));
5486 return Context.getDependentTemplateSpecializationType(Keyword, NNS, Name,
5487 Args.size(), Args.data());
5488 }
5489
5490 case TYPE_DEPENDENT_SIZED_ARRAY: {
5491 unsigned Idx = 0;
5492
5493 // ArrayType
5494 QualType ElementType = readType(*Loc.F, Record, Idx);
5495 ArrayType::ArraySizeModifier ASM
5496 = (ArrayType::ArraySizeModifier)Record[Idx++];
5497 unsigned IndexTypeQuals = Record[Idx++];
5498
5499 // DependentSizedArrayType
5500 Expr *NumElts = ReadExpr(*Loc.F);
5501 SourceRange Brackets = ReadSourceRange(*Loc.F, Record, Idx);
5502
5503 return Context.getDependentSizedArrayType(ElementType, NumElts, ASM,
5504 IndexTypeQuals, Brackets);
5505 }
5506
5507 case TYPE_TEMPLATE_SPECIALIZATION: {
5508 unsigned Idx = 0;
5509 bool IsDependent = Record[Idx++];
5510 TemplateName Name = ReadTemplateName(*Loc.F, Record, Idx);
5511 SmallVector<TemplateArgument, 8> Args;
5512 ReadTemplateArgumentList(Args, *Loc.F, Record, Idx);
5513 QualType Underlying = readType(*Loc.F, Record, Idx);
5514 QualType T;
5515 if (Underlying.isNull())
5516 T = Context.getCanonicalTemplateSpecializationType(Name, Args.data(),
5517 Args.size());
5518 else
5519 T = Context.getTemplateSpecializationType(Name, Args.data(),
5520 Args.size(), Underlying);
5521 const_cast<Type*>(T.getTypePtr())->setDependent(IsDependent);
5522 return T;
5523 }
5524
5525 case TYPE_ATOMIC: {
5526 if (Record.size() != 1) {
5527 Error("Incorrect encoding of atomic type");
5528 return QualType();
5529 }
5530 QualType ValueType = readType(*Loc.F, Record, Idx);
5531 return Context.getAtomicType(ValueType);
5532 }
5533 }
5534 llvm_unreachable("Invalid TypeCode!");
5535}
5536
Richard Smith564417a2014-03-20 21:47:22 +00005537void ASTReader::readExceptionSpec(ModuleFile &ModuleFile,
5538 SmallVectorImpl<QualType> &Exceptions,
Richard Smith8acb4282014-07-31 21:57:55 +00005539 FunctionProtoType::ExceptionSpecInfo &ESI,
Richard Smith564417a2014-03-20 21:47:22 +00005540 const RecordData &Record, unsigned &Idx) {
5541 ExceptionSpecificationType EST =
5542 static_cast<ExceptionSpecificationType>(Record[Idx++]);
Richard Smith8acb4282014-07-31 21:57:55 +00005543 ESI.Type = EST;
Richard Smith564417a2014-03-20 21:47:22 +00005544 if (EST == EST_Dynamic) {
Richard Smith8acb4282014-07-31 21:57:55 +00005545 for (unsigned I = 0, N = Record[Idx++]; I != N; ++I)
Richard Smith564417a2014-03-20 21:47:22 +00005546 Exceptions.push_back(readType(ModuleFile, Record, Idx));
Richard Smith8acb4282014-07-31 21:57:55 +00005547 ESI.Exceptions = Exceptions;
Richard Smith564417a2014-03-20 21:47:22 +00005548 } else if (EST == EST_ComputedNoexcept) {
Richard Smith8acb4282014-07-31 21:57:55 +00005549 ESI.NoexceptExpr = ReadExpr(ModuleFile);
Richard Smith564417a2014-03-20 21:47:22 +00005550 } else if (EST == EST_Uninstantiated) {
Richard Smith8acb4282014-07-31 21:57:55 +00005551 ESI.SourceDecl = ReadDeclAs<FunctionDecl>(ModuleFile, Record, Idx);
5552 ESI.SourceTemplate = ReadDeclAs<FunctionDecl>(ModuleFile, Record, Idx);
Richard Smith564417a2014-03-20 21:47:22 +00005553 } else if (EST == EST_Unevaluated) {
Richard Smith8acb4282014-07-31 21:57:55 +00005554 ESI.SourceDecl = ReadDeclAs<FunctionDecl>(ModuleFile, Record, Idx);
Richard Smith564417a2014-03-20 21:47:22 +00005555 }
5556}
5557
Guy Benyei11169dd2012-12-18 14:30:41 +00005558class clang::TypeLocReader : public TypeLocVisitor<TypeLocReader> {
5559 ASTReader &Reader;
5560 ModuleFile &F;
5561 const ASTReader::RecordData &Record;
5562 unsigned &Idx;
5563
5564 SourceLocation ReadSourceLocation(const ASTReader::RecordData &R,
5565 unsigned &I) {
5566 return Reader.ReadSourceLocation(F, R, I);
5567 }
5568
5569 template<typename T>
5570 T *ReadDeclAs(const ASTReader::RecordData &Record, unsigned &Idx) {
5571 return Reader.ReadDeclAs<T>(F, Record, Idx);
5572 }
5573
5574public:
5575 TypeLocReader(ASTReader &Reader, ModuleFile &F,
5576 const ASTReader::RecordData &Record, unsigned &Idx)
5577 : Reader(Reader), F(F), Record(Record), Idx(Idx)
5578 { }
5579
5580 // We want compile-time assurance that we've enumerated all of
5581 // these, so unfortunately we have to declare them first, then
5582 // define them out-of-line.
5583#define ABSTRACT_TYPELOC(CLASS, PARENT)
5584#define TYPELOC(CLASS, PARENT) \
5585 void Visit##CLASS##TypeLoc(CLASS##TypeLoc TyLoc);
5586#include "clang/AST/TypeLocNodes.def"
5587
5588 void VisitFunctionTypeLoc(FunctionTypeLoc);
5589 void VisitArrayTypeLoc(ArrayTypeLoc);
5590};
5591
5592void TypeLocReader::VisitQualifiedTypeLoc(QualifiedTypeLoc TL) {
5593 // nothing to do
5594}
5595void TypeLocReader::VisitBuiltinTypeLoc(BuiltinTypeLoc TL) {
5596 TL.setBuiltinLoc(ReadSourceLocation(Record, Idx));
5597 if (TL.needsExtraLocalData()) {
5598 TL.setWrittenTypeSpec(static_cast<DeclSpec::TST>(Record[Idx++]));
5599 TL.setWrittenSignSpec(static_cast<DeclSpec::TSS>(Record[Idx++]));
5600 TL.setWrittenWidthSpec(static_cast<DeclSpec::TSW>(Record[Idx++]));
5601 TL.setModeAttr(Record[Idx++]);
5602 }
5603}
5604void TypeLocReader::VisitComplexTypeLoc(ComplexTypeLoc TL) {
5605 TL.setNameLoc(ReadSourceLocation(Record, Idx));
5606}
5607void TypeLocReader::VisitPointerTypeLoc(PointerTypeLoc TL) {
5608 TL.setStarLoc(ReadSourceLocation(Record, Idx));
5609}
Reid Kleckner8a365022013-06-24 17:51:48 +00005610void TypeLocReader::VisitDecayedTypeLoc(DecayedTypeLoc TL) {
5611 // nothing to do
5612}
Reid Kleckner0503a872013-12-05 01:23:43 +00005613void TypeLocReader::VisitAdjustedTypeLoc(AdjustedTypeLoc TL) {
5614 // nothing to do
5615}
Guy Benyei11169dd2012-12-18 14:30:41 +00005616void TypeLocReader::VisitBlockPointerTypeLoc(BlockPointerTypeLoc TL) {
5617 TL.setCaretLoc(ReadSourceLocation(Record, Idx));
5618}
5619void TypeLocReader::VisitLValueReferenceTypeLoc(LValueReferenceTypeLoc TL) {
5620 TL.setAmpLoc(ReadSourceLocation(Record, Idx));
5621}
5622void TypeLocReader::VisitRValueReferenceTypeLoc(RValueReferenceTypeLoc TL) {
5623 TL.setAmpAmpLoc(ReadSourceLocation(Record, Idx));
5624}
5625void TypeLocReader::VisitMemberPointerTypeLoc(MemberPointerTypeLoc TL) {
5626 TL.setStarLoc(ReadSourceLocation(Record, Idx));
5627 TL.setClassTInfo(Reader.GetTypeSourceInfo(F, Record, Idx));
5628}
5629void TypeLocReader::VisitArrayTypeLoc(ArrayTypeLoc TL) {
5630 TL.setLBracketLoc(ReadSourceLocation(Record, Idx));
5631 TL.setRBracketLoc(ReadSourceLocation(Record, Idx));
5632 if (Record[Idx++])
5633 TL.setSizeExpr(Reader.ReadExpr(F));
5634 else
Craig Toppera13603a2014-05-22 05:54:18 +00005635 TL.setSizeExpr(nullptr);
Guy Benyei11169dd2012-12-18 14:30:41 +00005636}
5637void TypeLocReader::VisitConstantArrayTypeLoc(ConstantArrayTypeLoc TL) {
5638 VisitArrayTypeLoc(TL);
5639}
5640void TypeLocReader::VisitIncompleteArrayTypeLoc(IncompleteArrayTypeLoc TL) {
5641 VisitArrayTypeLoc(TL);
5642}
5643void TypeLocReader::VisitVariableArrayTypeLoc(VariableArrayTypeLoc TL) {
5644 VisitArrayTypeLoc(TL);
5645}
5646void TypeLocReader::VisitDependentSizedArrayTypeLoc(
5647 DependentSizedArrayTypeLoc TL) {
5648 VisitArrayTypeLoc(TL);
5649}
5650void TypeLocReader::VisitDependentSizedExtVectorTypeLoc(
5651 DependentSizedExtVectorTypeLoc TL) {
5652 TL.setNameLoc(ReadSourceLocation(Record, Idx));
5653}
5654void TypeLocReader::VisitVectorTypeLoc(VectorTypeLoc TL) {
5655 TL.setNameLoc(ReadSourceLocation(Record, Idx));
5656}
5657void TypeLocReader::VisitExtVectorTypeLoc(ExtVectorTypeLoc TL) {
5658 TL.setNameLoc(ReadSourceLocation(Record, Idx));
5659}
5660void TypeLocReader::VisitFunctionTypeLoc(FunctionTypeLoc TL) {
5661 TL.setLocalRangeBegin(ReadSourceLocation(Record, Idx));
5662 TL.setLParenLoc(ReadSourceLocation(Record, Idx));
5663 TL.setRParenLoc(ReadSourceLocation(Record, Idx));
5664 TL.setLocalRangeEnd(ReadSourceLocation(Record, Idx));
Alp Tokerb3fd5cf2014-01-21 00:32:38 +00005665 for (unsigned i = 0, e = TL.getNumParams(); i != e; ++i) {
5666 TL.setParam(i, ReadDeclAs<ParmVarDecl>(Record, Idx));
Guy Benyei11169dd2012-12-18 14:30:41 +00005667 }
5668}
5669void TypeLocReader::VisitFunctionProtoTypeLoc(FunctionProtoTypeLoc TL) {
5670 VisitFunctionTypeLoc(TL);
5671}
5672void TypeLocReader::VisitFunctionNoProtoTypeLoc(FunctionNoProtoTypeLoc TL) {
5673 VisitFunctionTypeLoc(TL);
5674}
5675void TypeLocReader::VisitUnresolvedUsingTypeLoc(UnresolvedUsingTypeLoc TL) {
5676 TL.setNameLoc(ReadSourceLocation(Record, Idx));
5677}
5678void TypeLocReader::VisitTypedefTypeLoc(TypedefTypeLoc TL) {
5679 TL.setNameLoc(ReadSourceLocation(Record, Idx));
5680}
5681void TypeLocReader::VisitTypeOfExprTypeLoc(TypeOfExprTypeLoc TL) {
5682 TL.setTypeofLoc(ReadSourceLocation(Record, Idx));
5683 TL.setLParenLoc(ReadSourceLocation(Record, Idx));
5684 TL.setRParenLoc(ReadSourceLocation(Record, Idx));
5685}
5686void TypeLocReader::VisitTypeOfTypeLoc(TypeOfTypeLoc TL) {
5687 TL.setTypeofLoc(ReadSourceLocation(Record, Idx));
5688 TL.setLParenLoc(ReadSourceLocation(Record, Idx));
5689 TL.setRParenLoc(ReadSourceLocation(Record, Idx));
5690 TL.setUnderlyingTInfo(Reader.GetTypeSourceInfo(F, Record, Idx));
5691}
5692void TypeLocReader::VisitDecltypeTypeLoc(DecltypeTypeLoc TL) {
5693 TL.setNameLoc(ReadSourceLocation(Record, Idx));
5694}
5695void TypeLocReader::VisitUnaryTransformTypeLoc(UnaryTransformTypeLoc TL) {
5696 TL.setKWLoc(ReadSourceLocation(Record, Idx));
5697 TL.setLParenLoc(ReadSourceLocation(Record, Idx));
5698 TL.setRParenLoc(ReadSourceLocation(Record, Idx));
5699 TL.setUnderlyingTInfo(Reader.GetTypeSourceInfo(F, Record, Idx));
5700}
5701void TypeLocReader::VisitAutoTypeLoc(AutoTypeLoc TL) {
5702 TL.setNameLoc(ReadSourceLocation(Record, Idx));
5703}
5704void TypeLocReader::VisitRecordTypeLoc(RecordTypeLoc TL) {
5705 TL.setNameLoc(ReadSourceLocation(Record, Idx));
5706}
5707void TypeLocReader::VisitEnumTypeLoc(EnumTypeLoc TL) {
5708 TL.setNameLoc(ReadSourceLocation(Record, Idx));
5709}
5710void TypeLocReader::VisitAttributedTypeLoc(AttributedTypeLoc TL) {
5711 TL.setAttrNameLoc(ReadSourceLocation(Record, Idx));
5712 if (TL.hasAttrOperand()) {
5713 SourceRange range;
5714 range.setBegin(ReadSourceLocation(Record, Idx));
5715 range.setEnd(ReadSourceLocation(Record, Idx));
5716 TL.setAttrOperandParensRange(range);
5717 }
5718 if (TL.hasAttrExprOperand()) {
5719 if (Record[Idx++])
5720 TL.setAttrExprOperand(Reader.ReadExpr(F));
5721 else
Craig Toppera13603a2014-05-22 05:54:18 +00005722 TL.setAttrExprOperand(nullptr);
Guy Benyei11169dd2012-12-18 14:30:41 +00005723 } else if (TL.hasAttrEnumOperand())
5724 TL.setAttrEnumOperandLoc(ReadSourceLocation(Record, Idx));
5725}
5726void TypeLocReader::VisitTemplateTypeParmTypeLoc(TemplateTypeParmTypeLoc TL) {
5727 TL.setNameLoc(ReadSourceLocation(Record, Idx));
5728}
5729void TypeLocReader::VisitSubstTemplateTypeParmTypeLoc(
5730 SubstTemplateTypeParmTypeLoc TL) {
5731 TL.setNameLoc(ReadSourceLocation(Record, Idx));
5732}
5733void TypeLocReader::VisitSubstTemplateTypeParmPackTypeLoc(
5734 SubstTemplateTypeParmPackTypeLoc TL) {
5735 TL.setNameLoc(ReadSourceLocation(Record, Idx));
5736}
5737void TypeLocReader::VisitTemplateSpecializationTypeLoc(
5738 TemplateSpecializationTypeLoc TL) {
5739 TL.setTemplateKeywordLoc(ReadSourceLocation(Record, Idx));
5740 TL.setTemplateNameLoc(ReadSourceLocation(Record, Idx));
5741 TL.setLAngleLoc(ReadSourceLocation(Record, Idx));
5742 TL.setRAngleLoc(ReadSourceLocation(Record, Idx));
5743 for (unsigned i = 0, e = TL.getNumArgs(); i != e; ++i)
5744 TL.setArgLocInfo(i,
5745 Reader.GetTemplateArgumentLocInfo(F,
5746 TL.getTypePtr()->getArg(i).getKind(),
5747 Record, Idx));
5748}
5749void TypeLocReader::VisitParenTypeLoc(ParenTypeLoc TL) {
5750 TL.setLParenLoc(ReadSourceLocation(Record, Idx));
5751 TL.setRParenLoc(ReadSourceLocation(Record, Idx));
5752}
5753void TypeLocReader::VisitElaboratedTypeLoc(ElaboratedTypeLoc TL) {
5754 TL.setElaboratedKeywordLoc(ReadSourceLocation(Record, Idx));
5755 TL.setQualifierLoc(Reader.ReadNestedNameSpecifierLoc(F, Record, Idx));
5756}
5757void TypeLocReader::VisitInjectedClassNameTypeLoc(InjectedClassNameTypeLoc TL) {
5758 TL.setNameLoc(ReadSourceLocation(Record, Idx));
5759}
5760void TypeLocReader::VisitDependentNameTypeLoc(DependentNameTypeLoc TL) {
5761 TL.setElaboratedKeywordLoc(ReadSourceLocation(Record, Idx));
5762 TL.setQualifierLoc(Reader.ReadNestedNameSpecifierLoc(F, Record, Idx));
5763 TL.setNameLoc(ReadSourceLocation(Record, Idx));
5764}
5765void TypeLocReader::VisitDependentTemplateSpecializationTypeLoc(
5766 DependentTemplateSpecializationTypeLoc TL) {
5767 TL.setElaboratedKeywordLoc(ReadSourceLocation(Record, Idx));
5768 TL.setQualifierLoc(Reader.ReadNestedNameSpecifierLoc(F, Record, Idx));
5769 TL.setTemplateKeywordLoc(ReadSourceLocation(Record, Idx));
5770 TL.setTemplateNameLoc(ReadSourceLocation(Record, Idx));
5771 TL.setLAngleLoc(ReadSourceLocation(Record, Idx));
5772 TL.setRAngleLoc(ReadSourceLocation(Record, Idx));
5773 for (unsigned I = 0, E = TL.getNumArgs(); I != E; ++I)
5774 TL.setArgLocInfo(I,
5775 Reader.GetTemplateArgumentLocInfo(F,
5776 TL.getTypePtr()->getArg(I).getKind(),
5777 Record, Idx));
5778}
5779void TypeLocReader::VisitPackExpansionTypeLoc(PackExpansionTypeLoc TL) {
5780 TL.setEllipsisLoc(ReadSourceLocation(Record, Idx));
5781}
5782void TypeLocReader::VisitObjCInterfaceTypeLoc(ObjCInterfaceTypeLoc TL) {
5783 TL.setNameLoc(ReadSourceLocation(Record, Idx));
5784}
5785void TypeLocReader::VisitObjCObjectTypeLoc(ObjCObjectTypeLoc TL) {
5786 TL.setHasBaseTypeAsWritten(Record[Idx++]);
5787 TL.setLAngleLoc(ReadSourceLocation(Record, Idx));
5788 TL.setRAngleLoc(ReadSourceLocation(Record, Idx));
5789 for (unsigned i = 0, e = TL.getNumProtocols(); i != e; ++i)
5790 TL.setProtocolLoc(i, ReadSourceLocation(Record, Idx));
5791}
5792void TypeLocReader::VisitObjCObjectPointerTypeLoc(ObjCObjectPointerTypeLoc TL) {
5793 TL.setStarLoc(ReadSourceLocation(Record, Idx));
5794}
5795void TypeLocReader::VisitAtomicTypeLoc(AtomicTypeLoc TL) {
5796 TL.setKWLoc(ReadSourceLocation(Record, Idx));
5797 TL.setLParenLoc(ReadSourceLocation(Record, Idx));
5798 TL.setRParenLoc(ReadSourceLocation(Record, Idx));
5799}
5800
5801TypeSourceInfo *ASTReader::GetTypeSourceInfo(ModuleFile &F,
5802 const RecordData &Record,
5803 unsigned &Idx) {
5804 QualType InfoTy = readType(F, Record, Idx);
5805 if (InfoTy.isNull())
Craig Toppera13603a2014-05-22 05:54:18 +00005806 return nullptr;
Guy Benyei11169dd2012-12-18 14:30:41 +00005807
5808 TypeSourceInfo *TInfo = getContext().CreateTypeSourceInfo(InfoTy);
5809 TypeLocReader TLR(*this, F, Record, Idx);
5810 for (TypeLoc TL = TInfo->getTypeLoc(); !TL.isNull(); TL = TL.getNextTypeLoc())
5811 TLR.Visit(TL);
5812 return TInfo;
5813}
5814
5815QualType ASTReader::GetType(TypeID ID) {
5816 unsigned FastQuals = ID & Qualifiers::FastMask;
5817 unsigned Index = ID >> Qualifiers::FastWidth;
5818
5819 if (Index < NUM_PREDEF_TYPE_IDS) {
5820 QualType T;
5821 switch ((PredefinedTypeIDs)Index) {
5822 case PREDEF_TYPE_NULL_ID: return QualType();
5823 case PREDEF_TYPE_VOID_ID: T = Context.VoidTy; break;
5824 case PREDEF_TYPE_BOOL_ID: T = Context.BoolTy; break;
5825
5826 case PREDEF_TYPE_CHAR_U_ID:
5827 case PREDEF_TYPE_CHAR_S_ID:
5828 // FIXME: Check that the signedness of CharTy is correct!
5829 T = Context.CharTy;
5830 break;
5831
5832 case PREDEF_TYPE_UCHAR_ID: T = Context.UnsignedCharTy; break;
5833 case PREDEF_TYPE_USHORT_ID: T = Context.UnsignedShortTy; break;
5834 case PREDEF_TYPE_UINT_ID: T = Context.UnsignedIntTy; break;
5835 case PREDEF_TYPE_ULONG_ID: T = Context.UnsignedLongTy; break;
5836 case PREDEF_TYPE_ULONGLONG_ID: T = Context.UnsignedLongLongTy; break;
5837 case PREDEF_TYPE_UINT128_ID: T = Context.UnsignedInt128Ty; break;
5838 case PREDEF_TYPE_SCHAR_ID: T = Context.SignedCharTy; break;
5839 case PREDEF_TYPE_WCHAR_ID: T = Context.WCharTy; break;
5840 case PREDEF_TYPE_SHORT_ID: T = Context.ShortTy; break;
5841 case PREDEF_TYPE_INT_ID: T = Context.IntTy; break;
5842 case PREDEF_TYPE_LONG_ID: T = Context.LongTy; break;
5843 case PREDEF_TYPE_LONGLONG_ID: T = Context.LongLongTy; break;
5844 case PREDEF_TYPE_INT128_ID: T = Context.Int128Ty; break;
5845 case PREDEF_TYPE_HALF_ID: T = Context.HalfTy; break;
5846 case PREDEF_TYPE_FLOAT_ID: T = Context.FloatTy; break;
5847 case PREDEF_TYPE_DOUBLE_ID: T = Context.DoubleTy; break;
5848 case PREDEF_TYPE_LONGDOUBLE_ID: T = Context.LongDoubleTy; break;
5849 case PREDEF_TYPE_OVERLOAD_ID: T = Context.OverloadTy; break;
5850 case PREDEF_TYPE_BOUND_MEMBER: T = Context.BoundMemberTy; break;
5851 case PREDEF_TYPE_PSEUDO_OBJECT: T = Context.PseudoObjectTy; break;
5852 case PREDEF_TYPE_DEPENDENT_ID: T = Context.DependentTy; break;
5853 case PREDEF_TYPE_UNKNOWN_ANY: T = Context.UnknownAnyTy; break;
5854 case PREDEF_TYPE_NULLPTR_ID: T = Context.NullPtrTy; break;
5855 case PREDEF_TYPE_CHAR16_ID: T = Context.Char16Ty; break;
5856 case PREDEF_TYPE_CHAR32_ID: T = Context.Char32Ty; break;
5857 case PREDEF_TYPE_OBJC_ID: T = Context.ObjCBuiltinIdTy; break;
5858 case PREDEF_TYPE_OBJC_CLASS: T = Context.ObjCBuiltinClassTy; break;
5859 case PREDEF_TYPE_OBJC_SEL: T = Context.ObjCBuiltinSelTy; break;
Guy Benyeid8a08ea2012-12-18 14:38:23 +00005860 case PREDEF_TYPE_IMAGE1D_ID: T = Context.OCLImage1dTy; break;
5861 case PREDEF_TYPE_IMAGE1D_ARR_ID: T = Context.OCLImage1dArrayTy; break;
5862 case PREDEF_TYPE_IMAGE1D_BUFF_ID: T = Context.OCLImage1dBufferTy; break;
5863 case PREDEF_TYPE_IMAGE2D_ID: T = Context.OCLImage2dTy; break;
5864 case PREDEF_TYPE_IMAGE2D_ARR_ID: T = Context.OCLImage2dArrayTy; break;
5865 case PREDEF_TYPE_IMAGE3D_ID: T = Context.OCLImage3dTy; break;
Guy Benyei61054192013-02-07 10:55:47 +00005866 case PREDEF_TYPE_SAMPLER_ID: T = Context.OCLSamplerTy; break;
Guy Benyei1b4fb3e2013-01-20 12:31:11 +00005867 case PREDEF_TYPE_EVENT_ID: T = Context.OCLEventTy; break;
Guy Benyei11169dd2012-12-18 14:30:41 +00005868 case PREDEF_TYPE_AUTO_DEDUCT: T = Context.getAutoDeductType(); break;
5869
5870 case PREDEF_TYPE_AUTO_RREF_DEDUCT:
5871 T = Context.getAutoRRefDeductType();
5872 break;
5873
5874 case PREDEF_TYPE_ARC_UNBRIDGED_CAST:
5875 T = Context.ARCUnbridgedCastTy;
5876 break;
5877
5878 case PREDEF_TYPE_VA_LIST_TAG:
5879 T = Context.getVaListTagType();
5880 break;
5881
5882 case PREDEF_TYPE_BUILTIN_FN:
5883 T = Context.BuiltinFnTy;
5884 break;
5885 }
5886
5887 assert(!T.isNull() && "Unknown predefined type");
5888 return T.withFastQualifiers(FastQuals);
5889 }
5890
5891 Index -= NUM_PREDEF_TYPE_IDS;
5892 assert(Index < TypesLoaded.size() && "Type index out-of-range");
5893 if (TypesLoaded[Index].isNull()) {
5894 TypesLoaded[Index] = readTypeRecord(Index);
5895 if (TypesLoaded[Index].isNull())
5896 return QualType();
5897
5898 TypesLoaded[Index]->setFromAST();
5899 if (DeserializationListener)
5900 DeserializationListener->TypeRead(TypeIdx::fromTypeID(ID),
5901 TypesLoaded[Index]);
5902 }
5903
5904 return TypesLoaded[Index].withFastQualifiers(FastQuals);
5905}
5906
5907QualType ASTReader::getLocalType(ModuleFile &F, unsigned LocalID) {
5908 return GetType(getGlobalTypeID(F, LocalID));
5909}
5910
5911serialization::TypeID
5912ASTReader::getGlobalTypeID(ModuleFile &F, unsigned LocalID) const {
5913 unsigned FastQuals = LocalID & Qualifiers::FastMask;
5914 unsigned LocalIndex = LocalID >> Qualifiers::FastWidth;
5915
5916 if (LocalIndex < NUM_PREDEF_TYPE_IDS)
5917 return LocalID;
5918
5919 ContinuousRangeMap<uint32_t, int, 2>::iterator I
5920 = F.TypeRemap.find(LocalIndex - NUM_PREDEF_TYPE_IDS);
5921 assert(I != F.TypeRemap.end() && "Invalid index into type index remap");
5922
5923 unsigned GlobalIndex = LocalIndex + I->second;
5924 return (GlobalIndex << Qualifiers::FastWidth) | FastQuals;
5925}
5926
5927TemplateArgumentLocInfo
5928ASTReader::GetTemplateArgumentLocInfo(ModuleFile &F,
5929 TemplateArgument::ArgKind Kind,
5930 const RecordData &Record,
5931 unsigned &Index) {
5932 switch (Kind) {
5933 case TemplateArgument::Expression:
5934 return ReadExpr(F);
5935 case TemplateArgument::Type:
5936 return GetTypeSourceInfo(F, Record, Index);
5937 case TemplateArgument::Template: {
5938 NestedNameSpecifierLoc QualifierLoc = ReadNestedNameSpecifierLoc(F, Record,
5939 Index);
5940 SourceLocation TemplateNameLoc = ReadSourceLocation(F, Record, Index);
5941 return TemplateArgumentLocInfo(QualifierLoc, TemplateNameLoc,
5942 SourceLocation());
5943 }
5944 case TemplateArgument::TemplateExpansion: {
5945 NestedNameSpecifierLoc QualifierLoc = ReadNestedNameSpecifierLoc(F, Record,
5946 Index);
5947 SourceLocation TemplateNameLoc = ReadSourceLocation(F, Record, Index);
5948 SourceLocation EllipsisLoc = ReadSourceLocation(F, Record, Index);
5949 return TemplateArgumentLocInfo(QualifierLoc, TemplateNameLoc,
5950 EllipsisLoc);
5951 }
5952 case TemplateArgument::Null:
5953 case TemplateArgument::Integral:
5954 case TemplateArgument::Declaration:
5955 case TemplateArgument::NullPtr:
5956 case TemplateArgument::Pack:
5957 // FIXME: Is this right?
5958 return TemplateArgumentLocInfo();
5959 }
5960 llvm_unreachable("unexpected template argument loc");
5961}
5962
5963TemplateArgumentLoc
5964ASTReader::ReadTemplateArgumentLoc(ModuleFile &F,
5965 const RecordData &Record, unsigned &Index) {
5966 TemplateArgument Arg = ReadTemplateArgument(F, Record, Index);
5967
5968 if (Arg.getKind() == TemplateArgument::Expression) {
5969 if (Record[Index++]) // bool InfoHasSameExpr.
5970 return TemplateArgumentLoc(Arg, TemplateArgumentLocInfo(Arg.getAsExpr()));
5971 }
5972 return TemplateArgumentLoc(Arg, GetTemplateArgumentLocInfo(F, Arg.getKind(),
5973 Record, Index));
5974}
5975
Enea Zaffanella6dbe1872013-08-10 07:24:53 +00005976const ASTTemplateArgumentListInfo*
5977ASTReader::ReadASTTemplateArgumentListInfo(ModuleFile &F,
5978 const RecordData &Record,
5979 unsigned &Index) {
5980 SourceLocation LAngleLoc = ReadSourceLocation(F, Record, Index);
5981 SourceLocation RAngleLoc = ReadSourceLocation(F, Record, Index);
5982 unsigned NumArgsAsWritten = Record[Index++];
5983 TemplateArgumentListInfo TemplArgsInfo(LAngleLoc, RAngleLoc);
5984 for (unsigned i = 0; i != NumArgsAsWritten; ++i)
5985 TemplArgsInfo.addArgument(ReadTemplateArgumentLoc(F, Record, Index));
5986 return ASTTemplateArgumentListInfo::Create(getContext(), TemplArgsInfo);
5987}
5988
Guy Benyei11169dd2012-12-18 14:30:41 +00005989Decl *ASTReader::GetExternalDecl(uint32_t ID) {
5990 return GetDecl(ID);
5991}
5992
Richard Smith053f6c62014-05-16 23:01:30 +00005993void ASTReader::CompleteRedeclChain(const Decl *D) {
Richard Smith851072e2014-05-19 20:59:20 +00005994 if (NumCurrentElementsDeserializing) {
5995 // We arrange to not care about the complete redeclaration chain while we're
5996 // deserializing. Just remember that the AST has marked this one as complete
5997 // but that it's not actually complete yet, so we know we still need to
5998 // complete it later.
5999 PendingIncompleteDeclChains.push_back(const_cast<Decl*>(D));
6000 return;
6001 }
6002
Richard Smith053f6c62014-05-16 23:01:30 +00006003 const DeclContext *DC = D->getDeclContext()->getRedeclContext();
6004
6005 // Recursively ensure that the decl context itself is complete
6006 // (in particular, this matters if the decl context is a namespace).
6007 //
6008 // FIXME: This should be performed by lookup instead of here.
6009 cast<Decl>(DC)->getMostRecentDecl();
6010
6011 // If this is a named declaration, complete it by looking it up
6012 // within its context.
6013 //
6014 // FIXME: We don't currently handle the cases where we can't do this;
6015 // merging a class definition that contains unnamed entities should merge
6016 // those entities. Likewise, merging a function definition should merge
6017 // all mergeable entities within it.
6018 if (isa<TranslationUnitDecl>(DC) || isa<NamespaceDecl>(DC) ||
6019 isa<CXXRecordDecl>(DC) || isa<EnumDecl>(DC)) {
6020 if (DeclarationName Name = cast<NamedDecl>(D)->getDeclName()) {
6021 auto *II = Name.getAsIdentifierInfo();
6022 if (isa<TranslationUnitDecl>(DC) && II) {
6023 // Outside of C++, we don't have a lookup table for the TU, so update
6024 // the identifier instead. In C++, either way should work fine.
6025 if (II->isOutOfDate())
6026 updateOutOfDateIdentifier(*II);
6027 } else
6028 DC->lookup(Name);
6029 }
6030 }
6031}
6032
Richard Smithcd45dbc2014-04-19 03:48:30 +00006033uint64_t ASTReader::readCXXBaseSpecifiers(ModuleFile &M,
6034 const RecordData &Record,
6035 unsigned &Idx) {
6036 if (Idx >= Record.size() || Record[Idx] > M.LocalNumCXXBaseSpecifiers) {
6037 Error("malformed AST file: missing C++ base specifier");
Guy Benyei11169dd2012-12-18 14:30:41 +00006038 return 0;
Richard Smithcd45dbc2014-04-19 03:48:30 +00006039 }
6040
Guy Benyei11169dd2012-12-18 14:30:41 +00006041 unsigned LocalID = Record[Idx++];
6042 return getGlobalBitOffset(M, M.CXXBaseSpecifiersOffsets[LocalID - 1]);
6043}
6044
6045CXXBaseSpecifier *ASTReader::GetExternalCXXBaseSpecifiers(uint64_t Offset) {
6046 RecordLocation Loc = getLocalBitOffset(Offset);
Chris Lattner7fb3bef2013-01-20 00:56:42 +00006047 BitstreamCursor &Cursor = Loc.F->DeclsCursor;
Guy Benyei11169dd2012-12-18 14:30:41 +00006048 SavedStreamPosition SavedPosition(Cursor);
6049 Cursor.JumpToBit(Loc.Offset);
6050 ReadingKindTracker ReadingKind(Read_Decl, *this);
6051 RecordData Record;
6052 unsigned Code = Cursor.ReadCode();
Chris Lattner0e6c9402013-01-20 02:38:54 +00006053 unsigned RecCode = Cursor.readRecord(Code, Record);
Guy Benyei11169dd2012-12-18 14:30:41 +00006054 if (RecCode != DECL_CXX_BASE_SPECIFIERS) {
Richard Smithcd45dbc2014-04-19 03:48:30 +00006055 Error("malformed AST file: missing C++ base specifiers");
Craig Toppera13603a2014-05-22 05:54:18 +00006056 return nullptr;
Guy Benyei11169dd2012-12-18 14:30:41 +00006057 }
6058
6059 unsigned Idx = 0;
6060 unsigned NumBases = Record[Idx++];
6061 void *Mem = Context.Allocate(sizeof(CXXBaseSpecifier) * NumBases);
6062 CXXBaseSpecifier *Bases = new (Mem) CXXBaseSpecifier [NumBases];
6063 for (unsigned I = 0; I != NumBases; ++I)
6064 Bases[I] = ReadCXXBaseSpecifier(*Loc.F, Record, Idx);
6065 return Bases;
6066}
6067
6068serialization::DeclID
6069ASTReader::getGlobalDeclID(ModuleFile &F, LocalDeclID LocalID) const {
6070 if (LocalID < NUM_PREDEF_DECL_IDS)
6071 return LocalID;
6072
6073 ContinuousRangeMap<uint32_t, int, 2>::iterator I
6074 = F.DeclRemap.find(LocalID - NUM_PREDEF_DECL_IDS);
6075 assert(I != F.DeclRemap.end() && "Invalid index into decl index remap");
6076
6077 return LocalID + I->second;
6078}
6079
6080bool ASTReader::isDeclIDFromModule(serialization::GlobalDeclID ID,
6081 ModuleFile &M) const {
6082 GlobalDeclMapType::const_iterator I = GlobalDeclMap.find(ID);
6083 assert(I != GlobalDeclMap.end() && "Corrupted global declaration map");
6084 return &M == I->second;
6085}
6086
Douglas Gregor9f782892013-01-21 15:25:38 +00006087ModuleFile *ASTReader::getOwningModuleFile(const Decl *D) {
Guy Benyei11169dd2012-12-18 14:30:41 +00006088 if (!D->isFromASTFile())
Craig Toppera13603a2014-05-22 05:54:18 +00006089 return nullptr;
Guy Benyei11169dd2012-12-18 14:30:41 +00006090 GlobalDeclMapType::const_iterator I = GlobalDeclMap.find(D->getGlobalID());
6091 assert(I != GlobalDeclMap.end() && "Corrupted global declaration map");
6092 return I->second;
6093}
6094
6095SourceLocation ASTReader::getSourceLocationForDeclID(GlobalDeclID ID) {
6096 if (ID < NUM_PREDEF_DECL_IDS)
6097 return SourceLocation();
Richard Smithcd45dbc2014-04-19 03:48:30 +00006098
Guy Benyei11169dd2012-12-18 14:30:41 +00006099 unsigned Index = ID - NUM_PREDEF_DECL_IDS;
6100
6101 if (Index > DeclsLoaded.size()) {
6102 Error("declaration ID out-of-range for AST file");
6103 return SourceLocation();
6104 }
Richard Smithcd45dbc2014-04-19 03:48:30 +00006105
Guy Benyei11169dd2012-12-18 14:30:41 +00006106 if (Decl *D = DeclsLoaded[Index])
6107 return D->getLocation();
6108
6109 unsigned RawLocation = 0;
6110 RecordLocation Rec = DeclCursorForID(ID, RawLocation);
6111 return ReadSourceLocation(*Rec.F, RawLocation);
6112}
6113
Richard Smithcd45dbc2014-04-19 03:48:30 +00006114Decl *ASTReader::GetExistingDecl(DeclID ID) {
6115 if (ID < NUM_PREDEF_DECL_IDS) {
Guy Benyei11169dd2012-12-18 14:30:41 +00006116 switch ((PredefinedDeclIDs)ID) {
6117 case PREDEF_DECL_NULL_ID:
Craig Toppera13603a2014-05-22 05:54:18 +00006118 return nullptr;
Richard Smithcd45dbc2014-04-19 03:48:30 +00006119
Guy Benyei11169dd2012-12-18 14:30:41 +00006120 case PREDEF_DECL_TRANSLATION_UNIT_ID:
6121 return Context.getTranslationUnitDecl();
Richard Smithcd45dbc2014-04-19 03:48:30 +00006122
Guy Benyei11169dd2012-12-18 14:30:41 +00006123 case PREDEF_DECL_OBJC_ID_ID:
6124 return Context.getObjCIdDecl();
6125
6126 case PREDEF_DECL_OBJC_SEL_ID:
6127 return Context.getObjCSelDecl();
6128
6129 case PREDEF_DECL_OBJC_CLASS_ID:
6130 return Context.getObjCClassDecl();
Richard Smithcd45dbc2014-04-19 03:48:30 +00006131
Guy Benyei11169dd2012-12-18 14:30:41 +00006132 case PREDEF_DECL_OBJC_PROTOCOL_ID:
6133 return Context.getObjCProtocolDecl();
Richard Smithcd45dbc2014-04-19 03:48:30 +00006134
Guy Benyei11169dd2012-12-18 14:30:41 +00006135 case PREDEF_DECL_INT_128_ID:
6136 return Context.getInt128Decl();
6137
6138 case PREDEF_DECL_UNSIGNED_INT_128_ID:
6139 return Context.getUInt128Decl();
Richard Smithcd45dbc2014-04-19 03:48:30 +00006140
Guy Benyei11169dd2012-12-18 14:30:41 +00006141 case PREDEF_DECL_OBJC_INSTANCETYPE_ID:
6142 return Context.getObjCInstanceTypeDecl();
6143
6144 case PREDEF_DECL_BUILTIN_VA_LIST_ID:
6145 return Context.getBuiltinVaListDecl();
6146 }
6147 }
Richard Smithcd45dbc2014-04-19 03:48:30 +00006148
Guy Benyei11169dd2012-12-18 14:30:41 +00006149 unsigned Index = ID - NUM_PREDEF_DECL_IDS;
6150
6151 if (Index >= DeclsLoaded.size()) {
6152 assert(0 && "declaration ID out-of-range for AST file");
6153 Error("declaration ID out-of-range for AST file");
Craig Toppera13603a2014-05-22 05:54:18 +00006154 return nullptr;
Guy Benyei11169dd2012-12-18 14:30:41 +00006155 }
Richard Smithcd45dbc2014-04-19 03:48:30 +00006156
6157 return DeclsLoaded[Index];
6158}
6159
6160Decl *ASTReader::GetDecl(DeclID ID) {
6161 if (ID < NUM_PREDEF_DECL_IDS)
6162 return GetExistingDecl(ID);
6163
6164 unsigned Index = ID - NUM_PREDEF_DECL_IDS;
6165
6166 if (Index >= DeclsLoaded.size()) {
6167 assert(0 && "declaration ID out-of-range for AST file");
6168 Error("declaration ID out-of-range for AST file");
Craig Toppera13603a2014-05-22 05:54:18 +00006169 return nullptr;
Richard Smithcd45dbc2014-04-19 03:48:30 +00006170 }
6171
Guy Benyei11169dd2012-12-18 14:30:41 +00006172 if (!DeclsLoaded[Index]) {
6173 ReadDeclRecord(ID);
6174 if (DeserializationListener)
6175 DeserializationListener->DeclRead(ID, DeclsLoaded[Index]);
6176 }
6177
6178 return DeclsLoaded[Index];
6179}
6180
6181DeclID ASTReader::mapGlobalIDToModuleFileGlobalID(ModuleFile &M,
6182 DeclID GlobalID) {
6183 if (GlobalID < NUM_PREDEF_DECL_IDS)
6184 return GlobalID;
6185
6186 GlobalDeclMapType::const_iterator I = GlobalDeclMap.find(GlobalID);
6187 assert(I != GlobalDeclMap.end() && "Corrupted global declaration map");
6188 ModuleFile *Owner = I->second;
6189
6190 llvm::DenseMap<ModuleFile *, serialization::DeclID>::iterator Pos
6191 = M.GlobalToLocalDeclIDs.find(Owner);
6192 if (Pos == M.GlobalToLocalDeclIDs.end())
6193 return 0;
6194
6195 return GlobalID - Owner->BaseDeclID + Pos->second;
6196}
6197
6198serialization::DeclID ASTReader::ReadDeclID(ModuleFile &F,
6199 const RecordData &Record,
6200 unsigned &Idx) {
6201 if (Idx >= Record.size()) {
6202 Error("Corrupted AST file");
6203 return 0;
6204 }
6205
6206 return getGlobalDeclID(F, Record[Idx++]);
6207}
6208
6209/// \brief Resolve the offset of a statement into a statement.
6210///
6211/// This operation will read a new statement from the external
6212/// source each time it is called, and is meant to be used via a
6213/// LazyOffsetPtr (which is used by Decls for the body of functions, etc).
6214Stmt *ASTReader::GetExternalDeclStmt(uint64_t Offset) {
6215 // Switch case IDs are per Decl.
6216 ClearSwitchCaseIDs();
6217
6218 // Offset here is a global offset across the entire chain.
6219 RecordLocation Loc = getLocalBitOffset(Offset);
6220 Loc.F->DeclsCursor.JumpToBit(Loc.Offset);
6221 return ReadStmtFromStream(*Loc.F);
6222}
6223
6224namespace {
6225 class FindExternalLexicalDeclsVisitor {
6226 ASTReader &Reader;
6227 const DeclContext *DC;
6228 bool (*isKindWeWant)(Decl::Kind);
6229
6230 SmallVectorImpl<Decl*> &Decls;
6231 bool PredefsVisited[NUM_PREDEF_DECL_IDS];
6232
6233 public:
6234 FindExternalLexicalDeclsVisitor(ASTReader &Reader, const DeclContext *DC,
6235 bool (*isKindWeWant)(Decl::Kind),
6236 SmallVectorImpl<Decl*> &Decls)
6237 : Reader(Reader), DC(DC), isKindWeWant(isKindWeWant), Decls(Decls)
6238 {
6239 for (unsigned I = 0; I != NUM_PREDEF_DECL_IDS; ++I)
6240 PredefsVisited[I] = false;
6241 }
6242
6243 static bool visit(ModuleFile &M, bool Preorder, void *UserData) {
6244 if (Preorder)
6245 return false;
6246
6247 FindExternalLexicalDeclsVisitor *This
6248 = static_cast<FindExternalLexicalDeclsVisitor *>(UserData);
6249
6250 ModuleFile::DeclContextInfosMap::iterator Info
6251 = M.DeclContextInfos.find(This->DC);
6252 if (Info == M.DeclContextInfos.end() || !Info->second.LexicalDecls)
6253 return false;
6254
6255 // Load all of the declaration IDs
6256 for (const KindDeclIDPair *ID = Info->second.LexicalDecls,
6257 *IDE = ID + Info->second.NumLexicalDecls;
6258 ID != IDE; ++ID) {
6259 if (This->isKindWeWant && !This->isKindWeWant((Decl::Kind)ID->first))
6260 continue;
6261
6262 // Don't add predefined declarations to the lexical context more
6263 // than once.
6264 if (ID->second < NUM_PREDEF_DECL_IDS) {
6265 if (This->PredefsVisited[ID->second])
6266 continue;
6267
6268 This->PredefsVisited[ID->second] = true;
6269 }
6270
6271 if (Decl *D = This->Reader.GetLocalDecl(M, ID->second)) {
6272 if (!This->DC->isDeclInLexicalTraversal(D))
6273 This->Decls.push_back(D);
6274 }
6275 }
6276
6277 return false;
6278 }
6279 };
6280}
6281
6282ExternalLoadResult ASTReader::FindExternalLexicalDecls(const DeclContext *DC,
6283 bool (*isKindWeWant)(Decl::Kind),
6284 SmallVectorImpl<Decl*> &Decls) {
6285 // There might be lexical decls in multiple modules, for the TU at
6286 // least. Walk all of the modules in the order they were loaded.
6287 FindExternalLexicalDeclsVisitor Visitor(*this, DC, isKindWeWant, Decls);
6288 ModuleMgr.visitDepthFirst(&FindExternalLexicalDeclsVisitor::visit, &Visitor);
6289 ++NumLexicalDeclContextsRead;
6290 return ELR_Success;
6291}
6292
6293namespace {
6294
6295class DeclIDComp {
6296 ASTReader &Reader;
6297 ModuleFile &Mod;
6298
6299public:
6300 DeclIDComp(ASTReader &Reader, ModuleFile &M) : Reader(Reader), Mod(M) {}
6301
6302 bool operator()(LocalDeclID L, LocalDeclID R) const {
6303 SourceLocation LHS = getLocation(L);
6304 SourceLocation RHS = getLocation(R);
6305 return Reader.getSourceManager().isBeforeInTranslationUnit(LHS, RHS);
6306 }
6307
6308 bool operator()(SourceLocation LHS, LocalDeclID R) const {
6309 SourceLocation RHS = getLocation(R);
6310 return Reader.getSourceManager().isBeforeInTranslationUnit(LHS, RHS);
6311 }
6312
6313 bool operator()(LocalDeclID L, SourceLocation RHS) const {
6314 SourceLocation LHS = getLocation(L);
6315 return Reader.getSourceManager().isBeforeInTranslationUnit(LHS, RHS);
6316 }
6317
6318 SourceLocation getLocation(LocalDeclID ID) const {
6319 return Reader.getSourceManager().getFileLoc(
6320 Reader.getSourceLocationForDeclID(Reader.getGlobalDeclID(Mod, ID)));
6321 }
6322};
6323
6324}
6325
6326void ASTReader::FindFileRegionDecls(FileID File,
6327 unsigned Offset, unsigned Length,
6328 SmallVectorImpl<Decl *> &Decls) {
6329 SourceManager &SM = getSourceManager();
6330
6331 llvm::DenseMap<FileID, FileDeclsInfo>::iterator I = FileDeclIDs.find(File);
6332 if (I == FileDeclIDs.end())
6333 return;
6334
6335 FileDeclsInfo &DInfo = I->second;
6336 if (DInfo.Decls.empty())
6337 return;
6338
6339 SourceLocation
6340 BeginLoc = SM.getLocForStartOfFile(File).getLocWithOffset(Offset);
6341 SourceLocation EndLoc = BeginLoc.getLocWithOffset(Length);
6342
6343 DeclIDComp DIDComp(*this, *DInfo.Mod);
6344 ArrayRef<serialization::LocalDeclID>::iterator
6345 BeginIt = std::lower_bound(DInfo.Decls.begin(), DInfo.Decls.end(),
6346 BeginLoc, DIDComp);
6347 if (BeginIt != DInfo.Decls.begin())
6348 --BeginIt;
6349
6350 // If we are pointing at a top-level decl inside an objc container, we need
6351 // to backtrack until we find it otherwise we will fail to report that the
6352 // region overlaps with an objc container.
6353 while (BeginIt != DInfo.Decls.begin() &&
6354 GetDecl(getGlobalDeclID(*DInfo.Mod, *BeginIt))
6355 ->isTopLevelDeclInObjCContainer())
6356 --BeginIt;
6357
6358 ArrayRef<serialization::LocalDeclID>::iterator
6359 EndIt = std::upper_bound(DInfo.Decls.begin(), DInfo.Decls.end(),
6360 EndLoc, DIDComp);
6361 if (EndIt != DInfo.Decls.end())
6362 ++EndIt;
6363
6364 for (ArrayRef<serialization::LocalDeclID>::iterator
6365 DIt = BeginIt; DIt != EndIt; ++DIt)
6366 Decls.push_back(GetDecl(getGlobalDeclID(*DInfo.Mod, *DIt)));
6367}
6368
6369namespace {
6370 /// \brief ModuleFile visitor used to perform name lookup into a
6371 /// declaration context.
6372 class DeclContextNameLookupVisitor {
6373 ASTReader &Reader;
Dmitri Gribenkof8579502013-01-12 19:30:44 +00006374 SmallVectorImpl<const DeclContext *> &Contexts;
Guy Benyei11169dd2012-12-18 14:30:41 +00006375 DeclarationName Name;
6376 SmallVectorImpl<NamedDecl *> &Decls;
6377
6378 public:
6379 DeclContextNameLookupVisitor(ASTReader &Reader,
6380 SmallVectorImpl<const DeclContext *> &Contexts,
6381 DeclarationName Name,
6382 SmallVectorImpl<NamedDecl *> &Decls)
6383 : Reader(Reader), Contexts(Contexts), Name(Name), Decls(Decls) { }
6384
6385 static bool visit(ModuleFile &M, void *UserData) {
6386 DeclContextNameLookupVisitor *This
6387 = static_cast<DeclContextNameLookupVisitor *>(UserData);
6388
6389 // Check whether we have any visible declaration information for
6390 // this context in this module.
6391 ModuleFile::DeclContextInfosMap::iterator Info;
6392 bool FoundInfo = false;
6393 for (unsigned I = 0, N = This->Contexts.size(); I != N; ++I) {
6394 Info = M.DeclContextInfos.find(This->Contexts[I]);
6395 if (Info != M.DeclContextInfos.end() &&
6396 Info->second.NameLookupTableData) {
6397 FoundInfo = true;
6398 break;
6399 }
6400 }
6401
6402 if (!FoundInfo)
6403 return false;
6404
6405 // Look for this name within this module.
Richard Smith52e3fba2014-03-11 07:17:35 +00006406 ASTDeclContextNameLookupTable *LookupTable =
Guy Benyei11169dd2012-12-18 14:30:41 +00006407 Info->second.NameLookupTableData;
6408 ASTDeclContextNameLookupTable::iterator Pos
6409 = LookupTable->find(This->Name);
6410 if (Pos == LookupTable->end())
6411 return false;
6412
6413 bool FoundAnything = false;
6414 ASTDeclContextNameLookupTrait::data_type Data = *Pos;
6415 for (; Data.first != Data.second; ++Data.first) {
6416 NamedDecl *ND = This->Reader.GetLocalDeclAs<NamedDecl>(M, *Data.first);
6417 if (!ND)
6418 continue;
6419
6420 if (ND->getDeclName() != This->Name) {
6421 // A name might be null because the decl's redeclarable part is
6422 // currently read before reading its name. The lookup is triggered by
6423 // building that decl (likely indirectly), and so it is later in the
6424 // sense of "already existing" and can be ignored here.
6425 continue;
6426 }
6427
6428 // Record this declaration.
6429 FoundAnything = true;
6430 This->Decls.push_back(ND);
6431 }
6432
6433 return FoundAnything;
6434 }
6435 };
6436}
6437
Douglas Gregor9f782892013-01-21 15:25:38 +00006438/// \brief Retrieve the "definitive" module file for the definition of the
6439/// given declaration context, if there is one.
6440///
6441/// The "definitive" module file is the only place where we need to look to
6442/// find information about the declarations within the given declaration
6443/// context. For example, C++ and Objective-C classes, C structs/unions, and
6444/// Objective-C protocols, categories, and extensions are all defined in a
6445/// single place in the source code, so they have definitive module files
6446/// associated with them. C++ namespaces, on the other hand, can have
6447/// definitions in multiple different module files.
6448///
6449/// Note: this needs to be kept in sync with ASTWriter::AddedVisibleDecl's
6450/// NDEBUG checking.
6451static ModuleFile *getDefinitiveModuleFileFor(const DeclContext *DC,
6452 ASTReader &Reader) {
Douglas Gregor7a6e2002013-01-22 17:08:30 +00006453 if (const DeclContext *DefDC = getDefinitiveDeclContext(DC))
6454 return Reader.getOwningModuleFile(cast<Decl>(DefDC));
Douglas Gregor9f782892013-01-21 15:25:38 +00006455
Craig Toppera13603a2014-05-22 05:54:18 +00006456 return nullptr;
Douglas Gregor9f782892013-01-21 15:25:38 +00006457}
6458
Richard Smith9ce12e32013-02-07 03:30:24 +00006459bool
Guy Benyei11169dd2012-12-18 14:30:41 +00006460ASTReader::FindExternalVisibleDeclsByName(const DeclContext *DC,
6461 DeclarationName Name) {
6462 assert(DC->hasExternalVisibleStorage() &&
6463 "DeclContext has no visible decls in storage");
6464 if (!Name)
Richard Smith9ce12e32013-02-07 03:30:24 +00006465 return false;
Guy Benyei11169dd2012-12-18 14:30:41 +00006466
6467 SmallVector<NamedDecl *, 64> Decls;
6468
6469 // Compute the declaration contexts we need to look into. Multiple such
6470 // declaration contexts occur when two declaration contexts from disjoint
6471 // modules get merged, e.g., when two namespaces with the same name are
6472 // independently defined in separate modules.
6473 SmallVector<const DeclContext *, 2> Contexts;
6474 Contexts.push_back(DC);
6475
6476 if (DC->isNamespace()) {
Richard Smithcd45dbc2014-04-19 03:48:30 +00006477 auto Merged = MergedDecls.find(const_cast<Decl *>(cast<Decl>(DC)));
Guy Benyei11169dd2012-12-18 14:30:41 +00006478 if (Merged != MergedDecls.end()) {
6479 for (unsigned I = 0, N = Merged->second.size(); I != N; ++I)
6480 Contexts.push_back(cast<DeclContext>(GetDecl(Merged->second[I])));
6481 }
6482 }
Richard Smithcd45dbc2014-04-19 03:48:30 +00006483 if (isa<CXXRecordDecl>(DC)) {
6484 auto Merged = MergedLookups.find(DC);
6485 if (Merged != MergedLookups.end())
6486 Contexts.insert(Contexts.end(), Merged->second.begin(),
6487 Merged->second.end());
6488 }
6489
Guy Benyei11169dd2012-12-18 14:30:41 +00006490 DeclContextNameLookupVisitor Visitor(*this, Contexts, Name, Decls);
Douglas Gregor9f782892013-01-21 15:25:38 +00006491
6492 // If we can definitively determine which module file to look into,
6493 // only look there. Otherwise, look in all module files.
6494 ModuleFile *Definitive;
6495 if (Contexts.size() == 1 &&
6496 (Definitive = getDefinitiveModuleFileFor(DC, *this))) {
6497 DeclContextNameLookupVisitor::visit(*Definitive, &Visitor);
6498 } else {
6499 ModuleMgr.visit(&DeclContextNameLookupVisitor::visit, &Visitor);
6500 }
Guy Benyei11169dd2012-12-18 14:30:41 +00006501 ++NumVisibleDeclContextsRead;
6502 SetExternalVisibleDeclsForName(DC, Name, Decls);
Richard Smith9ce12e32013-02-07 03:30:24 +00006503 return !Decls.empty();
Guy Benyei11169dd2012-12-18 14:30:41 +00006504}
6505
6506namespace {
6507 /// \brief ModuleFile visitor used to retrieve all visible names in a
6508 /// declaration context.
6509 class DeclContextAllNamesVisitor {
6510 ASTReader &Reader;
Dmitri Gribenkof8579502013-01-12 19:30:44 +00006511 SmallVectorImpl<const DeclContext *> &Contexts;
Craig Topper3598eb72013-07-05 04:43:31 +00006512 DeclsMap &Decls;
Argyrios Kyrtzidis2810e9d2012-12-19 22:21:18 +00006513 bool VisitAll;
Guy Benyei11169dd2012-12-18 14:30:41 +00006514
6515 public:
6516 DeclContextAllNamesVisitor(ASTReader &Reader,
6517 SmallVectorImpl<const DeclContext *> &Contexts,
Craig Topper3598eb72013-07-05 04:43:31 +00006518 DeclsMap &Decls, bool VisitAll)
Argyrios Kyrtzidis2810e9d2012-12-19 22:21:18 +00006519 : Reader(Reader), Contexts(Contexts), Decls(Decls), VisitAll(VisitAll) { }
Guy Benyei11169dd2012-12-18 14:30:41 +00006520
6521 static bool visit(ModuleFile &M, void *UserData) {
6522 DeclContextAllNamesVisitor *This
6523 = static_cast<DeclContextAllNamesVisitor *>(UserData);
6524
6525 // Check whether we have any visible declaration information for
6526 // this context in this module.
6527 ModuleFile::DeclContextInfosMap::iterator Info;
6528 bool FoundInfo = false;
6529 for (unsigned I = 0, N = This->Contexts.size(); I != N; ++I) {
6530 Info = M.DeclContextInfos.find(This->Contexts[I]);
6531 if (Info != M.DeclContextInfos.end() &&
6532 Info->second.NameLookupTableData) {
6533 FoundInfo = true;
6534 break;
6535 }
6536 }
6537
6538 if (!FoundInfo)
6539 return false;
6540
Richard Smith52e3fba2014-03-11 07:17:35 +00006541 ASTDeclContextNameLookupTable *LookupTable =
Guy Benyei11169dd2012-12-18 14:30:41 +00006542 Info->second.NameLookupTableData;
6543 bool FoundAnything = false;
6544 for (ASTDeclContextNameLookupTable::data_iterator
Douglas Gregor5e306b12013-01-23 22:38:11 +00006545 I = LookupTable->data_begin(), E = LookupTable->data_end();
6546 I != E;
6547 ++I) {
Guy Benyei11169dd2012-12-18 14:30:41 +00006548 ASTDeclContextNameLookupTrait::data_type Data = *I;
6549 for (; Data.first != Data.second; ++Data.first) {
6550 NamedDecl *ND = This->Reader.GetLocalDeclAs<NamedDecl>(M,
6551 *Data.first);
6552 if (!ND)
6553 continue;
6554
6555 // Record this declaration.
6556 FoundAnything = true;
6557 This->Decls[ND->getDeclName()].push_back(ND);
6558 }
6559 }
6560
Argyrios Kyrtzidis2810e9d2012-12-19 22:21:18 +00006561 return FoundAnything && !This->VisitAll;
Guy Benyei11169dd2012-12-18 14:30:41 +00006562 }
6563 };
6564}
6565
6566void ASTReader::completeVisibleDeclsMap(const DeclContext *DC) {
6567 if (!DC->hasExternalVisibleStorage())
6568 return;
Craig Topper79be4cd2013-07-05 04:33:53 +00006569 DeclsMap Decls;
Guy Benyei11169dd2012-12-18 14:30:41 +00006570
6571 // Compute the declaration contexts we need to look into. Multiple such
6572 // declaration contexts occur when two declaration contexts from disjoint
6573 // modules get merged, e.g., when two namespaces with the same name are
6574 // independently defined in separate modules.
6575 SmallVector<const DeclContext *, 2> Contexts;
6576 Contexts.push_back(DC);
6577
6578 if (DC->isNamespace()) {
6579 MergedDeclsMap::iterator Merged
6580 = MergedDecls.find(const_cast<Decl *>(cast<Decl>(DC)));
6581 if (Merged != MergedDecls.end()) {
6582 for (unsigned I = 0, N = Merged->second.size(); I != N; ++I)
6583 Contexts.push_back(cast<DeclContext>(GetDecl(Merged->second[I])));
6584 }
6585 }
6586
Argyrios Kyrtzidis2810e9d2012-12-19 22:21:18 +00006587 DeclContextAllNamesVisitor Visitor(*this, Contexts, Decls,
6588 /*VisitAll=*/DC->isFileContext());
Guy Benyei11169dd2012-12-18 14:30:41 +00006589 ModuleMgr.visit(&DeclContextAllNamesVisitor::visit, &Visitor);
6590 ++NumVisibleDeclContextsRead;
6591
Craig Topper79be4cd2013-07-05 04:33:53 +00006592 for (DeclsMap::iterator I = Decls.begin(), E = Decls.end(); I != E; ++I) {
Guy Benyei11169dd2012-12-18 14:30:41 +00006593 SetExternalVisibleDeclsForName(DC, I->first, I->second);
6594 }
6595 const_cast<DeclContext *>(DC)->setHasExternalVisibleStorage(false);
6596}
6597
6598/// \brief Under non-PCH compilation the consumer receives the objc methods
6599/// before receiving the implementation, and codegen depends on this.
6600/// We simulate this by deserializing and passing to consumer the methods of the
6601/// implementation before passing the deserialized implementation decl.
6602static void PassObjCImplDeclToConsumer(ObjCImplDecl *ImplD,
6603 ASTConsumer *Consumer) {
6604 assert(ImplD && Consumer);
6605
Aaron Ballmanaff18c02014-03-13 19:03:34 +00006606 for (auto *I : ImplD->methods())
6607 Consumer->HandleInterestingDecl(DeclGroupRef(I));
Guy Benyei11169dd2012-12-18 14:30:41 +00006608
6609 Consumer->HandleInterestingDecl(DeclGroupRef(ImplD));
6610}
6611
6612void ASTReader::PassInterestingDeclsToConsumer() {
6613 assert(Consumer);
Richard Smith04d05b52014-03-23 00:27:18 +00006614
6615 if (PassingDeclsToConsumer)
6616 return;
6617
6618 // Guard variable to avoid recursively redoing the process of passing
6619 // decls to consumer.
6620 SaveAndRestore<bool> GuardPassingDeclsToConsumer(PassingDeclsToConsumer,
6621 true);
6622
Guy Benyei11169dd2012-12-18 14:30:41 +00006623 while (!InterestingDecls.empty()) {
6624 Decl *D = InterestingDecls.front();
6625 InterestingDecls.pop_front();
6626
6627 PassInterestingDeclToConsumer(D);
6628 }
6629}
6630
6631void ASTReader::PassInterestingDeclToConsumer(Decl *D) {
6632 if (ObjCImplDecl *ImplD = dyn_cast<ObjCImplDecl>(D))
6633 PassObjCImplDeclToConsumer(ImplD, Consumer);
6634 else
6635 Consumer->HandleInterestingDecl(DeclGroupRef(D));
6636}
6637
6638void ASTReader::StartTranslationUnit(ASTConsumer *Consumer) {
6639 this->Consumer = Consumer;
6640
6641 if (!Consumer)
6642 return;
6643
Ben Langmuir332aafe2014-01-31 01:06:56 +00006644 for (unsigned I = 0, N = EagerlyDeserializedDecls.size(); I != N; ++I) {
Guy Benyei11169dd2012-12-18 14:30:41 +00006645 // Force deserialization of this decl, which will cause it to be queued for
6646 // passing to the consumer.
Ben Langmuir332aafe2014-01-31 01:06:56 +00006647 GetDecl(EagerlyDeserializedDecls[I]);
Guy Benyei11169dd2012-12-18 14:30:41 +00006648 }
Ben Langmuir332aafe2014-01-31 01:06:56 +00006649 EagerlyDeserializedDecls.clear();
Guy Benyei11169dd2012-12-18 14:30:41 +00006650
6651 PassInterestingDeclsToConsumer();
6652}
6653
6654void ASTReader::PrintStats() {
6655 std::fprintf(stderr, "*** AST File Statistics:\n");
6656
6657 unsigned NumTypesLoaded
6658 = TypesLoaded.size() - std::count(TypesLoaded.begin(), TypesLoaded.end(),
6659 QualType());
6660 unsigned NumDeclsLoaded
6661 = DeclsLoaded.size() - std::count(DeclsLoaded.begin(), DeclsLoaded.end(),
Craig Toppera13603a2014-05-22 05:54:18 +00006662 (Decl *)nullptr);
Guy Benyei11169dd2012-12-18 14:30:41 +00006663 unsigned NumIdentifiersLoaded
6664 = IdentifiersLoaded.size() - std::count(IdentifiersLoaded.begin(),
6665 IdentifiersLoaded.end(),
Craig Toppera13603a2014-05-22 05:54:18 +00006666 (IdentifierInfo *)nullptr);
Guy Benyei11169dd2012-12-18 14:30:41 +00006667 unsigned NumMacrosLoaded
6668 = MacrosLoaded.size() - std::count(MacrosLoaded.begin(),
6669 MacrosLoaded.end(),
Craig Toppera13603a2014-05-22 05:54:18 +00006670 (MacroInfo *)nullptr);
Guy Benyei11169dd2012-12-18 14:30:41 +00006671 unsigned NumSelectorsLoaded
6672 = SelectorsLoaded.size() - std::count(SelectorsLoaded.begin(),
6673 SelectorsLoaded.end(),
6674 Selector());
6675
6676 if (unsigned TotalNumSLocEntries = getTotalNumSLocs())
6677 std::fprintf(stderr, " %u/%u source location entries read (%f%%)\n",
6678 NumSLocEntriesRead, TotalNumSLocEntries,
6679 ((float)NumSLocEntriesRead/TotalNumSLocEntries * 100));
6680 if (!TypesLoaded.empty())
6681 std::fprintf(stderr, " %u/%u types read (%f%%)\n",
6682 NumTypesLoaded, (unsigned)TypesLoaded.size(),
6683 ((float)NumTypesLoaded/TypesLoaded.size() * 100));
6684 if (!DeclsLoaded.empty())
6685 std::fprintf(stderr, " %u/%u declarations read (%f%%)\n",
6686 NumDeclsLoaded, (unsigned)DeclsLoaded.size(),
6687 ((float)NumDeclsLoaded/DeclsLoaded.size() * 100));
6688 if (!IdentifiersLoaded.empty())
6689 std::fprintf(stderr, " %u/%u identifiers read (%f%%)\n",
6690 NumIdentifiersLoaded, (unsigned)IdentifiersLoaded.size(),
6691 ((float)NumIdentifiersLoaded/IdentifiersLoaded.size() * 100));
6692 if (!MacrosLoaded.empty())
6693 std::fprintf(stderr, " %u/%u macros read (%f%%)\n",
6694 NumMacrosLoaded, (unsigned)MacrosLoaded.size(),
6695 ((float)NumMacrosLoaded/MacrosLoaded.size() * 100));
6696 if (!SelectorsLoaded.empty())
6697 std::fprintf(stderr, " %u/%u selectors read (%f%%)\n",
6698 NumSelectorsLoaded, (unsigned)SelectorsLoaded.size(),
6699 ((float)NumSelectorsLoaded/SelectorsLoaded.size() * 100));
6700 if (TotalNumStatements)
6701 std::fprintf(stderr, " %u/%u statements read (%f%%)\n",
6702 NumStatementsRead, TotalNumStatements,
6703 ((float)NumStatementsRead/TotalNumStatements * 100));
6704 if (TotalNumMacros)
6705 std::fprintf(stderr, " %u/%u macros read (%f%%)\n",
6706 NumMacrosRead, TotalNumMacros,
6707 ((float)NumMacrosRead/TotalNumMacros * 100));
6708 if (TotalLexicalDeclContexts)
6709 std::fprintf(stderr, " %u/%u lexical declcontexts read (%f%%)\n",
6710 NumLexicalDeclContextsRead, TotalLexicalDeclContexts,
6711 ((float)NumLexicalDeclContextsRead/TotalLexicalDeclContexts
6712 * 100));
6713 if (TotalVisibleDeclContexts)
6714 std::fprintf(stderr, " %u/%u visible declcontexts read (%f%%)\n",
6715 NumVisibleDeclContextsRead, TotalVisibleDeclContexts,
6716 ((float)NumVisibleDeclContextsRead/TotalVisibleDeclContexts
6717 * 100));
6718 if (TotalNumMethodPoolEntries) {
6719 std::fprintf(stderr, " %u/%u method pool entries read (%f%%)\n",
6720 NumMethodPoolEntriesRead, TotalNumMethodPoolEntries,
6721 ((float)NumMethodPoolEntriesRead/TotalNumMethodPoolEntries
6722 * 100));
Guy Benyei11169dd2012-12-18 14:30:41 +00006723 }
Douglas Gregorad2f7a52013-01-28 17:54:36 +00006724 if (NumMethodPoolLookups) {
6725 std::fprintf(stderr, " %u/%u method pool lookups succeeded (%f%%)\n",
6726 NumMethodPoolHits, NumMethodPoolLookups,
6727 ((float)NumMethodPoolHits/NumMethodPoolLookups * 100.0));
6728 }
6729 if (NumMethodPoolTableLookups) {
6730 std::fprintf(stderr, " %u/%u method pool table lookups succeeded (%f%%)\n",
6731 NumMethodPoolTableHits, NumMethodPoolTableLookups,
6732 ((float)NumMethodPoolTableHits/NumMethodPoolTableLookups
6733 * 100.0));
6734 }
6735
Douglas Gregor00a50f72013-01-25 00:38:33 +00006736 if (NumIdentifierLookupHits) {
6737 std::fprintf(stderr,
6738 " %u / %u identifier table lookups succeeded (%f%%)\n",
6739 NumIdentifierLookupHits, NumIdentifierLookups,
6740 (double)NumIdentifierLookupHits*100.0/NumIdentifierLookups);
6741 }
6742
Douglas Gregore060e572013-01-25 01:03:03 +00006743 if (GlobalIndex) {
6744 std::fprintf(stderr, "\n");
6745 GlobalIndex->printStats();
6746 }
6747
Guy Benyei11169dd2012-12-18 14:30:41 +00006748 std::fprintf(stderr, "\n");
6749 dump();
6750 std::fprintf(stderr, "\n");
6751}
6752
6753template<typename Key, typename ModuleFile, unsigned InitialCapacity>
6754static void
6755dumpModuleIDMap(StringRef Name,
6756 const ContinuousRangeMap<Key, ModuleFile *,
6757 InitialCapacity> &Map) {
6758 if (Map.begin() == Map.end())
6759 return;
6760
6761 typedef ContinuousRangeMap<Key, ModuleFile *, InitialCapacity> MapType;
6762 llvm::errs() << Name << ":\n";
6763 for (typename MapType::const_iterator I = Map.begin(), IEnd = Map.end();
6764 I != IEnd; ++I) {
6765 llvm::errs() << " " << I->first << " -> " << I->second->FileName
6766 << "\n";
6767 }
6768}
6769
6770void ASTReader::dump() {
6771 llvm::errs() << "*** PCH/ModuleFile Remappings:\n";
6772 dumpModuleIDMap("Global bit offset map", GlobalBitOffsetsMap);
6773 dumpModuleIDMap("Global source location entry map", GlobalSLocEntryMap);
6774 dumpModuleIDMap("Global type map", GlobalTypeMap);
6775 dumpModuleIDMap("Global declaration map", GlobalDeclMap);
6776 dumpModuleIDMap("Global identifier map", GlobalIdentifierMap);
6777 dumpModuleIDMap("Global macro map", GlobalMacroMap);
6778 dumpModuleIDMap("Global submodule map", GlobalSubmoduleMap);
6779 dumpModuleIDMap("Global selector map", GlobalSelectorMap);
6780 dumpModuleIDMap("Global preprocessed entity map",
6781 GlobalPreprocessedEntityMap);
6782
6783 llvm::errs() << "\n*** PCH/Modules Loaded:";
6784 for (ModuleManager::ModuleConstIterator M = ModuleMgr.begin(),
6785 MEnd = ModuleMgr.end();
6786 M != MEnd; ++M)
6787 (*M)->dump();
6788}
6789
6790/// Return the amount of memory used by memory buffers, breaking down
6791/// by heap-backed versus mmap'ed memory.
6792void ASTReader::getMemoryBufferSizes(MemoryBufferSizes &sizes) const {
6793 for (ModuleConstIterator I = ModuleMgr.begin(),
6794 E = ModuleMgr.end(); I != E; ++I) {
6795 if (llvm::MemoryBuffer *buf = (*I)->Buffer.get()) {
6796 size_t bytes = buf->getBufferSize();
6797 switch (buf->getBufferKind()) {
6798 case llvm::MemoryBuffer::MemoryBuffer_Malloc:
6799 sizes.malloc_bytes += bytes;
6800 break;
6801 case llvm::MemoryBuffer::MemoryBuffer_MMap:
6802 sizes.mmap_bytes += bytes;
6803 break;
6804 }
6805 }
6806 }
6807}
6808
6809void ASTReader::InitializeSema(Sema &S) {
6810 SemaObj = &S;
6811 S.addExternalSource(this);
6812
6813 // Makes sure any declarations that were deserialized "too early"
6814 // still get added to the identifier's declaration chains.
6815 for (unsigned I = 0, N = PreloadedDecls.size(); I != N; ++I) {
Argyrios Kyrtzidise5edbf92013-04-26 21:33:35 +00006816 pushExternalDeclIntoScope(PreloadedDecls[I],
6817 PreloadedDecls[I]->getDeclName());
Guy Benyei11169dd2012-12-18 14:30:41 +00006818 }
6819 PreloadedDecls.clear();
6820
Richard Smith3d8e97e2013-10-18 06:54:39 +00006821 // FIXME: What happens if these are changed by a module import?
Guy Benyei11169dd2012-12-18 14:30:41 +00006822 if (!FPPragmaOptions.empty()) {
6823 assert(FPPragmaOptions.size() == 1 && "Wrong number of FP_PRAGMA_OPTIONS");
6824 SemaObj->FPFeatures.fp_contract = FPPragmaOptions[0];
6825 }
6826
Richard Smith3d8e97e2013-10-18 06:54:39 +00006827 // FIXME: What happens if these are changed by a module import?
Guy Benyei11169dd2012-12-18 14:30:41 +00006828 if (!OpenCLExtensions.empty()) {
6829 unsigned I = 0;
6830#define OPENCLEXT(nm) SemaObj->OpenCLFeatures.nm = OpenCLExtensions[I++];
6831#include "clang/Basic/OpenCLExtensions.def"
6832
6833 assert(OpenCLExtensions.size() == I && "Wrong number of OPENCL_EXTENSIONS");
6834 }
Richard Smith3d8e97e2013-10-18 06:54:39 +00006835
6836 UpdateSema();
6837}
6838
6839void ASTReader::UpdateSema() {
6840 assert(SemaObj && "no Sema to update");
6841
6842 // Load the offsets of the declarations that Sema references.
6843 // They will be lazily deserialized when needed.
6844 if (!SemaDeclRefs.empty()) {
6845 assert(SemaDeclRefs.size() % 2 == 0);
6846 for (unsigned I = 0; I != SemaDeclRefs.size(); I += 2) {
6847 if (!SemaObj->StdNamespace)
6848 SemaObj->StdNamespace = SemaDeclRefs[I];
6849 if (!SemaObj->StdBadAlloc)
6850 SemaObj->StdBadAlloc = SemaDeclRefs[I+1];
6851 }
6852 SemaDeclRefs.clear();
6853 }
Dario Domizioli13a0a382014-05-23 12:13:25 +00006854
6855 // Update the state of 'pragma clang optimize'. Use the same API as if we had
6856 // encountered the pragma in the source.
6857 if(OptimizeOffPragmaLocation.isValid())
6858 SemaObj->ActOnPragmaOptimize(/* IsOn = */ false, OptimizeOffPragmaLocation);
Guy Benyei11169dd2012-12-18 14:30:41 +00006859}
6860
6861IdentifierInfo* ASTReader::get(const char *NameStart, const char *NameEnd) {
6862 // Note that we are loading an identifier.
6863 Deserializing AnIdentifier(this);
Douglas Gregore060e572013-01-25 01:03:03 +00006864 StringRef Name(NameStart, NameEnd - NameStart);
6865
6866 // If there is a global index, look there first to determine which modules
6867 // provably do not have any results for this identifier.
Douglas Gregor7211ac12013-01-25 23:32:03 +00006868 GlobalModuleIndex::HitSet Hits;
Craig Toppera13603a2014-05-22 05:54:18 +00006869 GlobalModuleIndex::HitSet *HitsPtr = nullptr;
Douglas Gregore060e572013-01-25 01:03:03 +00006870 if (!loadGlobalIndex()) {
Douglas Gregor7211ac12013-01-25 23:32:03 +00006871 if (GlobalIndex->lookupIdentifier(Name, Hits)) {
6872 HitsPtr = &Hits;
Douglas Gregore060e572013-01-25 01:03:03 +00006873 }
6874 }
Douglas Gregor7211ac12013-01-25 23:32:03 +00006875 IdentifierLookupVisitor Visitor(Name, /*PriorGeneration=*/0,
Douglas Gregor00a50f72013-01-25 00:38:33 +00006876 NumIdentifierLookups,
6877 NumIdentifierLookupHits);
Douglas Gregor7211ac12013-01-25 23:32:03 +00006878 ModuleMgr.visit(IdentifierLookupVisitor::visit, &Visitor, HitsPtr);
Guy Benyei11169dd2012-12-18 14:30:41 +00006879 IdentifierInfo *II = Visitor.getIdentifierInfo();
6880 markIdentifierUpToDate(II);
6881 return II;
6882}
6883
6884namespace clang {
6885 /// \brief An identifier-lookup iterator that enumerates all of the
6886 /// identifiers stored within a set of AST files.
6887 class ASTIdentifierIterator : public IdentifierIterator {
6888 /// \brief The AST reader whose identifiers are being enumerated.
6889 const ASTReader &Reader;
6890
6891 /// \brief The current index into the chain of AST files stored in
6892 /// the AST reader.
6893 unsigned Index;
6894
6895 /// \brief The current position within the identifier lookup table
6896 /// of the current AST file.
6897 ASTIdentifierLookupTable::key_iterator Current;
6898
6899 /// \brief The end position within the identifier lookup table of
6900 /// the current AST file.
6901 ASTIdentifierLookupTable::key_iterator End;
6902
6903 public:
6904 explicit ASTIdentifierIterator(const ASTReader &Reader);
6905
Craig Topper3e89dfe2014-03-13 02:13:41 +00006906 StringRef Next() override;
Guy Benyei11169dd2012-12-18 14:30:41 +00006907 };
6908}
6909
6910ASTIdentifierIterator::ASTIdentifierIterator(const ASTReader &Reader)
6911 : Reader(Reader), Index(Reader.ModuleMgr.size() - 1) {
6912 ASTIdentifierLookupTable *IdTable
6913 = (ASTIdentifierLookupTable *)Reader.ModuleMgr[Index].IdentifierLookupTable;
6914 Current = IdTable->key_begin();
6915 End = IdTable->key_end();
6916}
6917
6918StringRef ASTIdentifierIterator::Next() {
6919 while (Current == End) {
6920 // If we have exhausted all of our AST files, we're done.
6921 if (Index == 0)
6922 return StringRef();
6923
6924 --Index;
6925 ASTIdentifierLookupTable *IdTable
6926 = (ASTIdentifierLookupTable *)Reader.ModuleMgr[Index].
6927 IdentifierLookupTable;
6928 Current = IdTable->key_begin();
6929 End = IdTable->key_end();
6930 }
6931
6932 // We have any identifiers remaining in the current AST file; return
6933 // the next one.
Douglas Gregorbfd73d72013-01-23 18:53:14 +00006934 StringRef Result = *Current;
Guy Benyei11169dd2012-12-18 14:30:41 +00006935 ++Current;
Douglas Gregorbfd73d72013-01-23 18:53:14 +00006936 return Result;
Guy Benyei11169dd2012-12-18 14:30:41 +00006937}
6938
Argyrios Kyrtzidis9aca3c62013-04-17 22:10:55 +00006939IdentifierIterator *ASTReader::getIdentifiers() {
6940 if (!loadGlobalIndex())
6941 return GlobalIndex->createIdentifierIterator();
6942
Guy Benyei11169dd2012-12-18 14:30:41 +00006943 return new ASTIdentifierIterator(*this);
6944}
6945
6946namespace clang { namespace serialization {
6947 class ReadMethodPoolVisitor {
6948 ASTReader &Reader;
6949 Selector Sel;
6950 unsigned PriorGeneration;
Argyrios Kyrtzidisd3da6e02013-04-17 00:08:58 +00006951 unsigned InstanceBits;
6952 unsigned FactoryBits;
Dmitri Gribenkof8579502013-01-12 19:30:44 +00006953 SmallVector<ObjCMethodDecl *, 4> InstanceMethods;
6954 SmallVector<ObjCMethodDecl *, 4> FactoryMethods;
Guy Benyei11169dd2012-12-18 14:30:41 +00006955
6956 public:
6957 ReadMethodPoolVisitor(ASTReader &Reader, Selector Sel,
6958 unsigned PriorGeneration)
Argyrios Kyrtzidisd3da6e02013-04-17 00:08:58 +00006959 : Reader(Reader), Sel(Sel), PriorGeneration(PriorGeneration),
6960 InstanceBits(0), FactoryBits(0) { }
Guy Benyei11169dd2012-12-18 14:30:41 +00006961
6962 static bool visit(ModuleFile &M, void *UserData) {
6963 ReadMethodPoolVisitor *This
6964 = static_cast<ReadMethodPoolVisitor *>(UserData);
6965
6966 if (!M.SelectorLookupTable)
6967 return false;
6968
6969 // If we've already searched this module file, skip it now.
6970 if (M.Generation <= This->PriorGeneration)
6971 return true;
6972
Douglas Gregorad2f7a52013-01-28 17:54:36 +00006973 ++This->Reader.NumMethodPoolTableLookups;
Guy Benyei11169dd2012-12-18 14:30:41 +00006974 ASTSelectorLookupTable *PoolTable
6975 = (ASTSelectorLookupTable*)M.SelectorLookupTable;
6976 ASTSelectorLookupTable::iterator Pos = PoolTable->find(This->Sel);
6977 if (Pos == PoolTable->end())
6978 return false;
Douglas Gregorad2f7a52013-01-28 17:54:36 +00006979
6980 ++This->Reader.NumMethodPoolTableHits;
Guy Benyei11169dd2012-12-18 14:30:41 +00006981 ++This->Reader.NumSelectorsRead;
6982 // FIXME: Not quite happy with the statistics here. We probably should
6983 // disable this tracking when called via LoadSelector.
6984 // Also, should entries without methods count as misses?
6985 ++This->Reader.NumMethodPoolEntriesRead;
6986 ASTSelectorLookupTrait::data_type Data = *Pos;
6987 if (This->Reader.DeserializationListener)
6988 This->Reader.DeserializationListener->SelectorRead(Data.ID,
6989 This->Sel);
6990
6991 This->InstanceMethods.append(Data.Instance.begin(), Data.Instance.end());
6992 This->FactoryMethods.append(Data.Factory.begin(), Data.Factory.end());
Argyrios Kyrtzidisd3da6e02013-04-17 00:08:58 +00006993 This->InstanceBits = Data.InstanceBits;
6994 This->FactoryBits = Data.FactoryBits;
Guy Benyei11169dd2012-12-18 14:30:41 +00006995 return true;
6996 }
6997
6998 /// \brief Retrieve the instance methods found by this visitor.
6999 ArrayRef<ObjCMethodDecl *> getInstanceMethods() const {
7000 return InstanceMethods;
7001 }
7002
7003 /// \brief Retrieve the instance methods found by this visitor.
7004 ArrayRef<ObjCMethodDecl *> getFactoryMethods() const {
7005 return FactoryMethods;
7006 }
Argyrios Kyrtzidisd3da6e02013-04-17 00:08:58 +00007007
7008 unsigned getInstanceBits() const { return InstanceBits; }
7009 unsigned getFactoryBits() const { return FactoryBits; }
Guy Benyei11169dd2012-12-18 14:30:41 +00007010 };
7011} } // end namespace clang::serialization
7012
7013/// \brief Add the given set of methods to the method list.
7014static void addMethodsToPool(Sema &S, ArrayRef<ObjCMethodDecl *> Methods,
7015 ObjCMethodList &List) {
7016 for (unsigned I = 0, N = Methods.size(); I != N; ++I) {
7017 S.addMethodToGlobalList(&List, Methods[I]);
7018 }
7019}
7020
7021void ASTReader::ReadMethodPool(Selector Sel) {
7022 // Get the selector generation and update it to the current generation.
7023 unsigned &Generation = SelectorGeneration[Sel];
7024 unsigned PriorGeneration = Generation;
Richard Smith053f6c62014-05-16 23:01:30 +00007025 Generation = getGeneration();
Guy Benyei11169dd2012-12-18 14:30:41 +00007026
7027 // Search for methods defined with this selector.
Douglas Gregorad2f7a52013-01-28 17:54:36 +00007028 ++NumMethodPoolLookups;
Guy Benyei11169dd2012-12-18 14:30:41 +00007029 ReadMethodPoolVisitor Visitor(*this, Sel, PriorGeneration);
7030 ModuleMgr.visit(&ReadMethodPoolVisitor::visit, &Visitor);
7031
7032 if (Visitor.getInstanceMethods().empty() &&
Douglas Gregorad2f7a52013-01-28 17:54:36 +00007033 Visitor.getFactoryMethods().empty())
Guy Benyei11169dd2012-12-18 14:30:41 +00007034 return;
Douglas Gregorad2f7a52013-01-28 17:54:36 +00007035
7036 ++NumMethodPoolHits;
7037
Guy Benyei11169dd2012-12-18 14:30:41 +00007038 if (!getSema())
7039 return;
7040
7041 Sema &S = *getSema();
7042 Sema::GlobalMethodPool::iterator Pos
7043 = S.MethodPool.insert(std::make_pair(Sel, Sema::GlobalMethods())).first;
7044
7045 addMethodsToPool(S, Visitor.getInstanceMethods(), Pos->second.first);
7046 addMethodsToPool(S, Visitor.getFactoryMethods(), Pos->second.second);
Argyrios Kyrtzidisd3da6e02013-04-17 00:08:58 +00007047 Pos->second.first.setBits(Visitor.getInstanceBits());
7048 Pos->second.second.setBits(Visitor.getFactoryBits());
Guy Benyei11169dd2012-12-18 14:30:41 +00007049}
7050
7051void ASTReader::ReadKnownNamespaces(
7052 SmallVectorImpl<NamespaceDecl *> &Namespaces) {
7053 Namespaces.clear();
7054
7055 for (unsigned I = 0, N = KnownNamespaces.size(); I != N; ++I) {
7056 if (NamespaceDecl *Namespace
7057 = dyn_cast_or_null<NamespaceDecl>(GetDecl(KnownNamespaces[I])))
7058 Namespaces.push_back(Namespace);
7059 }
7060}
7061
Nick Lewycky9c7eb1d2013-02-01 08:13:20 +00007062void ASTReader::ReadUndefinedButUsed(
Nick Lewyckyf0f56162013-01-31 03:23:57 +00007063 llvm::DenseMap<NamedDecl*, SourceLocation> &Undefined) {
Nick Lewycky9c7eb1d2013-02-01 08:13:20 +00007064 for (unsigned Idx = 0, N = UndefinedButUsed.size(); Idx != N;) {
7065 NamedDecl *D = cast<NamedDecl>(GetDecl(UndefinedButUsed[Idx++]));
Nick Lewycky8334af82013-01-26 00:35:08 +00007066 SourceLocation Loc =
Nick Lewycky9c7eb1d2013-02-01 08:13:20 +00007067 SourceLocation::getFromRawEncoding(UndefinedButUsed[Idx++]);
Nick Lewycky8334af82013-01-26 00:35:08 +00007068 Undefined.insert(std::make_pair(D, Loc));
7069 }
7070}
Nick Lewycky8334af82013-01-26 00:35:08 +00007071
Guy Benyei11169dd2012-12-18 14:30:41 +00007072void ASTReader::ReadTentativeDefinitions(
7073 SmallVectorImpl<VarDecl *> &TentativeDefs) {
7074 for (unsigned I = 0, N = TentativeDefinitions.size(); I != N; ++I) {
7075 VarDecl *Var = dyn_cast_or_null<VarDecl>(GetDecl(TentativeDefinitions[I]));
7076 if (Var)
7077 TentativeDefs.push_back(Var);
7078 }
7079 TentativeDefinitions.clear();
7080}
7081
7082void ASTReader::ReadUnusedFileScopedDecls(
7083 SmallVectorImpl<const DeclaratorDecl *> &Decls) {
7084 for (unsigned I = 0, N = UnusedFileScopedDecls.size(); I != N; ++I) {
7085 DeclaratorDecl *D
7086 = dyn_cast_or_null<DeclaratorDecl>(GetDecl(UnusedFileScopedDecls[I]));
7087 if (D)
7088 Decls.push_back(D);
7089 }
7090 UnusedFileScopedDecls.clear();
7091}
7092
7093void ASTReader::ReadDelegatingConstructors(
7094 SmallVectorImpl<CXXConstructorDecl *> &Decls) {
7095 for (unsigned I = 0, N = DelegatingCtorDecls.size(); I != N; ++I) {
7096 CXXConstructorDecl *D
7097 = dyn_cast_or_null<CXXConstructorDecl>(GetDecl(DelegatingCtorDecls[I]));
7098 if (D)
7099 Decls.push_back(D);
7100 }
7101 DelegatingCtorDecls.clear();
7102}
7103
7104void ASTReader::ReadExtVectorDecls(SmallVectorImpl<TypedefNameDecl *> &Decls) {
7105 for (unsigned I = 0, N = ExtVectorDecls.size(); I != N; ++I) {
7106 TypedefNameDecl *D
7107 = dyn_cast_or_null<TypedefNameDecl>(GetDecl(ExtVectorDecls[I]));
7108 if (D)
7109 Decls.push_back(D);
7110 }
7111 ExtVectorDecls.clear();
7112}
7113
7114void ASTReader::ReadDynamicClasses(SmallVectorImpl<CXXRecordDecl *> &Decls) {
7115 for (unsigned I = 0, N = DynamicClasses.size(); I != N; ++I) {
7116 CXXRecordDecl *D
7117 = dyn_cast_or_null<CXXRecordDecl>(GetDecl(DynamicClasses[I]));
7118 if (D)
7119 Decls.push_back(D);
7120 }
7121 DynamicClasses.clear();
7122}
7123
7124void
Richard Smith78165b52013-01-10 23:43:47 +00007125ASTReader::ReadLocallyScopedExternCDecls(SmallVectorImpl<NamedDecl *> &Decls) {
7126 for (unsigned I = 0, N = LocallyScopedExternCDecls.size(); I != N; ++I) {
7127 NamedDecl *D
7128 = dyn_cast_or_null<NamedDecl>(GetDecl(LocallyScopedExternCDecls[I]));
Guy Benyei11169dd2012-12-18 14:30:41 +00007129 if (D)
7130 Decls.push_back(D);
7131 }
Richard Smith78165b52013-01-10 23:43:47 +00007132 LocallyScopedExternCDecls.clear();
Guy Benyei11169dd2012-12-18 14:30:41 +00007133}
7134
7135void ASTReader::ReadReferencedSelectors(
7136 SmallVectorImpl<std::pair<Selector, SourceLocation> > &Sels) {
7137 if (ReferencedSelectorsData.empty())
7138 return;
7139
7140 // If there are @selector references added them to its pool. This is for
7141 // implementation of -Wselector.
7142 unsigned int DataSize = ReferencedSelectorsData.size()-1;
7143 unsigned I = 0;
7144 while (I < DataSize) {
7145 Selector Sel = DecodeSelector(ReferencedSelectorsData[I++]);
7146 SourceLocation SelLoc
7147 = SourceLocation::getFromRawEncoding(ReferencedSelectorsData[I++]);
7148 Sels.push_back(std::make_pair(Sel, SelLoc));
7149 }
7150 ReferencedSelectorsData.clear();
7151}
7152
7153void ASTReader::ReadWeakUndeclaredIdentifiers(
7154 SmallVectorImpl<std::pair<IdentifierInfo *, WeakInfo> > &WeakIDs) {
7155 if (WeakUndeclaredIdentifiers.empty())
7156 return;
7157
7158 for (unsigned I = 0, N = WeakUndeclaredIdentifiers.size(); I < N; /*none*/) {
7159 IdentifierInfo *WeakId
7160 = DecodeIdentifierInfo(WeakUndeclaredIdentifiers[I++]);
7161 IdentifierInfo *AliasId
7162 = DecodeIdentifierInfo(WeakUndeclaredIdentifiers[I++]);
7163 SourceLocation Loc
7164 = SourceLocation::getFromRawEncoding(WeakUndeclaredIdentifiers[I++]);
7165 bool Used = WeakUndeclaredIdentifiers[I++];
7166 WeakInfo WI(AliasId, Loc);
7167 WI.setUsed(Used);
7168 WeakIDs.push_back(std::make_pair(WeakId, WI));
7169 }
7170 WeakUndeclaredIdentifiers.clear();
7171}
7172
7173void ASTReader::ReadUsedVTables(SmallVectorImpl<ExternalVTableUse> &VTables) {
7174 for (unsigned Idx = 0, N = VTableUses.size(); Idx < N; /* In loop */) {
7175 ExternalVTableUse VT;
7176 VT.Record = dyn_cast_or_null<CXXRecordDecl>(GetDecl(VTableUses[Idx++]));
7177 VT.Location = SourceLocation::getFromRawEncoding(VTableUses[Idx++]);
7178 VT.DefinitionRequired = VTableUses[Idx++];
7179 VTables.push_back(VT);
7180 }
7181
7182 VTableUses.clear();
7183}
7184
7185void ASTReader::ReadPendingInstantiations(
7186 SmallVectorImpl<std::pair<ValueDecl *, SourceLocation> > &Pending) {
7187 for (unsigned Idx = 0, N = PendingInstantiations.size(); Idx < N;) {
7188 ValueDecl *D = cast<ValueDecl>(GetDecl(PendingInstantiations[Idx++]));
7189 SourceLocation Loc
7190 = SourceLocation::getFromRawEncoding(PendingInstantiations[Idx++]);
7191
7192 Pending.push_back(std::make_pair(D, Loc));
7193 }
7194 PendingInstantiations.clear();
7195}
7196
Richard Smithe40f2ba2013-08-07 21:41:30 +00007197void ASTReader::ReadLateParsedTemplates(
7198 llvm::DenseMap<const FunctionDecl *, LateParsedTemplate *> &LPTMap) {
7199 for (unsigned Idx = 0, N = LateParsedTemplates.size(); Idx < N;
7200 /* In loop */) {
7201 FunctionDecl *FD = cast<FunctionDecl>(GetDecl(LateParsedTemplates[Idx++]));
7202
7203 LateParsedTemplate *LT = new LateParsedTemplate;
7204 LT->D = GetDecl(LateParsedTemplates[Idx++]);
7205
7206 ModuleFile *F = getOwningModuleFile(LT->D);
7207 assert(F && "No module");
7208
7209 unsigned TokN = LateParsedTemplates[Idx++];
7210 LT->Toks.reserve(TokN);
7211 for (unsigned T = 0; T < TokN; ++T)
7212 LT->Toks.push_back(ReadToken(*F, LateParsedTemplates, Idx));
7213
7214 LPTMap[FD] = LT;
7215 }
7216
7217 LateParsedTemplates.clear();
7218}
7219
Guy Benyei11169dd2012-12-18 14:30:41 +00007220void ASTReader::LoadSelector(Selector Sel) {
7221 // It would be complicated to avoid reading the methods anyway. So don't.
7222 ReadMethodPool(Sel);
7223}
7224
7225void ASTReader::SetIdentifierInfo(IdentifierID ID, IdentifierInfo *II) {
7226 assert(ID && "Non-zero identifier ID required");
7227 assert(ID <= IdentifiersLoaded.size() && "identifier ID out of range");
7228 IdentifiersLoaded[ID - 1] = II;
7229 if (DeserializationListener)
7230 DeserializationListener->IdentifierRead(ID, II);
7231}
7232
7233/// \brief Set the globally-visible declarations associated with the given
7234/// identifier.
7235///
7236/// If the AST reader is currently in a state where the given declaration IDs
7237/// cannot safely be resolved, they are queued until it is safe to resolve
7238/// them.
7239///
7240/// \param II an IdentifierInfo that refers to one or more globally-visible
7241/// declarations.
7242///
7243/// \param DeclIDs the set of declaration IDs with the name @p II that are
7244/// visible at global scope.
7245///
Douglas Gregor6168bd22013-02-18 15:53:43 +00007246/// \param Decls if non-null, this vector will be populated with the set of
7247/// deserialized declarations. These declarations will not be pushed into
7248/// scope.
Guy Benyei11169dd2012-12-18 14:30:41 +00007249void
7250ASTReader::SetGloballyVisibleDecls(IdentifierInfo *II,
7251 const SmallVectorImpl<uint32_t> &DeclIDs,
Douglas Gregor6168bd22013-02-18 15:53:43 +00007252 SmallVectorImpl<Decl *> *Decls) {
7253 if (NumCurrentElementsDeserializing && !Decls) {
7254 PendingIdentifierInfos[II].append(DeclIDs.begin(), DeclIDs.end());
Guy Benyei11169dd2012-12-18 14:30:41 +00007255 return;
7256 }
7257
7258 for (unsigned I = 0, N = DeclIDs.size(); I != N; ++I) {
7259 NamedDecl *D = cast<NamedDecl>(GetDecl(DeclIDs[I]));
7260 if (SemaObj) {
Douglas Gregor6168bd22013-02-18 15:53:43 +00007261 // If we're simply supposed to record the declarations, do so now.
7262 if (Decls) {
7263 Decls->push_back(D);
7264 continue;
7265 }
7266
Guy Benyei11169dd2012-12-18 14:30:41 +00007267 // Introduce this declaration into the translation-unit scope
7268 // and add it to the declaration chain for this identifier, so
7269 // that (unqualified) name lookup will find it.
Argyrios Kyrtzidise5edbf92013-04-26 21:33:35 +00007270 pushExternalDeclIntoScope(D, II);
Guy Benyei11169dd2012-12-18 14:30:41 +00007271 } else {
7272 // Queue this declaration so that it will be added to the
7273 // translation unit scope and identifier's declaration chain
7274 // once a Sema object is known.
7275 PreloadedDecls.push_back(D);
7276 }
7277 }
7278}
7279
Douglas Gregorc8a992f2013-01-21 16:52:34 +00007280IdentifierInfo *ASTReader::DecodeIdentifierInfo(IdentifierID ID) {
Guy Benyei11169dd2012-12-18 14:30:41 +00007281 if (ID == 0)
Craig Toppera13603a2014-05-22 05:54:18 +00007282 return nullptr;
Guy Benyei11169dd2012-12-18 14:30:41 +00007283
7284 if (IdentifiersLoaded.empty()) {
7285 Error("no identifier table in AST file");
Craig Toppera13603a2014-05-22 05:54:18 +00007286 return nullptr;
Guy Benyei11169dd2012-12-18 14:30:41 +00007287 }
7288
7289 ID -= 1;
7290 if (!IdentifiersLoaded[ID]) {
7291 GlobalIdentifierMapType::iterator I = GlobalIdentifierMap.find(ID + 1);
7292 assert(I != GlobalIdentifierMap.end() && "Corrupted global identifier map");
7293 ModuleFile *M = I->second;
7294 unsigned Index = ID - M->BaseIdentifierID;
7295 const char *Str = M->IdentifierTableData + M->IdentifierOffsets[Index];
7296
7297 // All of the strings in the AST file are preceded by a 16-bit length.
7298 // Extract that 16-bit length to avoid having to execute strlen().
7299 // NOTE: 'StrLenPtr' is an 'unsigned char*' so that we load bytes as
7300 // unsigned integers. This is important to avoid integer overflow when
7301 // we cast them to 'unsigned'.
7302 const unsigned char *StrLenPtr = (const unsigned char*) Str - 2;
7303 unsigned StrLen = (((unsigned) StrLenPtr[0])
7304 | (((unsigned) StrLenPtr[1]) << 8)) - 1;
Douglas Gregorc8a992f2013-01-21 16:52:34 +00007305 IdentifiersLoaded[ID]
7306 = &PP.getIdentifierTable().get(StringRef(Str, StrLen));
Guy Benyei11169dd2012-12-18 14:30:41 +00007307 if (DeserializationListener)
7308 DeserializationListener->IdentifierRead(ID + 1, IdentifiersLoaded[ID]);
7309 }
7310
7311 return IdentifiersLoaded[ID];
7312}
7313
Douglas Gregorc8a992f2013-01-21 16:52:34 +00007314IdentifierInfo *ASTReader::getLocalIdentifier(ModuleFile &M, unsigned LocalID) {
7315 return DecodeIdentifierInfo(getGlobalIdentifierID(M, LocalID));
Guy Benyei11169dd2012-12-18 14:30:41 +00007316}
7317
7318IdentifierID ASTReader::getGlobalIdentifierID(ModuleFile &M, unsigned LocalID) {
7319 if (LocalID < NUM_PREDEF_IDENT_IDS)
7320 return LocalID;
7321
7322 ContinuousRangeMap<uint32_t, int, 2>::iterator I
7323 = M.IdentifierRemap.find(LocalID - NUM_PREDEF_IDENT_IDS);
7324 assert(I != M.IdentifierRemap.end()
7325 && "Invalid index into identifier index remap");
7326
7327 return LocalID + I->second;
7328}
7329
Argyrios Kyrtzidiseb663da2013-03-22 21:12:57 +00007330MacroInfo *ASTReader::getMacro(MacroID ID) {
Guy Benyei11169dd2012-12-18 14:30:41 +00007331 if (ID == 0)
Craig Toppera13603a2014-05-22 05:54:18 +00007332 return nullptr;
Guy Benyei11169dd2012-12-18 14:30:41 +00007333
7334 if (MacrosLoaded.empty()) {
7335 Error("no macro table in AST file");
Craig Toppera13603a2014-05-22 05:54:18 +00007336 return nullptr;
Guy Benyei11169dd2012-12-18 14:30:41 +00007337 }
7338
7339 ID -= NUM_PREDEF_MACRO_IDS;
7340 if (!MacrosLoaded[ID]) {
7341 GlobalMacroMapType::iterator I
7342 = GlobalMacroMap.find(ID + NUM_PREDEF_MACRO_IDS);
7343 assert(I != GlobalMacroMap.end() && "Corrupted global macro map");
7344 ModuleFile *M = I->second;
7345 unsigned Index = ID - M->BaseMacroID;
Argyrios Kyrtzidiseb663da2013-03-22 21:12:57 +00007346 MacrosLoaded[ID] = ReadMacroRecord(*M, M->MacroOffsets[Index]);
7347
7348 if (DeserializationListener)
7349 DeserializationListener->MacroRead(ID + NUM_PREDEF_MACRO_IDS,
7350 MacrosLoaded[ID]);
Guy Benyei11169dd2012-12-18 14:30:41 +00007351 }
7352
7353 return MacrosLoaded[ID];
7354}
7355
7356MacroID ASTReader::getGlobalMacroID(ModuleFile &M, unsigned LocalID) {
7357 if (LocalID < NUM_PREDEF_MACRO_IDS)
7358 return LocalID;
7359
7360 ContinuousRangeMap<uint32_t, int, 2>::iterator I
7361 = M.MacroRemap.find(LocalID - NUM_PREDEF_MACRO_IDS);
7362 assert(I != M.MacroRemap.end() && "Invalid index into macro index remap");
7363
7364 return LocalID + I->second;
7365}
7366
7367serialization::SubmoduleID
7368ASTReader::getGlobalSubmoduleID(ModuleFile &M, unsigned LocalID) {
7369 if (LocalID < NUM_PREDEF_SUBMODULE_IDS)
7370 return LocalID;
7371
7372 ContinuousRangeMap<uint32_t, int, 2>::iterator I
7373 = M.SubmoduleRemap.find(LocalID - NUM_PREDEF_SUBMODULE_IDS);
7374 assert(I != M.SubmoduleRemap.end()
7375 && "Invalid index into submodule index remap");
7376
7377 return LocalID + I->second;
7378}
7379
7380Module *ASTReader::getSubmodule(SubmoduleID GlobalID) {
7381 if (GlobalID < NUM_PREDEF_SUBMODULE_IDS) {
7382 assert(GlobalID == 0 && "Unhandled global submodule ID");
Craig Toppera13603a2014-05-22 05:54:18 +00007383 return nullptr;
Guy Benyei11169dd2012-12-18 14:30:41 +00007384 }
7385
7386 if (GlobalID > SubmodulesLoaded.size()) {
7387 Error("submodule ID out of range in AST file");
Craig Toppera13603a2014-05-22 05:54:18 +00007388 return nullptr;
Guy Benyei11169dd2012-12-18 14:30:41 +00007389 }
7390
7391 return SubmodulesLoaded[GlobalID - NUM_PREDEF_SUBMODULE_IDS];
7392}
Douglas Gregorc147b0b2013-01-12 01:29:50 +00007393
7394Module *ASTReader::getModule(unsigned ID) {
7395 return getSubmodule(ID);
7396}
7397
Guy Benyei11169dd2012-12-18 14:30:41 +00007398Selector ASTReader::getLocalSelector(ModuleFile &M, unsigned LocalID) {
7399 return DecodeSelector(getGlobalSelectorID(M, LocalID));
7400}
7401
7402Selector ASTReader::DecodeSelector(serialization::SelectorID ID) {
7403 if (ID == 0)
7404 return Selector();
7405
7406 if (ID > SelectorsLoaded.size()) {
7407 Error("selector ID out of range in AST file");
7408 return Selector();
7409 }
7410
Craig Toppera13603a2014-05-22 05:54:18 +00007411 if (SelectorsLoaded[ID - 1].getAsOpaquePtr() == nullptr) {
Guy Benyei11169dd2012-12-18 14:30:41 +00007412 // Load this selector from the selector table.
7413 GlobalSelectorMapType::iterator I = GlobalSelectorMap.find(ID);
7414 assert(I != GlobalSelectorMap.end() && "Corrupted global selector map");
7415 ModuleFile &M = *I->second;
7416 ASTSelectorLookupTrait Trait(*this, M);
7417 unsigned Idx = ID - M.BaseSelectorID - NUM_PREDEF_SELECTOR_IDS;
7418 SelectorsLoaded[ID - 1] =
7419 Trait.ReadKey(M.SelectorLookupTableData + M.SelectorOffsets[Idx], 0);
7420 if (DeserializationListener)
7421 DeserializationListener->SelectorRead(ID, SelectorsLoaded[ID - 1]);
7422 }
7423
7424 return SelectorsLoaded[ID - 1];
7425}
7426
7427Selector ASTReader::GetExternalSelector(serialization::SelectorID ID) {
7428 return DecodeSelector(ID);
7429}
7430
7431uint32_t ASTReader::GetNumExternalSelectors() {
7432 // ID 0 (the null selector) is considered an external selector.
7433 return getTotalNumSelectors() + 1;
7434}
7435
7436serialization::SelectorID
7437ASTReader::getGlobalSelectorID(ModuleFile &M, unsigned LocalID) const {
7438 if (LocalID < NUM_PREDEF_SELECTOR_IDS)
7439 return LocalID;
7440
7441 ContinuousRangeMap<uint32_t, int, 2>::iterator I
7442 = M.SelectorRemap.find(LocalID - NUM_PREDEF_SELECTOR_IDS);
7443 assert(I != M.SelectorRemap.end()
7444 && "Invalid index into selector index remap");
7445
7446 return LocalID + I->second;
7447}
7448
7449DeclarationName
7450ASTReader::ReadDeclarationName(ModuleFile &F,
7451 const RecordData &Record, unsigned &Idx) {
7452 DeclarationName::NameKind Kind = (DeclarationName::NameKind)Record[Idx++];
7453 switch (Kind) {
7454 case DeclarationName::Identifier:
Douglas Gregorc8a992f2013-01-21 16:52:34 +00007455 return DeclarationName(GetIdentifierInfo(F, Record, Idx));
Guy Benyei11169dd2012-12-18 14:30:41 +00007456
7457 case DeclarationName::ObjCZeroArgSelector:
7458 case DeclarationName::ObjCOneArgSelector:
7459 case DeclarationName::ObjCMultiArgSelector:
7460 return DeclarationName(ReadSelector(F, Record, Idx));
7461
7462 case DeclarationName::CXXConstructorName:
7463 return Context.DeclarationNames.getCXXConstructorName(
7464 Context.getCanonicalType(readType(F, Record, Idx)));
7465
7466 case DeclarationName::CXXDestructorName:
7467 return Context.DeclarationNames.getCXXDestructorName(
7468 Context.getCanonicalType(readType(F, Record, Idx)));
7469
7470 case DeclarationName::CXXConversionFunctionName:
7471 return Context.DeclarationNames.getCXXConversionFunctionName(
7472 Context.getCanonicalType(readType(F, Record, Idx)));
7473
7474 case DeclarationName::CXXOperatorName:
7475 return Context.DeclarationNames.getCXXOperatorName(
7476 (OverloadedOperatorKind)Record[Idx++]);
7477
7478 case DeclarationName::CXXLiteralOperatorName:
7479 return Context.DeclarationNames.getCXXLiteralOperatorName(
7480 GetIdentifierInfo(F, Record, Idx));
7481
7482 case DeclarationName::CXXUsingDirective:
7483 return DeclarationName::getUsingDirectiveName();
7484 }
7485
7486 llvm_unreachable("Invalid NameKind!");
7487}
7488
7489void ASTReader::ReadDeclarationNameLoc(ModuleFile &F,
7490 DeclarationNameLoc &DNLoc,
7491 DeclarationName Name,
7492 const RecordData &Record, unsigned &Idx) {
7493 switch (Name.getNameKind()) {
7494 case DeclarationName::CXXConstructorName:
7495 case DeclarationName::CXXDestructorName:
7496 case DeclarationName::CXXConversionFunctionName:
7497 DNLoc.NamedType.TInfo = GetTypeSourceInfo(F, Record, Idx);
7498 break;
7499
7500 case DeclarationName::CXXOperatorName:
7501 DNLoc.CXXOperatorName.BeginOpNameLoc
7502 = ReadSourceLocation(F, Record, Idx).getRawEncoding();
7503 DNLoc.CXXOperatorName.EndOpNameLoc
7504 = ReadSourceLocation(F, Record, Idx).getRawEncoding();
7505 break;
7506
7507 case DeclarationName::CXXLiteralOperatorName:
7508 DNLoc.CXXLiteralOperatorName.OpNameLoc
7509 = ReadSourceLocation(F, Record, Idx).getRawEncoding();
7510 break;
7511
7512 case DeclarationName::Identifier:
7513 case DeclarationName::ObjCZeroArgSelector:
7514 case DeclarationName::ObjCOneArgSelector:
7515 case DeclarationName::ObjCMultiArgSelector:
7516 case DeclarationName::CXXUsingDirective:
7517 break;
7518 }
7519}
7520
7521void ASTReader::ReadDeclarationNameInfo(ModuleFile &F,
7522 DeclarationNameInfo &NameInfo,
7523 const RecordData &Record, unsigned &Idx) {
7524 NameInfo.setName(ReadDeclarationName(F, Record, Idx));
7525 NameInfo.setLoc(ReadSourceLocation(F, Record, Idx));
7526 DeclarationNameLoc DNLoc;
7527 ReadDeclarationNameLoc(F, DNLoc, NameInfo.getName(), Record, Idx);
7528 NameInfo.setInfo(DNLoc);
7529}
7530
7531void ASTReader::ReadQualifierInfo(ModuleFile &F, QualifierInfo &Info,
7532 const RecordData &Record, unsigned &Idx) {
7533 Info.QualifierLoc = ReadNestedNameSpecifierLoc(F, Record, Idx);
7534 unsigned NumTPLists = Record[Idx++];
7535 Info.NumTemplParamLists = NumTPLists;
7536 if (NumTPLists) {
7537 Info.TemplParamLists = new (Context) TemplateParameterList*[NumTPLists];
7538 for (unsigned i=0; i != NumTPLists; ++i)
7539 Info.TemplParamLists[i] = ReadTemplateParameterList(F, Record, Idx);
7540 }
7541}
7542
7543TemplateName
7544ASTReader::ReadTemplateName(ModuleFile &F, const RecordData &Record,
7545 unsigned &Idx) {
7546 TemplateName::NameKind Kind = (TemplateName::NameKind)Record[Idx++];
7547 switch (Kind) {
7548 case TemplateName::Template:
7549 return TemplateName(ReadDeclAs<TemplateDecl>(F, Record, Idx));
7550
7551 case TemplateName::OverloadedTemplate: {
7552 unsigned size = Record[Idx++];
7553 UnresolvedSet<8> Decls;
7554 while (size--)
7555 Decls.addDecl(ReadDeclAs<NamedDecl>(F, Record, Idx));
7556
7557 return Context.getOverloadedTemplateName(Decls.begin(), Decls.end());
7558 }
7559
7560 case TemplateName::QualifiedTemplate: {
7561 NestedNameSpecifier *NNS = ReadNestedNameSpecifier(F, Record, Idx);
7562 bool hasTemplKeyword = Record[Idx++];
7563 TemplateDecl *Template = ReadDeclAs<TemplateDecl>(F, Record, Idx);
7564 return Context.getQualifiedTemplateName(NNS, hasTemplKeyword, Template);
7565 }
7566
7567 case TemplateName::DependentTemplate: {
7568 NestedNameSpecifier *NNS = ReadNestedNameSpecifier(F, Record, Idx);
7569 if (Record[Idx++]) // isIdentifier
7570 return Context.getDependentTemplateName(NNS,
7571 GetIdentifierInfo(F, Record,
7572 Idx));
7573 return Context.getDependentTemplateName(NNS,
7574 (OverloadedOperatorKind)Record[Idx++]);
7575 }
7576
7577 case TemplateName::SubstTemplateTemplateParm: {
7578 TemplateTemplateParmDecl *param
7579 = ReadDeclAs<TemplateTemplateParmDecl>(F, Record, Idx);
7580 if (!param) return TemplateName();
7581 TemplateName replacement = ReadTemplateName(F, Record, Idx);
7582 return Context.getSubstTemplateTemplateParm(param, replacement);
7583 }
7584
7585 case TemplateName::SubstTemplateTemplateParmPack: {
7586 TemplateTemplateParmDecl *Param
7587 = ReadDeclAs<TemplateTemplateParmDecl>(F, Record, Idx);
7588 if (!Param)
7589 return TemplateName();
7590
7591 TemplateArgument ArgPack = ReadTemplateArgument(F, Record, Idx);
7592 if (ArgPack.getKind() != TemplateArgument::Pack)
7593 return TemplateName();
7594
7595 return Context.getSubstTemplateTemplateParmPack(Param, ArgPack);
7596 }
7597 }
7598
7599 llvm_unreachable("Unhandled template name kind!");
7600}
7601
7602TemplateArgument
7603ASTReader::ReadTemplateArgument(ModuleFile &F,
7604 const RecordData &Record, unsigned &Idx) {
7605 TemplateArgument::ArgKind Kind = (TemplateArgument::ArgKind)Record[Idx++];
7606 switch (Kind) {
7607 case TemplateArgument::Null:
7608 return TemplateArgument();
7609 case TemplateArgument::Type:
7610 return TemplateArgument(readType(F, Record, Idx));
7611 case TemplateArgument::Declaration: {
7612 ValueDecl *D = ReadDeclAs<ValueDecl>(F, Record, Idx);
7613 bool ForReferenceParam = Record[Idx++];
7614 return TemplateArgument(D, ForReferenceParam);
7615 }
7616 case TemplateArgument::NullPtr:
7617 return TemplateArgument(readType(F, Record, Idx), /*isNullPtr*/true);
7618 case TemplateArgument::Integral: {
7619 llvm::APSInt Value = ReadAPSInt(Record, Idx);
7620 QualType T = readType(F, Record, Idx);
7621 return TemplateArgument(Context, Value, T);
7622 }
7623 case TemplateArgument::Template:
7624 return TemplateArgument(ReadTemplateName(F, Record, Idx));
7625 case TemplateArgument::TemplateExpansion: {
7626 TemplateName Name = ReadTemplateName(F, Record, Idx);
David Blaikie05785d12013-02-20 22:23:23 +00007627 Optional<unsigned> NumTemplateExpansions;
Guy Benyei11169dd2012-12-18 14:30:41 +00007628 if (unsigned NumExpansions = Record[Idx++])
7629 NumTemplateExpansions = NumExpansions - 1;
7630 return TemplateArgument(Name, NumTemplateExpansions);
7631 }
7632 case TemplateArgument::Expression:
7633 return TemplateArgument(ReadExpr(F));
7634 case TemplateArgument::Pack: {
7635 unsigned NumArgs = Record[Idx++];
7636 TemplateArgument *Args = new (Context) TemplateArgument[NumArgs];
7637 for (unsigned I = 0; I != NumArgs; ++I)
7638 Args[I] = ReadTemplateArgument(F, Record, Idx);
7639 return TemplateArgument(Args, NumArgs);
7640 }
7641 }
7642
7643 llvm_unreachable("Unhandled template argument kind!");
7644}
7645
7646TemplateParameterList *
7647ASTReader::ReadTemplateParameterList(ModuleFile &F,
7648 const RecordData &Record, unsigned &Idx) {
7649 SourceLocation TemplateLoc = ReadSourceLocation(F, Record, Idx);
7650 SourceLocation LAngleLoc = ReadSourceLocation(F, Record, Idx);
7651 SourceLocation RAngleLoc = ReadSourceLocation(F, Record, Idx);
7652
7653 unsigned NumParams = Record[Idx++];
7654 SmallVector<NamedDecl *, 16> Params;
7655 Params.reserve(NumParams);
7656 while (NumParams--)
7657 Params.push_back(ReadDeclAs<NamedDecl>(F, Record, Idx));
7658
7659 TemplateParameterList* TemplateParams =
7660 TemplateParameterList::Create(Context, TemplateLoc, LAngleLoc,
7661 Params.data(), Params.size(), RAngleLoc);
7662 return TemplateParams;
7663}
7664
7665void
7666ASTReader::
Craig Topper5603df42013-07-05 19:34:19 +00007667ReadTemplateArgumentList(SmallVectorImpl<TemplateArgument> &TemplArgs,
Guy Benyei11169dd2012-12-18 14:30:41 +00007668 ModuleFile &F, const RecordData &Record,
7669 unsigned &Idx) {
7670 unsigned NumTemplateArgs = Record[Idx++];
7671 TemplArgs.reserve(NumTemplateArgs);
7672 while (NumTemplateArgs--)
7673 TemplArgs.push_back(ReadTemplateArgument(F, Record, Idx));
7674}
7675
7676/// \brief Read a UnresolvedSet structure.
Richard Smitha4ba74c2013-08-30 04:46:40 +00007677void ASTReader::ReadUnresolvedSet(ModuleFile &F, LazyASTUnresolvedSet &Set,
Guy Benyei11169dd2012-12-18 14:30:41 +00007678 const RecordData &Record, unsigned &Idx) {
7679 unsigned NumDecls = Record[Idx++];
7680 Set.reserve(Context, NumDecls);
7681 while (NumDecls--) {
Richard Smitha4ba74c2013-08-30 04:46:40 +00007682 DeclID ID = ReadDeclID(F, Record, Idx);
Guy Benyei11169dd2012-12-18 14:30:41 +00007683 AccessSpecifier AS = (AccessSpecifier)Record[Idx++];
Richard Smitha4ba74c2013-08-30 04:46:40 +00007684 Set.addLazyDecl(Context, ID, AS);
Guy Benyei11169dd2012-12-18 14:30:41 +00007685 }
7686}
7687
7688CXXBaseSpecifier
7689ASTReader::ReadCXXBaseSpecifier(ModuleFile &F,
7690 const RecordData &Record, unsigned &Idx) {
7691 bool isVirtual = static_cast<bool>(Record[Idx++]);
7692 bool isBaseOfClass = static_cast<bool>(Record[Idx++]);
7693 AccessSpecifier AS = static_cast<AccessSpecifier>(Record[Idx++]);
7694 bool inheritConstructors = static_cast<bool>(Record[Idx++]);
7695 TypeSourceInfo *TInfo = GetTypeSourceInfo(F, Record, Idx);
7696 SourceRange Range = ReadSourceRange(F, Record, Idx);
7697 SourceLocation EllipsisLoc = ReadSourceLocation(F, Record, Idx);
7698 CXXBaseSpecifier Result(Range, isVirtual, isBaseOfClass, AS, TInfo,
7699 EllipsisLoc);
7700 Result.setInheritConstructors(inheritConstructors);
7701 return Result;
7702}
7703
7704std::pair<CXXCtorInitializer **, unsigned>
7705ASTReader::ReadCXXCtorInitializers(ModuleFile &F, const RecordData &Record,
7706 unsigned &Idx) {
Craig Toppera13603a2014-05-22 05:54:18 +00007707 CXXCtorInitializer **CtorInitializers = nullptr;
Guy Benyei11169dd2012-12-18 14:30:41 +00007708 unsigned NumInitializers = Record[Idx++];
7709 if (NumInitializers) {
7710 CtorInitializers
7711 = new (Context) CXXCtorInitializer*[NumInitializers];
7712 for (unsigned i=0; i != NumInitializers; ++i) {
Craig Toppera13603a2014-05-22 05:54:18 +00007713 TypeSourceInfo *TInfo = nullptr;
Guy Benyei11169dd2012-12-18 14:30:41 +00007714 bool IsBaseVirtual = false;
Craig Toppera13603a2014-05-22 05:54:18 +00007715 FieldDecl *Member = nullptr;
7716 IndirectFieldDecl *IndirectMember = nullptr;
Guy Benyei11169dd2012-12-18 14:30:41 +00007717
7718 CtorInitializerType Type = (CtorInitializerType)Record[Idx++];
7719 switch (Type) {
7720 case CTOR_INITIALIZER_BASE:
7721 TInfo = GetTypeSourceInfo(F, Record, Idx);
7722 IsBaseVirtual = Record[Idx++];
7723 break;
7724
7725 case CTOR_INITIALIZER_DELEGATING:
7726 TInfo = GetTypeSourceInfo(F, Record, Idx);
7727 break;
7728
7729 case CTOR_INITIALIZER_MEMBER:
7730 Member = ReadDeclAs<FieldDecl>(F, Record, Idx);
7731 break;
7732
7733 case CTOR_INITIALIZER_INDIRECT_MEMBER:
7734 IndirectMember = ReadDeclAs<IndirectFieldDecl>(F, Record, Idx);
7735 break;
7736 }
7737
7738 SourceLocation MemberOrEllipsisLoc = ReadSourceLocation(F, Record, Idx);
7739 Expr *Init = ReadExpr(F);
7740 SourceLocation LParenLoc = ReadSourceLocation(F, Record, Idx);
7741 SourceLocation RParenLoc = ReadSourceLocation(F, Record, Idx);
7742 bool IsWritten = Record[Idx++];
7743 unsigned SourceOrderOrNumArrayIndices;
7744 SmallVector<VarDecl *, 8> Indices;
7745 if (IsWritten) {
7746 SourceOrderOrNumArrayIndices = Record[Idx++];
7747 } else {
7748 SourceOrderOrNumArrayIndices = Record[Idx++];
7749 Indices.reserve(SourceOrderOrNumArrayIndices);
7750 for (unsigned i=0; i != SourceOrderOrNumArrayIndices; ++i)
7751 Indices.push_back(ReadDeclAs<VarDecl>(F, Record, Idx));
7752 }
7753
7754 CXXCtorInitializer *BOMInit;
7755 if (Type == CTOR_INITIALIZER_BASE) {
7756 BOMInit = new (Context) CXXCtorInitializer(Context, TInfo, IsBaseVirtual,
7757 LParenLoc, Init, RParenLoc,
7758 MemberOrEllipsisLoc);
7759 } else if (Type == CTOR_INITIALIZER_DELEGATING) {
7760 BOMInit = new (Context) CXXCtorInitializer(Context, TInfo, LParenLoc,
7761 Init, RParenLoc);
7762 } else if (IsWritten) {
7763 if (Member)
7764 BOMInit = new (Context) CXXCtorInitializer(Context, Member, MemberOrEllipsisLoc,
7765 LParenLoc, Init, RParenLoc);
7766 else
7767 BOMInit = new (Context) CXXCtorInitializer(Context, IndirectMember,
7768 MemberOrEllipsisLoc, LParenLoc,
7769 Init, RParenLoc);
7770 } else {
Argyrios Kyrtzidis794671d2013-05-30 23:59:46 +00007771 if (IndirectMember) {
7772 assert(Indices.empty() && "Indirect field improperly initialized");
7773 BOMInit = new (Context) CXXCtorInitializer(Context, IndirectMember,
7774 MemberOrEllipsisLoc, LParenLoc,
7775 Init, RParenLoc);
7776 } else {
7777 BOMInit = CXXCtorInitializer::Create(Context, Member, MemberOrEllipsisLoc,
7778 LParenLoc, Init, RParenLoc,
7779 Indices.data(), Indices.size());
7780 }
Guy Benyei11169dd2012-12-18 14:30:41 +00007781 }
7782
7783 if (IsWritten)
7784 BOMInit->setSourceOrder(SourceOrderOrNumArrayIndices);
7785 CtorInitializers[i] = BOMInit;
7786 }
7787 }
7788
7789 return std::make_pair(CtorInitializers, NumInitializers);
7790}
7791
7792NestedNameSpecifier *
7793ASTReader::ReadNestedNameSpecifier(ModuleFile &F,
7794 const RecordData &Record, unsigned &Idx) {
7795 unsigned N = Record[Idx++];
Craig Toppera13603a2014-05-22 05:54:18 +00007796 NestedNameSpecifier *NNS = nullptr, *Prev = nullptr;
Guy Benyei11169dd2012-12-18 14:30:41 +00007797 for (unsigned I = 0; I != N; ++I) {
7798 NestedNameSpecifier::SpecifierKind Kind
7799 = (NestedNameSpecifier::SpecifierKind)Record[Idx++];
7800 switch (Kind) {
7801 case NestedNameSpecifier::Identifier: {
7802 IdentifierInfo *II = GetIdentifierInfo(F, Record, Idx);
7803 NNS = NestedNameSpecifier::Create(Context, Prev, II);
7804 break;
7805 }
7806
7807 case NestedNameSpecifier::Namespace: {
7808 NamespaceDecl *NS = ReadDeclAs<NamespaceDecl>(F, Record, Idx);
7809 NNS = NestedNameSpecifier::Create(Context, Prev, NS);
7810 break;
7811 }
7812
7813 case NestedNameSpecifier::NamespaceAlias: {
7814 NamespaceAliasDecl *Alias =ReadDeclAs<NamespaceAliasDecl>(F, Record, Idx);
7815 NNS = NestedNameSpecifier::Create(Context, Prev, Alias);
7816 break;
7817 }
7818
7819 case NestedNameSpecifier::TypeSpec:
7820 case NestedNameSpecifier::TypeSpecWithTemplate: {
7821 const Type *T = readType(F, Record, Idx).getTypePtrOrNull();
7822 if (!T)
Craig Toppera13603a2014-05-22 05:54:18 +00007823 return nullptr;
7824
Guy Benyei11169dd2012-12-18 14:30:41 +00007825 bool Template = Record[Idx++];
7826 NNS = NestedNameSpecifier::Create(Context, Prev, Template, T);
7827 break;
7828 }
7829
7830 case NestedNameSpecifier::Global: {
7831 NNS = NestedNameSpecifier::GlobalSpecifier(Context);
7832 // No associated value, and there can't be a prefix.
7833 break;
7834 }
7835 }
7836 Prev = NNS;
7837 }
7838 return NNS;
7839}
7840
7841NestedNameSpecifierLoc
7842ASTReader::ReadNestedNameSpecifierLoc(ModuleFile &F, const RecordData &Record,
7843 unsigned &Idx) {
7844 unsigned N = Record[Idx++];
7845 NestedNameSpecifierLocBuilder Builder;
7846 for (unsigned I = 0; I != N; ++I) {
7847 NestedNameSpecifier::SpecifierKind Kind
7848 = (NestedNameSpecifier::SpecifierKind)Record[Idx++];
7849 switch (Kind) {
7850 case NestedNameSpecifier::Identifier: {
7851 IdentifierInfo *II = GetIdentifierInfo(F, Record, Idx);
7852 SourceRange Range = ReadSourceRange(F, Record, Idx);
7853 Builder.Extend(Context, II, Range.getBegin(), Range.getEnd());
7854 break;
7855 }
7856
7857 case NestedNameSpecifier::Namespace: {
7858 NamespaceDecl *NS = ReadDeclAs<NamespaceDecl>(F, Record, Idx);
7859 SourceRange Range = ReadSourceRange(F, Record, Idx);
7860 Builder.Extend(Context, NS, Range.getBegin(), Range.getEnd());
7861 break;
7862 }
7863
7864 case NestedNameSpecifier::NamespaceAlias: {
7865 NamespaceAliasDecl *Alias =ReadDeclAs<NamespaceAliasDecl>(F, Record, Idx);
7866 SourceRange Range = ReadSourceRange(F, Record, Idx);
7867 Builder.Extend(Context, Alias, Range.getBegin(), Range.getEnd());
7868 break;
7869 }
7870
7871 case NestedNameSpecifier::TypeSpec:
7872 case NestedNameSpecifier::TypeSpecWithTemplate: {
7873 bool Template = Record[Idx++];
7874 TypeSourceInfo *T = GetTypeSourceInfo(F, Record, Idx);
7875 if (!T)
7876 return NestedNameSpecifierLoc();
7877 SourceLocation ColonColonLoc = ReadSourceLocation(F, Record, Idx);
7878
7879 // FIXME: 'template' keyword location not saved anywhere, so we fake it.
7880 Builder.Extend(Context,
7881 Template? T->getTypeLoc().getBeginLoc() : SourceLocation(),
7882 T->getTypeLoc(), ColonColonLoc);
7883 break;
7884 }
7885
7886 case NestedNameSpecifier::Global: {
7887 SourceLocation ColonColonLoc = ReadSourceLocation(F, Record, Idx);
7888 Builder.MakeGlobal(Context, ColonColonLoc);
7889 break;
7890 }
7891 }
7892 }
7893
7894 return Builder.getWithLocInContext(Context);
7895}
7896
7897SourceRange
7898ASTReader::ReadSourceRange(ModuleFile &F, const RecordData &Record,
7899 unsigned &Idx) {
7900 SourceLocation beg = ReadSourceLocation(F, Record, Idx);
7901 SourceLocation end = ReadSourceLocation(F, Record, Idx);
7902 return SourceRange(beg, end);
7903}
7904
7905/// \brief Read an integral value
7906llvm::APInt ASTReader::ReadAPInt(const RecordData &Record, unsigned &Idx) {
7907 unsigned BitWidth = Record[Idx++];
7908 unsigned NumWords = llvm::APInt::getNumWords(BitWidth);
7909 llvm::APInt Result(BitWidth, NumWords, &Record[Idx]);
7910 Idx += NumWords;
7911 return Result;
7912}
7913
7914/// \brief Read a signed integral value
7915llvm::APSInt ASTReader::ReadAPSInt(const RecordData &Record, unsigned &Idx) {
7916 bool isUnsigned = Record[Idx++];
7917 return llvm::APSInt(ReadAPInt(Record, Idx), isUnsigned);
7918}
7919
7920/// \brief Read a floating-point value
Tim Northover178723a2013-01-22 09:46:51 +00007921llvm::APFloat ASTReader::ReadAPFloat(const RecordData &Record,
7922 const llvm::fltSemantics &Sem,
7923 unsigned &Idx) {
7924 return llvm::APFloat(Sem, ReadAPInt(Record, Idx));
Guy Benyei11169dd2012-12-18 14:30:41 +00007925}
7926
7927// \brief Read a string
7928std::string ASTReader::ReadString(const RecordData &Record, unsigned &Idx) {
7929 unsigned Len = Record[Idx++];
7930 std::string Result(Record.data() + Idx, Record.data() + Idx + Len);
7931 Idx += Len;
7932 return Result;
7933}
7934
7935VersionTuple ASTReader::ReadVersionTuple(const RecordData &Record,
7936 unsigned &Idx) {
7937 unsigned Major = Record[Idx++];
7938 unsigned Minor = Record[Idx++];
7939 unsigned Subminor = Record[Idx++];
7940 if (Minor == 0)
7941 return VersionTuple(Major);
7942 if (Subminor == 0)
7943 return VersionTuple(Major, Minor - 1);
7944 return VersionTuple(Major, Minor - 1, Subminor - 1);
7945}
7946
7947CXXTemporary *ASTReader::ReadCXXTemporary(ModuleFile &F,
7948 const RecordData &Record,
7949 unsigned &Idx) {
7950 CXXDestructorDecl *Decl = ReadDeclAs<CXXDestructorDecl>(F, Record, Idx);
7951 return CXXTemporary::Create(Context, Decl);
7952}
7953
7954DiagnosticBuilder ASTReader::Diag(unsigned DiagID) {
Argyrios Kyrtzidisdc9fdaf2013-05-24 05:44:08 +00007955 return Diag(CurrentImportLoc, DiagID);
Guy Benyei11169dd2012-12-18 14:30:41 +00007956}
7957
7958DiagnosticBuilder ASTReader::Diag(SourceLocation Loc, unsigned DiagID) {
7959 return Diags.Report(Loc, DiagID);
7960}
7961
7962/// \brief Retrieve the identifier table associated with the
7963/// preprocessor.
7964IdentifierTable &ASTReader::getIdentifierTable() {
7965 return PP.getIdentifierTable();
7966}
7967
7968/// \brief Record that the given ID maps to the given switch-case
7969/// statement.
7970void ASTReader::RecordSwitchCaseID(SwitchCase *SC, unsigned ID) {
Craig Toppera13603a2014-05-22 05:54:18 +00007971 assert((*CurrSwitchCaseStmts)[ID] == nullptr &&
Guy Benyei11169dd2012-12-18 14:30:41 +00007972 "Already have a SwitchCase with this ID");
7973 (*CurrSwitchCaseStmts)[ID] = SC;
7974}
7975
7976/// \brief Retrieve the switch-case statement with the given ID.
7977SwitchCase *ASTReader::getSwitchCaseWithID(unsigned ID) {
Craig Toppera13603a2014-05-22 05:54:18 +00007978 assert((*CurrSwitchCaseStmts)[ID] != nullptr && "No SwitchCase with this ID");
Guy Benyei11169dd2012-12-18 14:30:41 +00007979 return (*CurrSwitchCaseStmts)[ID];
7980}
7981
7982void ASTReader::ClearSwitchCaseIDs() {
7983 CurrSwitchCaseStmts->clear();
7984}
7985
7986void ASTReader::ReadComments() {
7987 std::vector<RawComment *> Comments;
Chris Lattner7fb3bef2013-01-20 00:56:42 +00007988 for (SmallVectorImpl<std::pair<BitstreamCursor,
Guy Benyei11169dd2012-12-18 14:30:41 +00007989 serialization::ModuleFile *> >::iterator
7990 I = CommentsCursors.begin(),
7991 E = CommentsCursors.end();
7992 I != E; ++I) {
Dmitri Gribenko9ee0e302014-03-27 15:40:39 +00007993 Comments.clear();
Chris Lattner7fb3bef2013-01-20 00:56:42 +00007994 BitstreamCursor &Cursor = I->first;
Guy Benyei11169dd2012-12-18 14:30:41 +00007995 serialization::ModuleFile &F = *I->second;
7996 SavedStreamPosition SavedPosition(Cursor);
7997
7998 RecordData Record;
7999 while (true) {
Chris Lattner7fb3bef2013-01-20 00:56:42 +00008000 llvm::BitstreamEntry Entry =
8001 Cursor.advanceSkippingSubblocks(BitstreamCursor::AF_DontPopBlockAtEnd);
Dmitri Gribenko9ee0e302014-03-27 15:40:39 +00008002
Chris Lattner7fb3bef2013-01-20 00:56:42 +00008003 switch (Entry.Kind) {
8004 case llvm::BitstreamEntry::SubBlock: // Handled for us already.
8005 case llvm::BitstreamEntry::Error:
8006 Error("malformed block record in AST file");
8007 return;
8008 case llvm::BitstreamEntry::EndBlock:
8009 goto NextCursor;
8010 case llvm::BitstreamEntry::Record:
8011 // The interesting case.
Guy Benyei11169dd2012-12-18 14:30:41 +00008012 break;
Guy Benyei11169dd2012-12-18 14:30:41 +00008013 }
8014
8015 // Read a record.
8016 Record.clear();
Chris Lattner0e6c9402013-01-20 02:38:54 +00008017 switch ((CommentRecordTypes)Cursor.readRecord(Entry.ID, Record)) {
Guy Benyei11169dd2012-12-18 14:30:41 +00008018 case COMMENTS_RAW_COMMENT: {
8019 unsigned Idx = 0;
8020 SourceRange SR = ReadSourceRange(F, Record, Idx);
8021 RawComment::CommentKind Kind =
8022 (RawComment::CommentKind) Record[Idx++];
8023 bool IsTrailingComment = Record[Idx++];
8024 bool IsAlmostTrailingComment = Record[Idx++];
Dmitri Gribenkoa7d16ce2013-04-10 15:35:17 +00008025 Comments.push_back(new (Context) RawComment(
8026 SR, Kind, IsTrailingComment, IsAlmostTrailingComment,
8027 Context.getLangOpts().CommentOpts.ParseAllComments));
Guy Benyei11169dd2012-12-18 14:30:41 +00008028 break;
8029 }
8030 }
8031 }
Dmitri Gribenko9ee0e302014-03-27 15:40:39 +00008032 NextCursor:
8033 Context.Comments.addDeserializedComments(Comments);
Guy Benyei11169dd2012-12-18 14:30:41 +00008034 }
Guy Benyei11169dd2012-12-18 14:30:41 +00008035}
8036
Richard Smithcd45dbc2014-04-19 03:48:30 +00008037std::string ASTReader::getOwningModuleNameForDiagnostic(const Decl *D) {
8038 // If we know the owning module, use it.
8039 if (Module *M = D->getOwningModule())
8040 return M->getFullModuleName();
8041
8042 // Otherwise, use the name of the top-level module the decl is within.
8043 if (ModuleFile *M = getOwningModuleFile(D))
8044 return M->ModuleName;
8045
8046 // Not from a module.
8047 return "";
8048}
8049
Guy Benyei11169dd2012-12-18 14:30:41 +00008050void ASTReader::finishPendingActions() {
Richard Smith851072e2014-05-19 20:59:20 +00008051 while (!PendingIdentifierInfos.empty() ||
8052 !PendingIncompleteDeclChains.empty() || !PendingDeclChains.empty() ||
Richard Smith2b9e3e32013-10-18 06:05:18 +00008053 !PendingMacroIDs.empty() || !PendingDeclContextInfos.empty() ||
Richard Smitha0ce9c42014-07-29 23:23:27 +00008054 !PendingUpdateRecords.empty()) {
Guy Benyei11169dd2012-12-18 14:30:41 +00008055 // If any identifiers with corresponding top-level declarations have
8056 // been loaded, load those declarations now.
Craig Topper79be4cd2013-07-05 04:33:53 +00008057 typedef llvm::DenseMap<IdentifierInfo *, SmallVector<Decl *, 2> >
8058 TopLevelDeclsMap;
8059 TopLevelDeclsMap TopLevelDecls;
8060
Guy Benyei11169dd2012-12-18 14:30:41 +00008061 while (!PendingIdentifierInfos.empty()) {
Douglas Gregor6168bd22013-02-18 15:53:43 +00008062 IdentifierInfo *II = PendingIdentifierInfos.back().first;
Richard Smithf0ae3c2d2014-03-28 17:31:23 +00008063 SmallVector<uint32_t, 4> DeclIDs =
8064 std::move(PendingIdentifierInfos.back().second);
Douglas Gregorcb15f082013-02-19 18:26:28 +00008065 PendingIdentifierInfos.pop_back();
Douglas Gregor6168bd22013-02-18 15:53:43 +00008066
8067 SetGloballyVisibleDecls(II, DeclIDs, &TopLevelDecls[II]);
Guy Benyei11169dd2012-12-18 14:30:41 +00008068 }
Richard Smithf0ae3c2d2014-03-28 17:31:23 +00008069
Richard Smith851072e2014-05-19 20:59:20 +00008070 // For each decl chain that we wanted to complete while deserializing, mark
8071 // it as "still needs to be completed".
8072 for (unsigned I = 0; I != PendingIncompleteDeclChains.size(); ++I) {
8073 markIncompleteDeclChain(PendingIncompleteDeclChains[I]);
8074 }
8075 PendingIncompleteDeclChains.clear();
8076
Guy Benyei11169dd2012-12-18 14:30:41 +00008077 // Load pending declaration chains.
8078 for (unsigned I = 0; I != PendingDeclChains.size(); ++I) {
8079 loadPendingDeclChain(PendingDeclChains[I]);
8080 PendingDeclChainsKnown.erase(PendingDeclChains[I]);
8081 }
8082 PendingDeclChains.clear();
8083
Douglas Gregor6168bd22013-02-18 15:53:43 +00008084 // Make the most recent of the top-level declarations visible.
Craig Topper79be4cd2013-07-05 04:33:53 +00008085 for (TopLevelDeclsMap::iterator TLD = TopLevelDecls.begin(),
8086 TLDEnd = TopLevelDecls.end(); TLD != TLDEnd; ++TLD) {
Douglas Gregor6168bd22013-02-18 15:53:43 +00008087 IdentifierInfo *II = TLD->first;
8088 for (unsigned I = 0, N = TLD->second.size(); I != N; ++I) {
Argyrios Kyrtzidise5edbf92013-04-26 21:33:35 +00008089 pushExternalDeclIntoScope(cast<NamedDecl>(TLD->second[I]), II);
Douglas Gregor6168bd22013-02-18 15:53:43 +00008090 }
8091 }
8092
Guy Benyei11169dd2012-12-18 14:30:41 +00008093 // Load any pending macro definitions.
8094 for (unsigned I = 0; I != PendingMacroIDs.size(); ++I) {
Argyrios Kyrtzidiseb663da2013-03-22 21:12:57 +00008095 IdentifierInfo *II = PendingMacroIDs.begin()[I].first;
8096 SmallVector<PendingMacroInfo, 2> GlobalIDs;
8097 GlobalIDs.swap(PendingMacroIDs.begin()[I].second);
8098 // Initialize the macro history from chained-PCHs ahead of module imports.
Richard Smith49f906a2014-03-01 00:08:04 +00008099 for (unsigned IDIdx = 0, NumIDs = GlobalIDs.size(); IDIdx != NumIDs;
Argyrios Kyrtzidis719736c2013-01-19 03:14:56 +00008100 ++IDIdx) {
Argyrios Kyrtzidiseb663da2013-03-22 21:12:57 +00008101 const PendingMacroInfo &Info = GlobalIDs[IDIdx];
8102 if (Info.M->Kind != MK_Module)
8103 resolvePendingMacro(II, Info);
8104 }
8105 // Handle module imports.
Richard Smith49f906a2014-03-01 00:08:04 +00008106 for (unsigned IDIdx = 0, NumIDs = GlobalIDs.size(); IDIdx != NumIDs;
Argyrios Kyrtzidiseb663da2013-03-22 21:12:57 +00008107 ++IDIdx) {
8108 const PendingMacroInfo &Info = GlobalIDs[IDIdx];
8109 if (Info.M->Kind == MK_Module)
8110 resolvePendingMacro(II, Info);
Guy Benyei11169dd2012-12-18 14:30:41 +00008111 }
8112 }
8113 PendingMacroIDs.clear();
Argyrios Kyrtzidis83a6e3b2013-02-16 00:48:59 +00008114
8115 // Wire up the DeclContexts for Decls that we delayed setting until
8116 // recursive loading is completed.
8117 while (!PendingDeclContextInfos.empty()) {
8118 PendingDeclContextInfo Info = PendingDeclContextInfos.front();
8119 PendingDeclContextInfos.pop_front();
8120 DeclContext *SemaDC = cast<DeclContext>(GetDecl(Info.SemaDC));
8121 DeclContext *LexicalDC = cast<DeclContext>(GetDecl(Info.LexicalDC));
8122 Info.D->setDeclContextsImpl(SemaDC, LexicalDC, getContext());
8123 }
Richard Smith2b9e3e32013-10-18 06:05:18 +00008124
Richard Smithd1c46742014-04-30 02:24:17 +00008125 // Perform any pending declaration updates.
Richard Smithd6db68c2014-08-07 20:58:41 +00008126 while (!PendingUpdateRecords.empty()) {
Richard Smithd1c46742014-04-30 02:24:17 +00008127 auto Update = PendingUpdateRecords.pop_back_val();
8128 ReadingKindTracker ReadingKind(Read_Decl, *this);
8129 loadDeclUpdateRecords(Update.first, Update.second);
8130 }
Guy Benyei11169dd2012-12-18 14:30:41 +00008131 }
8132
8133 // If we deserialized any C++ or Objective-C class definitions, any
8134 // Objective-C protocol definitions, or any redeclarable templates, make sure
8135 // that all redeclarations point to the definitions. Note that this can only
8136 // happen now, after the redeclaration chains have been fully wired.
8137 for (llvm::SmallPtrSet<Decl *, 4>::iterator D = PendingDefinitions.begin(),
8138 DEnd = PendingDefinitions.end();
8139 D != DEnd; ++D) {
8140 if (TagDecl *TD = dyn_cast<TagDecl>(*D)) {
Richard Smith5b21db82014-04-23 18:20:42 +00008141 if (const TagType *TagT = dyn_cast<TagType>(TD->getTypeForDecl())) {
Guy Benyei11169dd2012-12-18 14:30:41 +00008142 // Make sure that the TagType points at the definition.
8143 const_cast<TagType*>(TagT)->decl = TD;
8144 }
8145
Aaron Ballman86c93902014-03-06 23:45:36 +00008146 if (auto RD = dyn_cast<CXXRecordDecl>(*D)) {
8147 for (auto R : RD->redecls())
8148 cast<CXXRecordDecl>(R)->DefinitionData = RD->DefinitionData;
Guy Benyei11169dd2012-12-18 14:30:41 +00008149 }
8150
8151 continue;
8152 }
8153
Aaron Ballman86c93902014-03-06 23:45:36 +00008154 if (auto ID = dyn_cast<ObjCInterfaceDecl>(*D)) {
Guy Benyei11169dd2012-12-18 14:30:41 +00008155 // Make sure that the ObjCInterfaceType points at the definition.
8156 const_cast<ObjCInterfaceType *>(cast<ObjCInterfaceType>(ID->TypeForDecl))
8157 ->Decl = ID;
8158
Aaron Ballman86c93902014-03-06 23:45:36 +00008159 for (auto R : ID->redecls())
Guy Benyei11169dd2012-12-18 14:30:41 +00008160 R->Data = ID->Data;
8161
8162 continue;
8163 }
8164
Aaron Ballman86c93902014-03-06 23:45:36 +00008165 if (auto PD = dyn_cast<ObjCProtocolDecl>(*D)) {
8166 for (auto R : PD->redecls())
Guy Benyei11169dd2012-12-18 14:30:41 +00008167 R->Data = PD->Data;
8168
8169 continue;
8170 }
8171
Aaron Ballman86c93902014-03-06 23:45:36 +00008172 auto RTD = cast<RedeclarableTemplateDecl>(*D)->getCanonicalDecl();
8173 for (auto R : RTD->redecls())
Guy Benyei11169dd2012-12-18 14:30:41 +00008174 R->Common = RTD->Common;
8175 }
8176 PendingDefinitions.clear();
8177
8178 // Load the bodies of any functions or methods we've encountered. We do
8179 // this now (delayed) so that we can be sure that the declaration chains
8180 // have been fully wired up.
8181 for (PendingBodiesMap::iterator PB = PendingBodies.begin(),
8182 PBEnd = PendingBodies.end();
8183 PB != PBEnd; ++PB) {
8184 if (FunctionDecl *FD = dyn_cast<FunctionDecl>(PB->first)) {
8185 // FIXME: Check for =delete/=default?
8186 // FIXME: Complain about ODR violations here?
8187 if (!getContext().getLangOpts().Modules || !FD->hasBody())
8188 FD->setLazyBody(PB->second);
8189 continue;
8190 }
8191
8192 ObjCMethodDecl *MD = cast<ObjCMethodDecl>(PB->first);
8193 if (!getContext().getLangOpts().Modules || !MD->hasBody())
8194 MD->setLazyBody(PB->second);
8195 }
8196 PendingBodies.clear();
Richard Smitha0ce9c42014-07-29 23:23:27 +00008197}
8198
8199void ASTReader::diagnoseOdrViolations() {
8200 // Trigger the import of the full definition of each class that had any
8201 // odr-merging problems, so we can produce better diagnostics for them.
8202 for (auto &Merge : PendingOdrMergeFailures) {
8203 Merge.first->buildLookup();
8204 Merge.first->decls_begin();
8205 Merge.first->bases_begin();
8206 Merge.first->vbases_begin();
8207 for (auto *RD : Merge.second) {
8208 RD->decls_begin();
8209 RD->bases_begin();
8210 RD->vbases_begin();
8211 }
8212 }
8213
8214 // For each declaration from a merged context, check that the canonical
8215 // definition of that context also contains a declaration of the same
8216 // entity.
8217 //
8218 // Caution: this loop does things that might invalidate iterators into
8219 // PendingOdrMergeChecks. Don't turn this into a range-based for loop!
8220 while (!PendingOdrMergeChecks.empty()) {
8221 NamedDecl *D = PendingOdrMergeChecks.pop_back_val();
8222
8223 // FIXME: Skip over implicit declarations for now. This matters for things
8224 // like implicitly-declared special member functions. This isn't entirely
8225 // correct; we can end up with multiple unmerged declarations of the same
8226 // implicit entity.
8227 if (D->isImplicit())
8228 continue;
8229
8230 DeclContext *CanonDef = D->getDeclContext();
8231 DeclContext::lookup_result R = CanonDef->lookup(D->getDeclName());
8232
8233 bool Found = false;
8234 const Decl *DCanon = D->getCanonicalDecl();
8235
8236 llvm::SmallVector<const NamedDecl*, 4> Candidates;
8237 for (DeclContext::lookup_iterator I = R.begin(), E = R.end();
8238 !Found && I != E; ++I) {
8239 for (auto RI : (*I)->redecls()) {
8240 if (RI->getLexicalDeclContext() == CanonDef) {
8241 // This declaration is present in the canonical definition. If it's
8242 // in the same redecl chain, it's the one we're looking for.
8243 if (RI->getCanonicalDecl() == DCanon)
8244 Found = true;
8245 else
8246 Candidates.push_back(cast<NamedDecl>(RI));
8247 break;
8248 }
8249 }
8250 }
8251
8252 if (!Found) {
8253 D->setInvalidDecl();
8254
8255 std::string CanonDefModule =
8256 getOwningModuleNameForDiagnostic(cast<Decl>(CanonDef));
8257 Diag(D->getLocation(), diag::err_module_odr_violation_missing_decl)
8258 << D << getOwningModuleNameForDiagnostic(D)
8259 << CanonDef << CanonDefModule.empty() << CanonDefModule;
8260
8261 if (Candidates.empty())
8262 Diag(cast<Decl>(CanonDef)->getLocation(),
8263 diag::note_module_odr_violation_no_possible_decls) << D;
8264 else {
8265 for (unsigned I = 0, N = Candidates.size(); I != N; ++I)
8266 Diag(Candidates[I]->getLocation(),
8267 diag::note_module_odr_violation_possible_decl)
8268 << Candidates[I];
8269 }
8270
8271 DiagnosedOdrMergeFailures.insert(CanonDef);
8272 }
8273 }
Richard Smithcd45dbc2014-04-19 03:48:30 +00008274
8275 // Issue any pending ODR-failure diagnostics.
8276 for (auto &Merge : PendingOdrMergeFailures) {
Richard Smitha0ce9c42014-07-29 23:23:27 +00008277 // If we've already pointed out a specific problem with this class, don't
8278 // bother issuing a general "something's different" diagnostic.
Richard Smithcd45dbc2014-04-19 03:48:30 +00008279 if (!DiagnosedOdrMergeFailures.insert(Merge.first))
8280 continue;
8281
8282 bool Diagnosed = false;
8283 for (auto *RD : Merge.second) {
8284 // Multiple different declarations got merged together; tell the user
8285 // where they came from.
8286 if (Merge.first != RD) {
8287 // FIXME: Walk the definition, figure out what's different,
8288 // and diagnose that.
8289 if (!Diagnosed) {
8290 std::string Module = getOwningModuleNameForDiagnostic(Merge.first);
8291 Diag(Merge.first->getLocation(),
8292 diag::err_module_odr_violation_different_definitions)
8293 << Merge.first << Module.empty() << Module;
8294 Diagnosed = true;
8295 }
8296
8297 Diag(RD->getLocation(),
8298 diag::note_module_odr_violation_different_definitions)
8299 << getOwningModuleNameForDiagnostic(RD);
8300 }
8301 }
8302
8303 if (!Diagnosed) {
8304 // All definitions are updates to the same declaration. This happens if a
8305 // module instantiates the declaration of a class template specialization
8306 // and two or more other modules instantiate its definition.
8307 //
8308 // FIXME: Indicate which modules had instantiations of this definition.
8309 // FIXME: How can this even happen?
8310 Diag(Merge.first->getLocation(),
8311 diag::err_module_odr_violation_different_instantiations)
8312 << Merge.first;
8313 }
8314 }
8315 PendingOdrMergeFailures.clear();
Guy Benyei11169dd2012-12-18 14:30:41 +00008316}
8317
8318void ASTReader::FinishedDeserializing() {
8319 assert(NumCurrentElementsDeserializing &&
8320 "FinishedDeserializing not paired with StartedDeserializing");
8321 if (NumCurrentElementsDeserializing == 1) {
8322 // We decrease NumCurrentElementsDeserializing only after pending actions
8323 // are finished, to avoid recursively re-calling finishPendingActions().
8324 finishPendingActions();
8325 }
8326 --NumCurrentElementsDeserializing;
8327
Richard Smitha0ce9c42014-07-29 23:23:27 +00008328 if (NumCurrentElementsDeserializing == 0) {
8329 diagnoseOdrViolations();
8330
Richard Smith04d05b52014-03-23 00:27:18 +00008331 // We are not in recursive loading, so it's safe to pass the "interesting"
8332 // decls to the consumer.
Richard Smitha0ce9c42014-07-29 23:23:27 +00008333 if (Consumer)
8334 PassInterestingDeclsToConsumer();
Guy Benyei11169dd2012-12-18 14:30:41 +00008335 }
8336}
8337
Argyrios Kyrtzidise5edbf92013-04-26 21:33:35 +00008338void ASTReader::pushExternalDeclIntoScope(NamedDecl *D, DeclarationName Name) {
Rafael Espindola7b56f6c2013-10-19 16:55:03 +00008339 D = D->getMostRecentDecl();
Argyrios Kyrtzidise5edbf92013-04-26 21:33:35 +00008340
8341 if (SemaObj->IdResolver.tryAddTopLevelDecl(D, Name) && SemaObj->TUScope) {
8342 SemaObj->TUScope->AddDecl(D);
8343 } else if (SemaObj->TUScope) {
8344 // Adding the decl to IdResolver may have failed because it was already in
8345 // (even though it was not added in scope). If it is already in, make sure
8346 // it gets in the scope as well.
8347 if (std::find(SemaObj->IdResolver.begin(Name),
8348 SemaObj->IdResolver.end(), D) != SemaObj->IdResolver.end())
8349 SemaObj->TUScope->AddDecl(D);
8350 }
8351}
8352
Nico Weber824285e2014-05-08 04:26:47 +00008353ASTReader::ASTReader(Preprocessor &PP, ASTContext &Context, StringRef isysroot,
8354 bool DisableValidation, bool AllowASTWithCompilerErrors,
8355 bool AllowConfigurationMismatch, bool ValidateSystemInputs,
Ben Langmuir2cb4a782014-02-05 22:21:15 +00008356 bool UseGlobalIndex)
Craig Toppera13603a2014-05-22 05:54:18 +00008357 : Listener(new PCHValidator(PP, *this)), DeserializationListener(nullptr),
Nico Weber824285e2014-05-08 04:26:47 +00008358 OwnsDeserializationListener(false), SourceMgr(PP.getSourceManager()),
Craig Toppera13603a2014-05-22 05:54:18 +00008359 FileMgr(PP.getFileManager()), Diags(PP.getDiagnostics()),
8360 SemaObj(nullptr), PP(PP), Context(Context), Consumer(nullptr),
8361 ModuleMgr(PP.getFileManager()), isysroot(isysroot),
8362 DisableValidation(DisableValidation),
Nico Weber824285e2014-05-08 04:26:47 +00008363 AllowASTWithCompilerErrors(AllowASTWithCompilerErrors),
8364 AllowConfigurationMismatch(AllowConfigurationMismatch),
8365 ValidateSystemInputs(ValidateSystemInputs),
8366 UseGlobalIndex(UseGlobalIndex), TriedLoadingGlobalIndex(false),
Richard Smith053f6c62014-05-16 23:01:30 +00008367 CurrSwitchCaseStmts(&SwitchCaseStmts),
Nico Weber824285e2014-05-08 04:26:47 +00008368 NumSLocEntriesRead(0), TotalNumSLocEntries(0), NumStatementsRead(0),
8369 TotalNumStatements(0), NumMacrosRead(0), TotalNumMacros(0),
8370 NumIdentifierLookups(0), NumIdentifierLookupHits(0), NumSelectorsRead(0),
8371 NumMethodPoolEntriesRead(0), NumMethodPoolLookups(0),
8372 NumMethodPoolHits(0), NumMethodPoolTableLookups(0),
8373 NumMethodPoolTableHits(0), TotalNumMethodPoolEntries(0),
8374 NumLexicalDeclContextsRead(0), TotalLexicalDeclContexts(0),
8375 NumVisibleDeclContextsRead(0), TotalVisibleDeclContexts(0),
8376 TotalModulesSizeInBits(0), NumCurrentElementsDeserializing(0),
8377 PassingDeclsToConsumer(false), NumCXXBaseSpecifiersLoaded(0),
8378 ReadingKind(Read_None) {
Guy Benyei11169dd2012-12-18 14:30:41 +00008379 SourceMgr.setExternalSLocEntrySource(this);
8380}
8381
8382ASTReader::~ASTReader() {
Nico Weber824285e2014-05-08 04:26:47 +00008383 if (OwnsDeserializationListener)
8384 delete DeserializationListener;
8385
Guy Benyei11169dd2012-12-18 14:30:41 +00008386 for (DeclContextVisibleUpdatesPending::iterator
8387 I = PendingVisibleUpdates.begin(),
8388 E = PendingVisibleUpdates.end();
8389 I != E; ++I) {
8390 for (DeclContextVisibleUpdates::iterator J = I->second.begin(),
8391 F = I->second.end();
8392 J != F; ++J)
8393 delete J->first;
8394 }
8395}