blob: f9522aeaa3646a12589a9e11cdfcc4f9ae8bafa2 [file] [log] [blame]
Richard Smith9e2341d2015-03-23 03:25:59 +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"
Adrian Prantlbb165fb2015-06-20 18:53:08 +000022#include "clang/Frontend/PCHContainerOperations.h"
Guy Benyei11169dd2012-12-18 14:30:41 +000023#include "clang/AST/NestedNameSpecifier.h"
24#include "clang/AST/Type.h"
25#include "clang/AST/TypeLocVisitor.h"
Benjamin Kramerf3ca26982014-05-10 16:31:55 +000026#include "clang/Basic/DiagnosticOptions.h"
Guy Benyei11169dd2012-12-18 14:30:41 +000027#include "clang/Basic/FileManager.h"
Guy Benyei11169dd2012-12-18 14:30:41 +000028#include "clang/Basic/SourceManager.h"
29#include "clang/Basic/SourceManagerInternals.h"
30#include "clang/Basic/TargetInfo.h"
31#include "clang/Basic/TargetOptions.h"
32#include "clang/Basic/Version.h"
33#include "clang/Basic/VersionTuple.h"
Ben Langmuirb92de022014-04-29 16:25:26 +000034#include "clang/Frontend/Utils.h"
Guy Benyei11169dd2012-12-18 14:30:41 +000035#include "clang/Lex/HeaderSearch.h"
36#include "clang/Lex/HeaderSearchOptions.h"
37#include "clang/Lex/MacroInfo.h"
38#include "clang/Lex/PreprocessingRecord.h"
39#include "clang/Lex/Preprocessor.h"
40#include "clang/Lex/PreprocessorOptions.h"
41#include "clang/Sema/Scope.h"
42#include "clang/Sema/Sema.h"
43#include "clang/Serialization/ASTDeserializationListener.h"
Douglas Gregore060e572013-01-25 01:03:03 +000044#include "clang/Serialization/GlobalModuleIndex.h"
Guy Benyei11169dd2012-12-18 14:30:41 +000045#include "clang/Serialization/ModuleManager.h"
46#include "clang/Serialization/SerializationDiagnostic.h"
Argyrios Kyrtzidis5c2a3452013-03-06 18:12:47 +000047#include "llvm/ADT/Hashing.h"
Guy Benyei11169dd2012-12-18 14:30:41 +000048#include "llvm/ADT/StringExtras.h"
49#include "llvm/Bitcode/BitstreamReader.h"
50#include "llvm/Support/ErrorHandling.h"
51#include "llvm/Support/FileSystem.h"
52#include "llvm/Support/MemoryBuffer.h"
53#include "llvm/Support/Path.h"
54#include "llvm/Support/SaveAndRestore.h"
Dmitri Gribenkof430da42014-02-12 10:33:14 +000055#include "llvm/Support/raw_ostream.h"
Guy Benyei11169dd2012-12-18 14:30:41 +000056#include <algorithm>
Chris Lattner91f373e2013-01-20 00:57:52 +000057#include <cstdio>
Guy Benyei11169dd2012-12-18 14:30:41 +000058#include <iterator>
Rafael Espindola8a8e5542014-06-12 17:19:42 +000059#include <system_error>
Guy Benyei11169dd2012-12-18 14:30:41 +000060
61using namespace clang;
62using namespace clang::serialization;
63using namespace clang::serialization::reader;
Chris Lattner7fb3bef2013-01-20 00:56:42 +000064using llvm::BitstreamCursor;
Guy Benyei11169dd2012-12-18 14:30:41 +000065
Ben Langmuircb69b572014-03-07 06:40:32 +000066
67//===----------------------------------------------------------------------===//
68// ChainedASTReaderListener implementation
69//===----------------------------------------------------------------------===//
70
71bool
72ChainedASTReaderListener::ReadFullVersionInformation(StringRef FullVersion) {
73 return First->ReadFullVersionInformation(FullVersion) ||
74 Second->ReadFullVersionInformation(FullVersion);
75}
Ben Langmuir4f5212a2014-04-14 22:12:44 +000076void ChainedASTReaderListener::ReadModuleName(StringRef ModuleName) {
77 First->ReadModuleName(ModuleName);
78 Second->ReadModuleName(ModuleName);
79}
80void ChainedASTReaderListener::ReadModuleMapFile(StringRef ModuleMapPath) {
81 First->ReadModuleMapFile(ModuleMapPath);
82 Second->ReadModuleMapFile(ModuleMapPath);
83}
Richard Smith1e2cf0d2014-10-31 02:28:58 +000084bool
85ChainedASTReaderListener::ReadLanguageOptions(const LangOptions &LangOpts,
86 bool Complain,
87 bool AllowCompatibleDifferences) {
88 return First->ReadLanguageOptions(LangOpts, Complain,
89 AllowCompatibleDifferences) ||
90 Second->ReadLanguageOptions(LangOpts, Complain,
91 AllowCompatibleDifferences);
Ben Langmuircb69b572014-03-07 06:40:32 +000092}
Chandler Carruth0d745bc2015-03-14 04:47:43 +000093bool ChainedASTReaderListener::ReadTargetOptions(
94 const TargetOptions &TargetOpts, bool Complain,
95 bool AllowCompatibleDifferences) {
96 return First->ReadTargetOptions(TargetOpts, Complain,
97 AllowCompatibleDifferences) ||
98 Second->ReadTargetOptions(TargetOpts, Complain,
99 AllowCompatibleDifferences);
Ben Langmuircb69b572014-03-07 06:40:32 +0000100}
101bool ChainedASTReaderListener::ReadDiagnosticOptions(
Ben Langmuirb92de022014-04-29 16:25:26 +0000102 IntrusiveRefCntPtr<DiagnosticOptions> DiagOpts, bool Complain) {
Ben Langmuircb69b572014-03-07 06:40:32 +0000103 return First->ReadDiagnosticOptions(DiagOpts, Complain) ||
104 Second->ReadDiagnosticOptions(DiagOpts, Complain);
105}
106bool
107ChainedASTReaderListener::ReadFileSystemOptions(const FileSystemOptions &FSOpts,
108 bool Complain) {
109 return First->ReadFileSystemOptions(FSOpts, Complain) ||
110 Second->ReadFileSystemOptions(FSOpts, Complain);
111}
112
113bool ChainedASTReaderListener::ReadHeaderSearchOptions(
Argyrios Kyrtzidisbd0b6512015-02-19 20:12:20 +0000114 const HeaderSearchOptions &HSOpts, StringRef SpecificModuleCachePath,
115 bool Complain) {
116 return First->ReadHeaderSearchOptions(HSOpts, SpecificModuleCachePath,
117 Complain) ||
118 Second->ReadHeaderSearchOptions(HSOpts, SpecificModuleCachePath,
119 Complain);
Ben Langmuircb69b572014-03-07 06:40:32 +0000120}
121bool ChainedASTReaderListener::ReadPreprocessorOptions(
122 const PreprocessorOptions &PPOpts, bool Complain,
123 std::string &SuggestedPredefines) {
124 return First->ReadPreprocessorOptions(PPOpts, Complain,
125 SuggestedPredefines) ||
126 Second->ReadPreprocessorOptions(PPOpts, Complain, SuggestedPredefines);
127}
128void ChainedASTReaderListener::ReadCounter(const serialization::ModuleFile &M,
129 unsigned Value) {
130 First->ReadCounter(M, Value);
131 Second->ReadCounter(M, Value);
132}
133bool ChainedASTReaderListener::needsInputFileVisitation() {
134 return First->needsInputFileVisitation() ||
135 Second->needsInputFileVisitation();
136}
137bool ChainedASTReaderListener::needsSystemInputFileVisitation() {
138 return First->needsSystemInputFileVisitation() ||
139 Second->needsSystemInputFileVisitation();
140}
Richard Smith216a3bd2015-08-13 17:57:10 +0000141void ChainedASTReaderListener::visitModuleFile(StringRef Filename,
142 ModuleKind Kind) {
143 First->visitModuleFile(Filename, Kind);
144 Second->visitModuleFile(Filename, Kind);
Argyrios Kyrtzidis6d0753d2014-03-14 03:07:38 +0000145}
Ben Langmuircb69b572014-03-07 06:40:32 +0000146bool ChainedASTReaderListener::visitInputFile(StringRef Filename,
Argyrios Kyrtzidis68ccbe02014-03-14 02:26:31 +0000147 bool isSystem,
Richard Smith216a3bd2015-08-13 17:57:10 +0000148 bool isOverridden,
149 bool isExplicitModule) {
Justin Bognerc65a66d2014-05-22 06:04:59 +0000150 bool Continue = false;
151 if (First->needsInputFileVisitation() &&
152 (!isSystem || First->needsSystemInputFileVisitation()))
Richard Smith216a3bd2015-08-13 17:57:10 +0000153 Continue |= First->visitInputFile(Filename, isSystem, isOverridden,
154 isExplicitModule);
Justin Bognerc65a66d2014-05-22 06:04:59 +0000155 if (Second->needsInputFileVisitation() &&
156 (!isSystem || Second->needsSystemInputFileVisitation()))
Richard Smith216a3bd2015-08-13 17:57:10 +0000157 Continue |= Second->visitInputFile(Filename, isSystem, isOverridden,
158 isExplicitModule);
Justin Bognerc65a66d2014-05-22 06:04:59 +0000159 return Continue;
Ben Langmuircb69b572014-03-07 06:40:32 +0000160}
161
Guy Benyei11169dd2012-12-18 14:30:41 +0000162//===----------------------------------------------------------------------===//
163// PCH validator implementation
164//===----------------------------------------------------------------------===//
165
166ASTReaderListener::~ASTReaderListener() {}
167
168/// \brief Compare the given set of language options against an existing set of
169/// language options.
170///
171/// \param Diags If non-NULL, diagnostics will be emitted via this engine.
Richard Smith1e2cf0d2014-10-31 02:28:58 +0000172/// \param AllowCompatibleDifferences If true, differences between compatible
173/// language options will be permitted.
Guy Benyei11169dd2012-12-18 14:30:41 +0000174///
175/// \returns true if the languagae options mis-match, false otherwise.
176static bool checkLanguageOptions(const LangOptions &LangOpts,
177 const LangOptions &ExistingLangOpts,
Richard Smith1e2cf0d2014-10-31 02:28:58 +0000178 DiagnosticsEngine *Diags,
179 bool AllowCompatibleDifferences = true) {
Guy Benyei11169dd2012-12-18 14:30:41 +0000180#define LANGOPT(Name, Bits, Default, Description) \
181 if (ExistingLangOpts.Name != LangOpts.Name) { \
182 if (Diags) \
183 Diags->Report(diag::err_pch_langopt_mismatch) \
184 << Description << LangOpts.Name << ExistingLangOpts.Name; \
185 return true; \
186 }
187
188#define VALUE_LANGOPT(Name, Bits, Default, Description) \
189 if (ExistingLangOpts.Name != LangOpts.Name) { \
190 if (Diags) \
191 Diags->Report(diag::err_pch_langopt_value_mismatch) \
192 << Description; \
193 return true; \
194 }
195
196#define ENUM_LANGOPT(Name, Type, Bits, Default, Description) \
197 if (ExistingLangOpts.get##Name() != LangOpts.get##Name()) { \
198 if (Diags) \
199 Diags->Report(diag::err_pch_langopt_value_mismatch) \
200 << Description; \
201 return true; \
202 }
203
Richard Smith1e2cf0d2014-10-31 02:28:58 +0000204#define COMPATIBLE_LANGOPT(Name, Bits, Default, Description) \
205 if (!AllowCompatibleDifferences) \
206 LANGOPT(Name, Bits, Default, Description)
207
208#define COMPATIBLE_ENUM_LANGOPT(Name, Bits, Default, Description) \
209 if (!AllowCompatibleDifferences) \
210 ENUM_LANGOPT(Name, Bits, Default, Description)
211
Guy Benyei11169dd2012-12-18 14:30:41 +0000212#define BENIGN_LANGOPT(Name, Bits, Default, Description)
213#define BENIGN_ENUM_LANGOPT(Name, Type, Bits, Default, Description)
214#include "clang/Basic/LangOptions.def"
215
Ben Langmuircd98cb72015-06-23 18:20:18 +0000216 if (ExistingLangOpts.ModuleFeatures != LangOpts.ModuleFeatures) {
217 if (Diags)
218 Diags->Report(diag::err_pch_langopt_value_mismatch) << "module features";
219 return true;
220 }
221
Guy Benyei11169dd2012-12-18 14:30:41 +0000222 if (ExistingLangOpts.ObjCRuntime != LangOpts.ObjCRuntime) {
223 if (Diags)
224 Diags->Report(diag::err_pch_langopt_value_mismatch)
225 << "target Objective-C runtime";
226 return true;
227 }
228
Dmitri Gribenkoacf2e782013-02-22 14:21:27 +0000229 if (ExistingLangOpts.CommentOpts.BlockCommandNames !=
230 LangOpts.CommentOpts.BlockCommandNames) {
231 if (Diags)
232 Diags->Report(diag::err_pch_langopt_value_mismatch)
233 << "block command names";
234 return true;
235 }
236
Guy Benyei11169dd2012-12-18 14:30:41 +0000237 return false;
238}
239
240/// \brief Compare the given set of target options against an existing set of
241/// target options.
242///
243/// \param Diags If non-NULL, diagnostics will be emitted via this engine.
244///
245/// \returns true if the target options mis-match, false otherwise.
246static bool checkTargetOptions(const TargetOptions &TargetOpts,
247 const TargetOptions &ExistingTargetOpts,
Chandler Carruth0d745bc2015-03-14 04:47:43 +0000248 DiagnosticsEngine *Diags,
249 bool AllowCompatibleDifferences = true) {
Guy Benyei11169dd2012-12-18 14:30:41 +0000250#define CHECK_TARGET_OPT(Field, Name) \
251 if (TargetOpts.Field != ExistingTargetOpts.Field) { \
252 if (Diags) \
253 Diags->Report(diag::err_pch_targetopt_mismatch) \
254 << Name << TargetOpts.Field << ExistingTargetOpts.Field; \
255 return true; \
256 }
257
Chandler Carruth0d745bc2015-03-14 04:47:43 +0000258 // The triple and ABI must match exactly.
Guy Benyei11169dd2012-12-18 14:30:41 +0000259 CHECK_TARGET_OPT(Triple, "target");
Guy Benyei11169dd2012-12-18 14:30:41 +0000260 CHECK_TARGET_OPT(ABI, "target ABI");
Chandler Carruth0d745bc2015-03-14 04:47:43 +0000261
262 // We can tolerate different CPUs in many cases, notably when one CPU
263 // supports a strict superset of another. When allowing compatible
264 // differences skip this check.
265 if (!AllowCompatibleDifferences)
266 CHECK_TARGET_OPT(CPU, "target CPU");
267
Guy Benyei11169dd2012-12-18 14:30:41 +0000268#undef CHECK_TARGET_OPT
269
270 // Compare feature sets.
271 SmallVector<StringRef, 4> ExistingFeatures(
272 ExistingTargetOpts.FeaturesAsWritten.begin(),
273 ExistingTargetOpts.FeaturesAsWritten.end());
274 SmallVector<StringRef, 4> ReadFeatures(TargetOpts.FeaturesAsWritten.begin(),
275 TargetOpts.FeaturesAsWritten.end());
276 std::sort(ExistingFeatures.begin(), ExistingFeatures.end());
277 std::sort(ReadFeatures.begin(), ReadFeatures.end());
278
Chandler Carruth0d745bc2015-03-14 04:47:43 +0000279 // We compute the set difference in both directions explicitly so that we can
280 // diagnose the differences differently.
281 SmallVector<StringRef, 4> UnmatchedExistingFeatures, UnmatchedReadFeatures;
282 std::set_difference(
283 ExistingFeatures.begin(), ExistingFeatures.end(), ReadFeatures.begin(),
284 ReadFeatures.end(), std::back_inserter(UnmatchedExistingFeatures));
285 std::set_difference(ReadFeatures.begin(), ReadFeatures.end(),
286 ExistingFeatures.begin(), ExistingFeatures.end(),
287 std::back_inserter(UnmatchedReadFeatures));
Guy Benyei11169dd2012-12-18 14:30:41 +0000288
Chandler Carruth0d745bc2015-03-14 04:47:43 +0000289 // If we are allowing compatible differences and the read feature set is
290 // a strict subset of the existing feature set, there is nothing to diagnose.
291 if (AllowCompatibleDifferences && UnmatchedReadFeatures.empty())
292 return false;
Guy Benyei11169dd2012-12-18 14:30:41 +0000293
Chandler Carruth0d745bc2015-03-14 04:47:43 +0000294 if (Diags) {
295 for (StringRef Feature : UnmatchedReadFeatures)
Guy Benyei11169dd2012-12-18 14:30:41 +0000296 Diags->Report(diag::err_pch_targetopt_feature_mismatch)
Chandler Carruth0d745bc2015-03-14 04:47:43 +0000297 << /* is-existing-feature */ false << Feature;
298 for (StringRef Feature : UnmatchedExistingFeatures)
299 Diags->Report(diag::err_pch_targetopt_feature_mismatch)
300 << /* is-existing-feature */ true << Feature;
Guy Benyei11169dd2012-12-18 14:30:41 +0000301 }
302
Chandler Carruth0d745bc2015-03-14 04:47:43 +0000303 return !UnmatchedReadFeatures.empty() || !UnmatchedExistingFeatures.empty();
Guy Benyei11169dd2012-12-18 14:30:41 +0000304}
305
306bool
307PCHValidator::ReadLanguageOptions(const LangOptions &LangOpts,
Richard Smith1e2cf0d2014-10-31 02:28:58 +0000308 bool Complain,
309 bool AllowCompatibleDifferences) {
Guy Benyei11169dd2012-12-18 14:30:41 +0000310 const LangOptions &ExistingLangOpts = PP.getLangOpts();
311 return checkLanguageOptions(LangOpts, ExistingLangOpts,
Richard Smith1e2cf0d2014-10-31 02:28:58 +0000312 Complain ? &Reader.Diags : nullptr,
313 AllowCompatibleDifferences);
Guy Benyei11169dd2012-12-18 14:30:41 +0000314}
315
316bool PCHValidator::ReadTargetOptions(const TargetOptions &TargetOpts,
Chandler Carruth0d745bc2015-03-14 04:47:43 +0000317 bool Complain,
318 bool AllowCompatibleDifferences) {
Guy Benyei11169dd2012-12-18 14:30:41 +0000319 const TargetOptions &ExistingTargetOpts = PP.getTargetInfo().getTargetOpts();
320 return checkTargetOptions(TargetOpts, ExistingTargetOpts,
Chandler Carruth0d745bc2015-03-14 04:47:43 +0000321 Complain ? &Reader.Diags : nullptr,
322 AllowCompatibleDifferences);
Guy Benyei11169dd2012-12-18 14:30:41 +0000323}
324
325namespace {
326 typedef llvm::StringMap<std::pair<StringRef, bool /*IsUndef*/> >
327 MacroDefinitionsMap;
Craig Topper3598eb72013-07-05 04:43:31 +0000328 typedef llvm::DenseMap<DeclarationName, SmallVector<NamedDecl *, 8> >
329 DeclsMap;
Guy Benyei11169dd2012-12-18 14:30:41 +0000330}
331
Ben Langmuirb92de022014-04-29 16:25:26 +0000332static bool checkDiagnosticGroupMappings(DiagnosticsEngine &StoredDiags,
333 DiagnosticsEngine &Diags,
334 bool Complain) {
335 typedef DiagnosticsEngine::Level Level;
336
337 // Check current mappings for new -Werror mappings, and the stored mappings
338 // for cases that were explicitly mapped to *not* be errors that are now
339 // errors because of options like -Werror.
340 DiagnosticsEngine *MappingSources[] = { &Diags, &StoredDiags };
341
342 for (DiagnosticsEngine *MappingSource : MappingSources) {
343 for (auto DiagIDMappingPair : MappingSource->getDiagnosticMappings()) {
344 diag::kind DiagID = DiagIDMappingPair.first;
345 Level CurLevel = Diags.getDiagnosticLevel(DiagID, SourceLocation());
346 if (CurLevel < DiagnosticsEngine::Error)
347 continue; // not significant
348 Level StoredLevel =
349 StoredDiags.getDiagnosticLevel(DiagID, SourceLocation());
350 if (StoredLevel < DiagnosticsEngine::Error) {
351 if (Complain)
352 Diags.Report(diag::err_pch_diagopt_mismatch) << "-Werror=" +
353 Diags.getDiagnosticIDs()->getWarningOptionForDiag(DiagID).str();
354 return true;
355 }
356 }
357 }
358
359 return false;
360}
361
Alp Tokerac4e8e52014-06-22 21:58:33 +0000362static bool isExtHandlingFromDiagsError(DiagnosticsEngine &Diags) {
363 diag::Severity Ext = Diags.getExtensionHandlingBehavior();
364 if (Ext == diag::Severity::Warning && Diags.getWarningsAsErrors())
365 return true;
366 return Ext >= diag::Severity::Error;
Ben Langmuirb92de022014-04-29 16:25:26 +0000367}
368
369static bool checkDiagnosticMappings(DiagnosticsEngine &StoredDiags,
370 DiagnosticsEngine &Diags,
371 bool IsSystem, bool Complain) {
372 // Top-level options
373 if (IsSystem) {
374 if (Diags.getSuppressSystemWarnings())
375 return false;
376 // If -Wsystem-headers was not enabled before, be conservative
377 if (StoredDiags.getSuppressSystemWarnings()) {
378 if (Complain)
379 Diags.Report(diag::err_pch_diagopt_mismatch) << "-Wsystem-headers";
380 return true;
381 }
382 }
383
384 if (Diags.getWarningsAsErrors() && !StoredDiags.getWarningsAsErrors()) {
385 if (Complain)
386 Diags.Report(diag::err_pch_diagopt_mismatch) << "-Werror";
387 return true;
388 }
389
390 if (Diags.getWarningsAsErrors() && Diags.getEnableAllWarnings() &&
391 !StoredDiags.getEnableAllWarnings()) {
392 if (Complain)
393 Diags.Report(diag::err_pch_diagopt_mismatch) << "-Weverything -Werror";
394 return true;
395 }
396
397 if (isExtHandlingFromDiagsError(Diags) &&
398 !isExtHandlingFromDiagsError(StoredDiags)) {
399 if (Complain)
400 Diags.Report(diag::err_pch_diagopt_mismatch) << "-pedantic-errors";
401 return true;
402 }
403
404 return checkDiagnosticGroupMappings(StoredDiags, Diags, Complain);
405}
406
407bool PCHValidator::ReadDiagnosticOptions(
408 IntrusiveRefCntPtr<DiagnosticOptions> DiagOpts, bool Complain) {
409 DiagnosticsEngine &ExistingDiags = PP.getDiagnostics();
410 IntrusiveRefCntPtr<DiagnosticIDs> DiagIDs(ExistingDiags.getDiagnosticIDs());
411 IntrusiveRefCntPtr<DiagnosticsEngine> Diags(
Alp Tokerf994cef2014-07-05 03:08:06 +0000412 new DiagnosticsEngine(DiagIDs, DiagOpts.get()));
Ben Langmuirb92de022014-04-29 16:25:26 +0000413 // This should never fail, because we would have processed these options
414 // before writing them to an ASTFile.
415 ProcessWarningOptions(*Diags, *DiagOpts, /*Report*/false);
416
417 ModuleManager &ModuleMgr = Reader.getModuleManager();
418 assert(ModuleMgr.size() >= 1 && "what ASTFile is this then");
419
420 // If the original import came from a file explicitly generated by the user,
421 // don't check the diagnostic mappings.
422 // FIXME: currently this is approximated by checking whether this is not a
Richard Smithe842a472014-10-22 02:05:46 +0000423 // module import of an implicitly-loaded module file.
Ben Langmuirb92de022014-04-29 16:25:26 +0000424 // Note: ModuleMgr.rbegin() may not be the current module, but it must be in
425 // the transitive closure of its imports, since unrelated modules cannot be
426 // imported until after this module finishes validation.
427 ModuleFile *TopImport = *ModuleMgr.rbegin();
428 while (!TopImport->ImportedBy.empty())
429 TopImport = TopImport->ImportedBy[0];
Richard Smithe842a472014-10-22 02:05:46 +0000430 if (TopImport->Kind != MK_ImplicitModule)
Ben Langmuirb92de022014-04-29 16:25:26 +0000431 return false;
432
433 StringRef ModuleName = TopImport->ModuleName;
434 assert(!ModuleName.empty() && "diagnostic options read before module name");
435
436 Module *M = PP.getHeaderSearchInfo().lookupModule(ModuleName);
437 assert(M && "missing module");
438
439 // FIXME: if the diagnostics are incompatible, save a DiagnosticOptions that
440 // contains the union of their flags.
441 return checkDiagnosticMappings(*Diags, ExistingDiags, M->IsSystem, Complain);
442}
443
Guy Benyei11169dd2012-12-18 14:30:41 +0000444/// \brief Collect the macro definitions provided by the given preprocessor
445/// options.
Craig Toppera13603a2014-05-22 05:54:18 +0000446static void
447collectMacroDefinitions(const PreprocessorOptions &PPOpts,
448 MacroDefinitionsMap &Macros,
449 SmallVectorImpl<StringRef> *MacroNames = nullptr) {
Guy Benyei11169dd2012-12-18 14:30:41 +0000450 for (unsigned I = 0, N = PPOpts.Macros.size(); I != N; ++I) {
451 StringRef Macro = PPOpts.Macros[I].first;
452 bool IsUndef = PPOpts.Macros[I].second;
453
454 std::pair<StringRef, StringRef> MacroPair = Macro.split('=');
455 StringRef MacroName = MacroPair.first;
456 StringRef MacroBody = MacroPair.second;
457
458 // For an #undef'd macro, we only care about the name.
459 if (IsUndef) {
460 if (MacroNames && !Macros.count(MacroName))
461 MacroNames->push_back(MacroName);
462
463 Macros[MacroName] = std::make_pair("", true);
464 continue;
465 }
466
467 // For a #define'd macro, figure out the actual definition.
468 if (MacroName.size() == Macro.size())
469 MacroBody = "1";
470 else {
471 // Note: GCC drops anything following an end-of-line character.
472 StringRef::size_type End = MacroBody.find_first_of("\n\r");
473 MacroBody = MacroBody.substr(0, End);
474 }
475
476 if (MacroNames && !Macros.count(MacroName))
477 MacroNames->push_back(MacroName);
478 Macros[MacroName] = std::make_pair(MacroBody, false);
479 }
480}
Argyrios Kyrtzidisbd0b6512015-02-19 20:12:20 +0000481
Guy Benyei11169dd2012-12-18 14:30:41 +0000482/// \brief Check the preprocessor options deserialized from the control block
483/// against the preprocessor options in an existing preprocessor.
484///
485/// \param Diags If non-null, produce diagnostics for any mismatches incurred.
486static bool checkPreprocessorOptions(const PreprocessorOptions &PPOpts,
487 const PreprocessorOptions &ExistingPPOpts,
488 DiagnosticsEngine *Diags,
489 FileManager &FileMgr,
Argyrios Kyrtzidisd3afa0c2013-04-26 21:33:40 +0000490 std::string &SuggestedPredefines,
491 const LangOptions &LangOpts) {
Guy Benyei11169dd2012-12-18 14:30:41 +0000492 // Check macro definitions.
493 MacroDefinitionsMap ASTFileMacros;
494 collectMacroDefinitions(PPOpts, ASTFileMacros);
495 MacroDefinitionsMap ExistingMacros;
496 SmallVector<StringRef, 4> ExistingMacroNames;
497 collectMacroDefinitions(ExistingPPOpts, ExistingMacros, &ExistingMacroNames);
498
499 for (unsigned I = 0, N = ExistingMacroNames.size(); I != N; ++I) {
500 // Dig out the macro definition in the existing preprocessor options.
501 StringRef MacroName = ExistingMacroNames[I];
502 std::pair<StringRef, bool> Existing = ExistingMacros[MacroName];
503
504 // Check whether we know anything about this macro name or not.
505 llvm::StringMap<std::pair<StringRef, bool /*IsUndef*/> >::iterator Known
506 = ASTFileMacros.find(MacroName);
507 if (Known == ASTFileMacros.end()) {
508 // FIXME: Check whether this identifier was referenced anywhere in the
509 // AST file. If so, we should reject the AST file. Unfortunately, this
510 // information isn't in the control block. What shall we do about it?
511
512 if (Existing.second) {
513 SuggestedPredefines += "#undef ";
514 SuggestedPredefines += MacroName.str();
515 SuggestedPredefines += '\n';
516 } else {
517 SuggestedPredefines += "#define ";
518 SuggestedPredefines += MacroName.str();
519 SuggestedPredefines += ' ';
520 SuggestedPredefines += Existing.first.str();
521 SuggestedPredefines += '\n';
522 }
523 continue;
524 }
525
526 // If the macro was defined in one but undef'd in the other, we have a
527 // conflict.
528 if (Existing.second != Known->second.second) {
529 if (Diags) {
530 Diags->Report(diag::err_pch_macro_def_undef)
531 << MacroName << Known->second.second;
532 }
533 return true;
534 }
535
536 // If the macro was #undef'd in both, or if the macro bodies are identical,
537 // it's fine.
538 if (Existing.second || Existing.first == Known->second.first)
539 continue;
540
541 // The macro bodies differ; complain.
542 if (Diags) {
543 Diags->Report(diag::err_pch_macro_def_conflict)
544 << MacroName << Known->second.first << Existing.first;
545 }
546 return true;
547 }
548
549 // Check whether we're using predefines.
550 if (PPOpts.UsePredefines != ExistingPPOpts.UsePredefines) {
551 if (Diags) {
552 Diags->Report(diag::err_pch_undef) << ExistingPPOpts.UsePredefines;
553 }
554 return true;
555 }
556
Argyrios Kyrtzidisd3afa0c2013-04-26 21:33:40 +0000557 // Detailed record is important since it is used for the module cache hash.
558 if (LangOpts.Modules &&
559 PPOpts.DetailedRecord != ExistingPPOpts.DetailedRecord) {
560 if (Diags) {
561 Diags->Report(diag::err_pch_pp_detailed_record) << PPOpts.DetailedRecord;
562 }
563 return true;
564 }
565
Guy Benyei11169dd2012-12-18 14:30:41 +0000566 // Compute the #include and #include_macros lines we need.
567 for (unsigned I = 0, N = ExistingPPOpts.Includes.size(); I != N; ++I) {
568 StringRef File = ExistingPPOpts.Includes[I];
569 if (File == ExistingPPOpts.ImplicitPCHInclude)
570 continue;
571
572 if (std::find(PPOpts.Includes.begin(), PPOpts.Includes.end(), File)
573 != PPOpts.Includes.end())
574 continue;
575
576 SuggestedPredefines += "#include \"";
Manuel Klimek9af34ae2014-08-12 08:25:57 +0000577 SuggestedPredefines += File;
Guy Benyei11169dd2012-12-18 14:30:41 +0000578 SuggestedPredefines += "\"\n";
579 }
580
581 for (unsigned I = 0, N = ExistingPPOpts.MacroIncludes.size(); I != N; ++I) {
582 StringRef File = ExistingPPOpts.MacroIncludes[I];
583 if (std::find(PPOpts.MacroIncludes.begin(), PPOpts.MacroIncludes.end(),
584 File)
585 != PPOpts.MacroIncludes.end())
586 continue;
587
588 SuggestedPredefines += "#__include_macros \"";
Manuel Klimek9af34ae2014-08-12 08:25:57 +0000589 SuggestedPredefines += File;
Guy Benyei11169dd2012-12-18 14:30:41 +0000590 SuggestedPredefines += "\"\n##\n";
591 }
592
593 return false;
594}
595
596bool PCHValidator::ReadPreprocessorOptions(const PreprocessorOptions &PPOpts,
597 bool Complain,
598 std::string &SuggestedPredefines) {
599 const PreprocessorOptions &ExistingPPOpts = PP.getPreprocessorOpts();
600
601 return checkPreprocessorOptions(PPOpts, ExistingPPOpts,
Craig Toppera13603a2014-05-22 05:54:18 +0000602 Complain? &Reader.Diags : nullptr,
Guy Benyei11169dd2012-12-18 14:30:41 +0000603 PP.getFileManager(),
Argyrios Kyrtzidisd3afa0c2013-04-26 21:33:40 +0000604 SuggestedPredefines,
605 PP.getLangOpts());
Guy Benyei11169dd2012-12-18 14:30:41 +0000606}
607
Argyrios Kyrtzidisbd0b6512015-02-19 20:12:20 +0000608/// Check the header search options deserialized from the control block
609/// against the header search options in an existing preprocessor.
610///
611/// \param Diags If non-null, produce diagnostics for any mismatches incurred.
612static bool checkHeaderSearchOptions(const HeaderSearchOptions &HSOpts,
613 StringRef SpecificModuleCachePath,
614 StringRef ExistingModuleCachePath,
615 DiagnosticsEngine *Diags,
616 const LangOptions &LangOpts) {
617 if (LangOpts.Modules) {
618 if (SpecificModuleCachePath != ExistingModuleCachePath) {
619 if (Diags)
620 Diags->Report(diag::err_pch_modulecache_mismatch)
621 << SpecificModuleCachePath << ExistingModuleCachePath;
622 return true;
623 }
624 }
625
626 return false;
627}
628
629bool PCHValidator::ReadHeaderSearchOptions(const HeaderSearchOptions &HSOpts,
630 StringRef SpecificModuleCachePath,
631 bool Complain) {
632 return checkHeaderSearchOptions(HSOpts, SpecificModuleCachePath,
633 PP.getHeaderSearchInfo().getModuleCachePath(),
634 Complain ? &Reader.Diags : nullptr,
635 PP.getLangOpts());
636}
637
Guy Benyei11169dd2012-12-18 14:30:41 +0000638void PCHValidator::ReadCounter(const ModuleFile &M, unsigned Value) {
639 PP.setCounterValue(Value);
640}
641
642//===----------------------------------------------------------------------===//
643// AST reader implementation
644//===----------------------------------------------------------------------===//
645
Nico Weber824285e2014-05-08 04:26:47 +0000646void ASTReader::setDeserializationListener(ASTDeserializationListener *Listener,
647 bool TakeOwnership) {
Guy Benyei11169dd2012-12-18 14:30:41 +0000648 DeserializationListener = Listener;
Nico Weber824285e2014-05-08 04:26:47 +0000649 OwnsDeserializationListener = TakeOwnership;
Guy Benyei11169dd2012-12-18 14:30:41 +0000650}
651
652
653
654unsigned ASTSelectorLookupTrait::ComputeHash(Selector Sel) {
655 return serialization::ComputeHash(Sel);
656}
657
658
659std::pair<unsigned, unsigned>
660ASTSelectorLookupTrait::ReadKeyDataLength(const unsigned char*& d) {
Justin Bogner57ba0b22014-03-28 22:03:24 +0000661 using namespace llvm::support;
662 unsigned KeyLen = endian::readNext<uint16_t, little, unaligned>(d);
663 unsigned DataLen = endian::readNext<uint16_t, little, unaligned>(d);
Guy Benyei11169dd2012-12-18 14:30:41 +0000664 return std::make_pair(KeyLen, DataLen);
665}
666
667ASTSelectorLookupTrait::internal_key_type
668ASTSelectorLookupTrait::ReadKey(const unsigned char* d, unsigned) {
Justin Bogner57ba0b22014-03-28 22:03:24 +0000669 using namespace llvm::support;
Guy Benyei11169dd2012-12-18 14:30:41 +0000670 SelectorTable &SelTable = Reader.getContext().Selectors;
Justin Bogner57ba0b22014-03-28 22:03:24 +0000671 unsigned N = endian::readNext<uint16_t, little, unaligned>(d);
672 IdentifierInfo *FirstII = Reader.getLocalIdentifier(
673 F, endian::readNext<uint32_t, little, unaligned>(d));
Guy Benyei11169dd2012-12-18 14:30:41 +0000674 if (N == 0)
675 return SelTable.getNullarySelector(FirstII);
676 else if (N == 1)
677 return SelTable.getUnarySelector(FirstII);
678
679 SmallVector<IdentifierInfo *, 16> Args;
680 Args.push_back(FirstII);
681 for (unsigned I = 1; I != N; ++I)
Justin Bogner57ba0b22014-03-28 22:03:24 +0000682 Args.push_back(Reader.getLocalIdentifier(
683 F, endian::readNext<uint32_t, little, unaligned>(d)));
Guy Benyei11169dd2012-12-18 14:30:41 +0000684
685 return SelTable.getSelector(N, Args.data());
686}
687
688ASTSelectorLookupTrait::data_type
689ASTSelectorLookupTrait::ReadData(Selector, const unsigned char* d,
690 unsigned DataLen) {
Justin Bogner57ba0b22014-03-28 22:03:24 +0000691 using namespace llvm::support;
Guy Benyei11169dd2012-12-18 14:30:41 +0000692
693 data_type Result;
694
Justin Bogner57ba0b22014-03-28 22:03:24 +0000695 Result.ID = Reader.getGlobalSelectorID(
696 F, endian::readNext<uint32_t, little, unaligned>(d));
Nico Weberff4b35e2014-12-27 22:14:15 +0000697 unsigned FullInstanceBits = endian::readNext<uint16_t, little, unaligned>(d);
698 unsigned FullFactoryBits = endian::readNext<uint16_t, little, unaligned>(d);
699 Result.InstanceBits = FullInstanceBits & 0x3;
700 Result.InstanceHasMoreThanOneDecl = (FullInstanceBits >> 2) & 0x1;
701 Result.FactoryBits = FullFactoryBits & 0x3;
702 Result.FactoryHasMoreThanOneDecl = (FullFactoryBits >> 2) & 0x1;
703 unsigned NumInstanceMethods = FullInstanceBits >> 3;
704 unsigned NumFactoryMethods = FullFactoryBits >> 3;
Guy Benyei11169dd2012-12-18 14:30:41 +0000705
706 // Load instance methods
707 for (unsigned I = 0; I != NumInstanceMethods; ++I) {
Justin Bogner57ba0b22014-03-28 22:03:24 +0000708 if (ObjCMethodDecl *Method = Reader.GetLocalDeclAs<ObjCMethodDecl>(
709 F, endian::readNext<uint32_t, little, unaligned>(d)))
Guy Benyei11169dd2012-12-18 14:30:41 +0000710 Result.Instance.push_back(Method);
711 }
712
713 // Load factory methods
714 for (unsigned I = 0; I != NumFactoryMethods; ++I) {
Justin Bogner57ba0b22014-03-28 22:03:24 +0000715 if (ObjCMethodDecl *Method = Reader.GetLocalDeclAs<ObjCMethodDecl>(
716 F, endian::readNext<uint32_t, little, unaligned>(d)))
Guy Benyei11169dd2012-12-18 14:30:41 +0000717 Result.Factory.push_back(Method);
718 }
719
720 return Result;
721}
722
Douglas Gregorbfd73d72013-01-23 18:53:14 +0000723unsigned ASTIdentifierLookupTraitBase::ComputeHash(const internal_key_type& a) {
724 return llvm::HashString(a);
Guy Benyei11169dd2012-12-18 14:30:41 +0000725}
726
727std::pair<unsigned, unsigned>
Douglas Gregorbfd73d72013-01-23 18:53:14 +0000728ASTIdentifierLookupTraitBase::ReadKeyDataLength(const unsigned char*& d) {
Justin Bogner57ba0b22014-03-28 22:03:24 +0000729 using namespace llvm::support;
730 unsigned DataLen = endian::readNext<uint16_t, little, unaligned>(d);
731 unsigned KeyLen = endian::readNext<uint16_t, little, unaligned>(d);
Guy Benyei11169dd2012-12-18 14:30:41 +0000732 return std::make_pair(KeyLen, DataLen);
733}
734
Douglas Gregorbfd73d72013-01-23 18:53:14 +0000735ASTIdentifierLookupTraitBase::internal_key_type
736ASTIdentifierLookupTraitBase::ReadKey(const unsigned char* d, unsigned n) {
Guy Benyei11169dd2012-12-18 14:30:41 +0000737 assert(n >= 2 && d[n-1] == '\0');
Douglas Gregorbfd73d72013-01-23 18:53:14 +0000738 return StringRef((const char*) d, n-1);
Guy Benyei11169dd2012-12-18 14:30:41 +0000739}
740
Douglas Gregordcf25082013-02-11 18:16:18 +0000741/// \brief Whether the given identifier is "interesting".
Richard Smitha534a312015-07-21 23:54:07 +0000742static bool isInterestingIdentifier(ASTReader &Reader, IdentifierInfo &II,
743 bool IsModule) {
Richard Smithcab89802015-07-17 20:19:56 +0000744 return II.hadMacroDefinition() ||
745 II.isPoisoned() ||
Richard Smith9c254182015-07-19 21:41:12 +0000746 (IsModule ? II.hasRevertedBuiltin() : II.getObjCOrBuiltinID()) ||
Douglas Gregordcf25082013-02-11 18:16:18 +0000747 II.hasRevertedTokenIDToIdentifier() ||
Richard Smitha534a312015-07-21 23:54:07 +0000748 (!(IsModule && Reader.getContext().getLangOpts().CPlusPlus) &&
749 II.getFETokenInfo<void>());
Douglas Gregordcf25082013-02-11 18:16:18 +0000750}
751
Richard Smith76c2f2c2015-07-17 20:09:43 +0000752static bool readBit(unsigned &Bits) {
753 bool Value = Bits & 0x1;
754 Bits >>= 1;
755 return Value;
756}
757
Richard Smith79bf9202015-08-24 03:33:22 +0000758IdentID ASTIdentifierLookupTrait::ReadIdentifierID(const unsigned char *d) {
759 using namespace llvm::support;
760 unsigned RawID = endian::readNext<uint32_t, little, unaligned>(d);
761 return Reader.getGlobalIdentifierID(F, RawID >> 1);
762}
763
Guy Benyei11169dd2012-12-18 14:30:41 +0000764IdentifierInfo *ASTIdentifierLookupTrait::ReadData(const internal_key_type& k,
765 const unsigned char* d,
766 unsigned DataLen) {
Justin Bogner57ba0b22014-03-28 22:03:24 +0000767 using namespace llvm::support;
768 unsigned RawID = endian::readNext<uint32_t, little, unaligned>(d);
Guy Benyei11169dd2012-12-18 14:30:41 +0000769 bool IsInteresting = RawID & 0x01;
770
771 // Wipe out the "is interesting" bit.
772 RawID = RawID >> 1;
773
Richard Smith76c2f2c2015-07-17 20:09:43 +0000774 // Build the IdentifierInfo and link the identifier ID with it.
775 IdentifierInfo *II = KnownII;
776 if (!II) {
777 II = &Reader.getIdentifierTable().getOwn(k);
778 KnownII = II;
779 }
780 if (!II->isFromAST()) {
781 II->setIsFromAST();
Richard Smitha534a312015-07-21 23:54:07 +0000782 if (isInterestingIdentifier(Reader, *II, F.isModule()))
Richard Smith76c2f2c2015-07-17 20:09:43 +0000783 II->setChangedSinceDeserialization();
784 }
785 Reader.markIdentifierUpToDate(II);
786
Guy Benyei11169dd2012-12-18 14:30:41 +0000787 IdentID ID = Reader.getGlobalIdentifierID(F, RawID);
788 if (!IsInteresting) {
Richard Smith76c2f2c2015-07-17 20:09:43 +0000789 // For uninteresting identifiers, there's nothing else to do. Just notify
790 // the reader that we've finished loading this identifier.
Guy Benyei11169dd2012-12-18 14:30:41 +0000791 Reader.SetIdentifierInfo(ID, II);
Guy Benyei11169dd2012-12-18 14:30:41 +0000792 return II;
793 }
794
Justin Bogner57ba0b22014-03-28 22:03:24 +0000795 unsigned ObjCOrBuiltinID = endian::readNext<uint16_t, little, unaligned>(d);
796 unsigned Bits = endian::readNext<uint16_t, little, unaligned>(d);
Richard Smith76c2f2c2015-07-17 20:09:43 +0000797 bool CPlusPlusOperatorKeyword = readBit(Bits);
798 bool HasRevertedTokenIDToIdentifier = readBit(Bits);
Richard Smith9c254182015-07-19 21:41:12 +0000799 bool HasRevertedBuiltin = readBit(Bits);
Richard Smith76c2f2c2015-07-17 20:09:43 +0000800 bool Poisoned = readBit(Bits);
801 bool ExtensionToken = readBit(Bits);
802 bool HadMacroDefinition = readBit(Bits);
Guy Benyei11169dd2012-12-18 14:30:41 +0000803
804 assert(Bits == 0 && "Extra bits in the identifier?");
805 DataLen -= 8;
806
Guy Benyei11169dd2012-12-18 14:30:41 +0000807 // Set or check the various bits in the IdentifierInfo structure.
808 // Token IDs are read-only.
Argyrios Kyrtzidisddee8c92013-02-27 01:13:51 +0000809 if (HasRevertedTokenIDToIdentifier && II->getTokenID() != tok::identifier)
Richard Smith9c254182015-07-19 21:41:12 +0000810 II->revertTokenIDToIdentifier();
811 if (!F.isModule())
812 II->setObjCOrBuiltinID(ObjCOrBuiltinID);
813 else if (HasRevertedBuiltin && II->getBuiltinID()) {
814 II->revertBuiltin();
815 assert((II->hasRevertedBuiltin() ||
816 II->getObjCOrBuiltinID() == ObjCOrBuiltinID) &&
817 "Incorrect ObjC keyword or builtin ID");
818 }
Guy Benyei11169dd2012-12-18 14:30:41 +0000819 assert(II->isExtensionToken() == ExtensionToken &&
820 "Incorrect extension token flag");
821 (void)ExtensionToken;
822 if (Poisoned)
823 II->setIsPoisoned(true);
824 assert(II->isCPlusPlusOperatorKeyword() == CPlusPlusOperatorKeyword &&
825 "Incorrect C++ operator keyword flag");
826 (void)CPlusPlusOperatorKeyword;
827
828 // If this identifier is a macro, deserialize the macro
829 // definition.
Richard Smith76c2f2c2015-07-17 20:09:43 +0000830 if (HadMacroDefinition) {
Justin Bogner57ba0b22014-03-28 22:03:24 +0000831 uint32_t MacroDirectivesOffset =
832 endian::readNext<uint32_t, little, unaligned>(d);
Argyrios Kyrtzidiseb663da2013-03-22 21:12:57 +0000833 DataLen -= 4;
Argyrios Kyrtzidiseb663da2013-03-22 21:12:57 +0000834
Richard Smithd7329392015-04-21 21:46:32 +0000835 Reader.addPendingMacro(II, &F, MacroDirectivesOffset);
Guy Benyei11169dd2012-12-18 14:30:41 +0000836 }
837
838 Reader.SetIdentifierInfo(ID, II);
839
840 // Read all of the declarations visible at global scope with this
841 // name.
842 if (DataLen > 0) {
843 SmallVector<uint32_t, 4> DeclIDs;
844 for (; DataLen > 0; DataLen -= 4)
Justin Bogner57ba0b22014-03-28 22:03:24 +0000845 DeclIDs.push_back(Reader.getGlobalDeclID(
846 F, endian::readNext<uint32_t, little, unaligned>(d)));
Guy Benyei11169dd2012-12-18 14:30:41 +0000847 Reader.SetGloballyVisibleDecls(II, DeclIDs);
848 }
849
850 return II;
851}
852
853unsigned
Richard Smith3b637412015-07-14 18:42:41 +0000854ASTDeclContextNameLookupTrait::ComputeHash(const DeclNameKey &Key) {
Guy Benyei11169dd2012-12-18 14:30:41 +0000855 llvm::FoldingSetNodeID ID;
856 ID.AddInteger(Key.Kind);
857
858 switch (Key.Kind) {
859 case DeclarationName::Identifier:
860 case DeclarationName::CXXLiteralOperatorName:
861 ID.AddString(((IdentifierInfo*)Key.Data)->getName());
862 break;
863 case DeclarationName::ObjCZeroArgSelector:
864 case DeclarationName::ObjCOneArgSelector:
865 case DeclarationName::ObjCMultiArgSelector:
866 ID.AddInteger(serialization::ComputeHash(Selector(Key.Data)));
867 break;
868 case DeclarationName::CXXOperatorName:
869 ID.AddInteger((OverloadedOperatorKind)Key.Data);
870 break;
871 case DeclarationName::CXXConstructorName:
872 case DeclarationName::CXXDestructorName:
873 case DeclarationName::CXXConversionFunctionName:
874 case DeclarationName::CXXUsingDirective:
875 break;
876 }
877
878 return ID.ComputeHash();
879}
880
881ASTDeclContextNameLookupTrait::internal_key_type
882ASTDeclContextNameLookupTrait::GetInternalKey(
Richard Smith3b637412015-07-14 18:42:41 +0000883 const external_key_type& Name) {
Guy Benyei11169dd2012-12-18 14:30:41 +0000884 DeclNameKey Key;
885 Key.Kind = Name.getNameKind();
886 switch (Name.getNameKind()) {
887 case DeclarationName::Identifier:
888 Key.Data = (uint64_t)Name.getAsIdentifierInfo();
889 break;
890 case DeclarationName::ObjCZeroArgSelector:
891 case DeclarationName::ObjCOneArgSelector:
892 case DeclarationName::ObjCMultiArgSelector:
893 Key.Data = (uint64_t)Name.getObjCSelector().getAsOpaquePtr();
894 break;
895 case DeclarationName::CXXOperatorName:
896 Key.Data = Name.getCXXOverloadedOperator();
897 break;
898 case DeclarationName::CXXLiteralOperatorName:
899 Key.Data = (uint64_t)Name.getCXXLiteralIdentifier();
900 break;
901 case DeclarationName::CXXConstructorName:
902 case DeclarationName::CXXDestructorName:
903 case DeclarationName::CXXConversionFunctionName:
904 case DeclarationName::CXXUsingDirective:
905 Key.Data = 0;
906 break;
907 }
908
909 return Key;
910}
911
912std::pair<unsigned, unsigned>
913ASTDeclContextNameLookupTrait::ReadKeyDataLength(const unsigned char*& d) {
Justin Bogner57ba0b22014-03-28 22:03:24 +0000914 using namespace llvm::support;
915 unsigned KeyLen = endian::readNext<uint16_t, little, unaligned>(d);
916 unsigned DataLen = endian::readNext<uint16_t, little, unaligned>(d);
Guy Benyei11169dd2012-12-18 14:30:41 +0000917 return std::make_pair(KeyLen, DataLen);
918}
919
920ASTDeclContextNameLookupTrait::internal_key_type
921ASTDeclContextNameLookupTrait::ReadKey(const unsigned char* d, unsigned) {
Justin Bogner57ba0b22014-03-28 22:03:24 +0000922 using namespace llvm::support;
Guy Benyei11169dd2012-12-18 14:30:41 +0000923
924 DeclNameKey Key;
925 Key.Kind = (DeclarationName::NameKind)*d++;
926 switch (Key.Kind) {
927 case DeclarationName::Identifier:
Justin Bogner57ba0b22014-03-28 22:03:24 +0000928 Key.Data = (uint64_t)Reader.getLocalIdentifier(
929 F, endian::readNext<uint32_t, little, unaligned>(d));
Guy Benyei11169dd2012-12-18 14:30:41 +0000930 break;
931 case DeclarationName::ObjCZeroArgSelector:
932 case DeclarationName::ObjCOneArgSelector:
933 case DeclarationName::ObjCMultiArgSelector:
934 Key.Data =
Justin Bogner57ba0b22014-03-28 22:03:24 +0000935 (uint64_t)Reader.getLocalSelector(
936 F, endian::readNext<uint32_t, little, unaligned>(
937 d)).getAsOpaquePtr();
Guy Benyei11169dd2012-12-18 14:30:41 +0000938 break;
939 case DeclarationName::CXXOperatorName:
940 Key.Data = *d++; // OverloadedOperatorKind
941 break;
942 case DeclarationName::CXXLiteralOperatorName:
Justin Bogner57ba0b22014-03-28 22:03:24 +0000943 Key.Data = (uint64_t)Reader.getLocalIdentifier(
944 F, endian::readNext<uint32_t, little, unaligned>(d));
Guy Benyei11169dd2012-12-18 14:30:41 +0000945 break;
946 case DeclarationName::CXXConstructorName:
947 case DeclarationName::CXXDestructorName:
948 case DeclarationName::CXXConversionFunctionName:
949 case DeclarationName::CXXUsingDirective:
950 Key.Data = 0;
951 break;
952 }
953
954 return Key;
955}
956
Richard Smithf02662d2015-07-30 03:17:16 +0000957ASTDeclContextNameLookupTrait::data_type
958ASTDeclContextNameLookupTrait::ReadData(internal_key_type,
959 const unsigned char *d,
Guy Benyei11169dd2012-12-18 14:30:41 +0000960 unsigned DataLen) {
Justin Bogner57ba0b22014-03-28 22:03:24 +0000961 using namespace llvm::support;
Richard Smithf02662d2015-07-30 03:17:16 +0000962 unsigned NumDecls = DataLen / 4;
Argyrios Kyrtzidisc57e5032013-01-11 22:29:49 +0000963 LE32DeclID *Start = reinterpret_cast<LE32DeclID *>(
964 const_cast<unsigned char *>(d));
Guy Benyei11169dd2012-12-18 14:30:41 +0000965 return std::make_pair(Start, Start + NumDecls);
966}
967
Richard Smith0f4e2c42015-08-06 04:23:48 +0000968bool ASTReader::ReadLexicalDeclContextStorage(ModuleFile &M,
969 BitstreamCursor &Cursor,
970 uint64_t Offset,
971 DeclContext *DC) {
972 assert(Offset != 0);
973
Guy Benyei11169dd2012-12-18 14:30:41 +0000974 SavedStreamPosition SavedPosition(Cursor);
Richard Smith0f4e2c42015-08-06 04:23:48 +0000975 Cursor.JumpToBit(Offset);
Guy Benyei11169dd2012-12-18 14:30:41 +0000976
Richard Smith0f4e2c42015-08-06 04:23:48 +0000977 RecordData Record;
978 StringRef Blob;
979 unsigned Code = Cursor.ReadCode();
980 unsigned RecCode = Cursor.readRecord(Code, Record, &Blob);
981 if (RecCode != DECL_CONTEXT_LEXICAL) {
982 Error("Expected lexical block");
983 return true;
Guy Benyei11169dd2012-12-18 14:30:41 +0000984 }
985
Richard Smith82f8fcd2015-08-06 22:07:25 +0000986 assert(!isa<TranslationUnitDecl>(DC) &&
987 "expected a TU_UPDATE_LEXICAL record for TU");
Richard Smith9c9173d2015-08-11 22:00:24 +0000988 // If we are handling a C++ class template instantiation, we can see multiple
989 // lexical updates for the same record. It's important that we select only one
990 // of them, so that field numbering works properly. Just pick the first one we
991 // see.
992 auto &Lex = LexicalDecls[DC];
993 if (!Lex.first) {
994 Lex = std::make_pair(
995 &M, llvm::makeArrayRef(
996 reinterpret_cast<const llvm::support::unaligned_uint32_t *>(
997 Blob.data()),
998 Blob.size() / 4));
999 }
Richard Smith0f4e2c42015-08-06 04:23:48 +00001000 DC->setHasExternalLexicalStorage(true);
1001 return false;
1002}
Guy Benyei11169dd2012-12-18 14:30:41 +00001003
Richard Smith0f4e2c42015-08-06 04:23:48 +00001004bool ASTReader::ReadVisibleDeclContextStorage(ModuleFile &M,
1005 BitstreamCursor &Cursor,
1006 uint64_t Offset,
1007 DeclID ID) {
1008 assert(Offset != 0);
1009
1010 SavedStreamPosition SavedPosition(Cursor);
1011 Cursor.JumpToBit(Offset);
1012
1013 RecordData Record;
1014 StringRef Blob;
1015 unsigned Code = Cursor.ReadCode();
1016 unsigned RecCode = Cursor.readRecord(Code, Record, &Blob);
1017 if (RecCode != DECL_CONTEXT_VISIBLE) {
1018 Error("Expected visible lookup table block");
1019 return true;
Guy Benyei11169dd2012-12-18 14:30:41 +00001020 }
1021
Richard Smith0f4e2c42015-08-06 04:23:48 +00001022 // We can't safely determine the primary context yet, so delay attaching the
1023 // lookup table until we're done with recursive deserialization.
1024 unsigned BucketOffset = Record[0];
1025 PendingVisibleUpdates[ID].push_back(PendingVisibleUpdate{
1026 &M, (const unsigned char *)Blob.data(), BucketOffset});
Guy Benyei11169dd2012-12-18 14:30:41 +00001027 return false;
1028}
1029
1030void ASTReader::Error(StringRef Msg) {
1031 Error(diag::err_fe_pch_malformed, Msg);
Richard Smithfb1e7f72015-08-14 05:02:58 +00001032 if (Context.getLangOpts().Modules && !Diags.isDiagnosticInFlight() &&
1033 !PP.getHeaderSearchInfo().getModuleCachePath().empty()) {
Douglas Gregor940e8052013-05-10 22:15:13 +00001034 Diag(diag::note_module_cache_path)
1035 << PP.getHeaderSearchInfo().getModuleCachePath();
1036 }
Guy Benyei11169dd2012-12-18 14:30:41 +00001037}
1038
1039void ASTReader::Error(unsigned DiagID,
1040 StringRef Arg1, StringRef Arg2) {
1041 if (Diags.isDiagnosticInFlight())
1042 Diags.SetDelayedDiagnostic(DiagID, Arg1, Arg2);
1043 else
1044 Diag(DiagID) << Arg1 << Arg2;
1045}
1046
1047//===----------------------------------------------------------------------===//
1048// Source Manager Deserialization
1049//===----------------------------------------------------------------------===//
1050
1051/// \brief Read the line table in the source manager block.
1052/// \returns true if there was an error.
1053bool ASTReader::ParseLineTable(ModuleFile &F,
Richard Smith7ed1bc92014-12-05 22:42:13 +00001054 const RecordData &Record) {
Guy Benyei11169dd2012-12-18 14:30:41 +00001055 unsigned Idx = 0;
1056 LineTableInfo &LineTable = SourceMgr.getLineTable();
1057
1058 // Parse the file names
1059 std::map<int, int> FileIDs;
1060 for (int I = 0, N = Record[Idx++]; I != N; ++I) {
1061 // Extract the file name
Richard Smith7ed1bc92014-12-05 22:42:13 +00001062 auto Filename = ReadPath(F, Record, Idx);
Guy Benyei11169dd2012-12-18 14:30:41 +00001063 FileIDs[I] = LineTable.getLineTableFilenameID(Filename);
1064 }
1065
1066 // Parse the line entries
1067 std::vector<LineEntry> Entries;
1068 while (Idx < Record.size()) {
1069 int FID = Record[Idx++];
1070 assert(FID >= 0 && "Serialized line entries for non-local file.");
1071 // Remap FileID from 1-based old view.
1072 FID += F.SLocEntryBaseID - 1;
1073
1074 // Extract the line entries
1075 unsigned NumEntries = Record[Idx++];
1076 assert(NumEntries && "Numentries is 00000");
1077 Entries.clear();
1078 Entries.reserve(NumEntries);
1079 for (unsigned I = 0; I != NumEntries; ++I) {
1080 unsigned FileOffset = Record[Idx++];
1081 unsigned LineNo = Record[Idx++];
1082 int FilenameID = FileIDs[Record[Idx++]];
1083 SrcMgr::CharacteristicKind FileKind
1084 = (SrcMgr::CharacteristicKind)Record[Idx++];
1085 unsigned IncludeOffset = Record[Idx++];
1086 Entries.push_back(LineEntry::get(FileOffset, LineNo, FilenameID,
1087 FileKind, IncludeOffset));
1088 }
1089 LineTable.AddEntry(FileID::get(FID), Entries);
1090 }
1091
1092 return false;
1093}
1094
1095/// \brief Read a source manager block
1096bool ASTReader::ReadSourceManagerBlock(ModuleFile &F) {
1097 using namespace SrcMgr;
1098
Chris Lattner7fb3bef2013-01-20 00:56:42 +00001099 BitstreamCursor &SLocEntryCursor = F.SLocEntryCursor;
Guy Benyei11169dd2012-12-18 14:30:41 +00001100
1101 // Set the source-location entry cursor to the current position in
1102 // the stream. This cursor will be used to read the contents of the
1103 // source manager block initially, and then lazily read
1104 // source-location entries as needed.
1105 SLocEntryCursor = F.Stream;
1106
1107 // The stream itself is going to skip over the source manager block.
1108 if (F.Stream.SkipBlock()) {
1109 Error("malformed block record in AST file");
1110 return true;
1111 }
1112
1113 // Enter the source manager block.
1114 if (SLocEntryCursor.EnterSubBlock(SOURCE_MANAGER_BLOCK_ID)) {
1115 Error("malformed source manager block record in AST file");
1116 return true;
1117 }
1118
1119 RecordData Record;
1120 while (true) {
Chris Lattnere7b154b2013-01-19 21:39:22 +00001121 llvm::BitstreamEntry E = SLocEntryCursor.advanceSkippingSubblocks();
1122
1123 switch (E.Kind) {
1124 case llvm::BitstreamEntry::SubBlock: // Handled for us already.
1125 case llvm::BitstreamEntry::Error:
1126 Error("malformed block record in AST file");
1127 return true;
1128 case llvm::BitstreamEntry::EndBlock:
Guy Benyei11169dd2012-12-18 14:30:41 +00001129 return false;
Chris Lattnere7b154b2013-01-19 21:39:22 +00001130 case llvm::BitstreamEntry::Record:
1131 // The interesting case.
1132 break;
Guy Benyei11169dd2012-12-18 14:30:41 +00001133 }
Chris Lattnere7b154b2013-01-19 21:39:22 +00001134
Guy Benyei11169dd2012-12-18 14:30:41 +00001135 // Read a record.
Guy Benyei11169dd2012-12-18 14:30:41 +00001136 Record.clear();
Chris Lattner15c3e7d2013-01-21 18:28:26 +00001137 StringRef Blob;
1138 switch (SLocEntryCursor.readRecord(E.ID, Record, &Blob)) {
Guy Benyei11169dd2012-12-18 14:30:41 +00001139 default: // Default behavior: ignore.
1140 break;
1141
1142 case SM_SLOC_FILE_ENTRY:
1143 case SM_SLOC_BUFFER_ENTRY:
1144 case SM_SLOC_EXPANSION_ENTRY:
1145 // Once we hit one of the source location entries, we're done.
1146 return false;
1147 }
1148 }
1149}
1150
1151/// \brief If a header file is not found at the path that we expect it to be
1152/// and the PCH file was moved from its original location, try to resolve the
1153/// file by assuming that header+PCH were moved together and the header is in
1154/// the same place relative to the PCH.
1155static std::string
1156resolveFileRelativeToOriginalDir(const std::string &Filename,
1157 const std::string &OriginalDir,
1158 const std::string &CurrDir) {
1159 assert(OriginalDir != CurrDir &&
1160 "No point trying to resolve the file if the PCH dir didn't change");
1161 using namespace llvm::sys;
1162 SmallString<128> filePath(Filename);
1163 fs::make_absolute(filePath);
1164 assert(path::is_absolute(OriginalDir));
1165 SmallString<128> currPCHPath(CurrDir);
1166
1167 path::const_iterator fileDirI = path::begin(path::parent_path(filePath)),
1168 fileDirE = path::end(path::parent_path(filePath));
1169 path::const_iterator origDirI = path::begin(OriginalDir),
1170 origDirE = path::end(OriginalDir);
1171 // Skip the common path components from filePath and OriginalDir.
1172 while (fileDirI != fileDirE && origDirI != origDirE &&
1173 *fileDirI == *origDirI) {
1174 ++fileDirI;
1175 ++origDirI;
1176 }
1177 for (; origDirI != origDirE; ++origDirI)
1178 path::append(currPCHPath, "..");
1179 path::append(currPCHPath, fileDirI, fileDirE);
1180 path::append(currPCHPath, path::filename(Filename));
1181 return currPCHPath.str();
1182}
1183
1184bool ASTReader::ReadSLocEntry(int ID) {
1185 if (ID == 0)
1186 return false;
1187
1188 if (unsigned(-ID) - 2 >= getTotalNumSLocs() || ID > 0) {
1189 Error("source location entry ID out-of-range for AST file");
1190 return true;
1191 }
1192
1193 ModuleFile *F = GlobalSLocEntryMap.find(-ID)->second;
1194 F->SLocEntryCursor.JumpToBit(F->SLocEntryOffsets[ID - F->SLocEntryBaseID]);
Chris Lattner7fb3bef2013-01-20 00:56:42 +00001195 BitstreamCursor &SLocEntryCursor = F->SLocEntryCursor;
Guy Benyei11169dd2012-12-18 14:30:41 +00001196 unsigned BaseOffset = F->SLocEntryBaseOffset;
1197
1198 ++NumSLocEntriesRead;
Chris Lattnere7b154b2013-01-19 21:39:22 +00001199 llvm::BitstreamEntry Entry = SLocEntryCursor.advance();
1200 if (Entry.Kind != llvm::BitstreamEntry::Record) {
Guy Benyei11169dd2012-12-18 14:30:41 +00001201 Error("incorrectly-formatted source location entry in AST file");
1202 return true;
1203 }
Chris Lattnere7b154b2013-01-19 21:39:22 +00001204
Guy Benyei11169dd2012-12-18 14:30:41 +00001205 RecordData Record;
Chris Lattner0e6c9402013-01-20 02:38:54 +00001206 StringRef Blob;
1207 switch (SLocEntryCursor.readRecord(Entry.ID, Record, &Blob)) {
Guy Benyei11169dd2012-12-18 14:30:41 +00001208 default:
1209 Error("incorrectly-formatted source location entry in AST file");
1210 return true;
1211
1212 case SM_SLOC_FILE_ENTRY: {
1213 // We will detect whether a file changed and return 'Failure' for it, but
1214 // we will also try to fail gracefully by setting up the SLocEntry.
1215 unsigned InputID = Record[4];
1216 InputFile IF = getInputFile(*F, InputID);
Argyrios Kyrtzidis61c3d872013-03-01 03:26:04 +00001217 const FileEntry *File = IF.getFile();
1218 bool OverriddenBuffer = IF.isOverridden();
Guy Benyei11169dd2012-12-18 14:30:41 +00001219
Argyrios Kyrtzidis61c3d872013-03-01 03:26:04 +00001220 // Note that we only check if a File was returned. If it was out-of-date
1221 // we have complained but we will continue creating a FileID to recover
1222 // gracefully.
1223 if (!File)
Guy Benyei11169dd2012-12-18 14:30:41 +00001224 return true;
1225
1226 SourceLocation IncludeLoc = ReadSourceLocation(*F, Record[1]);
1227 if (IncludeLoc.isInvalid() && F->Kind != MK_MainFile) {
1228 // This is the module's main file.
1229 IncludeLoc = getImportLocation(F);
1230 }
1231 SrcMgr::CharacteristicKind
1232 FileCharacter = (SrcMgr::CharacteristicKind)Record[2];
1233 FileID FID = SourceMgr.createFileID(File, IncludeLoc, FileCharacter,
1234 ID, BaseOffset + Record[0]);
1235 SrcMgr::FileInfo &FileInfo =
1236 const_cast<SrcMgr::FileInfo&>(SourceMgr.getSLocEntry(FID).getFile());
1237 FileInfo.NumCreatedFIDs = Record[5];
1238 if (Record[3])
1239 FileInfo.setHasLineDirectives();
1240
1241 const DeclID *FirstDecl = F->FileSortedDecls + Record[6];
1242 unsigned NumFileDecls = Record[7];
1243 if (NumFileDecls) {
1244 assert(F->FileSortedDecls && "FILE_SORTED_DECLS not encountered yet ?");
1245 FileDeclIDs[FID] = FileDeclsInfo(F, llvm::makeArrayRef(FirstDecl,
1246 NumFileDecls));
1247 }
1248
1249 const SrcMgr::ContentCache *ContentCache
1250 = SourceMgr.getOrCreateContentCache(File,
1251 /*isSystemFile=*/FileCharacter != SrcMgr::C_User);
1252 if (OverriddenBuffer && !ContentCache->BufferOverridden &&
1253 ContentCache->ContentsEntry == ContentCache->OrigEntry) {
1254 unsigned Code = SLocEntryCursor.ReadCode();
1255 Record.clear();
Chris Lattner0e6c9402013-01-20 02:38:54 +00001256 unsigned RecCode = SLocEntryCursor.readRecord(Code, Record, &Blob);
Guy Benyei11169dd2012-12-18 14:30:41 +00001257
1258 if (RecCode != SM_SLOC_BUFFER_BLOB) {
1259 Error("AST record has invalid code");
1260 return true;
1261 }
1262
Rafael Espindolad87f8d72014-08-27 20:03:29 +00001263 std::unique_ptr<llvm::MemoryBuffer> Buffer
Chris Lattner0e6c9402013-01-20 02:38:54 +00001264 = llvm::MemoryBuffer::getMemBuffer(Blob.drop_back(1), File->getName());
David Blaikie49cc3182014-08-27 20:54:45 +00001265 SourceMgr.overrideFileContents(File, std::move(Buffer));
Guy Benyei11169dd2012-12-18 14:30:41 +00001266 }
1267
1268 break;
1269 }
1270
1271 case SM_SLOC_BUFFER_ENTRY: {
Chris Lattner0e6c9402013-01-20 02:38:54 +00001272 const char *Name = Blob.data();
Guy Benyei11169dd2012-12-18 14:30:41 +00001273 unsigned Offset = Record[0];
1274 SrcMgr::CharacteristicKind
1275 FileCharacter = (SrcMgr::CharacteristicKind)Record[2];
1276 SourceLocation IncludeLoc = ReadSourceLocation(*F, Record[1]);
Richard Smithe842a472014-10-22 02:05:46 +00001277 if (IncludeLoc.isInvalid() &&
1278 (F->Kind == MK_ImplicitModule || F->Kind == MK_ExplicitModule)) {
Guy Benyei11169dd2012-12-18 14:30:41 +00001279 IncludeLoc = getImportLocation(F);
1280 }
1281 unsigned Code = SLocEntryCursor.ReadCode();
1282 Record.clear();
1283 unsigned RecCode
Chris Lattner0e6c9402013-01-20 02:38:54 +00001284 = SLocEntryCursor.readRecord(Code, Record, &Blob);
Guy Benyei11169dd2012-12-18 14:30:41 +00001285
1286 if (RecCode != SM_SLOC_BUFFER_BLOB) {
1287 Error("AST record has invalid code");
1288 return true;
1289 }
1290
Rafael Espindolad87f8d72014-08-27 20:03:29 +00001291 std::unique_ptr<llvm::MemoryBuffer> Buffer =
1292 llvm::MemoryBuffer::getMemBuffer(Blob.drop_back(1), Name);
David Blaikie50a5f972014-08-29 07:59:55 +00001293 SourceMgr.createFileID(std::move(Buffer), FileCharacter, ID,
Rafael Espindolad87f8d72014-08-27 20:03:29 +00001294 BaseOffset + Offset, IncludeLoc);
Guy Benyei11169dd2012-12-18 14:30:41 +00001295 break;
1296 }
1297
1298 case SM_SLOC_EXPANSION_ENTRY: {
1299 SourceLocation SpellingLoc = ReadSourceLocation(*F, Record[1]);
1300 SourceMgr.createExpansionLoc(SpellingLoc,
1301 ReadSourceLocation(*F, Record[2]),
1302 ReadSourceLocation(*F, Record[3]),
1303 Record[4],
1304 ID,
1305 BaseOffset + Record[0]);
1306 break;
1307 }
1308 }
1309
1310 return false;
1311}
1312
1313std::pair<SourceLocation, StringRef> ASTReader::getModuleImportLoc(int ID) {
1314 if (ID == 0)
1315 return std::make_pair(SourceLocation(), "");
1316
1317 if (unsigned(-ID) - 2 >= getTotalNumSLocs() || ID > 0) {
1318 Error("source location entry ID out-of-range for AST file");
1319 return std::make_pair(SourceLocation(), "");
1320 }
1321
1322 // Find which module file this entry lands in.
1323 ModuleFile *M = GlobalSLocEntryMap.find(-ID)->second;
Richard Smithe842a472014-10-22 02:05:46 +00001324 if (M->Kind != MK_ImplicitModule && M->Kind != MK_ExplicitModule)
Guy Benyei11169dd2012-12-18 14:30:41 +00001325 return std::make_pair(SourceLocation(), "");
1326
1327 // FIXME: Can we map this down to a particular submodule? That would be
1328 // ideal.
Ben Langmuirbeee15e2014-04-14 18:00:01 +00001329 return std::make_pair(M->ImportLoc, StringRef(M->ModuleName));
Guy Benyei11169dd2012-12-18 14:30:41 +00001330}
1331
1332/// \brief Find the location where the module F is imported.
1333SourceLocation ASTReader::getImportLocation(ModuleFile *F) {
1334 if (F->ImportLoc.isValid())
1335 return F->ImportLoc;
1336
1337 // Otherwise we have a PCH. It's considered to be "imported" at the first
1338 // location of its includer.
1339 if (F->ImportedBy.empty() || !F->ImportedBy[0]) {
Ben Langmuirbeee15e2014-04-14 18:00:01 +00001340 // Main file is the importer.
1341 assert(!SourceMgr.getMainFileID().isInvalid() && "missing main file");
1342 return SourceMgr.getLocForStartOfFile(SourceMgr.getMainFileID());
Guy Benyei11169dd2012-12-18 14:30:41 +00001343 }
Guy Benyei11169dd2012-12-18 14:30:41 +00001344 return F->ImportedBy[0]->FirstLoc;
1345}
1346
1347/// ReadBlockAbbrevs - Enter a subblock of the specified BlockID with the
1348/// specified cursor. Read the abbreviations that are at the top of the block
1349/// and then leave the cursor pointing into the block.
Chris Lattner7fb3bef2013-01-20 00:56:42 +00001350bool ASTReader::ReadBlockAbbrevs(BitstreamCursor &Cursor, unsigned BlockID) {
Guy Benyei11169dd2012-12-18 14:30:41 +00001351 if (Cursor.EnterSubBlock(BlockID)) {
1352 Error("malformed block record in AST file");
1353 return Failure;
1354 }
1355
1356 while (true) {
1357 uint64_t Offset = Cursor.GetCurrentBitNo();
1358 unsigned Code = Cursor.ReadCode();
1359
1360 // We expect all abbrevs to be at the start of the block.
1361 if (Code != llvm::bitc::DEFINE_ABBREV) {
1362 Cursor.JumpToBit(Offset);
1363 return false;
1364 }
1365 Cursor.ReadAbbrevRecord();
1366 }
1367}
1368
Richard Smithe40f2ba2013-08-07 21:41:30 +00001369Token ASTReader::ReadToken(ModuleFile &F, const RecordDataImpl &Record,
John McCallf413f5e2013-05-03 00:10:13 +00001370 unsigned &Idx) {
1371 Token Tok;
1372 Tok.startToken();
1373 Tok.setLocation(ReadSourceLocation(F, Record, Idx));
1374 Tok.setLength(Record[Idx++]);
1375 if (IdentifierInfo *II = getLocalIdentifier(F, Record[Idx++]))
1376 Tok.setIdentifierInfo(II);
1377 Tok.setKind((tok::TokenKind)Record[Idx++]);
1378 Tok.setFlag((Token::TokenFlags)Record[Idx++]);
1379 return Tok;
1380}
1381
Argyrios Kyrtzidiseb663da2013-03-22 21:12:57 +00001382MacroInfo *ASTReader::ReadMacroRecord(ModuleFile &F, uint64_t Offset) {
Chris Lattner7fb3bef2013-01-20 00:56:42 +00001383 BitstreamCursor &Stream = F.MacroCursor;
Guy Benyei11169dd2012-12-18 14:30:41 +00001384
1385 // Keep track of where we are in the stream, then jump back there
1386 // after reading this macro.
1387 SavedStreamPosition SavedPosition(Stream);
1388
1389 Stream.JumpToBit(Offset);
1390 RecordData Record;
1391 SmallVector<IdentifierInfo*, 16> MacroArgs;
Craig Toppera13603a2014-05-22 05:54:18 +00001392 MacroInfo *Macro = nullptr;
Guy Benyei11169dd2012-12-18 14:30:41 +00001393
Guy Benyei11169dd2012-12-18 14:30:41 +00001394 while (true) {
Chris Lattnerefa77172013-01-20 00:00:22 +00001395 // Advance to the next record, but if we get to the end of the block, don't
1396 // pop it (removing all the abbreviations from the cursor) since we want to
1397 // be able to reseek within the block and read entries.
Chris Lattner7fb3bef2013-01-20 00:56:42 +00001398 unsigned Flags = BitstreamCursor::AF_DontPopBlockAtEnd;
Chris Lattnerefa77172013-01-20 00:00:22 +00001399 llvm::BitstreamEntry Entry = Stream.advanceSkippingSubblocks(Flags);
1400
1401 switch (Entry.Kind) {
1402 case llvm::BitstreamEntry::SubBlock: // Handled for us already.
1403 case llvm::BitstreamEntry::Error:
1404 Error("malformed block record in AST file");
Argyrios Kyrtzidiseb663da2013-03-22 21:12:57 +00001405 return Macro;
Chris Lattnerefa77172013-01-20 00:00:22 +00001406 case llvm::BitstreamEntry::EndBlock:
Argyrios Kyrtzidiseb663da2013-03-22 21:12:57 +00001407 return Macro;
Chris Lattnerefa77172013-01-20 00:00:22 +00001408 case llvm::BitstreamEntry::Record:
1409 // The interesting case.
1410 break;
Guy Benyei11169dd2012-12-18 14:30:41 +00001411 }
1412
1413 // Read a record.
Guy Benyei11169dd2012-12-18 14:30:41 +00001414 Record.clear();
1415 PreprocessorRecordTypes RecType =
Chris Lattner0e6c9402013-01-20 02:38:54 +00001416 (PreprocessorRecordTypes)Stream.readRecord(Entry.ID, Record);
Guy Benyei11169dd2012-12-18 14:30:41 +00001417 switch (RecType) {
Richard Smithd7329392015-04-21 21:46:32 +00001418 case PP_MODULE_MACRO:
Argyrios Kyrtzidiseb663da2013-03-22 21:12:57 +00001419 case PP_MACRO_DIRECTIVE_HISTORY:
1420 return Macro;
1421
Guy Benyei11169dd2012-12-18 14:30:41 +00001422 case PP_MACRO_OBJECT_LIKE:
1423 case PP_MACRO_FUNCTION_LIKE: {
1424 // If we already have a macro, that means that we've hit the end
1425 // of the definition of the macro we were looking for. We're
1426 // done.
1427 if (Macro)
Argyrios Kyrtzidiseb663da2013-03-22 21:12:57 +00001428 return Macro;
Guy Benyei11169dd2012-12-18 14:30:41 +00001429
Argyrios Kyrtzidiseb663da2013-03-22 21:12:57 +00001430 unsigned NextIndex = 1; // Skip identifier ID.
1431 SubmoduleID SubModID = getGlobalSubmoduleID(F, Record[NextIndex++]);
Guy Benyei11169dd2012-12-18 14:30:41 +00001432 SourceLocation Loc = ReadSourceLocation(F, Record, NextIndex);
Argyrios Kyrtzidiseb663da2013-03-22 21:12:57 +00001433 MacroInfo *MI = PP.AllocateDeserializedMacroInfo(Loc, SubModID);
Argyrios Kyrtzidis7572be22013-01-07 19:16:23 +00001434 MI->setDefinitionEndLoc(ReadSourceLocation(F, Record, NextIndex));
Guy Benyei11169dd2012-12-18 14:30:41 +00001435 MI->setIsUsed(Record[NextIndex++]);
Argyrios Kyrtzidis9ef53ce2014-04-09 18:21:23 +00001436 MI->setUsedForHeaderGuard(Record[NextIndex++]);
Guy Benyei11169dd2012-12-18 14:30:41 +00001437
Guy Benyei11169dd2012-12-18 14:30:41 +00001438 if (RecType == PP_MACRO_FUNCTION_LIKE) {
1439 // Decode function-like macro info.
1440 bool isC99VarArgs = Record[NextIndex++];
1441 bool isGNUVarArgs = Record[NextIndex++];
1442 bool hasCommaPasting = Record[NextIndex++];
1443 MacroArgs.clear();
1444 unsigned NumArgs = Record[NextIndex++];
1445 for (unsigned i = 0; i != NumArgs; ++i)
1446 MacroArgs.push_back(getLocalIdentifier(F, Record[NextIndex++]));
1447
1448 // Install function-like macro info.
1449 MI->setIsFunctionLike();
1450 if (isC99VarArgs) MI->setIsC99Varargs();
1451 if (isGNUVarArgs) MI->setIsGNUVarargs();
1452 if (hasCommaPasting) MI->setHasCommaPasting();
1453 MI->setArgumentList(MacroArgs.data(), MacroArgs.size(),
1454 PP.getPreprocessorAllocator());
1455 }
1456
Guy Benyei11169dd2012-12-18 14:30:41 +00001457 // Remember that we saw this macro last so that we add the tokens that
1458 // form its body to it.
1459 Macro = MI;
1460
1461 if (NextIndex + 1 == Record.size() && PP.getPreprocessingRecord() &&
1462 Record[NextIndex]) {
1463 // We have a macro definition. Register the association
1464 PreprocessedEntityID
1465 GlobalID = getGlobalPreprocessedEntityID(F, Record[NextIndex]);
1466 PreprocessingRecord &PPRec = *PP.getPreprocessingRecord();
Richard Smith66a81862015-05-04 02:25:31 +00001467 PreprocessingRecord::PPEntityID PPID =
1468 PPRec.getPPEntityID(GlobalID - 1, /*isLoaded=*/true);
1469 MacroDefinitionRecord *PPDef = cast_or_null<MacroDefinitionRecord>(
1470 PPRec.getPreprocessedEntity(PPID));
Argyrios Kyrtzidis832de9f2013-02-22 18:35:59 +00001471 if (PPDef)
1472 PPRec.RegisterMacroDefinition(Macro, PPDef);
Guy Benyei11169dd2012-12-18 14:30:41 +00001473 }
1474
1475 ++NumMacrosRead;
1476 break;
1477 }
1478
1479 case PP_TOKEN: {
1480 // If we see a TOKEN before a PP_MACRO_*, then the file is
1481 // erroneous, just pretend we didn't see this.
Craig Toppera13603a2014-05-22 05:54:18 +00001482 if (!Macro) break;
Guy Benyei11169dd2012-12-18 14:30:41 +00001483
John McCallf413f5e2013-05-03 00:10:13 +00001484 unsigned Idx = 0;
1485 Token Tok = ReadToken(F, Record, Idx);
Guy Benyei11169dd2012-12-18 14:30:41 +00001486 Macro->AddTokenToBody(Tok);
1487 break;
1488 }
1489 }
1490 }
1491}
1492
1493PreprocessedEntityID
1494ASTReader::getGlobalPreprocessedEntityID(ModuleFile &M, unsigned LocalID) const {
1495 ContinuousRangeMap<uint32_t, int, 2>::const_iterator
1496 I = M.PreprocessedEntityRemap.find(LocalID - NUM_PREDEF_PP_ENTITY_IDS);
1497 assert(I != M.PreprocessedEntityRemap.end()
1498 && "Invalid index into preprocessed entity index remap");
1499
1500 return LocalID + I->second;
1501}
1502
Argyrios Kyrtzidis5c2a3452013-03-06 18:12:47 +00001503unsigned HeaderFileInfoTrait::ComputeHash(internal_key_ref ikey) {
1504 return llvm::hash_combine(ikey.Size, ikey.ModTime);
Guy Benyei11169dd2012-12-18 14:30:41 +00001505}
Richard Smith7ed1bc92014-12-05 22:42:13 +00001506
Guy Benyei11169dd2012-12-18 14:30:41 +00001507HeaderFileInfoTrait::internal_key_type
Argyrios Kyrtzidis5c2a3452013-03-06 18:12:47 +00001508HeaderFileInfoTrait::GetInternalKey(const FileEntry *FE) {
Richard Smithe75ee0f2015-08-17 07:13:32 +00001509 internal_key_type ikey = {FE->getSize(),
1510 M.HasTimestamps ? FE->getModificationTime() : 0,
1511 FE->getName(), /*Imported*/ false};
Argyrios Kyrtzidis5c2a3452013-03-06 18:12:47 +00001512 return ikey;
1513}
Guy Benyei11169dd2012-12-18 14:30:41 +00001514
Argyrios Kyrtzidis5c2a3452013-03-06 18:12:47 +00001515bool HeaderFileInfoTrait::EqualKey(internal_key_ref a, internal_key_ref b) {
Richard Smithe75ee0f2015-08-17 07:13:32 +00001516 if (a.Size != b.Size || (a.ModTime && b.ModTime && a.ModTime != b.ModTime))
Guy Benyei11169dd2012-12-18 14:30:41 +00001517 return false;
1518
Richard Smith7ed1bc92014-12-05 22:42:13 +00001519 if (llvm::sys::path::is_absolute(a.Filename) &&
1520 strcmp(a.Filename, b.Filename) == 0)
Argyrios Kyrtzidis5c2a3452013-03-06 18:12:47 +00001521 return true;
1522
Guy Benyei11169dd2012-12-18 14:30:41 +00001523 // Determine whether the actual files are equivalent.
Argyrios Kyrtzidis2a513e82013-03-04 20:33:40 +00001524 FileManager &FileMgr = Reader.getFileManager();
Richard Smith7ed1bc92014-12-05 22:42:13 +00001525 auto GetFile = [&](const internal_key_type &Key) -> const FileEntry* {
1526 if (!Key.Imported)
1527 return FileMgr.getFile(Key.Filename);
1528
1529 std::string Resolved = Key.Filename;
1530 Reader.ResolveImportedPath(M, Resolved);
1531 return FileMgr.getFile(Resolved);
1532 };
1533
1534 const FileEntry *FEA = GetFile(a);
1535 const FileEntry *FEB = GetFile(b);
1536 return FEA && FEA == FEB;
Guy Benyei11169dd2012-12-18 14:30:41 +00001537}
1538
1539std::pair<unsigned, unsigned>
1540HeaderFileInfoTrait::ReadKeyDataLength(const unsigned char*& d) {
Justin Bogner57ba0b22014-03-28 22:03:24 +00001541 using namespace llvm::support;
1542 unsigned KeyLen = (unsigned) endian::readNext<uint16_t, little, unaligned>(d);
Guy Benyei11169dd2012-12-18 14:30:41 +00001543 unsigned DataLen = (unsigned) *d++;
Argyrios Kyrtzidis5c2a3452013-03-06 18:12:47 +00001544 return std::make_pair(KeyLen, DataLen);
Guy Benyei11169dd2012-12-18 14:30:41 +00001545}
Argyrios Kyrtzidis5c2a3452013-03-06 18:12:47 +00001546
1547HeaderFileInfoTrait::internal_key_type
1548HeaderFileInfoTrait::ReadKey(const unsigned char *d, unsigned) {
Justin Bogner57ba0b22014-03-28 22:03:24 +00001549 using namespace llvm::support;
Argyrios Kyrtzidis5c2a3452013-03-06 18:12:47 +00001550 internal_key_type ikey;
Justin Bogner57ba0b22014-03-28 22:03:24 +00001551 ikey.Size = off_t(endian::readNext<uint64_t, little, unaligned>(d));
1552 ikey.ModTime = time_t(endian::readNext<uint64_t, little, unaligned>(d));
Argyrios Kyrtzidis5c2a3452013-03-06 18:12:47 +00001553 ikey.Filename = (const char *)d;
Richard Smith7ed1bc92014-12-05 22:42:13 +00001554 ikey.Imported = true;
Argyrios Kyrtzidis5c2a3452013-03-06 18:12:47 +00001555 return ikey;
1556}
1557
Guy Benyei11169dd2012-12-18 14:30:41 +00001558HeaderFileInfoTrait::data_type
Argyrios Kyrtzidisb146baa2013-03-13 21:13:51 +00001559HeaderFileInfoTrait::ReadData(internal_key_ref key, const unsigned char *d,
Guy Benyei11169dd2012-12-18 14:30:41 +00001560 unsigned DataLen) {
1561 const unsigned char *End = d + DataLen;
Justin Bogner57ba0b22014-03-28 22:03:24 +00001562 using namespace llvm::support;
Guy Benyei11169dd2012-12-18 14:30:41 +00001563 HeaderFileInfo HFI;
1564 unsigned Flags = *d++;
Richard Smith386bb072015-08-18 23:42:23 +00001565 // FIXME: Refactor with mergeHeaderFileInfo in HeaderSearch.cpp.
1566 HFI.isImport |= (Flags >> 4) & 0x01;
1567 HFI.isPragmaOnce |= (Flags >> 3) & 0x01;
1568 HFI.DirInfo = (Flags >> 1) & 0x03;
Guy Benyei11169dd2012-12-18 14:30:41 +00001569 HFI.IndexHeaderMapHeader = Flags & 0x01;
Richard Smith386bb072015-08-18 23:42:23 +00001570 // FIXME: Find a better way to handle this. Maybe just store a
1571 // "has been included" flag?
1572 HFI.NumIncludes = std::max(endian::readNext<uint16_t, little, unaligned>(d),
1573 HFI.NumIncludes);
Justin Bogner57ba0b22014-03-28 22:03:24 +00001574 HFI.ControllingMacroID = Reader.getGlobalIdentifierID(
1575 M, endian::readNext<uint32_t, little, unaligned>(d));
1576 if (unsigned FrameworkOffset =
1577 endian::readNext<uint32_t, little, unaligned>(d)) {
Guy Benyei11169dd2012-12-18 14:30:41 +00001578 // The framework offset is 1 greater than the actual offset,
1579 // since 0 is used as an indicator for "no framework name".
1580 StringRef FrameworkName(FrameworkStrings + FrameworkOffset - 1);
1581 HFI.Framework = HS->getUniqueFrameworkName(FrameworkName);
1582 }
Richard Smith386bb072015-08-18 23:42:23 +00001583
1584 assert((End - d) % 4 == 0 &&
1585 "Wrong data length in HeaderFileInfo deserialization");
1586 while (d != End) {
Justin Bogner57ba0b22014-03-28 22:03:24 +00001587 uint32_t LocalSMID = endian::readNext<uint32_t, little, unaligned>(d);
Richard Smith386bb072015-08-18 23:42:23 +00001588 auto HeaderRole = static_cast<ModuleMap::ModuleHeaderRole>(LocalSMID & 3);
1589 LocalSMID >>= 2;
1590
1591 // This header is part of a module. Associate it with the module to enable
1592 // implicit module import.
1593 SubmoduleID GlobalSMID = Reader.getGlobalSubmoduleID(M, LocalSMID);
1594 Module *Mod = Reader.getSubmodule(GlobalSMID);
1595 FileManager &FileMgr = Reader.getFileManager();
1596 ModuleMap &ModMap =
1597 Reader.getPreprocessor().getHeaderSearchInfo().getModuleMap();
1598
1599 std::string Filename = key.Filename;
1600 if (key.Imported)
1601 Reader.ResolveImportedPath(M, Filename);
1602 // FIXME: This is not always the right filename-as-written, but we're not
1603 // going to use this information to rebuild the module, so it doesn't make
1604 // a lot of difference.
1605 Module::Header H = { key.Filename, FileMgr.getFile(Filename) };
Richard Smithd8879c82015-08-24 21:59:32 +00001606 ModMap.addHeader(Mod, H, HeaderRole, /*Imported*/true);
1607 HFI.isModuleHeader |= !(HeaderRole & ModuleMap::TextualHeader);
Argyrios Kyrtzidisb146baa2013-03-13 21:13:51 +00001608 }
1609
Guy Benyei11169dd2012-12-18 14:30:41 +00001610 // This HeaderFileInfo was externally loaded.
1611 HFI.External = true;
Richard Smithd8879c82015-08-24 21:59:32 +00001612 HFI.IsValid = true;
Guy Benyei11169dd2012-12-18 14:30:41 +00001613 return HFI;
1614}
1615
Richard Smithd7329392015-04-21 21:46:32 +00001616void ASTReader::addPendingMacro(IdentifierInfo *II,
1617 ModuleFile *M,
1618 uint64_t MacroDirectivesOffset) {
Argyrios Kyrtzidiseb663da2013-03-22 21:12:57 +00001619 assert(NumCurrentElementsDeserializing > 0 &&"Missing deserialization guard");
1620 PendingMacroIDs[II].push_back(PendingMacroInfo(M, MacroDirectivesOffset));
Guy Benyei11169dd2012-12-18 14:30:41 +00001621}
1622
1623void ASTReader::ReadDefinedMacros() {
1624 // Note that we are loading defined macros.
1625 Deserializing Macros(this);
1626
Pete Cooper57d3f142015-07-30 17:22:52 +00001627 for (auto &I : llvm::reverse(ModuleMgr)) {
1628 BitstreamCursor &MacroCursor = I->MacroCursor;
Guy Benyei11169dd2012-12-18 14:30:41 +00001629
1630 // If there was no preprocessor block, skip this file.
1631 if (!MacroCursor.getBitStreamReader())
1632 continue;
1633
Chris Lattner7fb3bef2013-01-20 00:56:42 +00001634 BitstreamCursor Cursor = MacroCursor;
Pete Cooper57d3f142015-07-30 17:22:52 +00001635 Cursor.JumpToBit(I->MacroStartOffset);
Guy Benyei11169dd2012-12-18 14:30:41 +00001636
1637 RecordData Record;
1638 while (true) {
Chris Lattnere7b154b2013-01-19 21:39:22 +00001639 llvm::BitstreamEntry E = Cursor.advanceSkippingSubblocks();
1640
1641 switch (E.Kind) {
1642 case llvm::BitstreamEntry::SubBlock: // Handled for us already.
1643 case llvm::BitstreamEntry::Error:
1644 Error("malformed block record in AST file");
1645 return;
1646 case llvm::BitstreamEntry::EndBlock:
1647 goto NextCursor;
1648
1649 case llvm::BitstreamEntry::Record:
Chris Lattnere7b154b2013-01-19 21:39:22 +00001650 Record.clear();
Chris Lattner0e6c9402013-01-20 02:38:54 +00001651 switch (Cursor.readRecord(E.ID, Record)) {
Chris Lattnere7b154b2013-01-19 21:39:22 +00001652 default: // Default behavior: ignore.
1653 break;
1654
1655 case PP_MACRO_OBJECT_LIKE:
1656 case PP_MACRO_FUNCTION_LIKE:
Pete Cooper57d3f142015-07-30 17:22:52 +00001657 getLocalIdentifier(*I, Record[0]);
Chris Lattnere7b154b2013-01-19 21:39:22 +00001658 break;
1659
1660 case PP_TOKEN:
1661 // Ignore tokens.
1662 break;
Guy Benyei11169dd2012-12-18 14:30:41 +00001663 }
Guy Benyei11169dd2012-12-18 14:30:41 +00001664 break;
1665 }
1666 }
Chris Lattnere7b154b2013-01-19 21:39:22 +00001667 NextCursor: ;
Guy Benyei11169dd2012-12-18 14:30:41 +00001668 }
1669}
1670
1671namespace {
1672 /// \brief Visitor class used to look up identifirs in an AST file.
1673 class IdentifierLookupVisitor {
1674 StringRef Name;
Richard Smith3b637412015-07-14 18:42:41 +00001675 unsigned NameHash;
Guy Benyei11169dd2012-12-18 14:30:41 +00001676 unsigned PriorGeneration;
Douglas Gregor00a50f72013-01-25 00:38:33 +00001677 unsigned &NumIdentifierLookups;
1678 unsigned &NumIdentifierLookupHits;
Guy Benyei11169dd2012-12-18 14:30:41 +00001679 IdentifierInfo *Found;
Douglas Gregor00a50f72013-01-25 00:38:33 +00001680
Guy Benyei11169dd2012-12-18 14:30:41 +00001681 public:
Douglas Gregor00a50f72013-01-25 00:38:33 +00001682 IdentifierLookupVisitor(StringRef Name, unsigned PriorGeneration,
1683 unsigned &NumIdentifierLookups,
1684 unsigned &NumIdentifierLookupHits)
Richard Smith3b637412015-07-14 18:42:41 +00001685 : Name(Name), NameHash(ASTIdentifierLookupTrait::ComputeHash(Name)),
1686 PriorGeneration(PriorGeneration),
Douglas Gregor00a50f72013-01-25 00:38:33 +00001687 NumIdentifierLookups(NumIdentifierLookups),
1688 NumIdentifierLookupHits(NumIdentifierLookupHits),
1689 Found()
1690 {
1691 }
Benjamin Kramer9a9efba2015-07-25 12:14:04 +00001692
1693 bool operator()(ModuleFile &M) {
Guy Benyei11169dd2012-12-18 14:30:41 +00001694 // If we've already searched this module file, skip it now.
Richard Smithbdf2d932015-07-30 03:37:16 +00001695 if (M.Generation <= PriorGeneration)
Guy Benyei11169dd2012-12-18 14:30:41 +00001696 return true;
Douglas Gregore060e572013-01-25 01:03:03 +00001697
Guy Benyei11169dd2012-12-18 14:30:41 +00001698 ASTIdentifierLookupTable *IdTable
1699 = (ASTIdentifierLookupTable *)M.IdentifierLookupTable;
1700 if (!IdTable)
1701 return false;
Benjamin Kramer9a9efba2015-07-25 12:14:04 +00001702
1703 ASTIdentifierLookupTrait Trait(IdTable->getInfoObj().getReader(), M,
Richard Smithbdf2d932015-07-30 03:37:16 +00001704 Found);
1705 ++NumIdentifierLookups;
Richard Smith3b637412015-07-14 18:42:41 +00001706 ASTIdentifierLookupTable::iterator Pos =
Richard Smithbdf2d932015-07-30 03:37:16 +00001707 IdTable->find_hashed(Name, NameHash, &Trait);
Guy Benyei11169dd2012-12-18 14:30:41 +00001708 if (Pos == IdTable->end())
1709 return false;
1710
1711 // Dereferencing the iterator has the effect of building the
1712 // IdentifierInfo node and populating it with the various
1713 // declarations it needs.
Richard Smithbdf2d932015-07-30 03:37:16 +00001714 ++NumIdentifierLookupHits;
1715 Found = *Pos;
Guy Benyei11169dd2012-12-18 14:30:41 +00001716 return true;
1717 }
1718
1719 // \brief Retrieve the identifier info found within the module
1720 // files.
1721 IdentifierInfo *getIdentifierInfo() const { return Found; }
1722 };
Alexander Kornienkoab9db512015-06-22 23:07:51 +00001723}
Guy Benyei11169dd2012-12-18 14:30:41 +00001724
1725void ASTReader::updateOutOfDateIdentifier(IdentifierInfo &II) {
1726 // Note that we are loading an identifier.
1727 Deserializing AnIdentifier(this);
1728
1729 unsigned PriorGeneration = 0;
1730 if (getContext().getLangOpts().Modules)
1731 PriorGeneration = IdentifierGeneration[&II];
Douglas Gregore060e572013-01-25 01:03:03 +00001732
1733 // If there is a global index, look there first to determine which modules
1734 // provably do not have any results for this identifier.
Douglas Gregor7211ac12013-01-25 23:32:03 +00001735 GlobalModuleIndex::HitSet Hits;
Craig Toppera13603a2014-05-22 05:54:18 +00001736 GlobalModuleIndex::HitSet *HitsPtr = nullptr;
Douglas Gregore060e572013-01-25 01:03:03 +00001737 if (!loadGlobalIndex()) {
Douglas Gregor7211ac12013-01-25 23:32:03 +00001738 if (GlobalIndex->lookupIdentifier(II.getName(), Hits)) {
1739 HitsPtr = &Hits;
Douglas Gregore060e572013-01-25 01:03:03 +00001740 }
1741 }
1742
Douglas Gregor7211ac12013-01-25 23:32:03 +00001743 IdentifierLookupVisitor Visitor(II.getName(), PriorGeneration,
Douglas Gregor00a50f72013-01-25 00:38:33 +00001744 NumIdentifierLookups,
1745 NumIdentifierLookupHits);
Benjamin Kramer9a9efba2015-07-25 12:14:04 +00001746 ModuleMgr.visit(Visitor, HitsPtr);
Guy Benyei11169dd2012-12-18 14:30:41 +00001747 markIdentifierUpToDate(&II);
1748}
1749
1750void ASTReader::markIdentifierUpToDate(IdentifierInfo *II) {
1751 if (!II)
1752 return;
1753
1754 II->setOutOfDate(false);
1755
1756 // Update the generation for this identifier.
1757 if (getContext().getLangOpts().Modules)
Richard Smith053f6c62014-05-16 23:01:30 +00001758 IdentifierGeneration[II] = getGeneration();
Guy Benyei11169dd2012-12-18 14:30:41 +00001759}
1760
Argyrios Kyrtzidiseb663da2013-03-22 21:12:57 +00001761void ASTReader::resolvePendingMacro(IdentifierInfo *II,
1762 const PendingMacroInfo &PMInfo) {
Richard Smithd7329392015-04-21 21:46:32 +00001763 ModuleFile &M = *PMInfo.M;
Argyrios Kyrtzidiseb663da2013-03-22 21:12:57 +00001764
1765 BitstreamCursor &Cursor = M.MacroCursor;
1766 SavedStreamPosition SavedPosition(Cursor);
Richard Smithd7329392015-04-21 21:46:32 +00001767 Cursor.JumpToBit(PMInfo.MacroDirectivesOffset);
Argyrios Kyrtzidiseb663da2013-03-22 21:12:57 +00001768
Richard Smith713369b2015-04-23 20:40:50 +00001769 struct ModuleMacroRecord {
1770 SubmoduleID SubModID;
1771 MacroInfo *MI;
1772 SmallVector<SubmoduleID, 8> Overrides;
1773 };
1774 llvm::SmallVector<ModuleMacroRecord, 8> ModuleMacros;
Argyrios Kyrtzidiseb663da2013-03-22 21:12:57 +00001775
Richard Smithd7329392015-04-21 21:46:32 +00001776 // We expect to see a sequence of PP_MODULE_MACRO records listing exported
1777 // macros, followed by a PP_MACRO_DIRECTIVE_HISTORY record with the complete
1778 // macro histroy.
Argyrios Kyrtzidiseb663da2013-03-22 21:12:57 +00001779 RecordData Record;
Richard Smithd7329392015-04-21 21:46:32 +00001780 while (true) {
1781 llvm::BitstreamEntry Entry =
1782 Cursor.advance(BitstreamCursor::AF_DontPopBlockAtEnd);
1783 if (Entry.Kind != llvm::BitstreamEntry::Record) {
1784 Error("malformed block record in AST file");
1785 return;
1786 }
1787
1788 Record.clear();
Aaron Ballmanc75a1922015-04-22 15:25:05 +00001789 switch ((PreprocessorRecordTypes)Cursor.readRecord(Entry.ID, Record)) {
Richard Smithd7329392015-04-21 21:46:32 +00001790 case PP_MACRO_DIRECTIVE_HISTORY:
1791 break;
1792
1793 case PP_MODULE_MACRO: {
Richard Smith713369b2015-04-23 20:40:50 +00001794 ModuleMacros.push_back(ModuleMacroRecord());
1795 auto &Info = ModuleMacros.back();
Richard Smithe56c8bc2015-04-22 00:26:11 +00001796 Info.SubModID = getGlobalSubmoduleID(M, Record[0]);
1797 Info.MI = getMacro(getGlobalMacroID(M, Record[1]));
Richard Smith713369b2015-04-23 20:40:50 +00001798 for (int I = 2, N = Record.size(); I != N; ++I)
1799 Info.Overrides.push_back(getGlobalSubmoduleID(M, Record[I]));
Richard Smithd7329392015-04-21 21:46:32 +00001800 continue;
1801 }
1802
1803 default:
1804 Error("malformed block record in AST file");
1805 return;
1806 }
1807
1808 // We found the macro directive history; that's the last record
1809 // for this macro.
1810 break;
Argyrios Kyrtzidiseb663da2013-03-22 21:12:57 +00001811 }
1812
Richard Smithd7329392015-04-21 21:46:32 +00001813 // Module macros are listed in reverse dependency order.
Richard Smithe56c8bc2015-04-22 00:26:11 +00001814 {
1815 std::reverse(ModuleMacros.begin(), ModuleMacros.end());
Richard Smithe56c8bc2015-04-22 00:26:11 +00001816 llvm::SmallVector<ModuleMacro*, 8> Overrides;
Richard Smith713369b2015-04-23 20:40:50 +00001817 for (auto &MMR : ModuleMacros) {
Richard Smithe56c8bc2015-04-22 00:26:11 +00001818 Overrides.clear();
Richard Smith713369b2015-04-23 20:40:50 +00001819 for (unsigned ModID : MMR.Overrides) {
Richard Smithb8b2ed62015-04-23 18:18:26 +00001820 Module *Mod = getSubmodule(ModID);
1821 auto *Macro = PP.getModuleMacro(Mod, II);
Richard Smithe56c8bc2015-04-22 00:26:11 +00001822 assert(Macro && "missing definition for overridden macro");
Richard Smith5dbef922015-04-22 02:09:43 +00001823 Overrides.push_back(Macro);
Richard Smithe56c8bc2015-04-22 00:26:11 +00001824 }
1825
1826 bool Inserted = false;
Richard Smith713369b2015-04-23 20:40:50 +00001827 Module *Owner = getSubmodule(MMR.SubModID);
Richard Smith20e883e2015-04-29 23:20:19 +00001828 PP.addModuleMacro(Owner, II, MMR.MI, Overrides, Inserted);
Richard Smithd7329392015-04-21 21:46:32 +00001829 }
1830 }
1831
1832 // Don't read the directive history for a module; we don't have anywhere
1833 // to put it.
1834 if (M.Kind == MK_ImplicitModule || M.Kind == MK_ExplicitModule)
1835 return;
1836
Argyrios Kyrtzidiseb663da2013-03-22 21:12:57 +00001837 // Deserialize the macro directives history in reverse source-order.
Craig Toppera13603a2014-05-22 05:54:18 +00001838 MacroDirective *Latest = nullptr, *Earliest = nullptr;
Argyrios Kyrtzidiseb663da2013-03-22 21:12:57 +00001839 unsigned Idx = 0, N = Record.size();
1840 while (Idx < N) {
Craig Toppera13603a2014-05-22 05:54:18 +00001841 MacroDirective *MD = nullptr;
Argyrios Kyrtzidiseb663da2013-03-22 21:12:57 +00001842 SourceLocation Loc = ReadSourceLocation(M, Record, Idx);
Argyrios Kyrtzidisb6210df2013-03-26 17:17:01 +00001843 MacroDirective::Kind K = (MacroDirective::Kind)Record[Idx++];
1844 switch (K) {
1845 case MacroDirective::MD_Define: {
Richard Smith713369b2015-04-23 20:40:50 +00001846 MacroInfo *MI = getMacro(getGlobalMacroID(M, Record[Idx++]));
Richard Smith3981b172015-04-30 02:16:23 +00001847 MD = PP.AllocateDefMacroDirective(MI, Loc);
Argyrios Kyrtzidisb6210df2013-03-26 17:17:01 +00001848 break;
1849 }
Richard Smithdaa69e02014-07-25 04:40:03 +00001850 case MacroDirective::MD_Undefine: {
Richard Smith3981b172015-04-30 02:16:23 +00001851 MD = PP.AllocateUndefMacroDirective(Loc);
Argyrios Kyrtzidisb6210df2013-03-26 17:17:01 +00001852 break;
Richard Smithdaa69e02014-07-25 04:40:03 +00001853 }
1854 case MacroDirective::MD_Visibility:
Argyrios Kyrtzidisb6210df2013-03-26 17:17:01 +00001855 bool isPublic = Record[Idx++];
1856 MD = PP.AllocateVisibilityMacroDirective(Loc, isPublic);
1857 break;
1858 }
Argyrios Kyrtzidiseb663da2013-03-22 21:12:57 +00001859
1860 if (!Latest)
1861 Latest = MD;
1862 if (Earliest)
1863 Earliest->setPrevious(MD);
1864 Earliest = MD;
1865 }
1866
Richard Smithd6e8c0d2015-05-04 19:58:00 +00001867 if (Latest)
1868 PP.setLoadedMacroDirective(II, Latest);
Argyrios Kyrtzidiseb663da2013-03-22 21:12:57 +00001869}
1870
Argyrios Kyrtzidisce9b49e2014-03-14 02:26:27 +00001871ASTReader::InputFileInfo
1872ASTReader::readInputFileInfo(ModuleFile &F, unsigned ID) {
Ben Langmuir198c1682014-03-07 07:27:49 +00001873 // Go find this input file.
1874 BitstreamCursor &Cursor = F.InputFilesCursor;
1875 SavedStreamPosition SavedPosition(Cursor);
1876 Cursor.JumpToBit(F.InputFileOffsets[ID-1]);
1877
1878 unsigned Code = Cursor.ReadCode();
1879 RecordData Record;
1880 StringRef Blob;
1881
1882 unsigned Result = Cursor.readRecord(Code, Record, &Blob);
1883 assert(static_cast<InputFileRecordTypes>(Result) == INPUT_FILE &&
1884 "invalid record type for input file");
1885 (void)Result;
1886
Argyrios Kyrtzidisce9b49e2014-03-14 02:26:27 +00001887 std::string Filename;
1888 off_t StoredSize;
1889 time_t StoredTime;
1890 bool Overridden;
Richard Smith7ed1bc92014-12-05 22:42:13 +00001891
Ben Langmuir198c1682014-03-07 07:27:49 +00001892 assert(Record[0] == ID && "Bogus stored ID or offset");
1893 StoredSize = static_cast<off_t>(Record[1]);
1894 StoredTime = static_cast<time_t>(Record[2]);
1895 Overridden = static_cast<bool>(Record[3]);
1896 Filename = Blob;
Richard Smith7ed1bc92014-12-05 22:42:13 +00001897 ResolveImportedPath(F, Filename);
1898
Hans Wennborg73945142014-03-14 17:45:06 +00001899 InputFileInfo R = { std::move(Filename), StoredSize, StoredTime, Overridden };
1900 return R;
Ben Langmuir198c1682014-03-07 07:27:49 +00001901}
1902
Argyrios Kyrtzidis61c3d872013-03-01 03:26:04 +00001903InputFile ASTReader::getInputFile(ModuleFile &F, unsigned ID, bool Complain) {
Guy Benyei11169dd2012-12-18 14:30:41 +00001904 // If this ID is bogus, just return an empty input file.
1905 if (ID == 0 || ID > F.InputFilesLoaded.size())
1906 return InputFile();
1907
1908 // If we've already loaded this input file, return it.
Argyrios Kyrtzidis61c3d872013-03-01 03:26:04 +00001909 if (F.InputFilesLoaded[ID-1].getFile())
Guy Benyei11169dd2012-12-18 14:30:41 +00001910 return F.InputFilesLoaded[ID-1];
1911
Argyrios Kyrtzidis9308f0a2014-01-08 19:13:34 +00001912 if (F.InputFilesLoaded[ID-1].isNotFound())
1913 return InputFile();
1914
Guy Benyei11169dd2012-12-18 14:30:41 +00001915 // Go find this input file.
Chris Lattner7fb3bef2013-01-20 00:56:42 +00001916 BitstreamCursor &Cursor = F.InputFilesCursor;
Guy Benyei11169dd2012-12-18 14:30:41 +00001917 SavedStreamPosition SavedPosition(Cursor);
1918 Cursor.JumpToBit(F.InputFileOffsets[ID-1]);
1919
Argyrios Kyrtzidisce9b49e2014-03-14 02:26:27 +00001920 InputFileInfo FI = readInputFileInfo(F, ID);
1921 off_t StoredSize = FI.StoredSize;
1922 time_t StoredTime = FI.StoredTime;
1923 bool Overridden = FI.Overridden;
1924 StringRef Filename = FI.Filename;
Argyrios Kyrtzidis61c3d872013-03-01 03:26:04 +00001925
Ben Langmuir198c1682014-03-07 07:27:49 +00001926 const FileEntry *File
1927 = Overridden? FileMgr.getVirtualFile(Filename, StoredSize, StoredTime)
1928 : FileMgr.getFile(Filename, /*OpenFile=*/false);
1929
1930 // If we didn't find the file, resolve it relative to the
1931 // original directory from which this AST file was created.
Craig Toppera13603a2014-05-22 05:54:18 +00001932 if (File == nullptr && !F.OriginalDir.empty() && !CurrentDir.empty() &&
Ben Langmuir198c1682014-03-07 07:27:49 +00001933 F.OriginalDir != CurrentDir) {
1934 std::string Resolved = resolveFileRelativeToOriginalDir(Filename,
1935 F.OriginalDir,
1936 CurrentDir);
1937 if (!Resolved.empty())
1938 File = FileMgr.getFile(Resolved);
1939 }
1940
1941 // For an overridden file, create a virtual file with the stored
1942 // size/timestamp.
Craig Toppera13603a2014-05-22 05:54:18 +00001943 if (Overridden && File == nullptr) {
Ben Langmuir198c1682014-03-07 07:27:49 +00001944 File = FileMgr.getVirtualFile(Filename, StoredSize, StoredTime);
1945 }
1946
Craig Toppera13603a2014-05-22 05:54:18 +00001947 if (File == nullptr) {
Ben Langmuir198c1682014-03-07 07:27:49 +00001948 if (Complain) {
1949 std::string ErrorStr = "could not find file '";
1950 ErrorStr += Filename;
1951 ErrorStr += "' referenced by AST file";
1952 Error(ErrorStr.c_str());
Guy Benyei11169dd2012-12-18 14:30:41 +00001953 }
Ben Langmuir198c1682014-03-07 07:27:49 +00001954 // Record that we didn't find the file.
1955 F.InputFilesLoaded[ID-1] = InputFile::getNotFound();
1956 return InputFile();
1957 }
Guy Benyei11169dd2012-12-18 14:30:41 +00001958
Ben Langmuir198c1682014-03-07 07:27:49 +00001959 // Check if there was a request to override the contents of the file
1960 // that was part of the precompiled header. Overridding such a file
1961 // can lead to problems when lexing using the source locations from the
1962 // PCH.
1963 SourceManager &SM = getSourceManager();
1964 if (!Overridden && SM.isFileOverridden(File)) {
1965 if (Complain)
1966 Error(diag::err_fe_pch_file_overridden, Filename);
1967 // After emitting the diagnostic, recover by disabling the override so
1968 // that the original file will be used.
1969 SM.disableFileContentsOverride(File);
1970 // The FileEntry is a virtual file entry with the size of the contents
1971 // that would override the original contents. Set it to the original's
1972 // size/time.
1973 FileMgr.modifyFileEntry(const_cast<FileEntry*>(File),
1974 StoredSize, StoredTime);
1975 }
Guy Benyei11169dd2012-12-18 14:30:41 +00001976
Ben Langmuir198c1682014-03-07 07:27:49 +00001977 bool IsOutOfDate = false;
1978
1979 // For an overridden file, there is nothing to validate.
Richard Smith96fdab62014-10-28 16:24:08 +00001980 if (!Overridden && //
1981 (StoredSize != File->getSize() ||
1982#if defined(LLVM_ON_WIN32)
1983 false
1984#else
Ben Langmuir198c1682014-03-07 07:27:49 +00001985 // In our regression testing, the Windows file system seems to
1986 // have inconsistent modification times that sometimes
1987 // erroneously trigger this error-handling path.
Richard Smith96fdab62014-10-28 16:24:08 +00001988 //
Richard Smithe75ee0f2015-08-17 07:13:32 +00001989 // FIXME: This probably also breaks HeaderFileInfo lookups on Windows.
1990 (StoredTime && StoredTime != File->getModificationTime() &&
1991 !DisableValidation)
Guy Benyei11169dd2012-12-18 14:30:41 +00001992#endif
Ben Langmuir198c1682014-03-07 07:27:49 +00001993 )) {
1994 if (Complain) {
1995 // Build a list of the PCH imports that got us here (in reverse).
1996 SmallVector<ModuleFile *, 4> ImportStack(1, &F);
1997 while (ImportStack.back()->ImportedBy.size() > 0)
1998 ImportStack.push_back(ImportStack.back()->ImportedBy[0]);
Ben Langmuire82630d2014-01-17 00:19:09 +00001999
Ben Langmuir198c1682014-03-07 07:27:49 +00002000 // The top-level PCH is stale.
2001 StringRef TopLevelPCHName(ImportStack.back()->FileName);
2002 Error(diag::err_fe_pch_file_modified, Filename, TopLevelPCHName);
Ben Langmuire82630d2014-01-17 00:19:09 +00002003
Ben Langmuir198c1682014-03-07 07:27:49 +00002004 // Print the import stack.
2005 if (ImportStack.size() > 1 && !Diags.isDiagnosticInFlight()) {
2006 Diag(diag::note_pch_required_by)
2007 << Filename << ImportStack[0]->FileName;
2008 for (unsigned I = 1; I < ImportStack.size(); ++I)
Ben Langmuire82630d2014-01-17 00:19:09 +00002009 Diag(diag::note_pch_required_by)
Ben Langmuir198c1682014-03-07 07:27:49 +00002010 << ImportStack[I-1]->FileName << ImportStack[I]->FileName;
Douglas Gregor7029ce12013-03-19 00:28:20 +00002011 }
2012
Ben Langmuir198c1682014-03-07 07:27:49 +00002013 if (!Diags.isDiagnosticInFlight())
2014 Diag(diag::note_pch_rebuild_required) << TopLevelPCHName;
Guy Benyei11169dd2012-12-18 14:30:41 +00002015 }
2016
Ben Langmuir198c1682014-03-07 07:27:49 +00002017 IsOutOfDate = true;
Guy Benyei11169dd2012-12-18 14:30:41 +00002018 }
2019
Ben Langmuir198c1682014-03-07 07:27:49 +00002020 InputFile IF = InputFile(File, Overridden, IsOutOfDate);
2021
2022 // Note that we've loaded this input file.
2023 F.InputFilesLoaded[ID-1] = IF;
2024 return IF;
Guy Benyei11169dd2012-12-18 14:30:41 +00002025}
2026
Richard Smith7ed1bc92014-12-05 22:42:13 +00002027/// \brief If we are loading a relocatable PCH or module file, and the filename
2028/// is not an absolute path, add the system or module root to the beginning of
2029/// the file name.
2030void ASTReader::ResolveImportedPath(ModuleFile &M, std::string &Filename) {
2031 // Resolve relative to the base directory, if we have one.
2032 if (!M.BaseDirectory.empty())
2033 return ResolveImportedPath(Filename, M.BaseDirectory);
Guy Benyei11169dd2012-12-18 14:30:41 +00002034}
2035
Richard Smith7ed1bc92014-12-05 22:42:13 +00002036void ASTReader::ResolveImportedPath(std::string &Filename, StringRef Prefix) {
Guy Benyei11169dd2012-12-18 14:30:41 +00002037 if (Filename.empty() || llvm::sys::path::is_absolute(Filename))
2038 return;
2039
Richard Smith7ed1bc92014-12-05 22:42:13 +00002040 SmallString<128> Buffer;
2041 llvm::sys::path::append(Buffer, Prefix, Filename);
2042 Filename.assign(Buffer.begin(), Buffer.end());
Guy Benyei11169dd2012-12-18 14:30:41 +00002043}
2044
Richard Smith0f99d6a2015-08-09 08:48:41 +00002045static bool isDiagnosedResult(ASTReader::ASTReadResult ARR, unsigned Caps) {
2046 switch (ARR) {
2047 case ASTReader::Failure: return true;
2048 case ASTReader::Missing: return !(Caps & ASTReader::ARR_Missing);
2049 case ASTReader::OutOfDate: return !(Caps & ASTReader::ARR_OutOfDate);
2050 case ASTReader::VersionMismatch: return !(Caps & ASTReader::ARR_VersionMismatch);
2051 case ASTReader::ConfigurationMismatch:
2052 return !(Caps & ASTReader::ARR_ConfigurationMismatch);
2053 case ASTReader::HadErrors: return true;
2054 case ASTReader::Success: return false;
2055 }
2056
2057 llvm_unreachable("unknown ASTReadResult");
2058}
2059
Guy Benyei11169dd2012-12-18 14:30:41 +00002060ASTReader::ASTReadResult
2061ASTReader::ReadControlBlock(ModuleFile &F,
Dmitri Gribenkof8579502013-01-12 19:30:44 +00002062 SmallVectorImpl<ImportedModule> &Loaded,
Ben Langmuirbeee15e2014-04-14 18:00:01 +00002063 const ModuleFile *ImportedBy,
Guy Benyei11169dd2012-12-18 14:30:41 +00002064 unsigned ClientLoadCapabilities) {
Chris Lattner7fb3bef2013-01-20 00:56:42 +00002065 BitstreamCursor &Stream = F.Stream;
Guy Benyei11169dd2012-12-18 14:30:41 +00002066
2067 if (Stream.EnterSubBlock(CONTROL_BLOCK_ID)) {
2068 Error("malformed block record in AST file");
2069 return Failure;
2070 }
2071
Richard Smith1e2cf0d2014-10-31 02:28:58 +00002072 // Should we allow the configuration of the module file to differ from the
2073 // configuration of the current translation unit in a compatible way?
2074 //
2075 // FIXME: Allow this for files explicitly specified with -include-pch too.
2076 bool AllowCompatibleConfigurationMismatch = F.Kind == MK_ExplicitModule;
2077
Guy Benyei11169dd2012-12-18 14:30:41 +00002078 // Read all of the records and blocks in the control block.
2079 RecordData Record;
Richard Smitha1825302014-10-23 22:18:29 +00002080 unsigned NumInputs = 0;
2081 unsigned NumUserInputs = 0;
Chris Lattnere7b154b2013-01-19 21:39:22 +00002082 while (1) {
2083 llvm::BitstreamEntry Entry = Stream.advance();
2084
2085 switch (Entry.Kind) {
2086 case llvm::BitstreamEntry::Error:
2087 Error("malformed block record in AST file");
2088 return Failure;
Dmitri Gribenkof430da42014-02-12 10:33:14 +00002089 case llvm::BitstreamEntry::EndBlock: {
2090 // Validate input files.
2091 const HeaderSearchOptions &HSOpts =
2092 PP.getHeaderSearchInfo().getHeaderSearchOpts();
Ben Langmuircb69b572014-03-07 06:40:32 +00002093
Richard Smitha1825302014-10-23 22:18:29 +00002094 // All user input files reside at the index range [0, NumUserInputs), and
Richard Smith0f99d6a2015-08-09 08:48:41 +00002095 // system input files reside at [NumUserInputs, NumInputs). For explicitly
2096 // loaded module files, ignore missing inputs.
2097 if (!DisableValidation && F.Kind != MK_ExplicitModule) {
Guy Benyei11169dd2012-12-18 14:30:41 +00002098 bool Complain = (ClientLoadCapabilities & ARR_OutOfDate) == 0;
Ben Langmuircb69b572014-03-07 06:40:32 +00002099
Dmitri Gribenkof430da42014-02-12 10:33:14 +00002100 // If we are reading a module, we will create a verification timestamp,
2101 // so we verify all input files. Otherwise, verify only user input
2102 // files.
Ben Langmuircb69b572014-03-07 06:40:32 +00002103
2104 unsigned N = NumUserInputs;
2105 if (ValidateSystemInputs ||
Richard Smithe842a472014-10-22 02:05:46 +00002106 (HSOpts.ModulesValidateOncePerBuildSession &&
Ben Langmuiracb803e2014-11-10 22:13:10 +00002107 F.InputFilesValidationTimestamp <= HSOpts.BuildSessionTimestamp &&
Richard Smithe842a472014-10-22 02:05:46 +00002108 F.Kind == MK_ImplicitModule))
Ben Langmuircb69b572014-03-07 06:40:32 +00002109 N = NumInputs;
2110
Ben Langmuir3d4417c2014-02-07 17:31:11 +00002111 for (unsigned I = 0; I < N; ++I) {
Argyrios Kyrtzidis61c3d872013-03-01 03:26:04 +00002112 InputFile IF = getInputFile(F, I+1, Complain);
2113 if (!IF.getFile() || IF.isOutOfDate())
Guy Benyei11169dd2012-12-18 14:30:41 +00002114 return OutOfDate;
Argyrios Kyrtzidis61c3d872013-03-01 03:26:04 +00002115 }
Guy Benyei11169dd2012-12-18 14:30:41 +00002116 }
Ben Langmuircb69b572014-03-07 06:40:32 +00002117
Argyrios Kyrtzidis6d0753d2014-03-14 03:07:38 +00002118 if (Listener)
Richard Smith216a3bd2015-08-13 17:57:10 +00002119 Listener->visitModuleFile(F.FileName, F.Kind);
Argyrios Kyrtzidis6d0753d2014-03-14 03:07:38 +00002120
Ben Langmuircb69b572014-03-07 06:40:32 +00002121 if (Listener && Listener->needsInputFileVisitation()) {
2122 unsigned N = Listener->needsSystemInputFileVisitation() ? NumInputs
2123 : NumUserInputs;
Argyrios Kyrtzidis68ccbe02014-03-14 02:26:31 +00002124 for (unsigned I = 0; I < N; ++I) {
2125 bool IsSystem = I >= NumUserInputs;
2126 InputFileInfo FI = readInputFileInfo(F, I+1);
Richard Smith216a3bd2015-08-13 17:57:10 +00002127 Listener->visitInputFile(FI.Filename, IsSystem, FI.Overridden,
2128 F.Kind == MK_ExplicitModule);
Argyrios Kyrtzidis68ccbe02014-03-14 02:26:31 +00002129 }
Ben Langmuircb69b572014-03-07 06:40:32 +00002130 }
2131
Guy Benyei11169dd2012-12-18 14:30:41 +00002132 return Success;
Dmitri Gribenkof430da42014-02-12 10:33:14 +00002133 }
2134
Chris Lattnere7b154b2013-01-19 21:39:22 +00002135 case llvm::BitstreamEntry::SubBlock:
2136 switch (Entry.ID) {
Guy Benyei11169dd2012-12-18 14:30:41 +00002137 case INPUT_FILES_BLOCK_ID:
2138 F.InputFilesCursor = Stream;
2139 if (Stream.SkipBlock() || // Skip with the main cursor
2140 // Read the abbreviations
2141 ReadBlockAbbrevs(F.InputFilesCursor, INPUT_FILES_BLOCK_ID)) {
2142 Error("malformed block record in AST file");
2143 return Failure;
2144 }
2145 continue;
Chris Lattnere7b154b2013-01-19 21:39:22 +00002146
Guy Benyei11169dd2012-12-18 14:30:41 +00002147 default:
Chris Lattnere7b154b2013-01-19 21:39:22 +00002148 if (Stream.SkipBlock()) {
2149 Error("malformed block record in AST file");
2150 return Failure;
2151 }
2152 continue;
Guy Benyei11169dd2012-12-18 14:30:41 +00002153 }
Chris Lattnere7b154b2013-01-19 21:39:22 +00002154
2155 case llvm::BitstreamEntry::Record:
2156 // The interesting case.
2157 break;
Guy Benyei11169dd2012-12-18 14:30:41 +00002158 }
2159
2160 // Read and process a record.
2161 Record.clear();
Chris Lattner0e6c9402013-01-20 02:38:54 +00002162 StringRef Blob;
2163 switch ((ControlRecordTypes)Stream.readRecord(Entry.ID, Record, &Blob)) {
Guy Benyei11169dd2012-12-18 14:30:41 +00002164 case METADATA: {
2165 if (Record[0] != VERSION_MAJOR && !DisableValidation) {
2166 if ((ClientLoadCapabilities & ARR_VersionMismatch) == 0)
Dmitri Gribenko2228cd32014-02-11 15:40:09 +00002167 Diag(Record[0] < VERSION_MAJOR? diag::err_pch_version_too_old
2168 : diag::err_pch_version_too_new);
Guy Benyei11169dd2012-12-18 14:30:41 +00002169 return VersionMismatch;
2170 }
2171
Richard Smithe75ee0f2015-08-17 07:13:32 +00002172 bool hasErrors = Record[6];
Guy Benyei11169dd2012-12-18 14:30:41 +00002173 if (hasErrors && !DisableValidation && !AllowASTWithCompilerErrors) {
2174 Diag(diag::err_pch_with_compiler_errors);
2175 return HadErrors;
2176 }
2177
2178 F.RelocatablePCH = Record[4];
Richard Smith7ed1bc92014-12-05 22:42:13 +00002179 // Relative paths in a relocatable PCH are relative to our sysroot.
2180 if (F.RelocatablePCH)
2181 F.BaseDirectory = isysroot.empty() ? "/" : isysroot;
Guy Benyei11169dd2012-12-18 14:30:41 +00002182
Richard Smithe75ee0f2015-08-17 07:13:32 +00002183 F.HasTimestamps = Record[5];
2184
Guy Benyei11169dd2012-12-18 14:30:41 +00002185 const std::string &CurBranch = getClangFullRepositoryVersion();
Chris Lattner0e6c9402013-01-20 02:38:54 +00002186 StringRef ASTBranch = Blob;
Guy Benyei11169dd2012-12-18 14:30:41 +00002187 if (StringRef(CurBranch) != ASTBranch && !DisableValidation) {
2188 if ((ClientLoadCapabilities & ARR_VersionMismatch) == 0)
Dmitri Gribenko2228cd32014-02-11 15:40:09 +00002189 Diag(diag::err_pch_different_branch) << ASTBranch << CurBranch;
Guy Benyei11169dd2012-12-18 14:30:41 +00002190 return VersionMismatch;
2191 }
2192 break;
2193 }
2194
Ben Langmuir487ea142014-10-23 18:05:36 +00002195 case SIGNATURE:
2196 assert((!F.Signature || F.Signature == Record[0]) && "signature changed");
2197 F.Signature = Record[0];
2198 break;
2199
Guy Benyei11169dd2012-12-18 14:30:41 +00002200 case IMPORTS: {
2201 // Load each of the imported PCH files.
2202 unsigned Idx = 0, N = Record.size();
2203 while (Idx < N) {
2204 // Read information about the AST file.
2205 ModuleKind ImportedKind = (ModuleKind)Record[Idx++];
2206 // The import location will be the local one for now; we will adjust
2207 // all import locations of module imports after the global source
2208 // location info are setup.
2209 SourceLocation ImportLoc =
2210 SourceLocation::getFromRawEncoding(Record[Idx++]);
Douglas Gregor7029ce12013-03-19 00:28:20 +00002211 off_t StoredSize = (off_t)Record[Idx++];
2212 time_t StoredModTime = (time_t)Record[Idx++];
Ben Langmuir487ea142014-10-23 18:05:36 +00002213 ASTFileSignature StoredSignature = Record[Idx++];
Richard Smith7ed1bc92014-12-05 22:42:13 +00002214 auto ImportedFile = ReadPath(F, Record, Idx);
Guy Benyei11169dd2012-12-18 14:30:41 +00002215
Richard Smith0f99d6a2015-08-09 08:48:41 +00002216 // If our client can't cope with us being out of date, we can't cope with
2217 // our dependency being missing.
2218 unsigned Capabilities = ClientLoadCapabilities;
2219 if ((ClientLoadCapabilities & ARR_OutOfDate) == 0)
2220 Capabilities &= ~ARR_Missing;
2221
Guy Benyei11169dd2012-12-18 14:30:41 +00002222 // Load the AST file.
Richard Smith0f99d6a2015-08-09 08:48:41 +00002223 auto Result = ReadASTCore(ImportedFile, ImportedKind, ImportLoc, &F,
2224 Loaded, StoredSize, StoredModTime,
2225 StoredSignature, Capabilities);
2226
2227 // If we diagnosed a problem, produce a backtrace.
2228 if (isDiagnosedResult(Result, Capabilities))
2229 Diag(diag::note_module_file_imported_by)
2230 << F.FileName << !F.ModuleName.empty() << F.ModuleName;
2231
2232 switch (Result) {
Guy Benyei11169dd2012-12-18 14:30:41 +00002233 case Failure: return Failure;
2234 // If we have to ignore the dependency, we'll have to ignore this too.
Douglas Gregor2f1806e2013-03-19 00:38:50 +00002235 case Missing:
Guy Benyei11169dd2012-12-18 14:30:41 +00002236 case OutOfDate: return OutOfDate;
2237 case VersionMismatch: return VersionMismatch;
2238 case ConfigurationMismatch: return ConfigurationMismatch;
2239 case HadErrors: return HadErrors;
2240 case Success: break;
2241 }
2242 }
2243 break;
2244 }
2245
2246 case LANGUAGE_OPTIONS: {
2247 bool Complain = (ClientLoadCapabilities & ARR_ConfigurationMismatch) == 0;
Richard Smith1e2cf0d2014-10-31 02:28:58 +00002248 // FIXME: The &F == *ModuleMgr.begin() check is wrong for modules.
Guy Benyei11169dd2012-12-18 14:30:41 +00002249 if (Listener && &F == *ModuleMgr.begin() &&
Richard Smith1e2cf0d2014-10-31 02:28:58 +00002250 ParseLanguageOptions(Record, Complain, *Listener,
2251 AllowCompatibleConfigurationMismatch) &&
Ben Langmuir2cb4a782014-02-05 22:21:15 +00002252 !DisableValidation && !AllowConfigurationMismatch)
Guy Benyei11169dd2012-12-18 14:30:41 +00002253 return ConfigurationMismatch;
2254 break;
2255 }
2256
2257 case TARGET_OPTIONS: {
2258 bool Complain = (ClientLoadCapabilities & ARR_ConfigurationMismatch)==0;
2259 if (Listener && &F == *ModuleMgr.begin() &&
Chandler Carruth0d745bc2015-03-14 04:47:43 +00002260 ParseTargetOptions(Record, Complain, *Listener,
2261 AllowCompatibleConfigurationMismatch) &&
Ben Langmuir2cb4a782014-02-05 22:21:15 +00002262 !DisableValidation && !AllowConfigurationMismatch)
Guy Benyei11169dd2012-12-18 14:30:41 +00002263 return ConfigurationMismatch;
2264 break;
2265 }
2266
2267 case DIAGNOSTIC_OPTIONS: {
Ben Langmuirb92de022014-04-29 16:25:26 +00002268 bool Complain = (ClientLoadCapabilities & ARR_OutOfDate)==0;
Guy Benyei11169dd2012-12-18 14:30:41 +00002269 if (Listener && &F == *ModuleMgr.begin() &&
Richard Smith1e2cf0d2014-10-31 02:28:58 +00002270 !AllowCompatibleConfigurationMismatch &&
Guy Benyei11169dd2012-12-18 14:30:41 +00002271 ParseDiagnosticOptions(Record, Complain, *Listener) &&
Ben Langmuirb92de022014-04-29 16:25:26 +00002272 !DisableValidation)
2273 return OutOfDate;
Guy Benyei11169dd2012-12-18 14:30:41 +00002274 break;
2275 }
2276
2277 case FILE_SYSTEM_OPTIONS: {
2278 bool Complain = (ClientLoadCapabilities & ARR_ConfigurationMismatch)==0;
2279 if (Listener && &F == *ModuleMgr.begin() &&
Richard Smith1e2cf0d2014-10-31 02:28:58 +00002280 !AllowCompatibleConfigurationMismatch &&
Guy Benyei11169dd2012-12-18 14:30:41 +00002281 ParseFileSystemOptions(Record, Complain, *Listener) &&
Ben Langmuir2cb4a782014-02-05 22:21:15 +00002282 !DisableValidation && !AllowConfigurationMismatch)
Guy Benyei11169dd2012-12-18 14:30:41 +00002283 return ConfigurationMismatch;
2284 break;
2285 }
2286
2287 case HEADER_SEARCH_OPTIONS: {
2288 bool Complain = (ClientLoadCapabilities & ARR_ConfigurationMismatch)==0;
2289 if (Listener && &F == *ModuleMgr.begin() &&
Richard Smith1e2cf0d2014-10-31 02:28:58 +00002290 !AllowCompatibleConfigurationMismatch &&
Guy Benyei11169dd2012-12-18 14:30:41 +00002291 ParseHeaderSearchOptions(Record, Complain, *Listener) &&
Ben Langmuir2cb4a782014-02-05 22:21:15 +00002292 !DisableValidation && !AllowConfigurationMismatch)
Guy Benyei11169dd2012-12-18 14:30:41 +00002293 return ConfigurationMismatch;
2294 break;
2295 }
2296
2297 case PREPROCESSOR_OPTIONS: {
2298 bool Complain = (ClientLoadCapabilities & ARR_ConfigurationMismatch)==0;
2299 if (Listener && &F == *ModuleMgr.begin() &&
Richard Smith1e2cf0d2014-10-31 02:28:58 +00002300 !AllowCompatibleConfigurationMismatch &&
Guy Benyei11169dd2012-12-18 14:30:41 +00002301 ParsePreprocessorOptions(Record, Complain, *Listener,
2302 SuggestedPredefines) &&
Ben Langmuir2cb4a782014-02-05 22:21:15 +00002303 !DisableValidation && !AllowConfigurationMismatch)
Guy Benyei11169dd2012-12-18 14:30:41 +00002304 return ConfigurationMismatch;
2305 break;
2306 }
2307
2308 case ORIGINAL_FILE:
2309 F.OriginalSourceFileID = FileID::get(Record[0]);
Chris Lattner0e6c9402013-01-20 02:38:54 +00002310 F.ActualOriginalSourceFileName = Blob;
Guy Benyei11169dd2012-12-18 14:30:41 +00002311 F.OriginalSourceFileName = F.ActualOriginalSourceFileName;
Richard Smith7ed1bc92014-12-05 22:42:13 +00002312 ResolveImportedPath(F, F.OriginalSourceFileName);
Guy Benyei11169dd2012-12-18 14:30:41 +00002313 break;
2314
2315 case ORIGINAL_FILE_ID:
2316 F.OriginalSourceFileID = FileID::get(Record[0]);
2317 break;
2318
2319 case ORIGINAL_PCH_DIR:
Chris Lattner0e6c9402013-01-20 02:38:54 +00002320 F.OriginalDir = Blob;
Guy Benyei11169dd2012-12-18 14:30:41 +00002321 break;
2322
Ben Langmuirbeee15e2014-04-14 18:00:01 +00002323 case MODULE_NAME:
2324 F.ModuleName = Blob;
Ben Langmuir4f5212a2014-04-14 22:12:44 +00002325 if (Listener)
2326 Listener->ReadModuleName(F.ModuleName);
Ben Langmuirbeee15e2014-04-14 18:00:01 +00002327 break;
2328
Richard Smith223d3f22014-12-06 03:21:08 +00002329 case MODULE_DIRECTORY: {
2330 assert(!F.ModuleName.empty() &&
2331 "MODULE_DIRECTORY found before MODULE_NAME");
2332 // If we've already loaded a module map file covering this module, we may
2333 // have a better path for it (relative to the current build).
2334 Module *M = PP.getHeaderSearchInfo().lookupModule(F.ModuleName);
2335 if (M && M->Directory) {
2336 // If we're implicitly loading a module, the base directory can't
2337 // change between the build and use.
2338 if (F.Kind != MK_ExplicitModule) {
2339 const DirectoryEntry *BuildDir =
2340 PP.getFileManager().getDirectory(Blob);
2341 if (!BuildDir || BuildDir != M->Directory) {
2342 if ((ClientLoadCapabilities & ARR_OutOfDate) == 0)
2343 Diag(diag::err_imported_module_relocated)
2344 << F.ModuleName << Blob << M->Directory->getName();
2345 return OutOfDate;
2346 }
2347 }
2348 F.BaseDirectory = M->Directory->getName();
2349 } else {
2350 F.BaseDirectory = Blob;
2351 }
Richard Smith7ed1bc92014-12-05 22:42:13 +00002352 break;
Richard Smith223d3f22014-12-06 03:21:08 +00002353 }
Richard Smith7ed1bc92014-12-05 22:42:13 +00002354
Ben Langmuirbeee15e2014-04-14 18:00:01 +00002355 case MODULE_MAP_FILE:
Ben Langmuir4b8a9e92014-08-12 16:42:33 +00002356 if (ASTReadResult Result =
2357 ReadModuleMapFileBlock(Record, F, ImportedBy, ClientLoadCapabilities))
2358 return Result;
Ben Langmuir264ea152014-11-08 00:06:39 +00002359 break;
2360
Justin Bognerca9c0cc2015-06-21 20:32:36 +00002361 case INPUT_FILE_OFFSETS:
Richard Smitha1825302014-10-23 22:18:29 +00002362 NumInputs = Record[0];
2363 NumUserInputs = Record[1];
Justin Bogner4c183242015-06-21 20:32:40 +00002364 F.InputFileOffsets =
2365 (const llvm::support::unaligned_uint64_t *)Blob.data();
Richard Smitha1825302014-10-23 22:18:29 +00002366 F.InputFilesLoaded.resize(NumInputs);
Guy Benyei11169dd2012-12-18 14:30:41 +00002367 break;
2368 }
2369 }
Guy Benyei11169dd2012-12-18 14:30:41 +00002370}
2371
Ben Langmuir2c9af442014-04-10 17:57:43 +00002372ASTReader::ASTReadResult
2373ASTReader::ReadASTBlock(ModuleFile &F, unsigned ClientLoadCapabilities) {
Chris Lattner7fb3bef2013-01-20 00:56:42 +00002374 BitstreamCursor &Stream = F.Stream;
Guy Benyei11169dd2012-12-18 14:30:41 +00002375
2376 if (Stream.EnterSubBlock(AST_BLOCK_ID)) {
2377 Error("malformed block record in AST file");
Ben Langmuir2c9af442014-04-10 17:57:43 +00002378 return Failure;
Guy Benyei11169dd2012-12-18 14:30:41 +00002379 }
2380
2381 // Read all of the records and blocks for the AST file.
2382 RecordData Record;
Chris Lattnere7b154b2013-01-19 21:39:22 +00002383 while (1) {
2384 llvm::BitstreamEntry Entry = Stream.advance();
2385
2386 switch (Entry.Kind) {
2387 case llvm::BitstreamEntry::Error:
2388 Error("error at end of module block in AST file");
Ben Langmuir2c9af442014-04-10 17:57:43 +00002389 return Failure;
Chris Lattnere7b154b2013-01-19 21:39:22 +00002390 case llvm::BitstreamEntry::EndBlock: {
Richard Smithc0fbba72013-04-03 22:49:41 +00002391 // Outside of C++, we do not store a lookup map for the translation unit.
2392 // Instead, mark it as needing a lookup map to be built if this module
2393 // contains any declarations lexically within it (which it always does!).
2394 // This usually has no cost, since we very rarely need the lookup map for
2395 // the translation unit outside C++.
Guy Benyei11169dd2012-12-18 14:30:41 +00002396 DeclContext *DC = Context.getTranslationUnitDecl();
Richard Smithc0fbba72013-04-03 22:49:41 +00002397 if (DC->hasExternalLexicalStorage() &&
2398 !getContext().getLangOpts().CPlusPlus)
Guy Benyei11169dd2012-12-18 14:30:41 +00002399 DC->setMustBuildLookupTable();
Chris Lattnere7b154b2013-01-19 21:39:22 +00002400
Ben Langmuir2c9af442014-04-10 17:57:43 +00002401 return Success;
Guy Benyei11169dd2012-12-18 14:30:41 +00002402 }
Chris Lattnere7b154b2013-01-19 21:39:22 +00002403 case llvm::BitstreamEntry::SubBlock:
2404 switch (Entry.ID) {
Guy Benyei11169dd2012-12-18 14:30:41 +00002405 case DECLTYPES_BLOCK_ID:
2406 // We lazily load the decls block, but we want to set up the
2407 // DeclsCursor cursor to point into it. Clone our current bitcode
2408 // cursor to it, enter the block and read the abbrevs in that block.
2409 // With the main cursor, we just skip over it.
2410 F.DeclsCursor = Stream;
2411 if (Stream.SkipBlock() || // Skip with the main cursor.
2412 // Read the abbrevs.
2413 ReadBlockAbbrevs(F.DeclsCursor, DECLTYPES_BLOCK_ID)) {
2414 Error("malformed block record in AST file");
Ben Langmuir2c9af442014-04-10 17:57:43 +00002415 return Failure;
Guy Benyei11169dd2012-12-18 14:30:41 +00002416 }
2417 break;
Richard Smithb9eab6d2014-03-20 19:44:17 +00002418
Guy Benyei11169dd2012-12-18 14:30:41 +00002419 case PREPROCESSOR_BLOCK_ID:
2420 F.MacroCursor = Stream;
2421 if (!PP.getExternalSource())
2422 PP.setExternalSource(this);
Chris Lattnere7b154b2013-01-19 21:39:22 +00002423
Guy Benyei11169dd2012-12-18 14:30:41 +00002424 if (Stream.SkipBlock() ||
2425 ReadBlockAbbrevs(F.MacroCursor, PREPROCESSOR_BLOCK_ID)) {
2426 Error("malformed block record in AST file");
Ben Langmuir2c9af442014-04-10 17:57:43 +00002427 return Failure;
Guy Benyei11169dd2012-12-18 14:30:41 +00002428 }
2429 F.MacroStartOffset = F.MacroCursor.GetCurrentBitNo();
2430 break;
Chris Lattnere7b154b2013-01-19 21:39:22 +00002431
Guy Benyei11169dd2012-12-18 14:30:41 +00002432 case PREPROCESSOR_DETAIL_BLOCK_ID:
2433 F.PreprocessorDetailCursor = Stream;
2434 if (Stream.SkipBlock() ||
Chris Lattnere7b154b2013-01-19 21:39:22 +00002435 ReadBlockAbbrevs(F.PreprocessorDetailCursor,
Guy Benyei11169dd2012-12-18 14:30:41 +00002436 PREPROCESSOR_DETAIL_BLOCK_ID)) {
Chris Lattnere7b154b2013-01-19 21:39:22 +00002437 Error("malformed preprocessor detail record in AST file");
Ben Langmuir2c9af442014-04-10 17:57:43 +00002438 return Failure;
Chris Lattnere7b154b2013-01-19 21:39:22 +00002439 }
Guy Benyei11169dd2012-12-18 14:30:41 +00002440 F.PreprocessorDetailStartOffset
Chris Lattnere7b154b2013-01-19 21:39:22 +00002441 = F.PreprocessorDetailCursor.GetCurrentBitNo();
2442
Guy Benyei11169dd2012-12-18 14:30:41 +00002443 if (!PP.getPreprocessingRecord())
2444 PP.createPreprocessingRecord();
2445 if (!PP.getPreprocessingRecord()->getExternalSource())
2446 PP.getPreprocessingRecord()->SetExternalSource(*this);
2447 break;
2448
2449 case SOURCE_MANAGER_BLOCK_ID:
2450 if (ReadSourceManagerBlock(F))
Ben Langmuir2c9af442014-04-10 17:57:43 +00002451 return Failure;
Guy Benyei11169dd2012-12-18 14:30:41 +00002452 break;
Chris Lattnere7b154b2013-01-19 21:39:22 +00002453
Guy Benyei11169dd2012-12-18 14:30:41 +00002454 case SUBMODULE_BLOCK_ID:
Ben Langmuir2c9af442014-04-10 17:57:43 +00002455 if (ASTReadResult Result = ReadSubmoduleBlock(F, ClientLoadCapabilities))
2456 return Result;
Guy Benyei11169dd2012-12-18 14:30:41 +00002457 break;
Chris Lattnere7b154b2013-01-19 21:39:22 +00002458
Guy Benyei11169dd2012-12-18 14:30:41 +00002459 case COMMENTS_BLOCK_ID: {
Chris Lattner7fb3bef2013-01-20 00:56:42 +00002460 BitstreamCursor C = Stream;
Guy Benyei11169dd2012-12-18 14:30:41 +00002461 if (Stream.SkipBlock() ||
2462 ReadBlockAbbrevs(C, COMMENTS_BLOCK_ID)) {
2463 Error("malformed comments block in AST file");
Ben Langmuir2c9af442014-04-10 17:57:43 +00002464 return Failure;
Guy Benyei11169dd2012-12-18 14:30:41 +00002465 }
2466 CommentsCursors.push_back(std::make_pair(C, &F));
2467 break;
2468 }
Chris Lattnere7b154b2013-01-19 21:39:22 +00002469
Guy Benyei11169dd2012-12-18 14:30:41 +00002470 default:
Chris Lattnere7b154b2013-01-19 21:39:22 +00002471 if (Stream.SkipBlock()) {
2472 Error("malformed block record in AST file");
Ben Langmuir2c9af442014-04-10 17:57:43 +00002473 return Failure;
Chris Lattnere7b154b2013-01-19 21:39:22 +00002474 }
2475 break;
Guy Benyei11169dd2012-12-18 14:30:41 +00002476 }
2477 continue;
Chris Lattnere7b154b2013-01-19 21:39:22 +00002478
2479 case llvm::BitstreamEntry::Record:
2480 // The interesting case.
2481 break;
Guy Benyei11169dd2012-12-18 14:30:41 +00002482 }
2483
2484 // Read and process a record.
2485 Record.clear();
Chris Lattner0e6c9402013-01-20 02:38:54 +00002486 StringRef Blob;
2487 switch ((ASTRecordTypes)Stream.readRecord(Entry.ID, Record, &Blob)) {
Guy Benyei11169dd2012-12-18 14:30:41 +00002488 default: // Default behavior: ignore.
2489 break;
2490
2491 case TYPE_OFFSET: {
2492 if (F.LocalNumTypes != 0) {
2493 Error("duplicate TYPE_OFFSET record in AST file");
Ben Langmuir2c9af442014-04-10 17:57:43 +00002494 return Failure;
Guy Benyei11169dd2012-12-18 14:30:41 +00002495 }
Chris Lattner0e6c9402013-01-20 02:38:54 +00002496 F.TypeOffsets = (const uint32_t *)Blob.data();
Guy Benyei11169dd2012-12-18 14:30:41 +00002497 F.LocalNumTypes = Record[0];
2498 unsigned LocalBaseTypeIndex = Record[1];
2499 F.BaseTypeIndex = getTotalNumTypes();
2500
2501 if (F.LocalNumTypes > 0) {
2502 // Introduce the global -> local mapping for types within this module.
2503 GlobalTypeMap.insert(std::make_pair(getTotalNumTypes(), &F));
2504
2505 // Introduce the local -> global mapping for types within this module.
2506 F.TypeRemap.insertOrReplace(
2507 std::make_pair(LocalBaseTypeIndex,
2508 F.BaseTypeIndex - LocalBaseTypeIndex));
Ben Langmuir52ca6782014-10-20 16:27:32 +00002509
2510 TypesLoaded.resize(TypesLoaded.size() + F.LocalNumTypes);
Guy Benyei11169dd2012-12-18 14:30:41 +00002511 }
2512 break;
2513 }
2514
2515 case DECL_OFFSET: {
2516 if (F.LocalNumDecls != 0) {
2517 Error("duplicate DECL_OFFSET record in AST file");
Ben Langmuir2c9af442014-04-10 17:57:43 +00002518 return Failure;
Guy Benyei11169dd2012-12-18 14:30:41 +00002519 }
Chris Lattner0e6c9402013-01-20 02:38:54 +00002520 F.DeclOffsets = (const DeclOffset *)Blob.data();
Guy Benyei11169dd2012-12-18 14:30:41 +00002521 F.LocalNumDecls = Record[0];
2522 unsigned LocalBaseDeclID = Record[1];
2523 F.BaseDeclID = getTotalNumDecls();
2524
2525 if (F.LocalNumDecls > 0) {
2526 // Introduce the global -> local mapping for declarations within this
2527 // module.
2528 GlobalDeclMap.insert(
2529 std::make_pair(getTotalNumDecls() + NUM_PREDEF_DECL_IDS, &F));
2530
2531 // Introduce the local -> global mapping for declarations within this
2532 // module.
2533 F.DeclRemap.insertOrReplace(
2534 std::make_pair(LocalBaseDeclID, F.BaseDeclID - LocalBaseDeclID));
2535
2536 // Introduce the global -> local mapping for declarations within this
2537 // module.
2538 F.GlobalToLocalDeclIDs[&F] = LocalBaseDeclID;
Ben Langmuirfe971d92014-08-16 04:54:18 +00002539
Ben Langmuir52ca6782014-10-20 16:27:32 +00002540 DeclsLoaded.resize(DeclsLoaded.size() + F.LocalNumDecls);
2541 }
Guy Benyei11169dd2012-12-18 14:30:41 +00002542 break;
2543 }
2544
2545 case TU_UPDATE_LEXICAL: {
2546 DeclContext *TU = Context.getTranslationUnitDecl();
Richard Smith82f8fcd2015-08-06 22:07:25 +00002547 LexicalContents Contents(
2548 reinterpret_cast<const llvm::support::unaligned_uint32_t *>(
2549 Blob.data()),
2550 static_cast<unsigned int>(Blob.size() / 4));
2551 TULexicalDecls.push_back(std::make_pair(&F, Contents));
Guy Benyei11169dd2012-12-18 14:30:41 +00002552 TU->setHasExternalLexicalStorage(true);
2553 break;
2554 }
2555
2556 case UPDATE_VISIBLE: {
2557 unsigned Idx = 0;
2558 serialization::DeclID ID = ReadDeclID(F, Record, Idx);
Richard Smith0f4e2c42015-08-06 04:23:48 +00002559 auto *Data = (const unsigned char*)Blob.data();
2560 unsigned BucketOffset = Record[Idx++];
2561 PendingVisibleUpdates[ID].push_back(
2562 PendingVisibleUpdate{&F, Data, BucketOffset});
2563 // If we've already loaded the decl, perform the updates when we finish
2564 // loading this block.
2565 if (Decl *D = GetExistingDecl(ID))
2566 PendingUpdateRecords.push_back(std::make_pair(ID, D));
Guy Benyei11169dd2012-12-18 14:30:41 +00002567 break;
2568 }
2569
2570 case IDENTIFIER_TABLE:
Chris Lattner0e6c9402013-01-20 02:38:54 +00002571 F.IdentifierTableData = Blob.data();
Guy Benyei11169dd2012-12-18 14:30:41 +00002572 if (Record[0]) {
Justin Bognerda4e6502014-04-14 16:34:29 +00002573 F.IdentifierLookupTable = ASTIdentifierLookupTable::Create(
2574 (const unsigned char *)F.IdentifierTableData + Record[0],
2575 (const unsigned char *)F.IdentifierTableData + sizeof(uint32_t),
2576 (const unsigned char *)F.IdentifierTableData,
2577 ASTIdentifierLookupTrait(*this, F));
Guy Benyei11169dd2012-12-18 14:30:41 +00002578
2579 PP.getIdentifierTable().setExternalIdentifierLookup(this);
2580 }
2581 break;
2582
2583 case IDENTIFIER_OFFSET: {
2584 if (F.LocalNumIdentifiers != 0) {
2585 Error("duplicate IDENTIFIER_OFFSET record in AST file");
Ben Langmuir2c9af442014-04-10 17:57:43 +00002586 return Failure;
Guy Benyei11169dd2012-12-18 14:30:41 +00002587 }
Chris Lattner0e6c9402013-01-20 02:38:54 +00002588 F.IdentifierOffsets = (const uint32_t *)Blob.data();
Guy Benyei11169dd2012-12-18 14:30:41 +00002589 F.LocalNumIdentifiers = Record[0];
2590 unsigned LocalBaseIdentifierID = Record[1];
2591 F.BaseIdentifierID = getTotalNumIdentifiers();
2592
2593 if (F.LocalNumIdentifiers > 0) {
2594 // Introduce the global -> local mapping for identifiers within this
2595 // module.
2596 GlobalIdentifierMap.insert(std::make_pair(getTotalNumIdentifiers() + 1,
2597 &F));
2598
2599 // Introduce the local -> global mapping for identifiers within this
2600 // module.
2601 F.IdentifierRemap.insertOrReplace(
2602 std::make_pair(LocalBaseIdentifierID,
2603 F.BaseIdentifierID - LocalBaseIdentifierID));
Ben Langmuirfe971d92014-08-16 04:54:18 +00002604
Ben Langmuir52ca6782014-10-20 16:27:32 +00002605 IdentifiersLoaded.resize(IdentifiersLoaded.size()
2606 + F.LocalNumIdentifiers);
2607 }
Guy Benyei11169dd2012-12-18 14:30:41 +00002608 break;
2609 }
2610
Richard Smith33e0f7e2015-07-22 02:08:40 +00002611 case INTERESTING_IDENTIFIERS:
2612 F.PreloadIdentifierOffsets.assign(Record.begin(), Record.end());
2613 break;
2614
Ben Langmuir332aafe2014-01-31 01:06:56 +00002615 case EAGERLY_DESERIALIZED_DECLS:
Richard Smith9e2341d2015-03-23 03:25:59 +00002616 // FIXME: Skip reading this record if our ASTConsumer doesn't care
2617 // about "interesting" decls (for instance, if we're building a module).
Guy Benyei11169dd2012-12-18 14:30:41 +00002618 for (unsigned I = 0, N = Record.size(); I != N; ++I)
Ben Langmuir332aafe2014-01-31 01:06:56 +00002619 EagerlyDeserializedDecls.push_back(getGlobalDeclID(F, Record[I]));
Guy Benyei11169dd2012-12-18 14:30:41 +00002620 break;
2621
2622 case SPECIAL_TYPES:
Douglas Gregor44180f82013-02-01 23:45:03 +00002623 if (SpecialTypes.empty()) {
2624 for (unsigned I = 0, N = Record.size(); I != N; ++I)
2625 SpecialTypes.push_back(getGlobalTypeID(F, Record[I]));
2626 break;
2627 }
2628
2629 if (SpecialTypes.size() != Record.size()) {
2630 Error("invalid special-types record");
Ben Langmuir2c9af442014-04-10 17:57:43 +00002631 return Failure;
Douglas Gregor44180f82013-02-01 23:45:03 +00002632 }
2633
2634 for (unsigned I = 0, N = Record.size(); I != N; ++I) {
2635 serialization::TypeID ID = getGlobalTypeID(F, Record[I]);
2636 if (!SpecialTypes[I])
2637 SpecialTypes[I] = ID;
2638 // FIXME: If ID && SpecialTypes[I] != ID, do we need a separate
2639 // merge step?
2640 }
Guy Benyei11169dd2012-12-18 14:30:41 +00002641 break;
2642
2643 case STATISTICS:
2644 TotalNumStatements += Record[0];
2645 TotalNumMacros += Record[1];
2646 TotalLexicalDeclContexts += Record[2];
2647 TotalVisibleDeclContexts += Record[3];
2648 break;
2649
2650 case UNUSED_FILESCOPED_DECLS:
2651 for (unsigned I = 0, N = Record.size(); I != N; ++I)
2652 UnusedFileScopedDecls.push_back(getGlobalDeclID(F, Record[I]));
2653 break;
2654
2655 case DELEGATING_CTORS:
2656 for (unsigned I = 0, N = Record.size(); I != N; ++I)
2657 DelegatingCtorDecls.push_back(getGlobalDeclID(F, Record[I]));
2658 break;
2659
2660 case WEAK_UNDECLARED_IDENTIFIERS:
2661 if (Record.size() % 4 != 0) {
2662 Error("invalid weak identifiers record");
Ben Langmuir2c9af442014-04-10 17:57:43 +00002663 return Failure;
Guy Benyei11169dd2012-12-18 14:30:41 +00002664 }
2665
2666 // FIXME: Ignore weak undeclared identifiers from non-original PCH
2667 // files. This isn't the way to do it :)
2668 WeakUndeclaredIdentifiers.clear();
2669
2670 // Translate the weak, undeclared identifiers into global IDs.
2671 for (unsigned I = 0, N = Record.size(); I < N; /* in loop */) {
2672 WeakUndeclaredIdentifiers.push_back(
2673 getGlobalIdentifierID(F, Record[I++]));
2674 WeakUndeclaredIdentifiers.push_back(
2675 getGlobalIdentifierID(F, Record[I++]));
2676 WeakUndeclaredIdentifiers.push_back(
2677 ReadSourceLocation(F, Record, I).getRawEncoding());
2678 WeakUndeclaredIdentifiers.push_back(Record[I++]);
2679 }
2680 break;
2681
Guy Benyei11169dd2012-12-18 14:30:41 +00002682 case SELECTOR_OFFSETS: {
Chris Lattner0e6c9402013-01-20 02:38:54 +00002683 F.SelectorOffsets = (const uint32_t *)Blob.data();
Guy Benyei11169dd2012-12-18 14:30:41 +00002684 F.LocalNumSelectors = Record[0];
2685 unsigned LocalBaseSelectorID = Record[1];
2686 F.BaseSelectorID = getTotalNumSelectors();
2687
2688 if (F.LocalNumSelectors > 0) {
2689 // Introduce the global -> local mapping for selectors within this
2690 // module.
2691 GlobalSelectorMap.insert(std::make_pair(getTotalNumSelectors()+1, &F));
2692
2693 // Introduce the local -> global mapping for selectors within this
2694 // module.
2695 F.SelectorRemap.insertOrReplace(
2696 std::make_pair(LocalBaseSelectorID,
2697 F.BaseSelectorID - LocalBaseSelectorID));
Ben Langmuir52ca6782014-10-20 16:27:32 +00002698
2699 SelectorsLoaded.resize(SelectorsLoaded.size() + F.LocalNumSelectors);
Guy Benyei11169dd2012-12-18 14:30:41 +00002700 }
2701 break;
2702 }
2703
2704 case METHOD_POOL:
Chris Lattner0e6c9402013-01-20 02:38:54 +00002705 F.SelectorLookupTableData = (const unsigned char *)Blob.data();
Guy Benyei11169dd2012-12-18 14:30:41 +00002706 if (Record[0])
2707 F.SelectorLookupTable
2708 = ASTSelectorLookupTable::Create(
2709 F.SelectorLookupTableData + Record[0],
2710 F.SelectorLookupTableData,
2711 ASTSelectorLookupTrait(*this, F));
2712 TotalNumMethodPoolEntries += Record[1];
2713 break;
2714
2715 case REFERENCED_SELECTOR_POOL:
2716 if (!Record.empty()) {
2717 for (unsigned Idx = 0, N = Record.size() - 1; Idx < N; /* in loop */) {
2718 ReferencedSelectorsData.push_back(getGlobalSelectorID(F,
2719 Record[Idx++]));
2720 ReferencedSelectorsData.push_back(ReadSourceLocation(F, Record, Idx).
2721 getRawEncoding());
2722 }
2723 }
2724 break;
2725
2726 case PP_COUNTER_VALUE:
2727 if (!Record.empty() && Listener)
2728 Listener->ReadCounter(F, Record[0]);
2729 break;
2730
2731 case FILE_SORTED_DECLS:
Chris Lattner0e6c9402013-01-20 02:38:54 +00002732 F.FileSortedDecls = (const DeclID *)Blob.data();
Guy Benyei11169dd2012-12-18 14:30:41 +00002733 F.NumFileSortedDecls = Record[0];
2734 break;
2735
2736 case SOURCE_LOCATION_OFFSETS: {
Chris Lattner0e6c9402013-01-20 02:38:54 +00002737 F.SLocEntryOffsets = (const uint32_t *)Blob.data();
Guy Benyei11169dd2012-12-18 14:30:41 +00002738 F.LocalNumSLocEntries = Record[0];
2739 unsigned SLocSpaceSize = Record[1];
Benjamin Kramer867ea1d2014-03-02 13:01:17 +00002740 std::tie(F.SLocEntryBaseID, F.SLocEntryBaseOffset) =
Ben Langmuir52ca6782014-10-20 16:27:32 +00002741 SourceMgr.AllocateLoadedSLocEntries(F.LocalNumSLocEntries,
Guy Benyei11169dd2012-12-18 14:30:41 +00002742 SLocSpaceSize);
Richard Smith78d81ec2015-08-12 22:25:24 +00002743 if (!F.SLocEntryBaseID) {
2744 Error("ran out of source locations");
2745 break;
2746 }
Guy Benyei11169dd2012-12-18 14:30:41 +00002747 // Make our entry in the range map. BaseID is negative and growing, so
2748 // we invert it. Because we invert it, though, we need the other end of
2749 // the range.
2750 unsigned RangeStart =
2751 unsigned(-F.SLocEntryBaseID) - F.LocalNumSLocEntries + 1;
2752 GlobalSLocEntryMap.insert(std::make_pair(RangeStart, &F));
2753 F.FirstLoc = SourceLocation::getFromRawEncoding(F.SLocEntryBaseOffset);
2754
2755 // SLocEntryBaseOffset is lower than MaxLoadedOffset and decreasing.
2756 assert((F.SLocEntryBaseOffset & (1U << 31U)) == 0);
2757 GlobalSLocOffsetMap.insert(
2758 std::make_pair(SourceManager::MaxLoadedOffset - F.SLocEntryBaseOffset
2759 - SLocSpaceSize,&F));
2760
2761 // Initialize the remapping table.
2762 // Invalid stays invalid.
Richard Smithb9eab6d2014-03-20 19:44:17 +00002763 F.SLocRemap.insertOrReplace(std::make_pair(0U, 0));
Guy Benyei11169dd2012-12-18 14:30:41 +00002764 // This module. Base was 2 when being compiled.
Richard Smithb9eab6d2014-03-20 19:44:17 +00002765 F.SLocRemap.insertOrReplace(std::make_pair(2U,
Guy Benyei11169dd2012-12-18 14:30:41 +00002766 static_cast<int>(F.SLocEntryBaseOffset - 2)));
2767
2768 TotalNumSLocEntries += F.LocalNumSLocEntries;
2769 break;
2770 }
2771
2772 case MODULE_OFFSET_MAP: {
2773 // Additional remapping information.
Chris Lattner0e6c9402013-01-20 02:38:54 +00002774 const unsigned char *Data = (const unsigned char*)Blob.data();
2775 const unsigned char *DataEnd = Data + Blob.size();
Richard Smithb9eab6d2014-03-20 19:44:17 +00002776
2777 // If we see this entry before SOURCE_LOCATION_OFFSETS, add placeholders.
2778 if (F.SLocRemap.find(0) == F.SLocRemap.end()) {
2779 F.SLocRemap.insert(std::make_pair(0U, 0));
2780 F.SLocRemap.insert(std::make_pair(2U, 1));
2781 }
2782
Guy Benyei11169dd2012-12-18 14:30:41 +00002783 // Continuous range maps we may be updating in our module.
Ben Langmuir785180e2014-10-20 16:27:30 +00002784 typedef ContinuousRangeMap<uint32_t, int, 2>::Builder
2785 RemapBuilder;
2786 RemapBuilder SLocRemap(F.SLocRemap);
2787 RemapBuilder IdentifierRemap(F.IdentifierRemap);
2788 RemapBuilder MacroRemap(F.MacroRemap);
2789 RemapBuilder PreprocessedEntityRemap(F.PreprocessedEntityRemap);
2790 RemapBuilder SubmoduleRemap(F.SubmoduleRemap);
2791 RemapBuilder SelectorRemap(F.SelectorRemap);
2792 RemapBuilder DeclRemap(F.DeclRemap);
2793 RemapBuilder TypeRemap(F.TypeRemap);
Guy Benyei11169dd2012-12-18 14:30:41 +00002794
Richard Smithd8879c82015-08-24 21:59:32 +00002795 while (Data < DataEnd) {
Justin Bogner57ba0b22014-03-28 22:03:24 +00002796 using namespace llvm::support;
2797 uint16_t Len = endian::readNext<uint16_t, little, unaligned>(Data);
Guy Benyei11169dd2012-12-18 14:30:41 +00002798 StringRef Name = StringRef((const char*)Data, Len);
2799 Data += Len;
2800 ModuleFile *OM = ModuleMgr.lookup(Name);
2801 if (!OM) {
2802 Error("SourceLocation remap refers to unknown module");
Ben Langmuir2c9af442014-04-10 17:57:43 +00002803 return Failure;
Guy Benyei11169dd2012-12-18 14:30:41 +00002804 }
2805
Justin Bogner57ba0b22014-03-28 22:03:24 +00002806 uint32_t SLocOffset =
2807 endian::readNext<uint32_t, little, unaligned>(Data);
2808 uint32_t IdentifierIDOffset =
2809 endian::readNext<uint32_t, little, unaligned>(Data);
2810 uint32_t MacroIDOffset =
2811 endian::readNext<uint32_t, little, unaligned>(Data);
2812 uint32_t PreprocessedEntityIDOffset =
2813 endian::readNext<uint32_t, little, unaligned>(Data);
2814 uint32_t SubmoduleIDOffset =
2815 endian::readNext<uint32_t, little, unaligned>(Data);
2816 uint32_t SelectorIDOffset =
2817 endian::readNext<uint32_t, little, unaligned>(Data);
2818 uint32_t DeclIDOffset =
2819 endian::readNext<uint32_t, little, unaligned>(Data);
2820 uint32_t TypeIndexOffset =
2821 endian::readNext<uint32_t, little, unaligned>(Data);
2822
Ben Langmuir785180e2014-10-20 16:27:30 +00002823 uint32_t None = std::numeric_limits<uint32_t>::max();
2824
2825 auto mapOffset = [&](uint32_t Offset, uint32_t BaseOffset,
2826 RemapBuilder &Remap) {
2827 if (Offset != None)
2828 Remap.insert(std::make_pair(Offset,
2829 static_cast<int>(BaseOffset - Offset)));
2830 };
2831 mapOffset(SLocOffset, OM->SLocEntryBaseOffset, SLocRemap);
2832 mapOffset(IdentifierIDOffset, OM->BaseIdentifierID, IdentifierRemap);
2833 mapOffset(MacroIDOffset, OM->BaseMacroID, MacroRemap);
2834 mapOffset(PreprocessedEntityIDOffset, OM->BasePreprocessedEntityID,
2835 PreprocessedEntityRemap);
2836 mapOffset(SubmoduleIDOffset, OM->BaseSubmoduleID, SubmoduleRemap);
2837 mapOffset(SelectorIDOffset, OM->BaseSelectorID, SelectorRemap);
2838 mapOffset(DeclIDOffset, OM->BaseDeclID, DeclRemap);
2839 mapOffset(TypeIndexOffset, OM->BaseTypeIndex, TypeRemap);
Guy Benyei11169dd2012-12-18 14:30:41 +00002840
2841 // Global -> local mappings.
2842 F.GlobalToLocalDeclIDs[OM] = DeclIDOffset;
2843 }
2844 break;
2845 }
2846
2847 case SOURCE_MANAGER_LINE_TABLE:
2848 if (ParseLineTable(F, Record))
Ben Langmuir2c9af442014-04-10 17:57:43 +00002849 return Failure;
Guy Benyei11169dd2012-12-18 14:30:41 +00002850 break;
2851
2852 case SOURCE_LOCATION_PRELOADS: {
2853 // Need to transform from the local view (1-based IDs) to the global view,
2854 // which is based off F.SLocEntryBaseID.
2855 if (!F.PreloadSLocEntries.empty()) {
2856 Error("Multiple SOURCE_LOCATION_PRELOADS records in AST file");
Ben Langmuir2c9af442014-04-10 17:57:43 +00002857 return Failure;
Guy Benyei11169dd2012-12-18 14:30:41 +00002858 }
2859
2860 F.PreloadSLocEntries.swap(Record);
2861 break;
2862 }
2863
2864 case EXT_VECTOR_DECLS:
2865 for (unsigned I = 0, N = Record.size(); I != N; ++I)
2866 ExtVectorDecls.push_back(getGlobalDeclID(F, Record[I]));
2867 break;
2868
2869 case VTABLE_USES:
2870 if (Record.size() % 3 != 0) {
2871 Error("Invalid VTABLE_USES record");
Ben Langmuir2c9af442014-04-10 17:57:43 +00002872 return Failure;
Guy Benyei11169dd2012-12-18 14:30:41 +00002873 }
2874
2875 // Later tables overwrite earlier ones.
2876 // FIXME: Modules will have some trouble with this. This is clearly not
2877 // the right way to do this.
2878 VTableUses.clear();
2879
2880 for (unsigned Idx = 0, N = Record.size(); Idx != N; /* In loop */) {
2881 VTableUses.push_back(getGlobalDeclID(F, Record[Idx++]));
2882 VTableUses.push_back(
2883 ReadSourceLocation(F, Record, Idx).getRawEncoding());
2884 VTableUses.push_back(Record[Idx++]);
2885 }
2886 break;
2887
Guy Benyei11169dd2012-12-18 14:30:41 +00002888 case PENDING_IMPLICIT_INSTANTIATIONS:
2889 if (PendingInstantiations.size() % 2 != 0) {
2890 Error("Invalid existing PendingInstantiations");
Ben Langmuir2c9af442014-04-10 17:57:43 +00002891 return Failure;
Guy Benyei11169dd2012-12-18 14:30:41 +00002892 }
2893
2894 if (Record.size() % 2 != 0) {
2895 Error("Invalid PENDING_IMPLICIT_INSTANTIATIONS block");
Ben Langmuir2c9af442014-04-10 17:57:43 +00002896 return Failure;
Guy Benyei11169dd2012-12-18 14:30:41 +00002897 }
2898
2899 for (unsigned I = 0, N = Record.size(); I != N; /* in loop */) {
2900 PendingInstantiations.push_back(getGlobalDeclID(F, Record[I++]));
2901 PendingInstantiations.push_back(
2902 ReadSourceLocation(F, Record, I).getRawEncoding());
2903 }
2904 break;
2905
2906 case SEMA_DECL_REFS:
Richard Smith3d8e97e2013-10-18 06:54:39 +00002907 if (Record.size() != 2) {
2908 Error("Invalid SEMA_DECL_REFS block");
Ben Langmuir2c9af442014-04-10 17:57:43 +00002909 return Failure;
Richard Smith3d8e97e2013-10-18 06:54:39 +00002910 }
Guy Benyei11169dd2012-12-18 14:30:41 +00002911 for (unsigned I = 0, N = Record.size(); I != N; ++I)
2912 SemaDeclRefs.push_back(getGlobalDeclID(F, Record[I]));
2913 break;
2914
2915 case PPD_ENTITIES_OFFSETS: {
Chris Lattner0e6c9402013-01-20 02:38:54 +00002916 F.PreprocessedEntityOffsets = (const PPEntityOffset *)Blob.data();
2917 assert(Blob.size() % sizeof(PPEntityOffset) == 0);
2918 F.NumPreprocessedEntities = Blob.size() / sizeof(PPEntityOffset);
Guy Benyei11169dd2012-12-18 14:30:41 +00002919
2920 unsigned LocalBasePreprocessedEntityID = Record[0];
2921
2922 unsigned StartingID;
2923 if (!PP.getPreprocessingRecord())
2924 PP.createPreprocessingRecord();
2925 if (!PP.getPreprocessingRecord()->getExternalSource())
2926 PP.getPreprocessingRecord()->SetExternalSource(*this);
2927 StartingID
2928 = PP.getPreprocessingRecord()
Ben Langmuir52ca6782014-10-20 16:27:32 +00002929 ->allocateLoadedEntities(F.NumPreprocessedEntities);
Guy Benyei11169dd2012-12-18 14:30:41 +00002930 F.BasePreprocessedEntityID = StartingID;
2931
2932 if (F.NumPreprocessedEntities > 0) {
2933 // Introduce the global -> local mapping for preprocessed entities in
2934 // this module.
2935 GlobalPreprocessedEntityMap.insert(std::make_pair(StartingID, &F));
2936
2937 // Introduce the local -> global mapping for preprocessed entities in
2938 // this module.
2939 F.PreprocessedEntityRemap.insertOrReplace(
2940 std::make_pair(LocalBasePreprocessedEntityID,
2941 F.BasePreprocessedEntityID - LocalBasePreprocessedEntityID));
2942 }
2943
2944 break;
2945 }
2946
2947 case DECL_UPDATE_OFFSETS: {
2948 if (Record.size() % 2 != 0) {
2949 Error("invalid DECL_UPDATE_OFFSETS block in AST file");
Ben Langmuir2c9af442014-04-10 17:57:43 +00002950 return Failure;
Guy Benyei11169dd2012-12-18 14:30:41 +00002951 }
Richard Smithcd45dbc2014-04-19 03:48:30 +00002952 for (unsigned I = 0, N = Record.size(); I != N; I += 2) {
2953 GlobalDeclID ID = getGlobalDeclID(F, Record[I]);
2954 DeclUpdateOffsets[ID].push_back(std::make_pair(&F, Record[I + 1]));
2955
2956 // If we've already loaded the decl, perform the updates when we finish
2957 // loading this block.
2958 if (Decl *D = GetExistingDecl(ID))
2959 PendingUpdateRecords.push_back(std::make_pair(ID, D));
2960 }
Guy Benyei11169dd2012-12-18 14:30:41 +00002961 break;
2962 }
2963
2964 case DECL_REPLACEMENTS: {
2965 if (Record.size() % 3 != 0) {
2966 Error("invalid DECL_REPLACEMENTS block in AST file");
Ben Langmuir2c9af442014-04-10 17:57:43 +00002967 return Failure;
Guy Benyei11169dd2012-12-18 14:30:41 +00002968 }
2969 for (unsigned I = 0, N = Record.size(); I != N; I += 3)
2970 ReplacedDecls[getGlobalDeclID(F, Record[I])]
2971 = ReplacedDeclInfo(&F, Record[I+1], Record[I+2]);
2972 break;
2973 }
2974
2975 case OBJC_CATEGORIES_MAP: {
2976 if (F.LocalNumObjCCategoriesInMap != 0) {
2977 Error("duplicate OBJC_CATEGORIES_MAP record in AST file");
Ben Langmuir2c9af442014-04-10 17:57:43 +00002978 return Failure;
Guy Benyei11169dd2012-12-18 14:30:41 +00002979 }
2980
2981 F.LocalNumObjCCategoriesInMap = Record[0];
Chris Lattner0e6c9402013-01-20 02:38:54 +00002982 F.ObjCCategoriesMap = (const ObjCCategoriesInfo *)Blob.data();
Guy Benyei11169dd2012-12-18 14:30:41 +00002983 break;
2984 }
2985
2986 case OBJC_CATEGORIES:
2987 F.ObjCCategories.swap(Record);
2988 break;
Richard Smithc2bb8182015-03-24 06:36:48 +00002989
Guy Benyei11169dd2012-12-18 14:30:41 +00002990 case CXX_BASE_SPECIFIER_OFFSETS: {
2991 if (F.LocalNumCXXBaseSpecifiers != 0) {
2992 Error("duplicate CXX_BASE_SPECIFIER_OFFSETS record in AST file");
Ben Langmuir2c9af442014-04-10 17:57:43 +00002993 return Failure;
Guy Benyei11169dd2012-12-18 14:30:41 +00002994 }
Richard Smithc2bb8182015-03-24 06:36:48 +00002995
Guy Benyei11169dd2012-12-18 14:30:41 +00002996 F.LocalNumCXXBaseSpecifiers = Record[0];
Chris Lattner0e6c9402013-01-20 02:38:54 +00002997 F.CXXBaseSpecifiersOffsets = (const uint32_t *)Blob.data();
Richard Smithc2bb8182015-03-24 06:36:48 +00002998 break;
2999 }
3000
3001 case CXX_CTOR_INITIALIZERS_OFFSETS: {
3002 if (F.LocalNumCXXCtorInitializers != 0) {
3003 Error("duplicate CXX_CTOR_INITIALIZERS_OFFSETS record in AST file");
3004 return Failure;
3005 }
3006
3007 F.LocalNumCXXCtorInitializers = Record[0];
3008 F.CXXCtorInitializersOffsets = (const uint32_t *)Blob.data();
Guy Benyei11169dd2012-12-18 14:30:41 +00003009 break;
3010 }
3011
3012 case DIAG_PRAGMA_MAPPINGS:
3013 if (F.PragmaDiagMappings.empty())
3014 F.PragmaDiagMappings.swap(Record);
3015 else
3016 F.PragmaDiagMappings.insert(F.PragmaDiagMappings.end(),
3017 Record.begin(), Record.end());
3018 break;
3019
3020 case CUDA_SPECIAL_DECL_REFS:
3021 // Later tables overwrite earlier ones.
3022 // FIXME: Modules will have trouble with this.
3023 CUDASpecialDeclRefs.clear();
3024 for (unsigned I = 0, N = Record.size(); I != N; ++I)
3025 CUDASpecialDeclRefs.push_back(getGlobalDeclID(F, Record[I]));
3026 break;
3027
3028 case HEADER_SEARCH_TABLE: {
Chris Lattner0e6c9402013-01-20 02:38:54 +00003029 F.HeaderFileInfoTableData = Blob.data();
Guy Benyei11169dd2012-12-18 14:30:41 +00003030 F.LocalNumHeaderFileInfos = Record[1];
Guy Benyei11169dd2012-12-18 14:30:41 +00003031 if (Record[0]) {
3032 F.HeaderFileInfoTable
3033 = HeaderFileInfoLookupTable::Create(
3034 (const unsigned char *)F.HeaderFileInfoTableData + Record[0],
3035 (const unsigned char *)F.HeaderFileInfoTableData,
3036 HeaderFileInfoTrait(*this, F,
3037 &PP.getHeaderSearchInfo(),
Chris Lattner0e6c9402013-01-20 02:38:54 +00003038 Blob.data() + Record[2]));
Guy Benyei11169dd2012-12-18 14:30:41 +00003039
3040 PP.getHeaderSearchInfo().SetExternalSource(this);
3041 if (!PP.getHeaderSearchInfo().getExternalLookup())
3042 PP.getHeaderSearchInfo().SetExternalLookup(this);
3043 }
3044 break;
3045 }
3046
3047 case FP_PRAGMA_OPTIONS:
3048 // Later tables overwrite earlier ones.
3049 FPPragmaOptions.swap(Record);
3050 break;
3051
3052 case OPENCL_EXTENSIONS:
3053 // Later tables overwrite earlier ones.
3054 OpenCLExtensions.swap(Record);
3055 break;
3056
3057 case TENTATIVE_DEFINITIONS:
3058 for (unsigned I = 0, N = Record.size(); I != N; ++I)
3059 TentativeDefinitions.push_back(getGlobalDeclID(F, Record[I]));
3060 break;
3061
3062 case KNOWN_NAMESPACES:
3063 for (unsigned I = 0, N = Record.size(); I != N; ++I)
3064 KnownNamespaces.push_back(getGlobalDeclID(F, Record[I]));
3065 break;
Nick Lewycky8334af82013-01-26 00:35:08 +00003066
Nick Lewycky9c7eb1d2013-02-01 08:13:20 +00003067 case UNDEFINED_BUT_USED:
3068 if (UndefinedButUsed.size() % 2 != 0) {
3069 Error("Invalid existing UndefinedButUsed");
Ben Langmuir2c9af442014-04-10 17:57:43 +00003070 return Failure;
Nick Lewycky8334af82013-01-26 00:35:08 +00003071 }
3072
3073 if (Record.size() % 2 != 0) {
Nick Lewycky9c7eb1d2013-02-01 08:13:20 +00003074 Error("invalid undefined-but-used record");
Ben Langmuir2c9af442014-04-10 17:57:43 +00003075 return Failure;
Nick Lewycky8334af82013-01-26 00:35:08 +00003076 }
3077 for (unsigned I = 0, N = Record.size(); I != N; /* in loop */) {
Nick Lewycky9c7eb1d2013-02-01 08:13:20 +00003078 UndefinedButUsed.push_back(getGlobalDeclID(F, Record[I++]));
3079 UndefinedButUsed.push_back(
Nick Lewycky8334af82013-01-26 00:35:08 +00003080 ReadSourceLocation(F, Record, I).getRawEncoding());
3081 }
3082 break;
Ismail Pazarbasie5768d12015-05-18 19:59:11 +00003083 case DELETE_EXPRS_TO_ANALYZE:
3084 for (unsigned I = 0, N = Record.size(); I != N;) {
3085 DelayedDeleteExprs.push_back(getGlobalDeclID(F, Record[I++]));
3086 const uint64_t Count = Record[I++];
3087 DelayedDeleteExprs.push_back(Count);
3088 for (uint64_t C = 0; C < Count; ++C) {
3089 DelayedDeleteExprs.push_back(ReadSourceLocation(F, Record, I).getRawEncoding());
3090 bool IsArrayForm = Record[I++] == 1;
3091 DelayedDeleteExprs.push_back(IsArrayForm);
3092 }
3093 }
3094 break;
Nick Lewycky8334af82013-01-26 00:35:08 +00003095
Guy Benyei11169dd2012-12-18 14:30:41 +00003096 case IMPORTED_MODULES: {
Richard Smithe842a472014-10-22 02:05:46 +00003097 if (F.Kind != MK_ImplicitModule && F.Kind != MK_ExplicitModule) {
Guy Benyei11169dd2012-12-18 14:30:41 +00003098 // If we aren't loading a module (which has its own exports), make
3099 // all of the imported modules visible.
3100 // FIXME: Deal with macros-only imports.
Richard Smith56be7542014-03-21 00:33:59 +00003101 for (unsigned I = 0, N = Record.size(); I != N; /**/) {
3102 unsigned GlobalID = getGlobalSubmoduleID(F, Record[I++]);
3103 SourceLocation Loc = ReadSourceLocation(F, Record, I);
3104 if (GlobalID)
Aaron Ballman4f45b712014-03-21 15:22:56 +00003105 ImportedModules.push_back(ImportedSubmodule(GlobalID, Loc));
Guy Benyei11169dd2012-12-18 14:30:41 +00003106 }
3107 }
3108 break;
3109 }
3110
Guy Benyei11169dd2012-12-18 14:30:41 +00003111 case MACRO_OFFSET: {
3112 if (F.LocalNumMacros != 0) {
3113 Error("duplicate MACRO_OFFSET record in AST file");
Ben Langmuir2c9af442014-04-10 17:57:43 +00003114 return Failure;
Guy Benyei11169dd2012-12-18 14:30:41 +00003115 }
Chris Lattner0e6c9402013-01-20 02:38:54 +00003116 F.MacroOffsets = (const uint32_t *)Blob.data();
Guy Benyei11169dd2012-12-18 14:30:41 +00003117 F.LocalNumMacros = Record[0];
3118 unsigned LocalBaseMacroID = Record[1];
3119 F.BaseMacroID = getTotalNumMacros();
3120
3121 if (F.LocalNumMacros > 0) {
3122 // Introduce the global -> local mapping for macros within this module.
3123 GlobalMacroMap.insert(std::make_pair(getTotalNumMacros() + 1, &F));
3124
3125 // Introduce the local -> global mapping for macros within this module.
3126 F.MacroRemap.insertOrReplace(
3127 std::make_pair(LocalBaseMacroID,
3128 F.BaseMacroID - LocalBaseMacroID));
Ben Langmuir52ca6782014-10-20 16:27:32 +00003129
3130 MacrosLoaded.resize(MacrosLoaded.size() + F.LocalNumMacros);
Guy Benyei11169dd2012-12-18 14:30:41 +00003131 }
3132 break;
3133 }
3134
Richard Smithe40f2ba2013-08-07 21:41:30 +00003135 case LATE_PARSED_TEMPLATE: {
3136 LateParsedTemplates.append(Record.begin(), Record.end());
3137 break;
3138 }
Dario Domizioli13a0a382014-05-23 12:13:25 +00003139
3140 case OPTIMIZE_PRAGMA_OPTIONS:
3141 if (Record.size() != 1) {
3142 Error("invalid pragma optimize record");
3143 return Failure;
3144 }
3145 OptimizeOffPragmaLocation = ReadSourceLocation(F, Record[0]);
3146 break;
Nico Weber72889432014-09-06 01:25:55 +00003147
3148 case UNUSED_LOCAL_TYPEDEF_NAME_CANDIDATES:
3149 for (unsigned I = 0, N = Record.size(); I != N; ++I)
3150 UnusedLocalTypedefNameCandidates.push_back(
3151 getGlobalDeclID(F, Record[I]));
3152 break;
Guy Benyei11169dd2012-12-18 14:30:41 +00003153 }
3154 }
Guy Benyei11169dd2012-12-18 14:30:41 +00003155}
3156
Ben Langmuir4b8a9e92014-08-12 16:42:33 +00003157ASTReader::ASTReadResult
3158ASTReader::ReadModuleMapFileBlock(RecordData &Record, ModuleFile &F,
3159 const ModuleFile *ImportedBy,
3160 unsigned ClientLoadCapabilities) {
3161 unsigned Idx = 0;
Richard Smith7ed1bc92014-12-05 22:42:13 +00003162 F.ModuleMapPath = ReadPath(F, Record, Idx);
Ben Langmuir4b8a9e92014-08-12 16:42:33 +00003163
Richard Smithe842a472014-10-22 02:05:46 +00003164 if (F.Kind == MK_ExplicitModule) {
3165 // For an explicitly-loaded module, we don't care whether the original
3166 // module map file exists or matches.
3167 return Success;
3168 }
3169
Ben Langmuir4b8a9e92014-08-12 16:42:33 +00003170 // Try to resolve ModuleName in the current header search context and
3171 // verify that it is found in the same module map file as we saved. If the
3172 // top-level AST file is a main file, skip this check because there is no
3173 // usable header search context.
3174 assert(!F.ModuleName.empty() &&
Richard Smithe842a472014-10-22 02:05:46 +00003175 "MODULE_NAME should come before MODULE_MAP_FILE");
3176 if (F.Kind == MK_ImplicitModule &&
3177 (*ModuleMgr.begin())->Kind != MK_MainFile) {
3178 // An implicitly-loaded module file should have its module listed in some
3179 // module map file that we've already loaded.
Ben Langmuir4b8a9e92014-08-12 16:42:33 +00003180 Module *M = PP.getHeaderSearchInfo().lookupModule(F.ModuleName);
Richard Smithe842a472014-10-22 02:05:46 +00003181 auto &Map = PP.getHeaderSearchInfo().getModuleMap();
3182 const FileEntry *ModMap = M ? Map.getModuleMapFileForUniquing(M) : nullptr;
3183 if (!ModMap) {
Ben Langmuir4b8a9e92014-08-12 16:42:33 +00003184 assert(ImportedBy && "top-level import should be verified");
Richard Smith0f99d6a2015-08-09 08:48:41 +00003185 if ((ClientLoadCapabilities & ARR_OutOfDate) == 0) {
3186 if (auto *ASTFE = M ? M->getASTFile() : nullptr)
3187 // This module was defined by an imported (explicit) module.
3188 Diag(diag::err_module_file_conflict) << F.ModuleName << F.FileName
3189 << ASTFE->getName();
3190 else
3191 // This module was built with a different module map.
3192 Diag(diag::err_imported_module_not_found)
3193 << F.ModuleName << F.FileName << ImportedBy->FileName
3194 << F.ModuleMapPath;
3195 }
3196 return OutOfDate;
Ben Langmuir4b8a9e92014-08-12 16:42:33 +00003197 }
3198
Richard Smithe842a472014-10-22 02:05:46 +00003199 assert(M->Name == F.ModuleName && "found module with different name");
3200
Ben Langmuir4b8a9e92014-08-12 16:42:33 +00003201 // Check the primary module map file.
Ben Langmuir4b8a9e92014-08-12 16:42:33 +00003202 const FileEntry *StoredModMap = FileMgr.getFile(F.ModuleMapPath);
Ben Langmuir4b8a9e92014-08-12 16:42:33 +00003203 if (StoredModMap == nullptr || StoredModMap != ModMap) {
3204 assert(ModMap && "found module is missing module map file");
Ben Langmuir4b8a9e92014-08-12 16:42:33 +00003205 assert(ImportedBy && "top-level import should be verified");
3206 if ((ClientLoadCapabilities & ARR_OutOfDate) == 0)
3207 Diag(diag::err_imported_module_modmap_changed)
3208 << F.ModuleName << ImportedBy->FileName
3209 << ModMap->getName() << F.ModuleMapPath;
3210 return OutOfDate;
3211 }
3212
3213 llvm::SmallPtrSet<const FileEntry *, 1> AdditionalStoredMaps;
3214 for (unsigned I = 0, N = Record[Idx++]; I < N; ++I) {
3215 // FIXME: we should use input files rather than storing names.
Richard Smith7ed1bc92014-12-05 22:42:13 +00003216 std::string Filename = ReadPath(F, Record, Idx);
Ben Langmuir4b8a9e92014-08-12 16:42:33 +00003217 const FileEntry *F =
3218 FileMgr.getFile(Filename, false, false);
3219 if (F == nullptr) {
3220 if ((ClientLoadCapabilities & ARR_OutOfDate) == 0)
3221 Error("could not find file '" + Filename +"' referenced by AST file");
3222 return OutOfDate;
3223 }
3224 AdditionalStoredMaps.insert(F);
3225 }
3226
3227 // Check any additional module map files (e.g. module.private.modulemap)
3228 // that are not in the pcm.
3229 if (auto *AdditionalModuleMaps = Map.getAdditionalModuleMapFiles(M)) {
3230 for (const FileEntry *ModMap : *AdditionalModuleMaps) {
3231 // Remove files that match
3232 // Note: SmallPtrSet::erase is really remove
3233 if (!AdditionalStoredMaps.erase(ModMap)) {
3234 if ((ClientLoadCapabilities & ARR_OutOfDate) == 0)
3235 Diag(diag::err_module_different_modmap)
3236 << F.ModuleName << /*new*/0 << ModMap->getName();
3237 return OutOfDate;
3238 }
3239 }
3240 }
3241
3242 // Check any additional module map files that are in the pcm, but not
3243 // found in header search. Cases that match are already removed.
3244 for (const FileEntry *ModMap : AdditionalStoredMaps) {
3245 if ((ClientLoadCapabilities & ARR_OutOfDate) == 0)
3246 Diag(diag::err_module_different_modmap)
3247 << F.ModuleName << /*not new*/1 << ModMap->getName();
3248 return OutOfDate;
3249 }
3250 }
3251
3252 if (Listener)
3253 Listener->ReadModuleMapFile(F.ModuleMapPath);
3254 return Success;
3255}
3256
3257
Douglas Gregorc1489562013-02-12 23:36:21 +00003258/// \brief Move the given method to the back of the global list of methods.
3259static void moveMethodToBackOfGlobalList(Sema &S, ObjCMethodDecl *Method) {
3260 // Find the entry for this selector in the method pool.
3261 Sema::GlobalMethodPool::iterator Known
3262 = S.MethodPool.find(Method->getSelector());
3263 if (Known == S.MethodPool.end())
3264 return;
3265
3266 // Retrieve the appropriate method list.
3267 ObjCMethodList &Start = Method->isInstanceMethod()? Known->second.first
3268 : Known->second.second;
3269 bool Found = false;
Argyrios Kyrtzidisd3da6e02013-04-17 00:08:58 +00003270 for (ObjCMethodList *List = &Start; List; List = List->getNext()) {
Douglas Gregorc1489562013-02-12 23:36:21 +00003271 if (!Found) {
Nico Weber2e0c8f72014-12-27 03:58:08 +00003272 if (List->getMethod() == Method) {
Douglas Gregorc1489562013-02-12 23:36:21 +00003273 Found = true;
3274 } else {
3275 // Keep searching.
3276 continue;
3277 }
3278 }
3279
Argyrios Kyrtzidisd3da6e02013-04-17 00:08:58 +00003280 if (List->getNext())
Nico Weber2e0c8f72014-12-27 03:58:08 +00003281 List->setMethod(List->getNext()->getMethod());
Douglas Gregorc1489562013-02-12 23:36:21 +00003282 else
Nico Weber2e0c8f72014-12-27 03:58:08 +00003283 List->setMethod(Method);
Douglas Gregorc1489562013-02-12 23:36:21 +00003284 }
3285}
3286
Richard Smithde711422015-04-23 21:20:19 +00003287void ASTReader::makeNamesVisible(const HiddenNames &Names, Module *Owner) {
Richard Smith10434f32015-05-02 02:08:26 +00003288 assert(Owner->NameVisibility != Module::Hidden && "nothing to make visible?");
Richard Smith20e883e2015-04-29 23:20:19 +00003289 for (Decl *D : Names) {
Richard Smith49f906a2014-03-01 00:08:04 +00003290 bool wasHidden = D->Hidden;
3291 D->Hidden = false;
Guy Benyei11169dd2012-12-18 14:30:41 +00003292
Richard Smith49f906a2014-03-01 00:08:04 +00003293 if (wasHidden && SemaObj) {
3294 if (ObjCMethodDecl *Method = dyn_cast<ObjCMethodDecl>(D)) {
3295 moveMethodToBackOfGlobalList(*SemaObj, Method);
Douglas Gregorc1489562013-02-12 23:36:21 +00003296 }
Guy Benyei11169dd2012-12-18 14:30:41 +00003297 }
3298 }
3299}
3300
Richard Smith49f906a2014-03-01 00:08:04 +00003301void ASTReader::makeModuleVisible(Module *Mod,
Argyrios Kyrtzidis125df052013-02-01 16:36:12 +00003302 Module::NameVisibilityKind NameVisibility,
Richard Smitha7e2cc62015-05-01 01:53:09 +00003303 SourceLocation ImportLoc) {
Guy Benyei11169dd2012-12-18 14:30:41 +00003304 llvm::SmallPtrSet<Module *, 4> Visited;
Dmitri Gribenkof8579502013-01-12 19:30:44 +00003305 SmallVector<Module *, 4> Stack;
Robert Wilhelm25284cc2013-08-23 16:11:15 +00003306 Stack.push_back(Mod);
Guy Benyei11169dd2012-12-18 14:30:41 +00003307 while (!Stack.empty()) {
Robert Wilhelm25284cc2013-08-23 16:11:15 +00003308 Mod = Stack.pop_back_val();
Guy Benyei11169dd2012-12-18 14:30:41 +00003309
3310 if (NameVisibility <= Mod->NameVisibility) {
Robert Wilhelm25284cc2013-08-23 16:11:15 +00003311 // This module already has this level of visibility (or greater), so
Guy Benyei11169dd2012-12-18 14:30:41 +00003312 // there is nothing more to do.
3313 continue;
3314 }
Richard Smith49f906a2014-03-01 00:08:04 +00003315
Guy Benyei11169dd2012-12-18 14:30:41 +00003316 if (!Mod->isAvailable()) {
3317 // Modules that aren't available cannot be made visible.
3318 continue;
3319 }
3320
3321 // Update the module's name visibility.
3322 Mod->NameVisibility = NameVisibility;
Richard Smith49f906a2014-03-01 00:08:04 +00003323
Guy Benyei11169dd2012-12-18 14:30:41 +00003324 // If we've already deserialized any names from this module,
3325 // mark them as visible.
3326 HiddenNamesMapType::iterator Hidden = HiddenNamesMap.find(Mod);
3327 if (Hidden != HiddenNamesMap.end()) {
Richard Smith57721ac2014-07-21 04:10:40 +00003328 auto HiddenNames = std::move(*Hidden);
Guy Benyei11169dd2012-12-18 14:30:41 +00003329 HiddenNamesMap.erase(Hidden);
Richard Smithde711422015-04-23 21:20:19 +00003330 makeNamesVisible(HiddenNames.second, HiddenNames.first);
Richard Smith57721ac2014-07-21 04:10:40 +00003331 assert(HiddenNamesMap.find(Mod) == HiddenNamesMap.end() &&
3332 "making names visible added hidden names");
Guy Benyei11169dd2012-12-18 14:30:41 +00003333 }
Dmitri Gribenkoe9bcf5b2013-11-04 21:51:33 +00003334
Guy Benyei11169dd2012-12-18 14:30:41 +00003335 // Push any exported modules onto the stack to be marked as visible.
Argyrios Kyrtzidis8739f7b2013-02-19 19:34:40 +00003336 SmallVector<Module *, 16> Exports;
3337 Mod->getExportedModules(Exports);
3338 for (SmallVectorImpl<Module *>::iterator
3339 I = Exports.begin(), E = Exports.end(); I != E; ++I) {
3340 Module *Exported = *I;
David Blaikie82e95a32014-11-19 07:49:47 +00003341 if (Visited.insert(Exported).second)
Argyrios Kyrtzidis8739f7b2013-02-19 19:34:40 +00003342 Stack.push_back(Exported);
Guy Benyei11169dd2012-12-18 14:30:41 +00003343 }
3344 }
3345}
3346
Douglas Gregore060e572013-01-25 01:03:03 +00003347bool ASTReader::loadGlobalIndex() {
3348 if (GlobalIndex)
3349 return false;
3350
3351 if (TriedLoadingGlobalIndex || !UseGlobalIndex ||
3352 !Context.getLangOpts().Modules)
3353 return true;
3354
3355 // Try to load the global index.
3356 TriedLoadingGlobalIndex = true;
3357 StringRef ModuleCachePath
3358 = getPreprocessor().getHeaderSearchInfo().getModuleCachePath();
3359 std::pair<GlobalModuleIndex *, GlobalModuleIndex::ErrorCode> Result
Douglas Gregor7029ce12013-03-19 00:28:20 +00003360 = GlobalModuleIndex::readIndex(ModuleCachePath);
Douglas Gregore060e572013-01-25 01:03:03 +00003361 if (!Result.first)
3362 return true;
3363
3364 GlobalIndex.reset(Result.first);
Douglas Gregor7211ac12013-01-25 23:32:03 +00003365 ModuleMgr.setGlobalIndex(GlobalIndex.get());
Douglas Gregore060e572013-01-25 01:03:03 +00003366 return false;
3367}
3368
3369bool ASTReader::isGlobalIndexUnavailable() const {
3370 return Context.getLangOpts().Modules && UseGlobalIndex &&
3371 !hasGlobalIndex() && TriedLoadingGlobalIndex;
3372}
3373
Dmitri Gribenkof430da42014-02-12 10:33:14 +00003374static void updateModuleTimestamp(ModuleFile &MF) {
3375 // Overwrite the timestamp file contents so that file's mtime changes.
3376 std::string TimestampFilename = MF.getTimestampFilename();
Rafael Espindoladae941a2014-08-25 18:17:04 +00003377 std::error_code EC;
3378 llvm::raw_fd_ostream OS(TimestampFilename, EC, llvm::sys::fs::F_Text);
3379 if (EC)
Dmitri Gribenkof430da42014-02-12 10:33:14 +00003380 return;
3381 OS << "Timestamp file\n";
3382}
3383
Guy Benyei11169dd2012-12-18 14:30:41 +00003384ASTReader::ASTReadResult ASTReader::ReadAST(const std::string &FileName,
3385 ModuleKind Type,
3386 SourceLocation ImportLoc,
3387 unsigned ClientLoadCapabilities) {
Argyrios Kyrtzidisdc9fdaf2013-05-24 05:44:08 +00003388 llvm::SaveAndRestore<SourceLocation>
3389 SetCurImportLocRAII(CurrentImportLoc, ImportLoc);
3390
Richard Smithd1c46742014-04-30 02:24:17 +00003391 // Defer any pending actions until we get to the end of reading the AST file.
3392 Deserializing AnASTFile(this);
3393
Guy Benyei11169dd2012-12-18 14:30:41 +00003394 // Bump the generation number.
Richard Smith053f6c62014-05-16 23:01:30 +00003395 unsigned PreviousGeneration = incrementGeneration(Context);
Guy Benyei11169dd2012-12-18 14:30:41 +00003396
3397 unsigned NumModules = ModuleMgr.size();
Dmitri Gribenkof8579502013-01-12 19:30:44 +00003398 SmallVector<ImportedModule, 4> Loaded;
Guy Benyei11169dd2012-12-18 14:30:41 +00003399 switch(ASTReadResult ReadResult = ReadASTCore(FileName, Type, ImportLoc,
Craig Toppera13603a2014-05-22 05:54:18 +00003400 /*ImportedBy=*/nullptr, Loaded,
Ben Langmuir487ea142014-10-23 18:05:36 +00003401 0, 0, 0,
Guy Benyei11169dd2012-12-18 14:30:41 +00003402 ClientLoadCapabilities)) {
3403 case Failure:
Douglas Gregor7029ce12013-03-19 00:28:20 +00003404 case Missing:
Guy Benyei11169dd2012-12-18 14:30:41 +00003405 case OutOfDate:
3406 case VersionMismatch:
3407 case ConfigurationMismatch:
Ben Langmuir9801b252014-06-20 00:24:56 +00003408 case HadErrors: {
3409 llvm::SmallPtrSet<ModuleFile *, 4> LoadedSet;
3410 for (const ImportedModule &IM : Loaded)
3411 LoadedSet.insert(IM.Mod);
3412
Douglas Gregor7029ce12013-03-19 00:28:20 +00003413 ModuleMgr.removeModules(ModuleMgr.begin() + NumModules, ModuleMgr.end(),
Ben Langmuir9801b252014-06-20 00:24:56 +00003414 LoadedSet,
Douglas Gregor7029ce12013-03-19 00:28:20 +00003415 Context.getLangOpts().Modules
3416 ? &PP.getHeaderSearchInfo().getModuleMap()
Craig Toppera13603a2014-05-22 05:54:18 +00003417 : nullptr);
Douglas Gregore060e572013-01-25 01:03:03 +00003418
3419 // If we find that any modules are unusable, the global index is going
3420 // to be out-of-date. Just remove it.
3421 GlobalIndex.reset();
Craig Toppera13603a2014-05-22 05:54:18 +00003422 ModuleMgr.setGlobalIndex(nullptr);
Guy Benyei11169dd2012-12-18 14:30:41 +00003423 return ReadResult;
Ben Langmuir9801b252014-06-20 00:24:56 +00003424 }
Guy Benyei11169dd2012-12-18 14:30:41 +00003425 case Success:
3426 break;
3427 }
3428
3429 // Here comes stuff that we only do once the entire chain is loaded.
3430
3431 // Load the AST blocks of all of the modules that we loaded.
Dmitri Gribenkof8579502013-01-12 19:30:44 +00003432 for (SmallVectorImpl<ImportedModule>::iterator M = Loaded.begin(),
3433 MEnd = Loaded.end();
Guy Benyei11169dd2012-12-18 14:30:41 +00003434 M != MEnd; ++M) {
3435 ModuleFile &F = *M->Mod;
3436
3437 // Read the AST block.
Ben Langmuir2c9af442014-04-10 17:57:43 +00003438 if (ASTReadResult Result = ReadASTBlock(F, ClientLoadCapabilities))
3439 return Result;
Guy Benyei11169dd2012-12-18 14:30:41 +00003440
3441 // Once read, set the ModuleFile bit base offset and update the size in
3442 // bits of all files we've seen.
3443 F.GlobalBitOffset = TotalModulesSizeInBits;
3444 TotalModulesSizeInBits += F.SizeInBits;
3445 GlobalBitOffsetsMap.insert(std::make_pair(F.GlobalBitOffset, &F));
3446
3447 // Preload SLocEntries.
3448 for (unsigned I = 0, N = F.PreloadSLocEntries.size(); I != N; ++I) {
3449 int Index = int(F.PreloadSLocEntries[I] - 1) + F.SLocEntryBaseID;
3450 // Load it through the SourceManager and don't call ReadSLocEntry()
3451 // directly because the entry may have already been loaded in which case
3452 // calling ReadSLocEntry() directly would trigger an assertion in
3453 // SourceManager.
3454 SourceMgr.getLoadedSLocEntryByID(Index);
3455 }
Richard Smith33e0f7e2015-07-22 02:08:40 +00003456
3457 // Preload all the pending interesting identifiers by marking them out of
3458 // date.
3459 for (auto Offset : F.PreloadIdentifierOffsets) {
3460 const unsigned char *Data = reinterpret_cast<const unsigned char *>(
3461 F.IdentifierTableData + Offset);
3462
3463 ASTIdentifierLookupTrait Trait(*this, F);
3464 auto KeyDataLen = Trait.ReadKeyDataLength(Data);
3465 auto Key = Trait.ReadKey(Data, KeyDataLen.first);
Richard Smith79bf9202015-08-24 03:33:22 +00003466 auto &II = PP.getIdentifierTable().getOwn(Key);
3467 II.setOutOfDate(true);
3468
3469 // Mark this identifier as being from an AST file so that we can track
3470 // whether we need to serialize it.
3471 if (!II.isFromAST()) {
3472 II.setIsFromAST();
3473 if (isInterestingIdentifier(*this, II, F.isModule()))
3474 II.setChangedSinceDeserialization();
3475 }
3476
3477 // Associate the ID with the identifier so that the writer can reuse it.
3478 auto ID = Trait.ReadIdentifierID(Data + KeyDataLen.first);
3479 SetIdentifierInfo(ID, &II);
Richard Smith33e0f7e2015-07-22 02:08:40 +00003480 }
Guy Benyei11169dd2012-12-18 14:30:41 +00003481 }
3482
Douglas Gregor603cd862013-03-22 18:50:14 +00003483 // Setup the import locations and notify the module manager that we've
3484 // committed to these module files.
Dmitri Gribenkof8579502013-01-12 19:30:44 +00003485 for (SmallVectorImpl<ImportedModule>::iterator M = Loaded.begin(),
3486 MEnd = Loaded.end();
Guy Benyei11169dd2012-12-18 14:30:41 +00003487 M != MEnd; ++M) {
3488 ModuleFile &F = *M->Mod;
Douglas Gregor603cd862013-03-22 18:50:14 +00003489
3490 ModuleMgr.moduleFileAccepted(&F);
3491
3492 // Set the import location.
Argyrios Kyrtzidis71c1af82013-02-01 16:36:14 +00003493 F.DirectImportLoc = ImportLoc;
Guy Benyei11169dd2012-12-18 14:30:41 +00003494 if (!M->ImportedBy)
3495 F.ImportLoc = M->ImportLoc;
3496 else
3497 F.ImportLoc = ReadSourceLocation(*M->ImportedBy,
3498 M->ImportLoc.getRawEncoding());
3499 }
3500
Richard Smith33e0f7e2015-07-22 02:08:40 +00003501 if (!Context.getLangOpts().CPlusPlus ||
3502 (Type != MK_ImplicitModule && Type != MK_ExplicitModule)) {
3503 // Mark all of the identifiers in the identifier table as being out of date,
3504 // so that various accessors know to check the loaded modules when the
3505 // identifier is used.
3506 //
3507 // For C++ modules, we don't need information on many identifiers (just
3508 // those that provide macros or are poisoned), so we mark all of
3509 // the interesting ones via PreloadIdentifierOffsets.
3510 for (IdentifierTable::iterator Id = PP.getIdentifierTable().begin(),
3511 IdEnd = PP.getIdentifierTable().end();
3512 Id != IdEnd; ++Id)
3513 Id->second->setOutOfDate(true);
3514 }
Guy Benyei11169dd2012-12-18 14:30:41 +00003515
3516 // Resolve any unresolved module exports.
Douglas Gregorfb912652013-03-20 21:10:35 +00003517 for (unsigned I = 0, N = UnresolvedModuleRefs.size(); I != N; ++I) {
3518 UnresolvedModuleRef &Unresolved = UnresolvedModuleRefs[I];
Guy Benyei11169dd2012-12-18 14:30:41 +00003519 SubmoduleID GlobalID = getGlobalSubmoduleID(*Unresolved.File,Unresolved.ID);
3520 Module *ResolvedMod = getSubmodule(GlobalID);
Douglas Gregorfb912652013-03-20 21:10:35 +00003521
3522 switch (Unresolved.Kind) {
3523 case UnresolvedModuleRef::Conflict:
3524 if (ResolvedMod) {
3525 Module::Conflict Conflict;
3526 Conflict.Other = ResolvedMod;
3527 Conflict.Message = Unresolved.String.str();
3528 Unresolved.Mod->Conflicts.push_back(Conflict);
3529 }
3530 continue;
3531
3532 case UnresolvedModuleRef::Import:
Guy Benyei11169dd2012-12-18 14:30:41 +00003533 if (ResolvedMod)
Richard Smith38477db2015-05-02 00:45:56 +00003534 Unresolved.Mod->Imports.insert(ResolvedMod);
Guy Benyei11169dd2012-12-18 14:30:41 +00003535 continue;
Guy Benyei11169dd2012-12-18 14:30:41 +00003536
Douglas Gregorfb912652013-03-20 21:10:35 +00003537 case UnresolvedModuleRef::Export:
3538 if (ResolvedMod || Unresolved.IsWildcard)
3539 Unresolved.Mod->Exports.push_back(
3540 Module::ExportDecl(ResolvedMod, Unresolved.IsWildcard));
3541 continue;
3542 }
Guy Benyei11169dd2012-12-18 14:30:41 +00003543 }
Douglas Gregorfb912652013-03-20 21:10:35 +00003544 UnresolvedModuleRefs.clear();
Daniel Jasperba7f2f72013-09-24 09:14:14 +00003545
3546 // FIXME: How do we load the 'use'd modules? They may not be submodules.
3547 // Might be unnecessary as use declarations are only used to build the
3548 // module itself.
Guy Benyei11169dd2012-12-18 14:30:41 +00003549
3550 InitializeContext();
3551
Richard Smith3d8e97e2013-10-18 06:54:39 +00003552 if (SemaObj)
3553 UpdateSema();
3554
Guy Benyei11169dd2012-12-18 14:30:41 +00003555 if (DeserializationListener)
3556 DeserializationListener->ReaderInitialized(this);
3557
3558 ModuleFile &PrimaryModule = ModuleMgr.getPrimaryModule();
3559 if (!PrimaryModule.OriginalSourceFileID.isInvalid()) {
3560 PrimaryModule.OriginalSourceFileID
3561 = FileID::get(PrimaryModule.SLocEntryBaseID
3562 + PrimaryModule.OriginalSourceFileID.getOpaqueValue() - 1);
3563
3564 // If this AST file is a precompiled preamble, then set the
3565 // preamble file ID of the source manager to the file source file
3566 // from which the preamble was built.
3567 if (Type == MK_Preamble) {
3568 SourceMgr.setPreambleFileID(PrimaryModule.OriginalSourceFileID);
3569 } else if (Type == MK_MainFile) {
3570 SourceMgr.setMainFileID(PrimaryModule.OriginalSourceFileID);
3571 }
3572 }
3573
3574 // For any Objective-C class definitions we have already loaded, make sure
3575 // that we load any additional categories.
3576 for (unsigned I = 0, N = ObjCClassesLoaded.size(); I != N; ++I) {
3577 loadObjCCategories(ObjCClassesLoaded[I]->getGlobalID(),
3578 ObjCClassesLoaded[I],
3579 PreviousGeneration);
3580 }
Douglas Gregore060e572013-01-25 01:03:03 +00003581
Dmitri Gribenkof430da42014-02-12 10:33:14 +00003582 if (PP.getHeaderSearchInfo()
3583 .getHeaderSearchOpts()
3584 .ModulesValidateOncePerBuildSession) {
3585 // Now we are certain that the module and all modules it depends on are
3586 // up to date. Create or update timestamp files for modules that are
3587 // located in the module cache (not for PCH files that could be anywhere
3588 // in the filesystem).
3589 for (unsigned I = 0, N = Loaded.size(); I != N; ++I) {
3590 ImportedModule &M = Loaded[I];
Richard Smithe842a472014-10-22 02:05:46 +00003591 if (M.Mod->Kind == MK_ImplicitModule) {
Dmitri Gribenkof430da42014-02-12 10:33:14 +00003592 updateModuleTimestamp(*M.Mod);
3593 }
3594 }
3595 }
3596
Guy Benyei11169dd2012-12-18 14:30:41 +00003597 return Success;
3598}
3599
Ben Langmuir487ea142014-10-23 18:05:36 +00003600static ASTFileSignature readASTFileSignature(llvm::BitstreamReader &StreamFile);
3601
Ben Langmuir70a1b812015-03-24 04:43:52 +00003602/// \brief Whether \p Stream starts with the AST/PCH file magic number 'CPCH'.
3603static bool startsWithASTFileMagic(BitstreamCursor &Stream) {
3604 return Stream.Read(8) == 'C' &&
3605 Stream.Read(8) == 'P' &&
3606 Stream.Read(8) == 'C' &&
3607 Stream.Read(8) == 'H';
3608}
3609
Richard Smith0f99d6a2015-08-09 08:48:41 +00003610static unsigned moduleKindForDiagnostic(ModuleKind Kind) {
3611 switch (Kind) {
3612 case MK_PCH:
3613 return 0; // PCH
3614 case MK_ImplicitModule:
3615 case MK_ExplicitModule:
3616 return 1; // module
3617 case MK_MainFile:
3618 case MK_Preamble:
3619 return 2; // main source file
3620 }
3621 llvm_unreachable("unknown module kind");
3622}
3623
Guy Benyei11169dd2012-12-18 14:30:41 +00003624ASTReader::ASTReadResult
3625ASTReader::ReadASTCore(StringRef FileName,
3626 ModuleKind Type,
3627 SourceLocation ImportLoc,
3628 ModuleFile *ImportedBy,
Dmitri Gribenkof8579502013-01-12 19:30:44 +00003629 SmallVectorImpl<ImportedModule> &Loaded,
Douglas Gregor7029ce12013-03-19 00:28:20 +00003630 off_t ExpectedSize, time_t ExpectedModTime,
Ben Langmuir487ea142014-10-23 18:05:36 +00003631 ASTFileSignature ExpectedSignature,
Guy Benyei11169dd2012-12-18 14:30:41 +00003632 unsigned ClientLoadCapabilities) {
3633 ModuleFile *M;
Guy Benyei11169dd2012-12-18 14:30:41 +00003634 std::string ErrorStr;
Douglas Gregor7029ce12013-03-19 00:28:20 +00003635 ModuleManager::AddModuleResult AddResult
3636 = ModuleMgr.addModule(FileName, Type, ImportLoc, ImportedBy,
Richard Smith053f6c62014-05-16 23:01:30 +00003637 getGeneration(), ExpectedSize, ExpectedModTime,
Ben Langmuir487ea142014-10-23 18:05:36 +00003638 ExpectedSignature, readASTFileSignature,
Douglas Gregor7029ce12013-03-19 00:28:20 +00003639 M, ErrorStr);
Guy Benyei11169dd2012-12-18 14:30:41 +00003640
Douglas Gregor7029ce12013-03-19 00:28:20 +00003641 switch (AddResult) {
3642 case ModuleManager::AlreadyLoaded:
3643 return Success;
3644
3645 case ModuleManager::NewlyLoaded:
3646 // Load module file below.
3647 break;
3648
3649 case ModuleManager::Missing:
Richard Smithe842a472014-10-22 02:05:46 +00003650 // The module file was missing; if the client can handle that, return
Douglas Gregor7029ce12013-03-19 00:28:20 +00003651 // it.
3652 if (ClientLoadCapabilities & ARR_Missing)
3653 return Missing;
3654
3655 // Otherwise, return an error.
Richard Smith0f99d6a2015-08-09 08:48:41 +00003656 Diag(diag::err_module_file_not_found) << moduleKindForDiagnostic(Type)
3657 << FileName << ErrorStr.empty()
3658 << ErrorStr;
Douglas Gregor7029ce12013-03-19 00:28:20 +00003659 return Failure;
3660
3661 case ModuleManager::OutOfDate:
3662 // We couldn't load the module file because it is out-of-date. If the
3663 // client can handle out-of-date, return it.
3664 if (ClientLoadCapabilities & ARR_OutOfDate)
3665 return OutOfDate;
3666
3667 // Otherwise, return an error.
Richard Smith0f99d6a2015-08-09 08:48:41 +00003668 Diag(diag::err_module_file_out_of_date) << moduleKindForDiagnostic(Type)
3669 << FileName << ErrorStr.empty()
3670 << ErrorStr;
Guy Benyei11169dd2012-12-18 14:30:41 +00003671 return Failure;
3672 }
3673
Douglas Gregor7029ce12013-03-19 00:28:20 +00003674 assert(M && "Missing module file");
Guy Benyei11169dd2012-12-18 14:30:41 +00003675
3676 // FIXME: This seems rather a hack. Should CurrentDir be part of the
3677 // module?
3678 if (FileName != "-") {
3679 CurrentDir = llvm::sys::path::parent_path(FileName);
3680 if (CurrentDir.empty()) CurrentDir = ".";
3681 }
3682
3683 ModuleFile &F = *M;
Chris Lattner7fb3bef2013-01-20 00:56:42 +00003684 BitstreamCursor &Stream = F.Stream;
Adrian Prantlfb2398d2015-07-17 01:19:54 +00003685 PCHContainerRdr.ExtractPCH(F.Buffer->getMemBufferRef(), F.StreamFile);
Rafael Espindolafd832392014-11-12 14:48:44 +00003686 Stream.init(&F.StreamFile);
Adrian Prantlcbc368c2015-02-25 02:44:04 +00003687 F.SizeInBits = F.Buffer->getBufferSize() * 8;
3688
Guy Benyei11169dd2012-12-18 14:30:41 +00003689 // Sniff for the signature.
Ben Langmuir70a1b812015-03-24 04:43:52 +00003690 if (!startsWithASTFileMagic(Stream)) {
Richard Smith0f99d6a2015-08-09 08:48:41 +00003691 Diag(diag::err_module_file_invalid) << moduleKindForDiagnostic(Type)
3692 << FileName;
Guy Benyei11169dd2012-12-18 14:30:41 +00003693 return Failure;
3694 }
3695
3696 // This is used for compatibility with older PCH formats.
3697 bool HaveReadControlBlock = false;
3698
Chris Lattnerefa77172013-01-20 00:00:22 +00003699 while (1) {
3700 llvm::BitstreamEntry Entry = Stream.advance();
3701
3702 switch (Entry.Kind) {
3703 case llvm::BitstreamEntry::Error:
3704 case llvm::BitstreamEntry::EndBlock:
3705 case llvm::BitstreamEntry::Record:
Guy Benyei11169dd2012-12-18 14:30:41 +00003706 Error("invalid record at top-level of AST file");
3707 return Failure;
Chris Lattnerefa77172013-01-20 00:00:22 +00003708
3709 case llvm::BitstreamEntry::SubBlock:
3710 break;
Guy Benyei11169dd2012-12-18 14:30:41 +00003711 }
3712
Guy Benyei11169dd2012-12-18 14:30:41 +00003713 // We only know the control subblock ID.
Chris Lattnerefa77172013-01-20 00:00:22 +00003714 switch (Entry.ID) {
Guy Benyei11169dd2012-12-18 14:30:41 +00003715 case llvm::bitc::BLOCKINFO_BLOCK_ID:
3716 if (Stream.ReadBlockInfoBlock()) {
3717 Error("malformed BlockInfoBlock in AST file");
3718 return Failure;
3719 }
3720 break;
3721 case CONTROL_BLOCK_ID:
3722 HaveReadControlBlock = true;
Ben Langmuirbeee15e2014-04-14 18:00:01 +00003723 switch (ReadControlBlock(F, Loaded, ImportedBy, ClientLoadCapabilities)) {
Guy Benyei11169dd2012-12-18 14:30:41 +00003724 case Success:
Richard Smith0f99d6a2015-08-09 08:48:41 +00003725 // Check that we didn't try to load a non-module AST file as a module.
3726 //
3727 // FIXME: Should we also perform the converse check? Loading a module as
3728 // a PCH file sort of works, but it's a bit wonky.
3729 if ((Type == MK_ImplicitModule || Type == MK_ExplicitModule) &&
3730 F.ModuleName.empty()) {
3731 auto Result = (Type == MK_ImplicitModule) ? OutOfDate : Failure;
3732 if (Result != OutOfDate ||
3733 (ClientLoadCapabilities & ARR_OutOfDate) == 0)
3734 Diag(diag::err_module_file_not_module) << FileName;
3735 return Result;
3736 }
Guy Benyei11169dd2012-12-18 14:30:41 +00003737 break;
3738
3739 case Failure: return Failure;
Douglas Gregor7029ce12013-03-19 00:28:20 +00003740 case Missing: return Missing;
Guy Benyei11169dd2012-12-18 14:30:41 +00003741 case OutOfDate: return OutOfDate;
3742 case VersionMismatch: return VersionMismatch;
3743 case ConfigurationMismatch: return ConfigurationMismatch;
3744 case HadErrors: return HadErrors;
3745 }
3746 break;
3747 case AST_BLOCK_ID:
3748 if (!HaveReadControlBlock) {
3749 if ((ClientLoadCapabilities & ARR_VersionMismatch) == 0)
Dmitri Gribenko2228cd32014-02-11 15:40:09 +00003750 Diag(diag::err_pch_version_too_old);
Guy Benyei11169dd2012-12-18 14:30:41 +00003751 return VersionMismatch;
3752 }
3753
3754 // Record that we've loaded this module.
3755 Loaded.push_back(ImportedModule(M, ImportedBy, ImportLoc));
3756 return Success;
3757
3758 default:
3759 if (Stream.SkipBlock()) {
3760 Error("malformed block record in AST file");
3761 return Failure;
3762 }
3763 break;
3764 }
3765 }
Guy Benyei11169dd2012-12-18 14:30:41 +00003766}
3767
Richard Smitha7e2cc62015-05-01 01:53:09 +00003768void ASTReader::InitializeContext() {
Guy Benyei11169dd2012-12-18 14:30:41 +00003769 // If there's a listener, notify them that we "read" the translation unit.
3770 if (DeserializationListener)
3771 DeserializationListener->DeclRead(PREDEF_DECL_TRANSLATION_UNIT_ID,
3772 Context.getTranslationUnitDecl());
3773
Guy Benyei11169dd2012-12-18 14:30:41 +00003774 // FIXME: Find a better way to deal with collisions between these
3775 // built-in types. Right now, we just ignore the problem.
3776
3777 // Load the special types.
3778 if (SpecialTypes.size() >= NumSpecialTypeIDs) {
3779 if (unsigned String = SpecialTypes[SPECIAL_TYPE_CF_CONSTANT_STRING]) {
3780 if (!Context.CFConstantStringTypeDecl)
3781 Context.setCFConstantStringType(GetType(String));
3782 }
3783
3784 if (unsigned File = SpecialTypes[SPECIAL_TYPE_FILE]) {
3785 QualType FileType = GetType(File);
3786 if (FileType.isNull()) {
3787 Error("FILE type is NULL");
3788 return;
3789 }
3790
3791 if (!Context.FILEDecl) {
3792 if (const TypedefType *Typedef = FileType->getAs<TypedefType>())
3793 Context.setFILEDecl(Typedef->getDecl());
3794 else {
3795 const TagType *Tag = FileType->getAs<TagType>();
3796 if (!Tag) {
3797 Error("Invalid FILE type in AST file");
3798 return;
3799 }
3800 Context.setFILEDecl(Tag->getDecl());
3801 }
3802 }
3803 }
3804
3805 if (unsigned Jmp_buf = SpecialTypes[SPECIAL_TYPE_JMP_BUF]) {
3806 QualType Jmp_bufType = GetType(Jmp_buf);
3807 if (Jmp_bufType.isNull()) {
3808 Error("jmp_buf type is NULL");
3809 return;
3810 }
3811
3812 if (!Context.jmp_bufDecl) {
3813 if (const TypedefType *Typedef = Jmp_bufType->getAs<TypedefType>())
3814 Context.setjmp_bufDecl(Typedef->getDecl());
3815 else {
3816 const TagType *Tag = Jmp_bufType->getAs<TagType>();
3817 if (!Tag) {
3818 Error("Invalid jmp_buf type in AST file");
3819 return;
3820 }
3821 Context.setjmp_bufDecl(Tag->getDecl());
3822 }
3823 }
3824 }
3825
3826 if (unsigned Sigjmp_buf = SpecialTypes[SPECIAL_TYPE_SIGJMP_BUF]) {
3827 QualType Sigjmp_bufType = GetType(Sigjmp_buf);
3828 if (Sigjmp_bufType.isNull()) {
3829 Error("sigjmp_buf type is NULL");
3830 return;
3831 }
3832
3833 if (!Context.sigjmp_bufDecl) {
3834 if (const TypedefType *Typedef = Sigjmp_bufType->getAs<TypedefType>())
3835 Context.setsigjmp_bufDecl(Typedef->getDecl());
3836 else {
3837 const TagType *Tag = Sigjmp_bufType->getAs<TagType>();
3838 assert(Tag && "Invalid sigjmp_buf type in AST file");
3839 Context.setsigjmp_bufDecl(Tag->getDecl());
3840 }
3841 }
3842 }
3843
3844 if (unsigned ObjCIdRedef
3845 = SpecialTypes[SPECIAL_TYPE_OBJC_ID_REDEFINITION]) {
3846 if (Context.ObjCIdRedefinitionType.isNull())
3847 Context.ObjCIdRedefinitionType = GetType(ObjCIdRedef);
3848 }
3849
3850 if (unsigned ObjCClassRedef
3851 = SpecialTypes[SPECIAL_TYPE_OBJC_CLASS_REDEFINITION]) {
3852 if (Context.ObjCClassRedefinitionType.isNull())
3853 Context.ObjCClassRedefinitionType = GetType(ObjCClassRedef);
3854 }
3855
3856 if (unsigned ObjCSelRedef
3857 = SpecialTypes[SPECIAL_TYPE_OBJC_SEL_REDEFINITION]) {
3858 if (Context.ObjCSelRedefinitionType.isNull())
3859 Context.ObjCSelRedefinitionType = GetType(ObjCSelRedef);
3860 }
3861
3862 if (unsigned Ucontext_t = SpecialTypes[SPECIAL_TYPE_UCONTEXT_T]) {
3863 QualType Ucontext_tType = GetType(Ucontext_t);
3864 if (Ucontext_tType.isNull()) {
3865 Error("ucontext_t type is NULL");
3866 return;
3867 }
3868
3869 if (!Context.ucontext_tDecl) {
3870 if (const TypedefType *Typedef = Ucontext_tType->getAs<TypedefType>())
3871 Context.setucontext_tDecl(Typedef->getDecl());
3872 else {
3873 const TagType *Tag = Ucontext_tType->getAs<TagType>();
3874 assert(Tag && "Invalid ucontext_t type in AST file");
3875 Context.setucontext_tDecl(Tag->getDecl());
3876 }
3877 }
3878 }
3879 }
3880
3881 ReadPragmaDiagnosticMappings(Context.getDiagnostics());
3882
3883 // If there were any CUDA special declarations, deserialize them.
3884 if (!CUDASpecialDeclRefs.empty()) {
3885 assert(CUDASpecialDeclRefs.size() == 1 && "More decl refs than expected!");
3886 Context.setcudaConfigureCallDecl(
3887 cast<FunctionDecl>(GetDecl(CUDASpecialDeclRefs[0])));
3888 }
Richard Smith56be7542014-03-21 00:33:59 +00003889
Guy Benyei11169dd2012-12-18 14:30:41 +00003890 // Re-export any modules that were imported by a non-module AST file.
Richard Smitha7e2cc62015-05-01 01:53:09 +00003891 // FIXME: This does not make macro-only imports visible again.
Richard Smith56be7542014-03-21 00:33:59 +00003892 for (auto &Import : ImportedModules) {
Richard Smitha7e2cc62015-05-01 01:53:09 +00003893 if (Module *Imported = getSubmodule(Import.ID)) {
Argyrios Kyrtzidis125df052013-02-01 16:36:12 +00003894 makeModuleVisible(Imported, Module::AllVisible,
Richard Smitha7e2cc62015-05-01 01:53:09 +00003895 /*ImportLoc=*/Import.ImportLoc);
3896 PP.makeModuleVisible(Imported, Import.ImportLoc);
3897 }
Guy Benyei11169dd2012-12-18 14:30:41 +00003898 }
3899 ImportedModules.clear();
3900}
3901
3902void ASTReader::finalizeForWriting() {
Richard Smithde711422015-04-23 21:20:19 +00003903 // Nothing to do for now.
Guy Benyei11169dd2012-12-18 14:30:41 +00003904}
3905
Argyrios Kyrtzidisc4cd2c42013-05-06 19:23:40 +00003906/// \brief Given a cursor at the start of an AST file, scan ahead and drop the
3907/// cursor into the start of the given block ID, returning false on success and
3908/// true on failure.
3909static bool SkipCursorToBlock(BitstreamCursor &Cursor, unsigned BlockID) {
Chris Lattner7fb3bef2013-01-20 00:56:42 +00003910 while (1) {
3911 llvm::BitstreamEntry Entry = Cursor.advance();
3912 switch (Entry.Kind) {
3913 case llvm::BitstreamEntry::Error:
3914 case llvm::BitstreamEntry::EndBlock:
3915 return true;
3916
3917 case llvm::BitstreamEntry::Record:
3918 // Ignore top-level records.
3919 Cursor.skipRecord(Entry.ID);
3920 break;
3921
3922 case llvm::BitstreamEntry::SubBlock:
Argyrios Kyrtzidisc4cd2c42013-05-06 19:23:40 +00003923 if (Entry.ID == BlockID) {
3924 if (Cursor.EnterSubBlock(BlockID))
Chris Lattner7fb3bef2013-01-20 00:56:42 +00003925 return true;
3926 // Found it!
3927 return false;
3928 }
3929
3930 if (Cursor.SkipBlock())
3931 return true;
3932 }
3933 }
3934}
3935
Ben Langmuir70a1b812015-03-24 04:43:52 +00003936/// \brief Reads and return the signature record from \p StreamFile's control
3937/// block, or else returns 0.
Ben Langmuir487ea142014-10-23 18:05:36 +00003938static ASTFileSignature readASTFileSignature(llvm::BitstreamReader &StreamFile){
3939 BitstreamCursor Stream(StreamFile);
Ben Langmuir70a1b812015-03-24 04:43:52 +00003940 if (!startsWithASTFileMagic(Stream))
Ben Langmuir487ea142014-10-23 18:05:36 +00003941 return 0;
Ben Langmuir487ea142014-10-23 18:05:36 +00003942
3943 // Scan for the CONTROL_BLOCK_ID block.
3944 if (SkipCursorToBlock(Stream, CONTROL_BLOCK_ID))
3945 return 0;
3946
3947 // Scan for SIGNATURE inside the control block.
3948 ASTReader::RecordData Record;
3949 while (1) {
3950 llvm::BitstreamEntry Entry = Stream.advanceSkippingSubblocks();
3951 if (Entry.Kind == llvm::BitstreamEntry::EndBlock ||
3952 Entry.Kind != llvm::BitstreamEntry::Record)
3953 return 0;
3954
3955 Record.clear();
3956 StringRef Blob;
3957 if (SIGNATURE == Stream.readRecord(Entry.ID, Record, &Blob))
3958 return Record[0];
3959 }
3960}
3961
Guy Benyei11169dd2012-12-18 14:30:41 +00003962/// \brief Retrieve the name of the original source file name
3963/// directly from the AST file, without actually loading the AST
3964/// file.
Adrian Prantlbb165fb2015-06-20 18:53:08 +00003965std::string ASTReader::getOriginalSourceFile(
3966 const std::string &ASTFileName, FileManager &FileMgr,
Adrian Prantlfb2398d2015-07-17 01:19:54 +00003967 const PCHContainerReader &PCHContainerRdr, DiagnosticsEngine &Diags) {
Guy Benyei11169dd2012-12-18 14:30:41 +00003968 // Open the AST file.
Benjamin Kramera8857962014-10-26 22:44:13 +00003969 auto Buffer = FileMgr.getBufferForFile(ASTFileName);
Guy Benyei11169dd2012-12-18 14:30:41 +00003970 if (!Buffer) {
Benjamin Kramera8857962014-10-26 22:44:13 +00003971 Diags.Report(diag::err_fe_unable_to_read_pch_file)
3972 << ASTFileName << Buffer.getError().message();
Guy Benyei11169dd2012-12-18 14:30:41 +00003973 return std::string();
3974 }
3975
3976 // Initialize the stream
3977 llvm::BitstreamReader StreamFile;
Adrian Prantlfb2398d2015-07-17 01:19:54 +00003978 PCHContainerRdr.ExtractPCH((*Buffer)->getMemBufferRef(), StreamFile);
Rafael Espindolaaf0e40a2014-11-12 14:42:25 +00003979 BitstreamCursor Stream(StreamFile);
Guy Benyei11169dd2012-12-18 14:30:41 +00003980
3981 // Sniff for the signature.
Ben Langmuir70a1b812015-03-24 04:43:52 +00003982 if (!startsWithASTFileMagic(Stream)) {
Guy Benyei11169dd2012-12-18 14:30:41 +00003983 Diags.Report(diag::err_fe_not_a_pch_file) << ASTFileName;
3984 return std::string();
3985 }
Chris Lattner7fb3bef2013-01-20 00:56:42 +00003986
Chris Lattnere7b154b2013-01-19 21:39:22 +00003987 // Scan for the CONTROL_BLOCK_ID block.
Argyrios Kyrtzidisc4cd2c42013-05-06 19:23:40 +00003988 if (SkipCursorToBlock(Stream, CONTROL_BLOCK_ID)) {
Chris Lattner7fb3bef2013-01-20 00:56:42 +00003989 Diags.Report(diag::err_fe_pch_malformed_block) << ASTFileName;
3990 return std::string();
Chris Lattnere7b154b2013-01-19 21:39:22 +00003991 }
Guy Benyei11169dd2012-12-18 14:30:41 +00003992
Chris Lattner7fb3bef2013-01-20 00:56:42 +00003993 // Scan for ORIGINAL_FILE inside the control block.
3994 RecordData Record;
Chris Lattnere7b154b2013-01-19 21:39:22 +00003995 while (1) {
Chris Lattner7fb3bef2013-01-20 00:56:42 +00003996 llvm::BitstreamEntry Entry = Stream.advanceSkippingSubblocks();
Chris Lattnere7b154b2013-01-19 21:39:22 +00003997 if (Entry.Kind == llvm::BitstreamEntry::EndBlock)
3998 return std::string();
3999
4000 if (Entry.Kind != llvm::BitstreamEntry::Record) {
4001 Diags.Report(diag::err_fe_pch_malformed_block) << ASTFileName;
4002 return std::string();
Guy Benyei11169dd2012-12-18 14:30:41 +00004003 }
Chris Lattnere7b154b2013-01-19 21:39:22 +00004004
Guy Benyei11169dd2012-12-18 14:30:41 +00004005 Record.clear();
Chris Lattner0e6c9402013-01-20 02:38:54 +00004006 StringRef Blob;
4007 if (Stream.readRecord(Entry.ID, Record, &Blob) == ORIGINAL_FILE)
4008 return Blob.str();
Guy Benyei11169dd2012-12-18 14:30:41 +00004009 }
Guy Benyei11169dd2012-12-18 14:30:41 +00004010}
4011
4012namespace {
4013 class SimplePCHValidator : public ASTReaderListener {
4014 const LangOptions &ExistingLangOpts;
4015 const TargetOptions &ExistingTargetOpts;
4016 const PreprocessorOptions &ExistingPPOpts;
Argyrios Kyrtzidisbd0b6512015-02-19 20:12:20 +00004017 std::string ExistingModuleCachePath;
Guy Benyei11169dd2012-12-18 14:30:41 +00004018 FileManager &FileMgr;
Argyrios Kyrtzidisbd0b6512015-02-19 20:12:20 +00004019
Guy Benyei11169dd2012-12-18 14:30:41 +00004020 public:
4021 SimplePCHValidator(const LangOptions &ExistingLangOpts,
4022 const TargetOptions &ExistingTargetOpts,
4023 const PreprocessorOptions &ExistingPPOpts,
Argyrios Kyrtzidisbd0b6512015-02-19 20:12:20 +00004024 StringRef ExistingModuleCachePath,
Guy Benyei11169dd2012-12-18 14:30:41 +00004025 FileManager &FileMgr)
4026 : ExistingLangOpts(ExistingLangOpts),
4027 ExistingTargetOpts(ExistingTargetOpts),
4028 ExistingPPOpts(ExistingPPOpts),
Argyrios Kyrtzidisbd0b6512015-02-19 20:12:20 +00004029 ExistingModuleCachePath(ExistingModuleCachePath),
Guy Benyei11169dd2012-12-18 14:30:41 +00004030 FileMgr(FileMgr)
4031 {
4032 }
4033
Richard Smith1e2cf0d2014-10-31 02:28:58 +00004034 bool ReadLanguageOptions(const LangOptions &LangOpts, bool Complain,
4035 bool AllowCompatibleDifferences) override {
4036 return checkLanguageOptions(ExistingLangOpts, LangOpts, nullptr,
4037 AllowCompatibleDifferences);
Guy Benyei11169dd2012-12-18 14:30:41 +00004038 }
Chandler Carruth0d745bc2015-03-14 04:47:43 +00004039 bool ReadTargetOptions(const TargetOptions &TargetOpts, bool Complain,
4040 bool AllowCompatibleDifferences) override {
4041 return checkTargetOptions(ExistingTargetOpts, TargetOpts, nullptr,
4042 AllowCompatibleDifferences);
Guy Benyei11169dd2012-12-18 14:30:41 +00004043 }
Argyrios Kyrtzidisbd0b6512015-02-19 20:12:20 +00004044 bool ReadHeaderSearchOptions(const HeaderSearchOptions &HSOpts,
4045 StringRef SpecificModuleCachePath,
4046 bool Complain) override {
4047 return checkHeaderSearchOptions(HSOpts, SpecificModuleCachePath,
4048 ExistingModuleCachePath,
4049 nullptr, ExistingLangOpts);
4050 }
Craig Topper3e89dfe2014-03-13 02:13:41 +00004051 bool ReadPreprocessorOptions(const PreprocessorOptions &PPOpts,
4052 bool Complain,
4053 std::string &SuggestedPredefines) override {
Craig Toppera13603a2014-05-22 05:54:18 +00004054 return checkPreprocessorOptions(ExistingPPOpts, PPOpts, nullptr, FileMgr,
Argyrios Kyrtzidisd3afa0c2013-04-26 21:33:40 +00004055 SuggestedPredefines, ExistingLangOpts);
Guy Benyei11169dd2012-12-18 14:30:41 +00004056 }
4057 };
Alexander Kornienkoab9db512015-06-22 23:07:51 +00004058}
Guy Benyei11169dd2012-12-18 14:30:41 +00004059
Adrian Prantlbb165fb2015-06-20 18:53:08 +00004060bool ASTReader::readASTFileControlBlock(
4061 StringRef Filename, FileManager &FileMgr,
Adrian Prantlfb2398d2015-07-17 01:19:54 +00004062 const PCHContainerReader &PCHContainerRdr,
Adrian Prantlbb165fb2015-06-20 18:53:08 +00004063 ASTReaderListener &Listener) {
Guy Benyei11169dd2012-12-18 14:30:41 +00004064 // Open the AST file.
Richard Smith7f330cd2015-03-18 01:42:29 +00004065 // FIXME: This allows use of the VFS; we do not allow use of the
4066 // VFS when actually loading a module.
Benjamin Kramera8857962014-10-26 22:44:13 +00004067 auto Buffer = FileMgr.getBufferForFile(Filename);
Guy Benyei11169dd2012-12-18 14:30:41 +00004068 if (!Buffer) {
4069 return true;
4070 }
4071
4072 // Initialize the stream
4073 llvm::BitstreamReader StreamFile;
Adrian Prantlfb2398d2015-07-17 01:19:54 +00004074 PCHContainerRdr.ExtractPCH((*Buffer)->getMemBufferRef(), StreamFile);
Rafael Espindolaaf0e40a2014-11-12 14:42:25 +00004075 BitstreamCursor Stream(StreamFile);
Guy Benyei11169dd2012-12-18 14:30:41 +00004076
4077 // Sniff for the signature.
Ben Langmuir70a1b812015-03-24 04:43:52 +00004078 if (!startsWithASTFileMagic(Stream))
Guy Benyei11169dd2012-12-18 14:30:41 +00004079 return true;
Guy Benyei11169dd2012-12-18 14:30:41 +00004080
Chris Lattner7fb3bef2013-01-20 00:56:42 +00004081 // Scan for the CONTROL_BLOCK_ID block.
Argyrios Kyrtzidisc4cd2c42013-05-06 19:23:40 +00004082 if (SkipCursorToBlock(Stream, CONTROL_BLOCK_ID))
Chris Lattner7fb3bef2013-01-20 00:56:42 +00004083 return true;
Argyrios Kyrtzidisc4cd2c42013-05-06 19:23:40 +00004084
4085 bool NeedsInputFiles = Listener.needsInputFileVisitation();
Ben Langmuircb69b572014-03-07 06:40:32 +00004086 bool NeedsSystemInputFiles = Listener.needsSystemInputFileVisitation();
Richard Smithd4b230b2014-10-27 23:01:16 +00004087 bool NeedsImports = Listener.needsImportVisitation();
Argyrios Kyrtzidisc4cd2c42013-05-06 19:23:40 +00004088 BitstreamCursor InputFilesCursor;
4089 if (NeedsInputFiles) {
4090 InputFilesCursor = Stream;
4091 if (SkipCursorToBlock(InputFilesCursor, INPUT_FILES_BLOCK_ID))
4092 return true;
4093
4094 // Read the abbreviations
4095 while (true) {
4096 uint64_t Offset = InputFilesCursor.GetCurrentBitNo();
4097 unsigned Code = InputFilesCursor.ReadCode();
4098
4099 // We expect all abbrevs to be at the start of the block.
4100 if (Code != llvm::bitc::DEFINE_ABBREV) {
4101 InputFilesCursor.JumpToBit(Offset);
4102 break;
4103 }
4104 InputFilesCursor.ReadAbbrevRecord();
4105 }
4106 }
Chris Lattner7fb3bef2013-01-20 00:56:42 +00004107
4108 // Scan for ORIGINAL_FILE inside the control block.
Guy Benyei11169dd2012-12-18 14:30:41 +00004109 RecordData Record;
Richard Smith7ed1bc92014-12-05 22:42:13 +00004110 std::string ModuleDir;
Chris Lattner7fb3bef2013-01-20 00:56:42 +00004111 while (1) {
4112 llvm::BitstreamEntry Entry = Stream.advanceSkippingSubblocks();
4113 if (Entry.Kind == llvm::BitstreamEntry::EndBlock)
4114 return false;
4115
4116 if (Entry.Kind != llvm::BitstreamEntry::Record)
4117 return true;
4118
Guy Benyei11169dd2012-12-18 14:30:41 +00004119 Record.clear();
Chris Lattner0e6c9402013-01-20 02:38:54 +00004120 StringRef Blob;
4121 unsigned RecCode = Stream.readRecord(Entry.ID, Record, &Blob);
Chris Lattner7fb3bef2013-01-20 00:56:42 +00004122 switch ((ControlRecordTypes)RecCode) {
4123 case METADATA: {
4124 if (Record[0] != VERSION_MAJOR)
4125 return true;
Guy Benyei11169dd2012-12-18 14:30:41 +00004126
Douglas Gregorbf7fc9c2013-03-27 16:47:18 +00004127 if (Listener.ReadFullVersionInformation(Blob))
Chris Lattner7fb3bef2013-01-20 00:56:42 +00004128 return true;
Douglas Gregorbf7fc9c2013-03-27 16:47:18 +00004129
Chris Lattner7fb3bef2013-01-20 00:56:42 +00004130 break;
4131 }
Ben Langmuir4f5212a2014-04-14 22:12:44 +00004132 case MODULE_NAME:
4133 Listener.ReadModuleName(Blob);
4134 break;
Richard Smith7ed1bc92014-12-05 22:42:13 +00004135 case MODULE_DIRECTORY:
4136 ModuleDir = Blob;
4137 break;
Ben Langmuir4b8a9e92014-08-12 16:42:33 +00004138 case MODULE_MAP_FILE: {
4139 unsigned Idx = 0;
Richard Smith7ed1bc92014-12-05 22:42:13 +00004140 auto Path = ReadString(Record, Idx);
4141 ResolveImportedPath(Path, ModuleDir);
4142 Listener.ReadModuleMapFile(Path);
Ben Langmuir4f5212a2014-04-14 22:12:44 +00004143 break;
Ben Langmuir4b8a9e92014-08-12 16:42:33 +00004144 }
Chris Lattner7fb3bef2013-01-20 00:56:42 +00004145 case LANGUAGE_OPTIONS:
Richard Smith1e2cf0d2014-10-31 02:28:58 +00004146 if (ParseLanguageOptions(Record, false, Listener,
4147 /*AllowCompatibleConfigurationMismatch*/false))
Chris Lattner7fb3bef2013-01-20 00:56:42 +00004148 return true;
4149 break;
Guy Benyei11169dd2012-12-18 14:30:41 +00004150
Chris Lattner7fb3bef2013-01-20 00:56:42 +00004151 case TARGET_OPTIONS:
Chandler Carruth0d745bc2015-03-14 04:47:43 +00004152 if (ParseTargetOptions(Record, false, Listener,
4153 /*AllowCompatibleConfigurationMismatch*/ false))
Chris Lattner7fb3bef2013-01-20 00:56:42 +00004154 return true;
4155 break;
Guy Benyei11169dd2012-12-18 14:30:41 +00004156
Chris Lattner7fb3bef2013-01-20 00:56:42 +00004157 case DIAGNOSTIC_OPTIONS:
4158 if (ParseDiagnosticOptions(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 FILE_SYSTEM_OPTIONS:
4163 if (ParseFileSystemOptions(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 HEADER_SEARCH_OPTIONS:
4168 if (ParseHeaderSearchOptions(Record, false, Listener))
4169 return true;
4170 break;
Guy Benyei11169dd2012-12-18 14:30:41 +00004171
Chris Lattner7fb3bef2013-01-20 00:56:42 +00004172 case PREPROCESSOR_OPTIONS: {
4173 std::string IgnoredSuggestedPredefines;
4174 if (ParsePreprocessorOptions(Record, false, Listener,
4175 IgnoredSuggestedPredefines))
4176 return true;
4177 break;
4178 }
Guy Benyei11169dd2012-12-18 14:30:41 +00004179
Argyrios Kyrtzidisc4cd2c42013-05-06 19:23:40 +00004180 case INPUT_FILE_OFFSETS: {
4181 if (!NeedsInputFiles)
4182 break;
4183
4184 unsigned NumInputFiles = Record[0];
4185 unsigned NumUserFiles = Record[1];
Richard Smithec216502015-02-13 19:48:37 +00004186 const uint64_t *InputFileOffs = (const uint64_t *)Blob.data();
Argyrios Kyrtzidisc4cd2c42013-05-06 19:23:40 +00004187 for (unsigned I = 0; I != NumInputFiles; ++I) {
4188 // Go find this input file.
4189 bool isSystemFile = I >= NumUserFiles;
Ben Langmuircb69b572014-03-07 06:40:32 +00004190
4191 if (isSystemFile && !NeedsSystemInputFiles)
4192 break; // the rest are system input files
4193
Argyrios Kyrtzidisc4cd2c42013-05-06 19:23:40 +00004194 BitstreamCursor &Cursor = InputFilesCursor;
4195 SavedStreamPosition SavedPosition(Cursor);
4196 Cursor.JumpToBit(InputFileOffs[I]);
4197
4198 unsigned Code = Cursor.ReadCode();
4199 RecordData Record;
4200 StringRef Blob;
4201 bool shouldContinue = false;
4202 switch ((InputFileRecordTypes)Cursor.readRecord(Code, Record, &Blob)) {
4203 case INPUT_FILE:
Argyrios Kyrtzidis68ccbe02014-03-14 02:26:31 +00004204 bool Overridden = static_cast<bool>(Record[3]);
Richard Smith7ed1bc92014-12-05 22:42:13 +00004205 std::string Filename = Blob;
4206 ResolveImportedPath(Filename, ModuleDir);
Richard Smith216a3bd2015-08-13 17:57:10 +00004207 shouldContinue = Listener.visitInputFile(
4208 Filename, isSystemFile, Overridden, /*IsExplicitModule*/false);
Argyrios Kyrtzidisc4cd2c42013-05-06 19:23:40 +00004209 break;
4210 }
4211 if (!shouldContinue)
4212 break;
4213 }
4214 break;
4215 }
4216
Richard Smithd4b230b2014-10-27 23:01:16 +00004217 case IMPORTS: {
4218 if (!NeedsImports)
4219 break;
4220
4221 unsigned Idx = 0, N = Record.size();
4222 while (Idx < N) {
4223 // Read information about the AST file.
Richard Smith79c98cc2014-10-27 23:25:15 +00004224 Idx += 5; // ImportLoc, Size, ModTime, Signature
Richard Smith7ed1bc92014-12-05 22:42:13 +00004225 std::string Filename = ReadString(Record, Idx);
4226 ResolveImportedPath(Filename, ModuleDir);
4227 Listener.visitImport(Filename);
Richard Smithd4b230b2014-10-27 23:01:16 +00004228 }
4229 break;
4230 }
4231
Chris Lattner7fb3bef2013-01-20 00:56:42 +00004232 default:
4233 // No other validation to perform.
4234 break;
Guy Benyei11169dd2012-12-18 14:30:41 +00004235 }
4236 }
Guy Benyei11169dd2012-12-18 14:30:41 +00004237}
4238
Adrian Prantlbb165fb2015-06-20 18:53:08 +00004239bool ASTReader::isAcceptableASTFile(
4240 StringRef Filename, FileManager &FileMgr,
Adrian Prantlfb2398d2015-07-17 01:19:54 +00004241 const PCHContainerReader &PCHContainerRdr, const LangOptions &LangOpts,
Adrian Prantlbb165fb2015-06-20 18:53:08 +00004242 const TargetOptions &TargetOpts, const PreprocessorOptions &PPOpts,
4243 std::string ExistingModuleCachePath) {
Argyrios Kyrtzidisbd0b6512015-02-19 20:12:20 +00004244 SimplePCHValidator validator(LangOpts, TargetOpts, PPOpts,
4245 ExistingModuleCachePath, FileMgr);
Adrian Prantlfb2398d2015-07-17 01:19:54 +00004246 return !readASTFileControlBlock(Filename, FileMgr, PCHContainerRdr,
Adrian Prantlbb165fb2015-06-20 18:53:08 +00004247 validator);
Guy Benyei11169dd2012-12-18 14:30:41 +00004248}
4249
Ben Langmuir2c9af442014-04-10 17:57:43 +00004250ASTReader::ASTReadResult
4251ASTReader::ReadSubmoduleBlock(ModuleFile &F, unsigned ClientLoadCapabilities) {
Guy Benyei11169dd2012-12-18 14:30:41 +00004252 // Enter the submodule block.
4253 if (F.Stream.EnterSubBlock(SUBMODULE_BLOCK_ID)) {
4254 Error("malformed submodule block record in AST file");
Ben Langmuir2c9af442014-04-10 17:57:43 +00004255 return Failure;
Guy Benyei11169dd2012-12-18 14:30:41 +00004256 }
4257
4258 ModuleMap &ModMap = PP.getHeaderSearchInfo().getModuleMap();
4259 bool First = true;
Craig Toppera13603a2014-05-22 05:54:18 +00004260 Module *CurrentModule = nullptr;
Guy Benyei11169dd2012-12-18 14:30:41 +00004261 RecordData Record;
4262 while (true) {
Chris Lattner7fb3bef2013-01-20 00:56:42 +00004263 llvm::BitstreamEntry Entry = F.Stream.advanceSkippingSubblocks();
4264
4265 switch (Entry.Kind) {
4266 case llvm::BitstreamEntry::SubBlock: // Handled for us already.
4267 case llvm::BitstreamEntry::Error:
4268 Error("malformed block record in AST file");
Ben Langmuir2c9af442014-04-10 17:57:43 +00004269 return Failure;
Chris Lattner7fb3bef2013-01-20 00:56:42 +00004270 case llvm::BitstreamEntry::EndBlock:
Ben Langmuir2c9af442014-04-10 17:57:43 +00004271 return Success;
Chris Lattner7fb3bef2013-01-20 00:56:42 +00004272 case llvm::BitstreamEntry::Record:
4273 // The interesting case.
4274 break;
Guy Benyei11169dd2012-12-18 14:30:41 +00004275 }
Chris Lattner7fb3bef2013-01-20 00:56:42 +00004276
Guy Benyei11169dd2012-12-18 14:30:41 +00004277 // Read a record.
Chris Lattner0e6c9402013-01-20 02:38:54 +00004278 StringRef Blob;
Guy Benyei11169dd2012-12-18 14:30:41 +00004279 Record.clear();
Richard Smith03478d92014-10-23 22:12:14 +00004280 auto Kind = F.Stream.readRecord(Entry.ID, Record, &Blob);
4281
4282 if ((Kind == SUBMODULE_METADATA) != First) {
4283 Error("submodule metadata record should be at beginning of block");
4284 return Failure;
4285 }
4286 First = false;
4287
4288 // Submodule information is only valid if we have a current module.
4289 // FIXME: Should we error on these cases?
4290 if (!CurrentModule && Kind != SUBMODULE_METADATA &&
4291 Kind != SUBMODULE_DEFINITION)
4292 continue;
4293
4294 switch (Kind) {
Guy Benyei11169dd2012-12-18 14:30:41 +00004295 default: // Default behavior: ignore.
4296 break;
Guy Benyei11169dd2012-12-18 14:30:41 +00004297
Richard Smith03478d92014-10-23 22:12:14 +00004298 case SUBMODULE_DEFINITION: {
Douglas Gregor8d932422013-03-20 03:59:18 +00004299 if (Record.size() < 8) {
Guy Benyei11169dd2012-12-18 14:30:41 +00004300 Error("malformed module definition");
Ben Langmuir2c9af442014-04-10 17:57:43 +00004301 return Failure;
Guy Benyei11169dd2012-12-18 14:30:41 +00004302 }
Richard Smith03478d92014-10-23 22:12:14 +00004303
Chris Lattner0e6c9402013-01-20 02:38:54 +00004304 StringRef Name = Blob;
Richard Smith9bca2982014-03-08 00:03:56 +00004305 unsigned Idx = 0;
4306 SubmoduleID GlobalID = getGlobalSubmoduleID(F, Record[Idx++]);
4307 SubmoduleID Parent = getGlobalSubmoduleID(F, Record[Idx++]);
4308 bool IsFramework = Record[Idx++];
4309 bool IsExplicit = Record[Idx++];
4310 bool IsSystem = Record[Idx++];
4311 bool IsExternC = Record[Idx++];
4312 bool InferSubmodules = Record[Idx++];
4313 bool InferExplicitSubmodules = Record[Idx++];
4314 bool InferExportWildcard = Record[Idx++];
4315 bool ConfigMacrosExhaustive = Record[Idx++];
Douglas Gregor8d932422013-03-20 03:59:18 +00004316
Ben Langmuirbeee15e2014-04-14 18:00:01 +00004317 Module *ParentModule = nullptr;
Ben Langmuir9d6448b2014-08-09 00:57:23 +00004318 if (Parent)
Guy Benyei11169dd2012-12-18 14:30:41 +00004319 ParentModule = getSubmodule(Parent);
Ben Langmuirbeee15e2014-04-14 18:00:01 +00004320
Guy Benyei11169dd2012-12-18 14:30:41 +00004321 // Retrieve this (sub)module from the module map, creating it if
4322 // necessary.
Ben Langmuir9d6448b2014-08-09 00:57:23 +00004323 CurrentModule = ModMap.findOrCreateModule(Name, ParentModule, IsFramework,
Guy Benyei11169dd2012-12-18 14:30:41 +00004324 IsExplicit).first;
Ben Langmuir9d6448b2014-08-09 00:57:23 +00004325
4326 // FIXME: set the definition loc for CurrentModule, or call
4327 // ModMap.setInferredModuleAllowedBy()
4328
Guy Benyei11169dd2012-12-18 14:30:41 +00004329 SubmoduleID GlobalIndex = GlobalID - NUM_PREDEF_SUBMODULE_IDS;
4330 if (GlobalIndex >= SubmodulesLoaded.size() ||
4331 SubmodulesLoaded[GlobalIndex]) {
4332 Error("too many submodules");
Ben Langmuir2c9af442014-04-10 17:57:43 +00004333 return Failure;
Guy Benyei11169dd2012-12-18 14:30:41 +00004334 }
Douglas Gregor8a114ab2013-02-06 22:40:31 +00004335
Douglas Gregor7029ce12013-03-19 00:28:20 +00004336 if (!ParentModule) {
4337 if (const FileEntry *CurFile = CurrentModule->getASTFile()) {
4338 if (CurFile != F.File) {
4339 if (!Diags.isDiagnosticInFlight()) {
4340 Diag(diag::err_module_file_conflict)
4341 << CurrentModule->getTopLevelModuleName()
4342 << CurFile->getName()
4343 << F.File->getName();
4344 }
Ben Langmuir2c9af442014-04-10 17:57:43 +00004345 return Failure;
Douglas Gregor8a114ab2013-02-06 22:40:31 +00004346 }
Douglas Gregor8a114ab2013-02-06 22:40:31 +00004347 }
Douglas Gregor7029ce12013-03-19 00:28:20 +00004348
4349 CurrentModule->setASTFile(F.File);
Douglas Gregor8a114ab2013-02-06 22:40:31 +00004350 }
Ben Langmuirbeee15e2014-04-14 18:00:01 +00004351
Adrian Prantl15bcf702015-06-30 17:39:43 +00004352 CurrentModule->Signature = F.Signature;
Guy Benyei11169dd2012-12-18 14:30:41 +00004353 CurrentModule->IsFromModuleFile = true;
4354 CurrentModule->IsSystem = IsSystem || CurrentModule->IsSystem;
Richard Smith9bca2982014-03-08 00:03:56 +00004355 CurrentModule->IsExternC = IsExternC;
Guy Benyei11169dd2012-12-18 14:30:41 +00004356 CurrentModule->InferSubmodules = InferSubmodules;
4357 CurrentModule->InferExplicitSubmodules = InferExplicitSubmodules;
4358 CurrentModule->InferExportWildcard = InferExportWildcard;
Douglas Gregor8d932422013-03-20 03:59:18 +00004359 CurrentModule->ConfigMacrosExhaustive = ConfigMacrosExhaustive;
Guy Benyei11169dd2012-12-18 14:30:41 +00004360 if (DeserializationListener)
4361 DeserializationListener->ModuleRead(GlobalID, CurrentModule);
4362
4363 SubmodulesLoaded[GlobalIndex] = CurrentModule;
Douglas Gregor6ddfca92013-01-14 17:21:00 +00004364
Douglas Gregorfb912652013-03-20 21:10:35 +00004365 // Clear out data that will be replaced by what is the module file.
Douglas Gregor6ddfca92013-01-14 17:21:00 +00004366 CurrentModule->LinkLibraries.clear();
Douglas Gregor8d932422013-03-20 03:59:18 +00004367 CurrentModule->ConfigMacros.clear();
Douglas Gregorfb912652013-03-20 21:10:35 +00004368 CurrentModule->UnresolvedConflicts.clear();
4369 CurrentModule->Conflicts.clear();
Guy Benyei11169dd2012-12-18 14:30:41 +00004370 break;
4371 }
4372
4373 case SUBMODULE_UMBRELLA_HEADER: {
Richard Smith2b63d152015-05-16 02:28:53 +00004374 std::string Filename = Blob;
4375 ResolveImportedPath(F, Filename);
4376 if (auto *Umbrella = PP.getFileManager().getFile(Filename)) {
Guy Benyei11169dd2012-12-18 14:30:41 +00004377 if (!CurrentModule->getUmbrellaHeader())
Richard Smith2b63d152015-05-16 02:28:53 +00004378 ModMap.setUmbrellaHeader(CurrentModule, Umbrella, Blob);
4379 else if (CurrentModule->getUmbrellaHeader().Entry != Umbrella) {
Ben Langmuirbc35fbe2015-02-20 21:46:39 +00004380 // This can be a spurious difference caused by changing the VFS to
4381 // point to a different copy of the file, and it is too late to
4382 // to rebuild safely.
4383 // FIXME: If we wrote the virtual paths instead of the 'real' paths,
4384 // after input file validation only real problems would remain and we
4385 // could just error. For now, assume it's okay.
4386 break;
Guy Benyei11169dd2012-12-18 14:30:41 +00004387 }
4388 }
4389 break;
4390 }
4391
Richard Smith202210b2014-10-24 20:23:01 +00004392 case SUBMODULE_HEADER:
4393 case SUBMODULE_EXCLUDED_HEADER:
4394 case SUBMODULE_PRIVATE_HEADER:
4395 // We lazily associate headers with their modules via the HeaderInfo table.
Argyrios Kyrtzidisb146baa2013-03-13 21:13:51 +00004396 // FIXME: Re-evaluate this section; maybe only store InputFile IDs instead
4397 // of complete filenames or remove it entirely.
Richard Smith202210b2014-10-24 20:23:01 +00004398 break;
Guy Benyei11169dd2012-12-18 14:30:41 +00004399
Richard Smith202210b2014-10-24 20:23:01 +00004400 case SUBMODULE_TEXTUAL_HEADER:
4401 case SUBMODULE_PRIVATE_TEXTUAL_HEADER:
4402 // FIXME: Textual headers are not marked in the HeaderInfo table. Load
4403 // them here.
4404 break;
Lawrence Crowlb53e5482013-06-20 21:14:14 +00004405
Guy Benyei11169dd2012-12-18 14:30:41 +00004406 case SUBMODULE_TOPHEADER: {
Argyrios Kyrtzidis3c5305c2013-03-13 21:13:43 +00004407 CurrentModule->addTopHeaderFilename(Blob);
Guy Benyei11169dd2012-12-18 14:30:41 +00004408 break;
4409 }
4410
4411 case SUBMODULE_UMBRELLA_DIR: {
Richard Smith2b63d152015-05-16 02:28:53 +00004412 std::string Dirname = Blob;
4413 ResolveImportedPath(F, Dirname);
4414 if (auto *Umbrella = PP.getFileManager().getDirectory(Dirname)) {
Guy Benyei11169dd2012-12-18 14:30:41 +00004415 if (!CurrentModule->getUmbrellaDir())
Richard Smith2b63d152015-05-16 02:28:53 +00004416 ModMap.setUmbrellaDir(CurrentModule, Umbrella, Blob);
4417 else if (CurrentModule->getUmbrellaDir().Entry != Umbrella) {
Ben Langmuir2c9af442014-04-10 17:57:43 +00004418 if ((ClientLoadCapabilities & ARR_OutOfDate) == 0)
4419 Error("mismatched umbrella directories in submodule");
4420 return OutOfDate;
Guy Benyei11169dd2012-12-18 14:30:41 +00004421 }
4422 }
4423 break;
4424 }
4425
4426 case SUBMODULE_METADATA: {
Guy Benyei11169dd2012-12-18 14:30:41 +00004427 F.BaseSubmoduleID = getTotalNumSubmodules();
4428 F.LocalNumSubmodules = Record[0];
4429 unsigned LocalBaseSubmoduleID = Record[1];
4430 if (F.LocalNumSubmodules > 0) {
4431 // Introduce the global -> local mapping for submodules within this
4432 // module.
4433 GlobalSubmoduleMap.insert(std::make_pair(getTotalNumSubmodules()+1,&F));
4434
4435 // Introduce the local -> global mapping for submodules within this
4436 // module.
4437 F.SubmoduleRemap.insertOrReplace(
4438 std::make_pair(LocalBaseSubmoduleID,
4439 F.BaseSubmoduleID - LocalBaseSubmoduleID));
Ben Langmuirfe971d92014-08-16 04:54:18 +00004440
Ben Langmuir52ca6782014-10-20 16:27:32 +00004441 SubmodulesLoaded.resize(SubmodulesLoaded.size() + F.LocalNumSubmodules);
4442 }
Guy Benyei11169dd2012-12-18 14:30:41 +00004443 break;
4444 }
4445
4446 case SUBMODULE_IMPORTS: {
Guy Benyei11169dd2012-12-18 14:30:41 +00004447 for (unsigned Idx = 0; Idx != Record.size(); ++Idx) {
Douglas Gregorfb912652013-03-20 21:10:35 +00004448 UnresolvedModuleRef Unresolved;
Guy Benyei11169dd2012-12-18 14:30:41 +00004449 Unresolved.File = &F;
4450 Unresolved.Mod = CurrentModule;
4451 Unresolved.ID = Record[Idx];
Douglas Gregorfb912652013-03-20 21:10:35 +00004452 Unresolved.Kind = UnresolvedModuleRef::Import;
Guy Benyei11169dd2012-12-18 14:30:41 +00004453 Unresolved.IsWildcard = false;
Douglas Gregorfb912652013-03-20 21:10:35 +00004454 UnresolvedModuleRefs.push_back(Unresolved);
Guy Benyei11169dd2012-12-18 14:30:41 +00004455 }
4456 break;
4457 }
4458
4459 case SUBMODULE_EXPORTS: {
Guy Benyei11169dd2012-12-18 14:30:41 +00004460 for (unsigned Idx = 0; Idx + 1 < Record.size(); Idx += 2) {
Douglas Gregorfb912652013-03-20 21:10:35 +00004461 UnresolvedModuleRef Unresolved;
Guy Benyei11169dd2012-12-18 14:30:41 +00004462 Unresolved.File = &F;
4463 Unresolved.Mod = CurrentModule;
4464 Unresolved.ID = Record[Idx];
Douglas Gregorfb912652013-03-20 21:10:35 +00004465 Unresolved.Kind = UnresolvedModuleRef::Export;
Guy Benyei11169dd2012-12-18 14:30:41 +00004466 Unresolved.IsWildcard = Record[Idx + 1];
Douglas Gregorfb912652013-03-20 21:10:35 +00004467 UnresolvedModuleRefs.push_back(Unresolved);
Guy Benyei11169dd2012-12-18 14:30:41 +00004468 }
4469
4470 // Once we've loaded the set of exports, there's no reason to keep
4471 // the parsed, unresolved exports around.
4472 CurrentModule->UnresolvedExports.clear();
4473 break;
4474 }
4475 case SUBMODULE_REQUIRES: {
Richard Smitha3feee22013-10-28 22:18:19 +00004476 CurrentModule->addRequirement(Blob, Record[0], Context.getLangOpts(),
Guy Benyei11169dd2012-12-18 14:30:41 +00004477 Context.getTargetInfo());
4478 break;
4479 }
Douglas Gregor6ddfca92013-01-14 17:21:00 +00004480
4481 case SUBMODULE_LINK_LIBRARY:
Douglas Gregor6ddfca92013-01-14 17:21:00 +00004482 CurrentModule->LinkLibraries.push_back(
Chris Lattner0e6c9402013-01-20 02:38:54 +00004483 Module::LinkLibrary(Blob, Record[0]));
Douglas Gregor6ddfca92013-01-14 17:21:00 +00004484 break;
Douglas Gregor35b13ec2013-03-20 00:22:05 +00004485
4486 case SUBMODULE_CONFIG_MACRO:
Douglas Gregor35b13ec2013-03-20 00:22:05 +00004487 CurrentModule->ConfigMacros.push_back(Blob.str());
4488 break;
Douglas Gregorfb912652013-03-20 21:10:35 +00004489
4490 case SUBMODULE_CONFLICT: {
Douglas Gregorfb912652013-03-20 21:10:35 +00004491 UnresolvedModuleRef Unresolved;
4492 Unresolved.File = &F;
4493 Unresolved.Mod = CurrentModule;
4494 Unresolved.ID = Record[0];
4495 Unresolved.Kind = UnresolvedModuleRef::Conflict;
4496 Unresolved.IsWildcard = false;
4497 Unresolved.String = Blob;
4498 UnresolvedModuleRefs.push_back(Unresolved);
4499 break;
4500 }
Guy Benyei11169dd2012-12-18 14:30:41 +00004501 }
4502 }
4503}
4504
4505/// \brief Parse the record that corresponds to a LangOptions data
4506/// structure.
4507///
4508/// This routine parses the language options from the AST file and then gives
4509/// them to the AST listener if one is set.
4510///
4511/// \returns true if the listener deems the file unacceptable, false otherwise.
4512bool ASTReader::ParseLanguageOptions(const RecordData &Record,
4513 bool Complain,
Richard Smith1e2cf0d2014-10-31 02:28:58 +00004514 ASTReaderListener &Listener,
4515 bool AllowCompatibleDifferences) {
Guy Benyei11169dd2012-12-18 14:30:41 +00004516 LangOptions LangOpts;
4517 unsigned Idx = 0;
4518#define LANGOPT(Name, Bits, Default, Description) \
4519 LangOpts.Name = Record[Idx++];
4520#define ENUM_LANGOPT(Name, Type, Bits, Default, Description) \
4521 LangOpts.set##Name(static_cast<LangOptions::Type>(Record[Idx++]));
4522#include "clang/Basic/LangOptions.def"
Alexey Samsonovedf99a92014-11-07 22:29:38 +00004523#define SANITIZER(NAME, ID) \
4524 LangOpts.Sanitize.set(SanitizerKind::ID, Record[Idx++]);
Will Dietzf54319c2013-01-18 11:30:38 +00004525#include "clang/Basic/Sanitizers.def"
Guy Benyei11169dd2012-12-18 14:30:41 +00004526
Ben Langmuircd98cb72015-06-23 18:20:18 +00004527 for (unsigned N = Record[Idx++]; N; --N)
4528 LangOpts.ModuleFeatures.push_back(ReadString(Record, Idx));
4529
Guy Benyei11169dd2012-12-18 14:30:41 +00004530 ObjCRuntime::Kind runtimeKind = (ObjCRuntime::Kind) Record[Idx++];
4531 VersionTuple runtimeVersion = ReadVersionTuple(Record, Idx);
4532 LangOpts.ObjCRuntime = ObjCRuntime(runtimeKind, runtimeVersion);
Dmitri Gribenkoacf2e782013-02-22 14:21:27 +00004533
Ben Langmuird4a667a2015-06-23 18:20:23 +00004534 LangOpts.CurrentModule = ReadString(Record, Idx);
Dmitri Gribenkoacf2e782013-02-22 14:21:27 +00004535
4536 // Comment options.
4537 for (unsigned N = Record[Idx++]; N; --N) {
4538 LangOpts.CommentOpts.BlockCommandNames.push_back(
4539 ReadString(Record, Idx));
4540 }
Dmitri Gribenkoa7d16ce2013-04-10 15:35:17 +00004541 LangOpts.CommentOpts.ParseAllComments = Record[Idx++];
Dmitri Gribenkoacf2e782013-02-22 14:21:27 +00004542
Richard Smith1e2cf0d2014-10-31 02:28:58 +00004543 return Listener.ReadLanguageOptions(LangOpts, Complain,
4544 AllowCompatibleDifferences);
Guy Benyei11169dd2012-12-18 14:30:41 +00004545}
4546
Chandler Carruth0d745bc2015-03-14 04:47:43 +00004547bool ASTReader::ParseTargetOptions(const RecordData &Record, bool Complain,
4548 ASTReaderListener &Listener,
4549 bool AllowCompatibleDifferences) {
Guy Benyei11169dd2012-12-18 14:30:41 +00004550 unsigned Idx = 0;
4551 TargetOptions TargetOpts;
4552 TargetOpts.Triple = ReadString(Record, Idx);
4553 TargetOpts.CPU = ReadString(Record, Idx);
4554 TargetOpts.ABI = ReadString(Record, Idx);
Guy Benyei11169dd2012-12-18 14:30:41 +00004555 for (unsigned N = Record[Idx++]; N; --N) {
4556 TargetOpts.FeaturesAsWritten.push_back(ReadString(Record, Idx));
4557 }
4558 for (unsigned N = Record[Idx++]; N; --N) {
4559 TargetOpts.Features.push_back(ReadString(Record, Idx));
4560 }
4561
Chandler Carruth0d745bc2015-03-14 04:47:43 +00004562 return Listener.ReadTargetOptions(TargetOpts, Complain,
4563 AllowCompatibleDifferences);
Guy Benyei11169dd2012-12-18 14:30:41 +00004564}
4565
4566bool ASTReader::ParseDiagnosticOptions(const RecordData &Record, bool Complain,
4567 ASTReaderListener &Listener) {
Ben Langmuirb92de022014-04-29 16:25:26 +00004568 IntrusiveRefCntPtr<DiagnosticOptions> DiagOpts(new DiagnosticOptions);
Guy Benyei11169dd2012-12-18 14:30:41 +00004569 unsigned Idx = 0;
Ben Langmuirb92de022014-04-29 16:25:26 +00004570#define DIAGOPT(Name, Bits, Default) DiagOpts->Name = Record[Idx++];
Guy Benyei11169dd2012-12-18 14:30:41 +00004571#define ENUM_DIAGOPT(Name, Type, Bits, Default) \
Ben Langmuirb92de022014-04-29 16:25:26 +00004572 DiagOpts->set##Name(static_cast<Type>(Record[Idx++]));
Guy Benyei11169dd2012-12-18 14:30:41 +00004573#include "clang/Basic/DiagnosticOptions.def"
4574
Richard Smith3be1cb22014-08-07 00:24:21 +00004575 for (unsigned N = Record[Idx++]; N; --N)
Ben Langmuirb92de022014-04-29 16:25:26 +00004576 DiagOpts->Warnings.push_back(ReadString(Record, Idx));
Richard Smith3be1cb22014-08-07 00:24:21 +00004577 for (unsigned N = Record[Idx++]; N; --N)
4578 DiagOpts->Remarks.push_back(ReadString(Record, Idx));
Guy Benyei11169dd2012-12-18 14:30:41 +00004579
4580 return Listener.ReadDiagnosticOptions(DiagOpts, Complain);
4581}
4582
4583bool ASTReader::ParseFileSystemOptions(const RecordData &Record, bool Complain,
4584 ASTReaderListener &Listener) {
4585 FileSystemOptions FSOpts;
4586 unsigned Idx = 0;
4587 FSOpts.WorkingDir = ReadString(Record, Idx);
4588 return Listener.ReadFileSystemOptions(FSOpts, Complain);
4589}
4590
4591bool ASTReader::ParseHeaderSearchOptions(const RecordData &Record,
4592 bool Complain,
4593 ASTReaderListener &Listener) {
4594 HeaderSearchOptions HSOpts;
4595 unsigned Idx = 0;
4596 HSOpts.Sysroot = ReadString(Record, Idx);
4597
4598 // Include entries.
4599 for (unsigned N = Record[Idx++]; N; --N) {
4600 std::string Path = ReadString(Record, Idx);
4601 frontend::IncludeDirGroup Group
4602 = static_cast<frontend::IncludeDirGroup>(Record[Idx++]);
Guy Benyei11169dd2012-12-18 14:30:41 +00004603 bool IsFramework = Record[Idx++];
4604 bool IgnoreSysRoot = Record[Idx++];
Benjamin Kramer3204b152015-05-29 19:42:19 +00004605 HSOpts.UserEntries.emplace_back(std::move(Path), Group, IsFramework,
4606 IgnoreSysRoot);
Guy Benyei11169dd2012-12-18 14:30:41 +00004607 }
4608
4609 // System header prefixes.
4610 for (unsigned N = Record[Idx++]; N; --N) {
4611 std::string Prefix = ReadString(Record, Idx);
4612 bool IsSystemHeader = Record[Idx++];
Benjamin Kramer3204b152015-05-29 19:42:19 +00004613 HSOpts.SystemHeaderPrefixes.emplace_back(std::move(Prefix), IsSystemHeader);
Guy Benyei11169dd2012-12-18 14:30:41 +00004614 }
4615
4616 HSOpts.ResourceDir = ReadString(Record, Idx);
4617 HSOpts.ModuleCachePath = ReadString(Record, Idx);
Argyrios Kyrtzidis1594c152014-03-03 08:12:05 +00004618 HSOpts.ModuleUserBuildPath = ReadString(Record, Idx);
Guy Benyei11169dd2012-12-18 14:30:41 +00004619 HSOpts.DisableModuleHash = Record[Idx++];
4620 HSOpts.UseBuiltinIncludes = Record[Idx++];
4621 HSOpts.UseStandardSystemIncludes = Record[Idx++];
4622 HSOpts.UseStandardCXXIncludes = Record[Idx++];
4623 HSOpts.UseLibcxx = Record[Idx++];
Argyrios Kyrtzidisbd0b6512015-02-19 20:12:20 +00004624 std::string SpecificModuleCachePath = ReadString(Record, Idx);
Guy Benyei11169dd2012-12-18 14:30:41 +00004625
Argyrios Kyrtzidisbd0b6512015-02-19 20:12:20 +00004626 return Listener.ReadHeaderSearchOptions(HSOpts, SpecificModuleCachePath,
4627 Complain);
Guy Benyei11169dd2012-12-18 14:30:41 +00004628}
4629
4630bool ASTReader::ParsePreprocessorOptions(const RecordData &Record,
4631 bool Complain,
4632 ASTReaderListener &Listener,
4633 std::string &SuggestedPredefines) {
4634 PreprocessorOptions PPOpts;
4635 unsigned Idx = 0;
4636
4637 // Macro definitions/undefs
4638 for (unsigned N = Record[Idx++]; N; --N) {
4639 std::string Macro = ReadString(Record, Idx);
4640 bool IsUndef = Record[Idx++];
4641 PPOpts.Macros.push_back(std::make_pair(Macro, IsUndef));
4642 }
4643
4644 // Includes
4645 for (unsigned N = Record[Idx++]; N; --N) {
4646 PPOpts.Includes.push_back(ReadString(Record, Idx));
4647 }
4648
4649 // Macro Includes
4650 for (unsigned N = Record[Idx++]; N; --N) {
4651 PPOpts.MacroIncludes.push_back(ReadString(Record, Idx));
4652 }
4653
4654 PPOpts.UsePredefines = Record[Idx++];
Argyrios Kyrtzidisd3afa0c2013-04-26 21:33:40 +00004655 PPOpts.DetailedRecord = Record[Idx++];
Guy Benyei11169dd2012-12-18 14:30:41 +00004656 PPOpts.ImplicitPCHInclude = ReadString(Record, Idx);
4657 PPOpts.ImplicitPTHInclude = ReadString(Record, Idx);
4658 PPOpts.ObjCXXARCStandardLibrary =
4659 static_cast<ObjCXXARCStandardLibraryKind>(Record[Idx++]);
4660 SuggestedPredefines.clear();
4661 return Listener.ReadPreprocessorOptions(PPOpts, Complain,
4662 SuggestedPredefines);
4663}
4664
4665std::pair<ModuleFile *, unsigned>
4666ASTReader::getModulePreprocessedEntity(unsigned GlobalIndex) {
4667 GlobalPreprocessedEntityMapType::iterator
4668 I = GlobalPreprocessedEntityMap.find(GlobalIndex);
4669 assert(I != GlobalPreprocessedEntityMap.end() &&
4670 "Corrupted global preprocessed entity map");
4671 ModuleFile *M = I->second;
4672 unsigned LocalIndex = GlobalIndex - M->BasePreprocessedEntityID;
4673 return std::make_pair(M, LocalIndex);
4674}
4675
Benjamin Kramerb4ef6682015-02-06 17:25:10 +00004676llvm::iterator_range<PreprocessingRecord::iterator>
Guy Benyei11169dd2012-12-18 14:30:41 +00004677ASTReader::getModulePreprocessedEntities(ModuleFile &Mod) const {
4678 if (PreprocessingRecord *PPRec = PP.getPreprocessingRecord())
4679 return PPRec->getIteratorsForLoadedRange(Mod.BasePreprocessedEntityID,
4680 Mod.NumPreprocessedEntities);
4681
Benjamin Kramerb4ef6682015-02-06 17:25:10 +00004682 return llvm::make_range(PreprocessingRecord::iterator(),
4683 PreprocessingRecord::iterator());
Guy Benyei11169dd2012-12-18 14:30:41 +00004684}
4685
Benjamin Kramerb4ef6682015-02-06 17:25:10 +00004686llvm::iterator_range<ASTReader::ModuleDeclIterator>
Guy Benyei11169dd2012-12-18 14:30:41 +00004687ASTReader::getModuleFileLevelDecls(ModuleFile &Mod) {
Benjamin Kramerb4ef6682015-02-06 17:25:10 +00004688 return llvm::make_range(
4689 ModuleDeclIterator(this, &Mod, Mod.FileSortedDecls),
4690 ModuleDeclIterator(this, &Mod,
4691 Mod.FileSortedDecls + Mod.NumFileSortedDecls));
Guy Benyei11169dd2012-12-18 14:30:41 +00004692}
4693
4694PreprocessedEntity *ASTReader::ReadPreprocessedEntity(unsigned Index) {
4695 PreprocessedEntityID PPID = Index+1;
4696 std::pair<ModuleFile *, unsigned> PPInfo = getModulePreprocessedEntity(Index);
4697 ModuleFile &M = *PPInfo.first;
4698 unsigned LocalIndex = PPInfo.second;
4699 const PPEntityOffset &PPOffs = M.PreprocessedEntityOffsets[LocalIndex];
4700
Guy Benyei11169dd2012-12-18 14:30:41 +00004701 if (!PP.getPreprocessingRecord()) {
4702 Error("no preprocessing record");
Craig Toppera13603a2014-05-22 05:54:18 +00004703 return nullptr;
Guy Benyei11169dd2012-12-18 14:30:41 +00004704 }
4705
Chris Lattner7fb3bef2013-01-20 00:56:42 +00004706 SavedStreamPosition SavedPosition(M.PreprocessorDetailCursor);
4707 M.PreprocessorDetailCursor.JumpToBit(PPOffs.BitOffset);
4708
4709 llvm::BitstreamEntry Entry =
4710 M.PreprocessorDetailCursor.advance(BitstreamCursor::AF_DontPopBlockAtEnd);
4711 if (Entry.Kind != llvm::BitstreamEntry::Record)
Craig Toppera13603a2014-05-22 05:54:18 +00004712 return nullptr;
Chris Lattner7fb3bef2013-01-20 00:56:42 +00004713
Guy Benyei11169dd2012-12-18 14:30:41 +00004714 // Read the record.
4715 SourceRange Range(ReadSourceLocation(M, PPOffs.Begin),
4716 ReadSourceLocation(M, PPOffs.End));
4717 PreprocessingRecord &PPRec = *PP.getPreprocessingRecord();
Chris Lattner0e6c9402013-01-20 02:38:54 +00004718 StringRef Blob;
Guy Benyei11169dd2012-12-18 14:30:41 +00004719 RecordData Record;
4720 PreprocessorDetailRecordTypes RecType =
Chris Lattner0e6c9402013-01-20 02:38:54 +00004721 (PreprocessorDetailRecordTypes)M.PreprocessorDetailCursor.readRecord(
4722 Entry.ID, Record, &Blob);
Guy Benyei11169dd2012-12-18 14:30:41 +00004723 switch (RecType) {
4724 case PPD_MACRO_EXPANSION: {
4725 bool isBuiltin = Record[0];
Craig Toppera13603a2014-05-22 05:54:18 +00004726 IdentifierInfo *Name = nullptr;
Richard Smith66a81862015-05-04 02:25:31 +00004727 MacroDefinitionRecord *Def = nullptr;
Guy Benyei11169dd2012-12-18 14:30:41 +00004728 if (isBuiltin)
4729 Name = getLocalIdentifier(M, Record[1]);
4730 else {
Richard Smith66a81862015-05-04 02:25:31 +00004731 PreprocessedEntityID GlobalID =
4732 getGlobalPreprocessedEntityID(M, Record[1]);
4733 Def = cast<MacroDefinitionRecord>(
4734 PPRec.getLoadedPreprocessedEntity(GlobalID - 1));
Guy Benyei11169dd2012-12-18 14:30:41 +00004735 }
4736
4737 MacroExpansion *ME;
4738 if (isBuiltin)
4739 ME = new (PPRec) MacroExpansion(Name, Range);
4740 else
4741 ME = new (PPRec) MacroExpansion(Def, Range);
4742
4743 return ME;
4744 }
4745
4746 case PPD_MACRO_DEFINITION: {
4747 // Decode the identifier info and then check again; if the macro is
4748 // still defined and associated with the identifier,
4749 IdentifierInfo *II = getLocalIdentifier(M, Record[0]);
Richard Smith66a81862015-05-04 02:25:31 +00004750 MacroDefinitionRecord *MD = new (PPRec) MacroDefinitionRecord(II, Range);
Guy Benyei11169dd2012-12-18 14:30:41 +00004751
4752 if (DeserializationListener)
4753 DeserializationListener->MacroDefinitionRead(PPID, MD);
4754
4755 return MD;
4756 }
4757
4758 case PPD_INCLUSION_DIRECTIVE: {
Chris Lattner0e6c9402013-01-20 02:38:54 +00004759 const char *FullFileNameStart = Blob.data() + Record[0];
4760 StringRef FullFileName(FullFileNameStart, Blob.size() - Record[0]);
Craig Toppera13603a2014-05-22 05:54:18 +00004761 const FileEntry *File = nullptr;
Guy Benyei11169dd2012-12-18 14:30:41 +00004762 if (!FullFileName.empty())
4763 File = PP.getFileManager().getFile(FullFileName);
4764
4765 // FIXME: Stable encoding
4766 InclusionDirective::InclusionKind Kind
4767 = static_cast<InclusionDirective::InclusionKind>(Record[2]);
4768 InclusionDirective *ID
4769 = new (PPRec) InclusionDirective(PPRec, Kind,
Chris Lattner0e6c9402013-01-20 02:38:54 +00004770 StringRef(Blob.data(), Record[0]),
Guy Benyei11169dd2012-12-18 14:30:41 +00004771 Record[1], Record[3],
4772 File,
4773 Range);
4774 return ID;
4775 }
4776 }
4777
4778 llvm_unreachable("Invalid PreprocessorDetailRecordTypes");
4779}
4780
4781/// \brief \arg SLocMapI points at a chunk of a module that contains no
4782/// preprocessed entities or the entities it contains are not the ones we are
4783/// looking for. Find the next module that contains entities and return the ID
4784/// of the first entry.
4785PreprocessedEntityID ASTReader::findNextPreprocessedEntity(
4786 GlobalSLocOffsetMapType::const_iterator SLocMapI) const {
4787 ++SLocMapI;
4788 for (GlobalSLocOffsetMapType::const_iterator
4789 EndI = GlobalSLocOffsetMap.end(); SLocMapI != EndI; ++SLocMapI) {
4790 ModuleFile &M = *SLocMapI->second;
4791 if (M.NumPreprocessedEntities)
4792 return M.BasePreprocessedEntityID;
4793 }
4794
4795 return getTotalNumPreprocessedEntities();
4796}
4797
4798namespace {
4799
4800template <unsigned PPEntityOffset::*PPLoc>
4801struct PPEntityComp {
4802 const ASTReader &Reader;
4803 ModuleFile &M;
4804
4805 PPEntityComp(const ASTReader &Reader, ModuleFile &M) : Reader(Reader), M(M) { }
4806
4807 bool operator()(const PPEntityOffset &L, const PPEntityOffset &R) const {
4808 SourceLocation LHS = getLoc(L);
4809 SourceLocation RHS = getLoc(R);
4810 return Reader.getSourceManager().isBeforeInTranslationUnit(LHS, RHS);
4811 }
4812
4813 bool operator()(const PPEntityOffset &L, SourceLocation RHS) const {
4814 SourceLocation LHS = getLoc(L);
4815 return Reader.getSourceManager().isBeforeInTranslationUnit(LHS, RHS);
4816 }
4817
4818 bool operator()(SourceLocation LHS, const PPEntityOffset &R) const {
4819 SourceLocation RHS = getLoc(R);
4820 return Reader.getSourceManager().isBeforeInTranslationUnit(LHS, RHS);
4821 }
4822
4823 SourceLocation getLoc(const PPEntityOffset &PPE) const {
4824 return Reader.ReadSourceLocation(M, PPE.*PPLoc);
4825 }
4826};
4827
Alexander Kornienkoab9db512015-06-22 23:07:51 +00004828}
Guy Benyei11169dd2012-12-18 14:30:41 +00004829
Alp Toker2e9ce4c2014-05-16 18:59:21 +00004830PreprocessedEntityID ASTReader::findPreprocessedEntity(SourceLocation Loc,
4831 bool EndsAfter) const {
4832 if (SourceMgr.isLocalSourceLocation(Loc))
Guy Benyei11169dd2012-12-18 14:30:41 +00004833 return getTotalNumPreprocessedEntities();
4834
Alp Toker2e9ce4c2014-05-16 18:59:21 +00004835 GlobalSLocOffsetMapType::const_iterator SLocMapI = GlobalSLocOffsetMap.find(
4836 SourceManager::MaxLoadedOffset - Loc.getOffset() - 1);
Guy Benyei11169dd2012-12-18 14:30:41 +00004837 assert(SLocMapI != GlobalSLocOffsetMap.end() &&
4838 "Corrupted global sloc offset map");
4839
4840 if (SLocMapI->second->NumPreprocessedEntities == 0)
4841 return findNextPreprocessedEntity(SLocMapI);
4842
4843 ModuleFile &M = *SLocMapI->second;
4844 typedef const PPEntityOffset *pp_iterator;
4845 pp_iterator pp_begin = M.PreprocessedEntityOffsets;
4846 pp_iterator pp_end = pp_begin + M.NumPreprocessedEntities;
4847
4848 size_t Count = M.NumPreprocessedEntities;
4849 size_t Half;
4850 pp_iterator First = pp_begin;
4851 pp_iterator PPI;
4852
Alp Toker2e9ce4c2014-05-16 18:59:21 +00004853 if (EndsAfter) {
4854 PPI = std::upper_bound(pp_begin, pp_end, Loc,
4855 PPEntityComp<&PPEntityOffset::Begin>(*this, M));
4856 } else {
4857 // Do a binary search manually instead of using std::lower_bound because
4858 // The end locations of entities may be unordered (when a macro expansion
4859 // is inside another macro argument), but for this case it is not important
4860 // whether we get the first macro expansion or its containing macro.
4861 while (Count > 0) {
4862 Half = Count / 2;
4863 PPI = First;
4864 std::advance(PPI, Half);
4865 if (SourceMgr.isBeforeInTranslationUnit(ReadSourceLocation(M, PPI->End),
4866 Loc)) {
4867 First = PPI;
4868 ++First;
4869 Count = Count - Half - 1;
4870 } else
4871 Count = Half;
4872 }
Guy Benyei11169dd2012-12-18 14:30:41 +00004873 }
4874
4875 if (PPI == pp_end)
4876 return findNextPreprocessedEntity(SLocMapI);
4877
4878 return M.BasePreprocessedEntityID + (PPI - pp_begin);
4879}
4880
Guy Benyei11169dd2012-12-18 14:30:41 +00004881/// \brief Returns a pair of [Begin, End) indices of preallocated
4882/// preprocessed entities that \arg Range encompasses.
4883std::pair<unsigned, unsigned>
4884 ASTReader::findPreprocessedEntitiesInRange(SourceRange Range) {
4885 if (Range.isInvalid())
4886 return std::make_pair(0,0);
4887 assert(!SourceMgr.isBeforeInTranslationUnit(Range.getEnd(),Range.getBegin()));
4888
Alp Toker2e9ce4c2014-05-16 18:59:21 +00004889 PreprocessedEntityID BeginID =
4890 findPreprocessedEntity(Range.getBegin(), false);
4891 PreprocessedEntityID EndID = findPreprocessedEntity(Range.getEnd(), true);
Guy Benyei11169dd2012-12-18 14:30:41 +00004892 return std::make_pair(BeginID, EndID);
4893}
4894
4895/// \brief Optionally returns true or false if the preallocated preprocessed
4896/// entity with index \arg Index came from file \arg FID.
David Blaikie05785d12013-02-20 22:23:23 +00004897Optional<bool> ASTReader::isPreprocessedEntityInFileID(unsigned Index,
Guy Benyei11169dd2012-12-18 14:30:41 +00004898 FileID FID) {
4899 if (FID.isInvalid())
4900 return false;
4901
4902 std::pair<ModuleFile *, unsigned> PPInfo = getModulePreprocessedEntity(Index);
4903 ModuleFile &M = *PPInfo.first;
4904 unsigned LocalIndex = PPInfo.second;
4905 const PPEntityOffset &PPOffs = M.PreprocessedEntityOffsets[LocalIndex];
4906
4907 SourceLocation Loc = ReadSourceLocation(M, PPOffs.Begin);
4908 if (Loc.isInvalid())
4909 return false;
4910
4911 if (SourceMgr.isInFileID(SourceMgr.getFileLoc(Loc), FID))
4912 return true;
4913 else
4914 return false;
4915}
4916
4917namespace {
4918 /// \brief Visitor used to search for information about a header file.
4919 class HeaderFileInfoVisitor {
Guy Benyei11169dd2012-12-18 14:30:41 +00004920 const FileEntry *FE;
4921
David Blaikie05785d12013-02-20 22:23:23 +00004922 Optional<HeaderFileInfo> HFI;
Guy Benyei11169dd2012-12-18 14:30:41 +00004923
4924 public:
Argyrios Kyrtzidis61a38962013-03-06 18:12:44 +00004925 explicit HeaderFileInfoVisitor(const FileEntry *FE)
4926 : FE(FE) { }
Benjamin Kramer9a9efba2015-07-25 12:14:04 +00004927
4928 bool operator()(ModuleFile &M) {
Guy Benyei11169dd2012-12-18 14:30:41 +00004929 HeaderFileInfoLookupTable *Table
4930 = static_cast<HeaderFileInfoLookupTable *>(M.HeaderFileInfoTable);
4931 if (!Table)
4932 return false;
4933
4934 // Look in the on-disk hash table for an entry for this file name.
Richard Smithbdf2d932015-07-30 03:37:16 +00004935 HeaderFileInfoLookupTable::iterator Pos = Table->find(FE);
Guy Benyei11169dd2012-12-18 14:30:41 +00004936 if (Pos == Table->end())
4937 return false;
4938
Richard Smithbdf2d932015-07-30 03:37:16 +00004939 HFI = *Pos;
Guy Benyei11169dd2012-12-18 14:30:41 +00004940 return true;
4941 }
4942
David Blaikie05785d12013-02-20 22:23:23 +00004943 Optional<HeaderFileInfo> getHeaderFileInfo() const { return HFI; }
Guy Benyei11169dd2012-12-18 14:30:41 +00004944 };
Alexander Kornienkoab9db512015-06-22 23:07:51 +00004945}
Guy Benyei11169dd2012-12-18 14:30:41 +00004946
4947HeaderFileInfo ASTReader::GetHeaderFileInfo(const FileEntry *FE) {
Argyrios Kyrtzidis61a38962013-03-06 18:12:44 +00004948 HeaderFileInfoVisitor Visitor(FE);
Benjamin Kramer9a9efba2015-07-25 12:14:04 +00004949 ModuleMgr.visit(Visitor);
Argyrios Kyrtzidis1054bbf2013-05-08 23:46:55 +00004950 if (Optional<HeaderFileInfo> HFI = Visitor.getHeaderFileInfo())
Guy Benyei11169dd2012-12-18 14:30:41 +00004951 return *HFI;
Guy Benyei11169dd2012-12-18 14:30:41 +00004952
4953 return HeaderFileInfo();
4954}
4955
4956void ASTReader::ReadPragmaDiagnosticMappings(DiagnosticsEngine &Diag) {
4957 // FIXME: Make it work properly with modules.
Dmitri Gribenkof8579502013-01-12 19:30:44 +00004958 SmallVector<DiagnosticsEngine::DiagState *, 32> DiagStates;
Guy Benyei11169dd2012-12-18 14:30:41 +00004959 for (ModuleIterator I = ModuleMgr.begin(), E = ModuleMgr.end(); I != E; ++I) {
4960 ModuleFile &F = *(*I);
4961 unsigned Idx = 0;
4962 DiagStates.clear();
4963 assert(!Diag.DiagStates.empty());
4964 DiagStates.push_back(&Diag.DiagStates.front()); // the command-line one.
4965 while (Idx < F.PragmaDiagMappings.size()) {
4966 SourceLocation Loc = ReadSourceLocation(F, F.PragmaDiagMappings[Idx++]);
4967 unsigned DiagStateID = F.PragmaDiagMappings[Idx++];
4968 if (DiagStateID != 0) {
4969 Diag.DiagStatePoints.push_back(
4970 DiagnosticsEngine::DiagStatePoint(DiagStates[DiagStateID-1],
4971 FullSourceLoc(Loc, SourceMgr)));
4972 continue;
4973 }
4974
4975 assert(DiagStateID == 0);
4976 // A new DiagState was created here.
4977 Diag.DiagStates.push_back(*Diag.GetCurDiagState());
4978 DiagnosticsEngine::DiagState *NewState = &Diag.DiagStates.back();
4979 DiagStates.push_back(NewState);
4980 Diag.DiagStatePoints.push_back(
4981 DiagnosticsEngine::DiagStatePoint(NewState,
4982 FullSourceLoc(Loc, SourceMgr)));
4983 while (1) {
4984 assert(Idx < F.PragmaDiagMappings.size() &&
4985 "Invalid data, didn't find '-1' marking end of diag/map pairs");
4986 if (Idx >= F.PragmaDiagMappings.size()) {
4987 break; // Something is messed up but at least avoid infinite loop in
4988 // release build.
4989 }
4990 unsigned DiagID = F.PragmaDiagMappings[Idx++];
4991 if (DiagID == (unsigned)-1) {
4992 break; // no more diag/map pairs for this location.
4993 }
Alp Tokerc726c362014-06-10 09:31:37 +00004994 diag::Severity Map = (diag::Severity)F.PragmaDiagMappings[Idx++];
4995 DiagnosticMapping Mapping = Diag.makeUserMapping(Map, Loc);
4996 Diag.GetCurDiagState()->setMapping(DiagID, Mapping);
Guy Benyei11169dd2012-12-18 14:30:41 +00004997 }
4998 }
4999 }
5000}
5001
5002/// \brief Get the correct cursor and offset for loading a type.
5003ASTReader::RecordLocation ASTReader::TypeCursorForIndex(unsigned Index) {
5004 GlobalTypeMapType::iterator I = GlobalTypeMap.find(Index);
5005 assert(I != GlobalTypeMap.end() && "Corrupted global type map");
5006 ModuleFile *M = I->second;
5007 return RecordLocation(M, M->TypeOffsets[Index - M->BaseTypeIndex]);
5008}
5009
5010/// \brief Read and return the type with the given index..
5011///
5012/// The index is the type ID, shifted and minus the number of predefs. This
5013/// routine actually reads the record corresponding to the type at the given
5014/// location. It is a helper routine for GetType, which deals with reading type
5015/// IDs.
5016QualType ASTReader::readTypeRecord(unsigned Index) {
5017 RecordLocation Loc = TypeCursorForIndex(Index);
Chris Lattner7fb3bef2013-01-20 00:56:42 +00005018 BitstreamCursor &DeclsCursor = Loc.F->DeclsCursor;
Guy Benyei11169dd2012-12-18 14:30:41 +00005019
5020 // Keep track of where we are in the stream, then jump back there
5021 // after reading this type.
5022 SavedStreamPosition SavedPosition(DeclsCursor);
5023
5024 ReadingKindTracker ReadingKind(Read_Type, *this);
5025
5026 // Note that we are loading a type record.
5027 Deserializing AType(this);
5028
5029 unsigned Idx = 0;
5030 DeclsCursor.JumpToBit(Loc.Offset);
5031 RecordData Record;
5032 unsigned Code = DeclsCursor.ReadCode();
Chris Lattner0e6c9402013-01-20 02:38:54 +00005033 switch ((TypeCode)DeclsCursor.readRecord(Code, Record)) {
Guy Benyei11169dd2012-12-18 14:30:41 +00005034 case TYPE_EXT_QUAL: {
5035 if (Record.size() != 2) {
5036 Error("Incorrect encoding of extended qualifier type");
5037 return QualType();
5038 }
5039 QualType Base = readType(*Loc.F, Record, Idx);
5040 Qualifiers Quals = Qualifiers::fromOpaqueValue(Record[Idx++]);
5041 return Context.getQualifiedType(Base, Quals);
5042 }
5043
5044 case TYPE_COMPLEX: {
5045 if (Record.size() != 1) {
5046 Error("Incorrect encoding of complex type");
5047 return QualType();
5048 }
5049 QualType ElemType = readType(*Loc.F, Record, Idx);
5050 return Context.getComplexType(ElemType);
5051 }
5052
5053 case TYPE_POINTER: {
5054 if (Record.size() != 1) {
5055 Error("Incorrect encoding of pointer type");
5056 return QualType();
5057 }
5058 QualType PointeeType = readType(*Loc.F, Record, Idx);
5059 return Context.getPointerType(PointeeType);
5060 }
5061
Reid Kleckner8a365022013-06-24 17:51:48 +00005062 case TYPE_DECAYED: {
5063 if (Record.size() != 1) {
5064 Error("Incorrect encoding of decayed type");
5065 return QualType();
5066 }
5067 QualType OriginalType = readType(*Loc.F, Record, Idx);
5068 QualType DT = Context.getAdjustedParameterType(OriginalType);
5069 if (!isa<DecayedType>(DT))
5070 Error("Decayed type does not decay");
5071 return DT;
5072 }
5073
Reid Kleckner0503a872013-12-05 01:23:43 +00005074 case TYPE_ADJUSTED: {
5075 if (Record.size() != 2) {
5076 Error("Incorrect encoding of adjusted type");
5077 return QualType();
5078 }
5079 QualType OriginalTy = readType(*Loc.F, Record, Idx);
5080 QualType AdjustedTy = readType(*Loc.F, Record, Idx);
5081 return Context.getAdjustedType(OriginalTy, AdjustedTy);
5082 }
5083
Guy Benyei11169dd2012-12-18 14:30:41 +00005084 case TYPE_BLOCK_POINTER: {
5085 if (Record.size() != 1) {
5086 Error("Incorrect encoding of block pointer type");
5087 return QualType();
5088 }
5089 QualType PointeeType = readType(*Loc.F, Record, Idx);
5090 return Context.getBlockPointerType(PointeeType);
5091 }
5092
5093 case TYPE_LVALUE_REFERENCE: {
5094 if (Record.size() != 2) {
5095 Error("Incorrect encoding of lvalue reference type");
5096 return QualType();
5097 }
5098 QualType PointeeType = readType(*Loc.F, Record, Idx);
5099 return Context.getLValueReferenceType(PointeeType, Record[1]);
5100 }
5101
5102 case TYPE_RVALUE_REFERENCE: {
5103 if (Record.size() != 1) {
5104 Error("Incorrect encoding of rvalue reference type");
5105 return QualType();
5106 }
5107 QualType PointeeType = readType(*Loc.F, Record, Idx);
5108 return Context.getRValueReferenceType(PointeeType);
5109 }
5110
5111 case TYPE_MEMBER_POINTER: {
5112 if (Record.size() != 2) {
5113 Error("Incorrect encoding of member pointer type");
5114 return QualType();
5115 }
5116 QualType PointeeType = readType(*Loc.F, Record, Idx);
5117 QualType ClassType = readType(*Loc.F, Record, Idx);
5118 if (PointeeType.isNull() || ClassType.isNull())
5119 return QualType();
5120
5121 return Context.getMemberPointerType(PointeeType, ClassType.getTypePtr());
5122 }
5123
5124 case TYPE_CONSTANT_ARRAY: {
5125 QualType ElementType = readType(*Loc.F, Record, Idx);
5126 ArrayType::ArraySizeModifier ASM = (ArrayType::ArraySizeModifier)Record[1];
5127 unsigned IndexTypeQuals = Record[2];
5128 unsigned Idx = 3;
5129 llvm::APInt Size = ReadAPInt(Record, Idx);
5130 return Context.getConstantArrayType(ElementType, Size,
5131 ASM, IndexTypeQuals);
5132 }
5133
5134 case TYPE_INCOMPLETE_ARRAY: {
5135 QualType ElementType = readType(*Loc.F, Record, Idx);
5136 ArrayType::ArraySizeModifier ASM = (ArrayType::ArraySizeModifier)Record[1];
5137 unsigned IndexTypeQuals = Record[2];
5138 return Context.getIncompleteArrayType(ElementType, ASM, IndexTypeQuals);
5139 }
5140
5141 case TYPE_VARIABLE_ARRAY: {
5142 QualType ElementType = readType(*Loc.F, Record, Idx);
5143 ArrayType::ArraySizeModifier ASM = (ArrayType::ArraySizeModifier)Record[1];
5144 unsigned IndexTypeQuals = Record[2];
5145 SourceLocation LBLoc = ReadSourceLocation(*Loc.F, Record[3]);
5146 SourceLocation RBLoc = ReadSourceLocation(*Loc.F, Record[4]);
5147 return Context.getVariableArrayType(ElementType, ReadExpr(*Loc.F),
5148 ASM, IndexTypeQuals,
5149 SourceRange(LBLoc, RBLoc));
5150 }
5151
5152 case TYPE_VECTOR: {
5153 if (Record.size() != 3) {
5154 Error("incorrect encoding of vector type in AST file");
5155 return QualType();
5156 }
5157
5158 QualType ElementType = readType(*Loc.F, Record, Idx);
5159 unsigned NumElements = Record[1];
5160 unsigned VecKind = Record[2];
5161 return Context.getVectorType(ElementType, NumElements,
5162 (VectorType::VectorKind)VecKind);
5163 }
5164
5165 case TYPE_EXT_VECTOR: {
5166 if (Record.size() != 3) {
5167 Error("incorrect encoding of extended vector type in AST file");
5168 return QualType();
5169 }
5170
5171 QualType ElementType = readType(*Loc.F, Record, Idx);
5172 unsigned NumElements = Record[1];
5173 return Context.getExtVectorType(ElementType, NumElements);
5174 }
5175
5176 case TYPE_FUNCTION_NO_PROTO: {
5177 if (Record.size() != 6) {
5178 Error("incorrect encoding of no-proto function type");
5179 return QualType();
5180 }
5181 QualType ResultType = readType(*Loc.F, Record, Idx);
5182 FunctionType::ExtInfo Info(Record[1], Record[2], Record[3],
5183 (CallingConv)Record[4], Record[5]);
5184 return Context.getFunctionNoProtoType(ResultType, Info);
5185 }
5186
5187 case TYPE_FUNCTION_PROTO: {
5188 QualType ResultType = readType(*Loc.F, Record, Idx);
5189
5190 FunctionProtoType::ExtProtoInfo EPI;
5191 EPI.ExtInfo = FunctionType::ExtInfo(/*noreturn*/ Record[1],
5192 /*hasregparm*/ Record[2],
5193 /*regparm*/ Record[3],
5194 static_cast<CallingConv>(Record[4]),
5195 /*produces*/ Record[5]);
5196
5197 unsigned Idx = 6;
Guy Benyei11169dd2012-12-18 14:30:41 +00005198
5199 EPI.Variadic = Record[Idx++];
5200 EPI.HasTrailingReturn = Record[Idx++];
5201 EPI.TypeQuals = Record[Idx++];
5202 EPI.RefQualifier = static_cast<RefQualifierKind>(Record[Idx++]);
Richard Smith564417a2014-03-20 21:47:22 +00005203 SmallVector<QualType, 8> ExceptionStorage;
Richard Smith8acb4282014-07-31 21:57:55 +00005204 readExceptionSpec(*Loc.F, ExceptionStorage, EPI.ExceptionSpec, Record, Idx);
Richard Smith01b2cb42014-07-26 06:37:51 +00005205
5206 unsigned NumParams = Record[Idx++];
5207 SmallVector<QualType, 16> ParamTypes;
5208 for (unsigned I = 0; I != NumParams; ++I)
5209 ParamTypes.push_back(readType(*Loc.F, Record, Idx));
5210
Jordan Rose5c382722013-03-08 21:51:21 +00005211 return Context.getFunctionType(ResultType, ParamTypes, EPI);
Guy Benyei11169dd2012-12-18 14:30:41 +00005212 }
5213
5214 case TYPE_UNRESOLVED_USING: {
5215 unsigned Idx = 0;
5216 return Context.getTypeDeclType(
5217 ReadDeclAs<UnresolvedUsingTypenameDecl>(*Loc.F, Record, Idx));
5218 }
5219
5220 case TYPE_TYPEDEF: {
5221 if (Record.size() != 2) {
5222 Error("incorrect encoding of typedef type");
5223 return QualType();
5224 }
5225 unsigned Idx = 0;
5226 TypedefNameDecl *Decl = ReadDeclAs<TypedefNameDecl>(*Loc.F, Record, Idx);
5227 QualType Canonical = readType(*Loc.F, Record, Idx);
5228 if (!Canonical.isNull())
5229 Canonical = Context.getCanonicalType(Canonical);
5230 return Context.getTypedefType(Decl, Canonical);
5231 }
5232
5233 case TYPE_TYPEOF_EXPR:
5234 return Context.getTypeOfExprType(ReadExpr(*Loc.F));
5235
5236 case TYPE_TYPEOF: {
5237 if (Record.size() != 1) {
5238 Error("incorrect encoding of typeof(type) in AST file");
5239 return QualType();
5240 }
5241 QualType UnderlyingType = readType(*Loc.F, Record, Idx);
5242 return Context.getTypeOfType(UnderlyingType);
5243 }
5244
5245 case TYPE_DECLTYPE: {
5246 QualType UnderlyingType = readType(*Loc.F, Record, Idx);
5247 return Context.getDecltypeType(ReadExpr(*Loc.F), UnderlyingType);
5248 }
5249
5250 case TYPE_UNARY_TRANSFORM: {
5251 QualType BaseType = readType(*Loc.F, Record, Idx);
5252 QualType UnderlyingType = readType(*Loc.F, Record, Idx);
5253 UnaryTransformType::UTTKind UKind = (UnaryTransformType::UTTKind)Record[2];
5254 return Context.getUnaryTransformType(BaseType, UnderlyingType, UKind);
5255 }
5256
Richard Smith74aeef52013-04-26 16:15:35 +00005257 case TYPE_AUTO: {
5258 QualType Deduced = readType(*Loc.F, Record, Idx);
5259 bool IsDecltypeAuto = Record[Idx++];
Richard Smith27d807c2013-04-30 13:56:41 +00005260 bool IsDependent = Deduced.isNull() ? Record[Idx++] : false;
Manuel Klimek2fdbea22013-08-22 12:12:24 +00005261 return Context.getAutoType(Deduced, IsDecltypeAuto, IsDependent);
Richard Smith74aeef52013-04-26 16:15:35 +00005262 }
Guy Benyei11169dd2012-12-18 14:30:41 +00005263
5264 case TYPE_RECORD: {
5265 if (Record.size() != 2) {
5266 Error("incorrect encoding of record type");
5267 return QualType();
5268 }
5269 unsigned Idx = 0;
5270 bool IsDependent = Record[Idx++];
5271 RecordDecl *RD = ReadDeclAs<RecordDecl>(*Loc.F, Record, Idx);
5272 RD = cast_or_null<RecordDecl>(RD->getCanonicalDecl());
5273 QualType T = Context.getRecordType(RD);
5274 const_cast<Type*>(T.getTypePtr())->setDependent(IsDependent);
5275 return T;
5276 }
5277
5278 case TYPE_ENUM: {
5279 if (Record.size() != 2) {
5280 Error("incorrect encoding of enum type");
5281 return QualType();
5282 }
5283 unsigned Idx = 0;
5284 bool IsDependent = Record[Idx++];
5285 QualType T
5286 = Context.getEnumType(ReadDeclAs<EnumDecl>(*Loc.F, Record, Idx));
5287 const_cast<Type*>(T.getTypePtr())->setDependent(IsDependent);
5288 return T;
5289 }
5290
5291 case TYPE_ATTRIBUTED: {
5292 if (Record.size() != 3) {
5293 Error("incorrect encoding of attributed type");
5294 return QualType();
5295 }
5296 QualType modifiedType = readType(*Loc.F, Record, Idx);
5297 QualType equivalentType = readType(*Loc.F, Record, Idx);
5298 AttributedType::Kind kind = static_cast<AttributedType::Kind>(Record[2]);
5299 return Context.getAttributedType(kind, modifiedType, equivalentType);
5300 }
5301
5302 case TYPE_PAREN: {
5303 if (Record.size() != 1) {
5304 Error("incorrect encoding of paren type");
5305 return QualType();
5306 }
5307 QualType InnerType = readType(*Loc.F, Record, Idx);
5308 return Context.getParenType(InnerType);
5309 }
5310
5311 case TYPE_PACK_EXPANSION: {
5312 if (Record.size() != 2) {
5313 Error("incorrect encoding of pack expansion type");
5314 return QualType();
5315 }
5316 QualType Pattern = readType(*Loc.F, Record, Idx);
5317 if (Pattern.isNull())
5318 return QualType();
David Blaikie05785d12013-02-20 22:23:23 +00005319 Optional<unsigned> NumExpansions;
Guy Benyei11169dd2012-12-18 14:30:41 +00005320 if (Record[1])
5321 NumExpansions = Record[1] - 1;
5322 return Context.getPackExpansionType(Pattern, NumExpansions);
5323 }
5324
5325 case TYPE_ELABORATED: {
5326 unsigned Idx = 0;
5327 ElaboratedTypeKeyword Keyword = (ElaboratedTypeKeyword)Record[Idx++];
5328 NestedNameSpecifier *NNS = ReadNestedNameSpecifier(*Loc.F, Record, Idx);
5329 QualType NamedType = readType(*Loc.F, Record, Idx);
5330 return Context.getElaboratedType(Keyword, NNS, NamedType);
5331 }
5332
5333 case TYPE_OBJC_INTERFACE: {
5334 unsigned Idx = 0;
5335 ObjCInterfaceDecl *ItfD
5336 = ReadDeclAs<ObjCInterfaceDecl>(*Loc.F, Record, Idx);
5337 return Context.getObjCInterfaceType(ItfD->getCanonicalDecl());
5338 }
5339
5340 case TYPE_OBJC_OBJECT: {
5341 unsigned Idx = 0;
5342 QualType Base = readType(*Loc.F, Record, Idx);
Douglas Gregore9d95f12015-07-07 03:57:35 +00005343 unsigned NumTypeArgs = Record[Idx++];
5344 SmallVector<QualType, 4> TypeArgs;
5345 for (unsigned I = 0; I != NumTypeArgs; ++I)
5346 TypeArgs.push_back(readType(*Loc.F, Record, Idx));
Guy Benyei11169dd2012-12-18 14:30:41 +00005347 unsigned NumProtos = Record[Idx++];
5348 SmallVector<ObjCProtocolDecl*, 4> Protos;
5349 for (unsigned I = 0; I != NumProtos; ++I)
5350 Protos.push_back(ReadDeclAs<ObjCProtocolDecl>(*Loc.F, Record, Idx));
Douglas Gregorab209d82015-07-07 03:58:42 +00005351 bool IsKindOf = Record[Idx++];
5352 return Context.getObjCObjectType(Base, TypeArgs, Protos, IsKindOf);
Guy Benyei11169dd2012-12-18 14:30:41 +00005353 }
5354
5355 case TYPE_OBJC_OBJECT_POINTER: {
5356 unsigned Idx = 0;
5357 QualType Pointee = readType(*Loc.F, Record, Idx);
5358 return Context.getObjCObjectPointerType(Pointee);
5359 }
5360
5361 case TYPE_SUBST_TEMPLATE_TYPE_PARM: {
5362 unsigned Idx = 0;
5363 QualType Parm = readType(*Loc.F, Record, Idx);
5364 QualType Replacement = readType(*Loc.F, Record, Idx);
Stephan Tolksdorfe96f8b32014-03-15 10:23:27 +00005365 return Context.getSubstTemplateTypeParmType(
5366 cast<TemplateTypeParmType>(Parm),
5367 Context.getCanonicalType(Replacement));
Guy Benyei11169dd2012-12-18 14:30:41 +00005368 }
5369
5370 case TYPE_SUBST_TEMPLATE_TYPE_PARM_PACK: {
5371 unsigned Idx = 0;
5372 QualType Parm = readType(*Loc.F, Record, Idx);
5373 TemplateArgument ArgPack = ReadTemplateArgument(*Loc.F, Record, Idx);
5374 return Context.getSubstTemplateTypeParmPackType(
5375 cast<TemplateTypeParmType>(Parm),
5376 ArgPack);
5377 }
5378
5379 case TYPE_INJECTED_CLASS_NAME: {
5380 CXXRecordDecl *D = ReadDeclAs<CXXRecordDecl>(*Loc.F, Record, Idx);
5381 QualType TST = readType(*Loc.F, Record, Idx); // probably derivable
5382 // FIXME: ASTContext::getInjectedClassNameType is not currently suitable
5383 // for AST reading, too much interdependencies.
Richard Smith6377f8f2014-10-21 21:15:18 +00005384 const Type *T = nullptr;
5385 for (auto *DI = D; DI; DI = DI->getPreviousDecl()) {
5386 if (const Type *Existing = DI->getTypeForDecl()) {
5387 T = Existing;
5388 break;
5389 }
5390 }
5391 if (!T) {
Richard Smithf17fdbd2014-04-24 02:25:27 +00005392 T = new (Context, TypeAlignment) InjectedClassNameType(D, TST);
Richard Smith6377f8f2014-10-21 21:15:18 +00005393 for (auto *DI = D; DI; DI = DI->getPreviousDecl())
5394 DI->setTypeForDecl(T);
5395 }
Richard Smithf17fdbd2014-04-24 02:25:27 +00005396 return QualType(T, 0);
Guy Benyei11169dd2012-12-18 14:30:41 +00005397 }
5398
5399 case TYPE_TEMPLATE_TYPE_PARM: {
5400 unsigned Idx = 0;
5401 unsigned Depth = Record[Idx++];
5402 unsigned Index = Record[Idx++];
5403 bool Pack = Record[Idx++];
5404 TemplateTypeParmDecl *D
5405 = ReadDeclAs<TemplateTypeParmDecl>(*Loc.F, Record, Idx);
5406 return Context.getTemplateTypeParmType(Depth, Index, Pack, D);
5407 }
5408
5409 case TYPE_DEPENDENT_NAME: {
5410 unsigned Idx = 0;
5411 ElaboratedTypeKeyword Keyword = (ElaboratedTypeKeyword)Record[Idx++];
5412 NestedNameSpecifier *NNS = ReadNestedNameSpecifier(*Loc.F, Record, Idx);
Richard Smithbdf2d932015-07-30 03:37:16 +00005413 const IdentifierInfo *Name = GetIdentifierInfo(*Loc.F, Record, Idx);
Guy Benyei11169dd2012-12-18 14:30:41 +00005414 QualType Canon = readType(*Loc.F, Record, Idx);
5415 if (!Canon.isNull())
5416 Canon = Context.getCanonicalType(Canon);
5417 return Context.getDependentNameType(Keyword, NNS, Name, Canon);
5418 }
5419
5420 case TYPE_DEPENDENT_TEMPLATE_SPECIALIZATION: {
5421 unsigned Idx = 0;
5422 ElaboratedTypeKeyword Keyword = (ElaboratedTypeKeyword)Record[Idx++];
5423 NestedNameSpecifier *NNS = ReadNestedNameSpecifier(*Loc.F, Record, Idx);
Richard Smithbdf2d932015-07-30 03:37:16 +00005424 const IdentifierInfo *Name = GetIdentifierInfo(*Loc.F, Record, Idx);
Guy Benyei11169dd2012-12-18 14:30:41 +00005425 unsigned NumArgs = Record[Idx++];
5426 SmallVector<TemplateArgument, 8> Args;
5427 Args.reserve(NumArgs);
5428 while (NumArgs--)
5429 Args.push_back(ReadTemplateArgument(*Loc.F, Record, Idx));
5430 return Context.getDependentTemplateSpecializationType(Keyword, NNS, Name,
5431 Args.size(), Args.data());
5432 }
5433
5434 case TYPE_DEPENDENT_SIZED_ARRAY: {
5435 unsigned Idx = 0;
5436
5437 // ArrayType
5438 QualType ElementType = readType(*Loc.F, Record, Idx);
5439 ArrayType::ArraySizeModifier ASM
5440 = (ArrayType::ArraySizeModifier)Record[Idx++];
5441 unsigned IndexTypeQuals = Record[Idx++];
5442
5443 // DependentSizedArrayType
5444 Expr *NumElts = ReadExpr(*Loc.F);
5445 SourceRange Brackets = ReadSourceRange(*Loc.F, Record, Idx);
5446
5447 return Context.getDependentSizedArrayType(ElementType, NumElts, ASM,
5448 IndexTypeQuals, Brackets);
5449 }
5450
5451 case TYPE_TEMPLATE_SPECIALIZATION: {
5452 unsigned Idx = 0;
5453 bool IsDependent = Record[Idx++];
5454 TemplateName Name = ReadTemplateName(*Loc.F, Record, Idx);
5455 SmallVector<TemplateArgument, 8> Args;
5456 ReadTemplateArgumentList(Args, *Loc.F, Record, Idx);
5457 QualType Underlying = readType(*Loc.F, Record, Idx);
5458 QualType T;
5459 if (Underlying.isNull())
5460 T = Context.getCanonicalTemplateSpecializationType(Name, Args.data(),
5461 Args.size());
5462 else
5463 T = Context.getTemplateSpecializationType(Name, Args.data(),
5464 Args.size(), Underlying);
5465 const_cast<Type*>(T.getTypePtr())->setDependent(IsDependent);
5466 return T;
5467 }
5468
5469 case TYPE_ATOMIC: {
5470 if (Record.size() != 1) {
5471 Error("Incorrect encoding of atomic type");
5472 return QualType();
5473 }
5474 QualType ValueType = readType(*Loc.F, Record, Idx);
5475 return Context.getAtomicType(ValueType);
5476 }
5477 }
5478 llvm_unreachable("Invalid TypeCode!");
5479}
5480
Richard Smith564417a2014-03-20 21:47:22 +00005481void ASTReader::readExceptionSpec(ModuleFile &ModuleFile,
5482 SmallVectorImpl<QualType> &Exceptions,
Richard Smith8acb4282014-07-31 21:57:55 +00005483 FunctionProtoType::ExceptionSpecInfo &ESI,
Richard Smith564417a2014-03-20 21:47:22 +00005484 const RecordData &Record, unsigned &Idx) {
5485 ExceptionSpecificationType EST =
5486 static_cast<ExceptionSpecificationType>(Record[Idx++]);
Richard Smith8acb4282014-07-31 21:57:55 +00005487 ESI.Type = EST;
Richard Smith564417a2014-03-20 21:47:22 +00005488 if (EST == EST_Dynamic) {
Richard Smith8acb4282014-07-31 21:57:55 +00005489 for (unsigned I = 0, N = Record[Idx++]; I != N; ++I)
Richard Smith564417a2014-03-20 21:47:22 +00005490 Exceptions.push_back(readType(ModuleFile, Record, Idx));
Richard Smith8acb4282014-07-31 21:57:55 +00005491 ESI.Exceptions = Exceptions;
Richard Smith564417a2014-03-20 21:47:22 +00005492 } else if (EST == EST_ComputedNoexcept) {
Richard Smith8acb4282014-07-31 21:57:55 +00005493 ESI.NoexceptExpr = ReadExpr(ModuleFile);
Richard Smith564417a2014-03-20 21:47:22 +00005494 } else if (EST == EST_Uninstantiated) {
Richard Smith8acb4282014-07-31 21:57:55 +00005495 ESI.SourceDecl = ReadDeclAs<FunctionDecl>(ModuleFile, Record, Idx);
5496 ESI.SourceTemplate = ReadDeclAs<FunctionDecl>(ModuleFile, Record, Idx);
Richard Smith564417a2014-03-20 21:47:22 +00005497 } else if (EST == EST_Unevaluated) {
Richard Smith8acb4282014-07-31 21:57:55 +00005498 ESI.SourceDecl = ReadDeclAs<FunctionDecl>(ModuleFile, Record, Idx);
Richard Smith564417a2014-03-20 21:47:22 +00005499 }
5500}
5501
Guy Benyei11169dd2012-12-18 14:30:41 +00005502class clang::TypeLocReader : public TypeLocVisitor<TypeLocReader> {
5503 ASTReader &Reader;
5504 ModuleFile &F;
5505 const ASTReader::RecordData &Record;
5506 unsigned &Idx;
5507
5508 SourceLocation ReadSourceLocation(const ASTReader::RecordData &R,
5509 unsigned &I) {
5510 return Reader.ReadSourceLocation(F, R, I);
5511 }
5512
5513 template<typename T>
5514 T *ReadDeclAs(const ASTReader::RecordData &Record, unsigned &Idx) {
5515 return Reader.ReadDeclAs<T>(F, Record, Idx);
5516 }
5517
5518public:
5519 TypeLocReader(ASTReader &Reader, ModuleFile &F,
5520 const ASTReader::RecordData &Record, unsigned &Idx)
5521 : Reader(Reader), F(F), Record(Record), Idx(Idx)
5522 { }
5523
5524 // We want compile-time assurance that we've enumerated all of
5525 // these, so unfortunately we have to declare them first, then
5526 // define them out-of-line.
5527#define ABSTRACT_TYPELOC(CLASS, PARENT)
5528#define TYPELOC(CLASS, PARENT) \
5529 void Visit##CLASS##TypeLoc(CLASS##TypeLoc TyLoc);
5530#include "clang/AST/TypeLocNodes.def"
5531
5532 void VisitFunctionTypeLoc(FunctionTypeLoc);
5533 void VisitArrayTypeLoc(ArrayTypeLoc);
5534};
5535
5536void TypeLocReader::VisitQualifiedTypeLoc(QualifiedTypeLoc TL) {
5537 // nothing to do
5538}
5539void TypeLocReader::VisitBuiltinTypeLoc(BuiltinTypeLoc TL) {
5540 TL.setBuiltinLoc(ReadSourceLocation(Record, Idx));
5541 if (TL.needsExtraLocalData()) {
5542 TL.setWrittenTypeSpec(static_cast<DeclSpec::TST>(Record[Idx++]));
5543 TL.setWrittenSignSpec(static_cast<DeclSpec::TSS>(Record[Idx++]));
5544 TL.setWrittenWidthSpec(static_cast<DeclSpec::TSW>(Record[Idx++]));
5545 TL.setModeAttr(Record[Idx++]);
5546 }
5547}
5548void TypeLocReader::VisitComplexTypeLoc(ComplexTypeLoc TL) {
5549 TL.setNameLoc(ReadSourceLocation(Record, Idx));
5550}
5551void TypeLocReader::VisitPointerTypeLoc(PointerTypeLoc TL) {
5552 TL.setStarLoc(ReadSourceLocation(Record, Idx));
5553}
Reid Kleckner8a365022013-06-24 17:51:48 +00005554void TypeLocReader::VisitDecayedTypeLoc(DecayedTypeLoc TL) {
5555 // nothing to do
5556}
Reid Kleckner0503a872013-12-05 01:23:43 +00005557void TypeLocReader::VisitAdjustedTypeLoc(AdjustedTypeLoc TL) {
5558 // nothing to do
5559}
Guy Benyei11169dd2012-12-18 14:30:41 +00005560void TypeLocReader::VisitBlockPointerTypeLoc(BlockPointerTypeLoc TL) {
5561 TL.setCaretLoc(ReadSourceLocation(Record, Idx));
5562}
5563void TypeLocReader::VisitLValueReferenceTypeLoc(LValueReferenceTypeLoc TL) {
5564 TL.setAmpLoc(ReadSourceLocation(Record, Idx));
5565}
5566void TypeLocReader::VisitRValueReferenceTypeLoc(RValueReferenceTypeLoc TL) {
5567 TL.setAmpAmpLoc(ReadSourceLocation(Record, Idx));
5568}
5569void TypeLocReader::VisitMemberPointerTypeLoc(MemberPointerTypeLoc TL) {
5570 TL.setStarLoc(ReadSourceLocation(Record, Idx));
5571 TL.setClassTInfo(Reader.GetTypeSourceInfo(F, Record, Idx));
5572}
5573void TypeLocReader::VisitArrayTypeLoc(ArrayTypeLoc TL) {
5574 TL.setLBracketLoc(ReadSourceLocation(Record, Idx));
5575 TL.setRBracketLoc(ReadSourceLocation(Record, Idx));
5576 if (Record[Idx++])
5577 TL.setSizeExpr(Reader.ReadExpr(F));
5578 else
Craig Toppera13603a2014-05-22 05:54:18 +00005579 TL.setSizeExpr(nullptr);
Guy Benyei11169dd2012-12-18 14:30:41 +00005580}
5581void TypeLocReader::VisitConstantArrayTypeLoc(ConstantArrayTypeLoc TL) {
5582 VisitArrayTypeLoc(TL);
5583}
5584void TypeLocReader::VisitIncompleteArrayTypeLoc(IncompleteArrayTypeLoc TL) {
5585 VisitArrayTypeLoc(TL);
5586}
5587void TypeLocReader::VisitVariableArrayTypeLoc(VariableArrayTypeLoc TL) {
5588 VisitArrayTypeLoc(TL);
5589}
5590void TypeLocReader::VisitDependentSizedArrayTypeLoc(
5591 DependentSizedArrayTypeLoc TL) {
5592 VisitArrayTypeLoc(TL);
5593}
5594void TypeLocReader::VisitDependentSizedExtVectorTypeLoc(
5595 DependentSizedExtVectorTypeLoc TL) {
5596 TL.setNameLoc(ReadSourceLocation(Record, Idx));
5597}
5598void TypeLocReader::VisitVectorTypeLoc(VectorTypeLoc TL) {
5599 TL.setNameLoc(ReadSourceLocation(Record, Idx));
5600}
5601void TypeLocReader::VisitExtVectorTypeLoc(ExtVectorTypeLoc TL) {
5602 TL.setNameLoc(ReadSourceLocation(Record, Idx));
5603}
5604void TypeLocReader::VisitFunctionTypeLoc(FunctionTypeLoc TL) {
5605 TL.setLocalRangeBegin(ReadSourceLocation(Record, Idx));
5606 TL.setLParenLoc(ReadSourceLocation(Record, Idx));
5607 TL.setRParenLoc(ReadSourceLocation(Record, Idx));
5608 TL.setLocalRangeEnd(ReadSourceLocation(Record, Idx));
Alp Tokerb3fd5cf2014-01-21 00:32:38 +00005609 for (unsigned i = 0, e = TL.getNumParams(); i != e; ++i) {
5610 TL.setParam(i, ReadDeclAs<ParmVarDecl>(Record, Idx));
Guy Benyei11169dd2012-12-18 14:30:41 +00005611 }
5612}
5613void TypeLocReader::VisitFunctionProtoTypeLoc(FunctionProtoTypeLoc TL) {
5614 VisitFunctionTypeLoc(TL);
5615}
5616void TypeLocReader::VisitFunctionNoProtoTypeLoc(FunctionNoProtoTypeLoc TL) {
5617 VisitFunctionTypeLoc(TL);
5618}
5619void TypeLocReader::VisitUnresolvedUsingTypeLoc(UnresolvedUsingTypeLoc TL) {
5620 TL.setNameLoc(ReadSourceLocation(Record, Idx));
5621}
5622void TypeLocReader::VisitTypedefTypeLoc(TypedefTypeLoc TL) {
5623 TL.setNameLoc(ReadSourceLocation(Record, Idx));
5624}
5625void TypeLocReader::VisitTypeOfExprTypeLoc(TypeOfExprTypeLoc TL) {
5626 TL.setTypeofLoc(ReadSourceLocation(Record, Idx));
5627 TL.setLParenLoc(ReadSourceLocation(Record, Idx));
5628 TL.setRParenLoc(ReadSourceLocation(Record, Idx));
5629}
5630void TypeLocReader::VisitTypeOfTypeLoc(TypeOfTypeLoc TL) {
5631 TL.setTypeofLoc(ReadSourceLocation(Record, Idx));
5632 TL.setLParenLoc(ReadSourceLocation(Record, Idx));
5633 TL.setRParenLoc(ReadSourceLocation(Record, Idx));
5634 TL.setUnderlyingTInfo(Reader.GetTypeSourceInfo(F, Record, Idx));
5635}
5636void TypeLocReader::VisitDecltypeTypeLoc(DecltypeTypeLoc TL) {
5637 TL.setNameLoc(ReadSourceLocation(Record, Idx));
5638}
5639void TypeLocReader::VisitUnaryTransformTypeLoc(UnaryTransformTypeLoc TL) {
5640 TL.setKWLoc(ReadSourceLocation(Record, Idx));
5641 TL.setLParenLoc(ReadSourceLocation(Record, Idx));
5642 TL.setRParenLoc(ReadSourceLocation(Record, Idx));
5643 TL.setUnderlyingTInfo(Reader.GetTypeSourceInfo(F, Record, Idx));
5644}
5645void TypeLocReader::VisitAutoTypeLoc(AutoTypeLoc TL) {
5646 TL.setNameLoc(ReadSourceLocation(Record, Idx));
5647}
5648void TypeLocReader::VisitRecordTypeLoc(RecordTypeLoc TL) {
5649 TL.setNameLoc(ReadSourceLocation(Record, Idx));
5650}
5651void TypeLocReader::VisitEnumTypeLoc(EnumTypeLoc TL) {
5652 TL.setNameLoc(ReadSourceLocation(Record, Idx));
5653}
5654void TypeLocReader::VisitAttributedTypeLoc(AttributedTypeLoc TL) {
5655 TL.setAttrNameLoc(ReadSourceLocation(Record, Idx));
5656 if (TL.hasAttrOperand()) {
5657 SourceRange range;
5658 range.setBegin(ReadSourceLocation(Record, Idx));
5659 range.setEnd(ReadSourceLocation(Record, Idx));
5660 TL.setAttrOperandParensRange(range);
5661 }
5662 if (TL.hasAttrExprOperand()) {
5663 if (Record[Idx++])
5664 TL.setAttrExprOperand(Reader.ReadExpr(F));
5665 else
Craig Toppera13603a2014-05-22 05:54:18 +00005666 TL.setAttrExprOperand(nullptr);
Guy Benyei11169dd2012-12-18 14:30:41 +00005667 } else if (TL.hasAttrEnumOperand())
5668 TL.setAttrEnumOperandLoc(ReadSourceLocation(Record, Idx));
5669}
5670void TypeLocReader::VisitTemplateTypeParmTypeLoc(TemplateTypeParmTypeLoc TL) {
5671 TL.setNameLoc(ReadSourceLocation(Record, Idx));
5672}
5673void TypeLocReader::VisitSubstTemplateTypeParmTypeLoc(
5674 SubstTemplateTypeParmTypeLoc TL) {
5675 TL.setNameLoc(ReadSourceLocation(Record, Idx));
5676}
5677void TypeLocReader::VisitSubstTemplateTypeParmPackTypeLoc(
5678 SubstTemplateTypeParmPackTypeLoc TL) {
5679 TL.setNameLoc(ReadSourceLocation(Record, Idx));
5680}
5681void TypeLocReader::VisitTemplateSpecializationTypeLoc(
5682 TemplateSpecializationTypeLoc TL) {
5683 TL.setTemplateKeywordLoc(ReadSourceLocation(Record, Idx));
5684 TL.setTemplateNameLoc(ReadSourceLocation(Record, Idx));
5685 TL.setLAngleLoc(ReadSourceLocation(Record, Idx));
5686 TL.setRAngleLoc(ReadSourceLocation(Record, Idx));
5687 for (unsigned i = 0, e = TL.getNumArgs(); i != e; ++i)
5688 TL.setArgLocInfo(i,
5689 Reader.GetTemplateArgumentLocInfo(F,
5690 TL.getTypePtr()->getArg(i).getKind(),
5691 Record, Idx));
5692}
5693void TypeLocReader::VisitParenTypeLoc(ParenTypeLoc TL) {
5694 TL.setLParenLoc(ReadSourceLocation(Record, Idx));
5695 TL.setRParenLoc(ReadSourceLocation(Record, Idx));
5696}
5697void TypeLocReader::VisitElaboratedTypeLoc(ElaboratedTypeLoc TL) {
5698 TL.setElaboratedKeywordLoc(ReadSourceLocation(Record, Idx));
5699 TL.setQualifierLoc(Reader.ReadNestedNameSpecifierLoc(F, Record, Idx));
5700}
5701void TypeLocReader::VisitInjectedClassNameTypeLoc(InjectedClassNameTypeLoc TL) {
5702 TL.setNameLoc(ReadSourceLocation(Record, Idx));
5703}
5704void TypeLocReader::VisitDependentNameTypeLoc(DependentNameTypeLoc TL) {
5705 TL.setElaboratedKeywordLoc(ReadSourceLocation(Record, Idx));
5706 TL.setQualifierLoc(Reader.ReadNestedNameSpecifierLoc(F, Record, Idx));
5707 TL.setNameLoc(ReadSourceLocation(Record, Idx));
5708}
5709void TypeLocReader::VisitDependentTemplateSpecializationTypeLoc(
5710 DependentTemplateSpecializationTypeLoc TL) {
5711 TL.setElaboratedKeywordLoc(ReadSourceLocation(Record, Idx));
5712 TL.setQualifierLoc(Reader.ReadNestedNameSpecifierLoc(F, Record, Idx));
5713 TL.setTemplateKeywordLoc(ReadSourceLocation(Record, Idx));
5714 TL.setTemplateNameLoc(ReadSourceLocation(Record, Idx));
5715 TL.setLAngleLoc(ReadSourceLocation(Record, Idx));
5716 TL.setRAngleLoc(ReadSourceLocation(Record, Idx));
5717 for (unsigned I = 0, E = TL.getNumArgs(); I != E; ++I)
5718 TL.setArgLocInfo(I,
5719 Reader.GetTemplateArgumentLocInfo(F,
5720 TL.getTypePtr()->getArg(I).getKind(),
5721 Record, Idx));
5722}
5723void TypeLocReader::VisitPackExpansionTypeLoc(PackExpansionTypeLoc TL) {
5724 TL.setEllipsisLoc(ReadSourceLocation(Record, Idx));
5725}
5726void TypeLocReader::VisitObjCInterfaceTypeLoc(ObjCInterfaceTypeLoc TL) {
5727 TL.setNameLoc(ReadSourceLocation(Record, Idx));
5728}
5729void TypeLocReader::VisitObjCObjectTypeLoc(ObjCObjectTypeLoc TL) {
5730 TL.setHasBaseTypeAsWritten(Record[Idx++]);
Douglas Gregore9d95f12015-07-07 03:57:35 +00005731 TL.setTypeArgsLAngleLoc(ReadSourceLocation(Record, Idx));
5732 TL.setTypeArgsRAngleLoc(ReadSourceLocation(Record, Idx));
5733 for (unsigned i = 0, e = TL.getNumTypeArgs(); i != e; ++i)
5734 TL.setTypeArgTInfo(i, Reader.GetTypeSourceInfo(F, Record, Idx));
5735 TL.setProtocolLAngleLoc(ReadSourceLocation(Record, Idx));
5736 TL.setProtocolRAngleLoc(ReadSourceLocation(Record, Idx));
Guy Benyei11169dd2012-12-18 14:30:41 +00005737 for (unsigned i = 0, e = TL.getNumProtocols(); i != e; ++i)
5738 TL.setProtocolLoc(i, ReadSourceLocation(Record, Idx));
5739}
5740void TypeLocReader::VisitObjCObjectPointerTypeLoc(ObjCObjectPointerTypeLoc TL) {
5741 TL.setStarLoc(ReadSourceLocation(Record, Idx));
5742}
5743void TypeLocReader::VisitAtomicTypeLoc(AtomicTypeLoc TL) {
5744 TL.setKWLoc(ReadSourceLocation(Record, Idx));
5745 TL.setLParenLoc(ReadSourceLocation(Record, Idx));
5746 TL.setRParenLoc(ReadSourceLocation(Record, Idx));
5747}
5748
5749TypeSourceInfo *ASTReader::GetTypeSourceInfo(ModuleFile &F,
5750 const RecordData &Record,
5751 unsigned &Idx) {
5752 QualType InfoTy = readType(F, Record, Idx);
5753 if (InfoTy.isNull())
Craig Toppera13603a2014-05-22 05:54:18 +00005754 return nullptr;
Guy Benyei11169dd2012-12-18 14:30:41 +00005755
5756 TypeSourceInfo *TInfo = getContext().CreateTypeSourceInfo(InfoTy);
5757 TypeLocReader TLR(*this, F, Record, Idx);
5758 for (TypeLoc TL = TInfo->getTypeLoc(); !TL.isNull(); TL = TL.getNextTypeLoc())
5759 TLR.Visit(TL);
5760 return TInfo;
5761}
5762
5763QualType ASTReader::GetType(TypeID ID) {
5764 unsigned FastQuals = ID & Qualifiers::FastMask;
5765 unsigned Index = ID >> Qualifiers::FastWidth;
5766
5767 if (Index < NUM_PREDEF_TYPE_IDS) {
5768 QualType T;
5769 switch ((PredefinedTypeIDs)Index) {
5770 case PREDEF_TYPE_NULL_ID: return QualType();
5771 case PREDEF_TYPE_VOID_ID: T = Context.VoidTy; break;
5772 case PREDEF_TYPE_BOOL_ID: T = Context.BoolTy; break;
5773
5774 case PREDEF_TYPE_CHAR_U_ID:
5775 case PREDEF_TYPE_CHAR_S_ID:
5776 // FIXME: Check that the signedness of CharTy is correct!
5777 T = Context.CharTy;
5778 break;
5779
5780 case PREDEF_TYPE_UCHAR_ID: T = Context.UnsignedCharTy; break;
5781 case PREDEF_TYPE_USHORT_ID: T = Context.UnsignedShortTy; break;
5782 case PREDEF_TYPE_UINT_ID: T = Context.UnsignedIntTy; break;
5783 case PREDEF_TYPE_ULONG_ID: T = Context.UnsignedLongTy; break;
5784 case PREDEF_TYPE_ULONGLONG_ID: T = Context.UnsignedLongLongTy; break;
5785 case PREDEF_TYPE_UINT128_ID: T = Context.UnsignedInt128Ty; break;
5786 case PREDEF_TYPE_SCHAR_ID: T = Context.SignedCharTy; break;
5787 case PREDEF_TYPE_WCHAR_ID: T = Context.WCharTy; break;
5788 case PREDEF_TYPE_SHORT_ID: T = Context.ShortTy; break;
5789 case PREDEF_TYPE_INT_ID: T = Context.IntTy; break;
5790 case PREDEF_TYPE_LONG_ID: T = Context.LongTy; break;
5791 case PREDEF_TYPE_LONGLONG_ID: T = Context.LongLongTy; break;
5792 case PREDEF_TYPE_INT128_ID: T = Context.Int128Ty; break;
5793 case PREDEF_TYPE_HALF_ID: T = Context.HalfTy; break;
5794 case PREDEF_TYPE_FLOAT_ID: T = Context.FloatTy; break;
5795 case PREDEF_TYPE_DOUBLE_ID: T = Context.DoubleTy; break;
5796 case PREDEF_TYPE_LONGDOUBLE_ID: T = Context.LongDoubleTy; break;
5797 case PREDEF_TYPE_OVERLOAD_ID: T = Context.OverloadTy; break;
5798 case PREDEF_TYPE_BOUND_MEMBER: T = Context.BoundMemberTy; break;
5799 case PREDEF_TYPE_PSEUDO_OBJECT: T = Context.PseudoObjectTy; break;
5800 case PREDEF_TYPE_DEPENDENT_ID: T = Context.DependentTy; break;
5801 case PREDEF_TYPE_UNKNOWN_ANY: T = Context.UnknownAnyTy; break;
5802 case PREDEF_TYPE_NULLPTR_ID: T = Context.NullPtrTy; break;
5803 case PREDEF_TYPE_CHAR16_ID: T = Context.Char16Ty; break;
5804 case PREDEF_TYPE_CHAR32_ID: T = Context.Char32Ty; break;
5805 case PREDEF_TYPE_OBJC_ID: T = Context.ObjCBuiltinIdTy; break;
5806 case PREDEF_TYPE_OBJC_CLASS: T = Context.ObjCBuiltinClassTy; break;
5807 case PREDEF_TYPE_OBJC_SEL: T = Context.ObjCBuiltinSelTy; break;
Guy Benyeid8a08ea2012-12-18 14:38:23 +00005808 case PREDEF_TYPE_IMAGE1D_ID: T = Context.OCLImage1dTy; break;
5809 case PREDEF_TYPE_IMAGE1D_ARR_ID: T = Context.OCLImage1dArrayTy; break;
5810 case PREDEF_TYPE_IMAGE1D_BUFF_ID: T = Context.OCLImage1dBufferTy; break;
5811 case PREDEF_TYPE_IMAGE2D_ID: T = Context.OCLImage2dTy; break;
5812 case PREDEF_TYPE_IMAGE2D_ARR_ID: T = Context.OCLImage2dArrayTy; break;
5813 case PREDEF_TYPE_IMAGE3D_ID: T = Context.OCLImage3dTy; break;
Guy Benyei61054192013-02-07 10:55:47 +00005814 case PREDEF_TYPE_SAMPLER_ID: T = Context.OCLSamplerTy; break;
Guy Benyei1b4fb3e2013-01-20 12:31:11 +00005815 case PREDEF_TYPE_EVENT_ID: T = Context.OCLEventTy; break;
Guy Benyei11169dd2012-12-18 14:30:41 +00005816 case PREDEF_TYPE_AUTO_DEDUCT: T = Context.getAutoDeductType(); break;
5817
5818 case PREDEF_TYPE_AUTO_RREF_DEDUCT:
5819 T = Context.getAutoRRefDeductType();
5820 break;
5821
5822 case PREDEF_TYPE_ARC_UNBRIDGED_CAST:
5823 T = Context.ARCUnbridgedCastTy;
5824 break;
5825
Guy Benyei11169dd2012-12-18 14:30:41 +00005826 case PREDEF_TYPE_BUILTIN_FN:
5827 T = Context.BuiltinFnTy;
5828 break;
Alexey Bataev1a3320e2015-08-25 14:24:04 +00005829
5830 case PREDEF_TYPE_OMP_ARRAY_SECTION:
5831 T = Context.OMPArraySectionTy;
5832 break;
Guy Benyei11169dd2012-12-18 14:30:41 +00005833 }
5834
5835 assert(!T.isNull() && "Unknown predefined type");
5836 return T.withFastQualifiers(FastQuals);
5837 }
5838
5839 Index -= NUM_PREDEF_TYPE_IDS;
5840 assert(Index < TypesLoaded.size() && "Type index out-of-range");
5841 if (TypesLoaded[Index].isNull()) {
5842 TypesLoaded[Index] = readTypeRecord(Index);
5843 if (TypesLoaded[Index].isNull())
5844 return QualType();
5845
5846 TypesLoaded[Index]->setFromAST();
5847 if (DeserializationListener)
5848 DeserializationListener->TypeRead(TypeIdx::fromTypeID(ID),
5849 TypesLoaded[Index]);
5850 }
5851
5852 return TypesLoaded[Index].withFastQualifiers(FastQuals);
5853}
5854
5855QualType ASTReader::getLocalType(ModuleFile &F, unsigned LocalID) {
5856 return GetType(getGlobalTypeID(F, LocalID));
5857}
5858
5859serialization::TypeID
5860ASTReader::getGlobalTypeID(ModuleFile &F, unsigned LocalID) const {
5861 unsigned FastQuals = LocalID & Qualifiers::FastMask;
5862 unsigned LocalIndex = LocalID >> Qualifiers::FastWidth;
5863
5864 if (LocalIndex < NUM_PREDEF_TYPE_IDS)
5865 return LocalID;
5866
5867 ContinuousRangeMap<uint32_t, int, 2>::iterator I
5868 = F.TypeRemap.find(LocalIndex - NUM_PREDEF_TYPE_IDS);
5869 assert(I != F.TypeRemap.end() && "Invalid index into type index remap");
5870
5871 unsigned GlobalIndex = LocalIndex + I->second;
5872 return (GlobalIndex << Qualifiers::FastWidth) | FastQuals;
5873}
5874
5875TemplateArgumentLocInfo
5876ASTReader::GetTemplateArgumentLocInfo(ModuleFile &F,
5877 TemplateArgument::ArgKind Kind,
5878 const RecordData &Record,
5879 unsigned &Index) {
5880 switch (Kind) {
5881 case TemplateArgument::Expression:
5882 return ReadExpr(F);
5883 case TemplateArgument::Type:
5884 return GetTypeSourceInfo(F, Record, Index);
5885 case TemplateArgument::Template: {
5886 NestedNameSpecifierLoc QualifierLoc = ReadNestedNameSpecifierLoc(F, Record,
5887 Index);
5888 SourceLocation TemplateNameLoc = ReadSourceLocation(F, Record, Index);
5889 return TemplateArgumentLocInfo(QualifierLoc, TemplateNameLoc,
5890 SourceLocation());
5891 }
5892 case TemplateArgument::TemplateExpansion: {
5893 NestedNameSpecifierLoc QualifierLoc = ReadNestedNameSpecifierLoc(F, Record,
5894 Index);
5895 SourceLocation TemplateNameLoc = ReadSourceLocation(F, Record, Index);
5896 SourceLocation EllipsisLoc = ReadSourceLocation(F, Record, Index);
5897 return TemplateArgumentLocInfo(QualifierLoc, TemplateNameLoc,
5898 EllipsisLoc);
5899 }
5900 case TemplateArgument::Null:
5901 case TemplateArgument::Integral:
5902 case TemplateArgument::Declaration:
5903 case TemplateArgument::NullPtr:
5904 case TemplateArgument::Pack:
5905 // FIXME: Is this right?
5906 return TemplateArgumentLocInfo();
5907 }
5908 llvm_unreachable("unexpected template argument loc");
5909}
5910
5911TemplateArgumentLoc
5912ASTReader::ReadTemplateArgumentLoc(ModuleFile &F,
5913 const RecordData &Record, unsigned &Index) {
5914 TemplateArgument Arg = ReadTemplateArgument(F, Record, Index);
5915
5916 if (Arg.getKind() == TemplateArgument::Expression) {
5917 if (Record[Index++]) // bool InfoHasSameExpr.
5918 return TemplateArgumentLoc(Arg, TemplateArgumentLocInfo(Arg.getAsExpr()));
5919 }
5920 return TemplateArgumentLoc(Arg, GetTemplateArgumentLocInfo(F, Arg.getKind(),
5921 Record, Index));
5922}
5923
Enea Zaffanella6dbe1872013-08-10 07:24:53 +00005924const ASTTemplateArgumentListInfo*
5925ASTReader::ReadASTTemplateArgumentListInfo(ModuleFile &F,
5926 const RecordData &Record,
5927 unsigned &Index) {
5928 SourceLocation LAngleLoc = ReadSourceLocation(F, Record, Index);
5929 SourceLocation RAngleLoc = ReadSourceLocation(F, Record, Index);
5930 unsigned NumArgsAsWritten = Record[Index++];
5931 TemplateArgumentListInfo TemplArgsInfo(LAngleLoc, RAngleLoc);
5932 for (unsigned i = 0; i != NumArgsAsWritten; ++i)
5933 TemplArgsInfo.addArgument(ReadTemplateArgumentLoc(F, Record, Index));
5934 return ASTTemplateArgumentListInfo::Create(getContext(), TemplArgsInfo);
5935}
5936
Guy Benyei11169dd2012-12-18 14:30:41 +00005937Decl *ASTReader::GetExternalDecl(uint32_t ID) {
5938 return GetDecl(ID);
5939}
5940
Richard Smith50895422015-01-31 03:04:55 +00005941template<typename TemplateSpecializationDecl>
5942static void completeRedeclChainForTemplateSpecialization(Decl *D) {
5943 if (auto *TSD = dyn_cast<TemplateSpecializationDecl>(D))
5944 TSD->getSpecializedTemplate()->LoadLazySpecializations();
5945}
5946
Richard Smith053f6c62014-05-16 23:01:30 +00005947void ASTReader::CompleteRedeclChain(const Decl *D) {
Richard Smith851072e2014-05-19 20:59:20 +00005948 if (NumCurrentElementsDeserializing) {
5949 // We arrange to not care about the complete redeclaration chain while we're
5950 // deserializing. Just remember that the AST has marked this one as complete
5951 // but that it's not actually complete yet, so we know we still need to
5952 // complete it later.
5953 PendingIncompleteDeclChains.push_back(const_cast<Decl*>(D));
5954 return;
5955 }
5956
Richard Smith053f6c62014-05-16 23:01:30 +00005957 const DeclContext *DC = D->getDeclContext()->getRedeclContext();
5958
Richard Smith053f6c62014-05-16 23:01:30 +00005959 // If this is a named declaration, complete it by looking it up
5960 // within its context.
5961 //
Richard Smith01bdb7a2014-08-28 05:44:07 +00005962 // FIXME: Merging a function definition should merge
Richard Smith053f6c62014-05-16 23:01:30 +00005963 // all mergeable entities within it.
5964 if (isa<TranslationUnitDecl>(DC) || isa<NamespaceDecl>(DC) ||
5965 isa<CXXRecordDecl>(DC) || isa<EnumDecl>(DC)) {
5966 if (DeclarationName Name = cast<NamedDecl>(D)->getDeclName()) {
Richard Smitha534a312015-07-21 23:54:07 +00005967 if (!getContext().getLangOpts().CPlusPlus &&
5968 isa<TranslationUnitDecl>(DC)) {
Richard Smith053f6c62014-05-16 23:01:30 +00005969 // Outside of C++, we don't have a lookup table for the TU, so update
Richard Smitha534a312015-07-21 23:54:07 +00005970 // the identifier instead. (For C++ modules, we don't store decls
5971 // in the serialized identifier table, so we do the lookup in the TU.)
5972 auto *II = Name.getAsIdentifierInfo();
5973 assert(II && "non-identifier name in C?");
Richard Smith053f6c62014-05-16 23:01:30 +00005974 if (II->isOutOfDate())
5975 updateOutOfDateIdentifier(*II);
5976 } else
5977 DC->lookup(Name);
Richard Smith01bdb7a2014-08-28 05:44:07 +00005978 } else if (needsAnonymousDeclarationNumber(cast<NamedDecl>(D))) {
Richard Smith3cb15722015-08-05 22:41:45 +00005979 // Find all declarations of this kind from the relevant context.
5980 for (auto *DCDecl : cast<Decl>(D->getLexicalDeclContext())->redecls()) {
5981 auto *DC = cast<DeclContext>(DCDecl);
5982 SmallVector<Decl*, 8> Decls;
5983 FindExternalLexicalDecls(
5984 DC, [&](Decl::Kind K) { return K == D->getKind(); }, Decls);
5985 }
Richard Smith053f6c62014-05-16 23:01:30 +00005986 }
5987 }
Richard Smith50895422015-01-31 03:04:55 +00005988
5989 if (auto *CTSD = dyn_cast<ClassTemplateSpecializationDecl>(D))
5990 CTSD->getSpecializedTemplate()->LoadLazySpecializations();
5991 if (auto *VTSD = dyn_cast<VarTemplateSpecializationDecl>(D))
5992 VTSD->getSpecializedTemplate()->LoadLazySpecializations();
5993 if (auto *FD = dyn_cast<FunctionDecl>(D)) {
5994 if (auto *Template = FD->getPrimaryTemplate())
5995 Template->LoadLazySpecializations();
5996 }
Richard Smith053f6c62014-05-16 23:01:30 +00005997}
5998
Richard Smithc2bb8182015-03-24 06:36:48 +00005999uint64_t ASTReader::ReadCXXCtorInitializersRef(ModuleFile &M,
6000 const RecordData &Record,
6001 unsigned &Idx) {
6002 if (Idx >= Record.size() || Record[Idx] > M.LocalNumCXXCtorInitializers) {
6003 Error("malformed AST file: missing C++ ctor initializers");
6004 return 0;
6005 }
6006
6007 unsigned LocalID = Record[Idx++];
6008 return getGlobalBitOffset(M, M.CXXCtorInitializersOffsets[LocalID - 1]);
6009}
6010
6011CXXCtorInitializer **
6012ASTReader::GetExternalCXXCtorInitializers(uint64_t Offset) {
6013 RecordLocation Loc = getLocalBitOffset(Offset);
6014 BitstreamCursor &Cursor = Loc.F->DeclsCursor;
6015 SavedStreamPosition SavedPosition(Cursor);
6016 Cursor.JumpToBit(Loc.Offset);
6017 ReadingKindTracker ReadingKind(Read_Decl, *this);
6018
6019 RecordData Record;
6020 unsigned Code = Cursor.ReadCode();
6021 unsigned RecCode = Cursor.readRecord(Code, Record);
6022 if (RecCode != DECL_CXX_CTOR_INITIALIZERS) {
6023 Error("malformed AST file: missing C++ ctor initializers");
6024 return nullptr;
6025 }
6026
6027 unsigned Idx = 0;
6028 return ReadCXXCtorInitializers(*Loc.F, Record, Idx);
6029}
6030
Richard Smithcd45dbc2014-04-19 03:48:30 +00006031uint64_t ASTReader::readCXXBaseSpecifiers(ModuleFile &M,
6032 const RecordData &Record,
6033 unsigned &Idx) {
6034 if (Idx >= Record.size() || Record[Idx] > M.LocalNumCXXBaseSpecifiers) {
6035 Error("malformed AST file: missing C++ base specifier");
Guy Benyei11169dd2012-12-18 14:30:41 +00006036 return 0;
Richard Smithcd45dbc2014-04-19 03:48:30 +00006037 }
6038
Guy Benyei11169dd2012-12-18 14:30:41 +00006039 unsigned LocalID = Record[Idx++];
6040 return getGlobalBitOffset(M, M.CXXBaseSpecifiersOffsets[LocalID - 1]);
6041}
6042
6043CXXBaseSpecifier *ASTReader::GetExternalCXXBaseSpecifiers(uint64_t Offset) {
6044 RecordLocation Loc = getLocalBitOffset(Offset);
Chris Lattner7fb3bef2013-01-20 00:56:42 +00006045 BitstreamCursor &Cursor = Loc.F->DeclsCursor;
Guy Benyei11169dd2012-12-18 14:30:41 +00006046 SavedStreamPosition SavedPosition(Cursor);
6047 Cursor.JumpToBit(Loc.Offset);
6048 ReadingKindTracker ReadingKind(Read_Decl, *this);
6049 RecordData Record;
6050 unsigned Code = Cursor.ReadCode();
Chris Lattner0e6c9402013-01-20 02:38:54 +00006051 unsigned RecCode = Cursor.readRecord(Code, Record);
Guy Benyei11169dd2012-12-18 14:30:41 +00006052 if (RecCode != DECL_CXX_BASE_SPECIFIERS) {
Richard Smithcd45dbc2014-04-19 03:48:30 +00006053 Error("malformed AST file: missing C++ base specifiers");
Craig Toppera13603a2014-05-22 05:54:18 +00006054 return nullptr;
Guy Benyei11169dd2012-12-18 14:30:41 +00006055 }
6056
6057 unsigned Idx = 0;
6058 unsigned NumBases = Record[Idx++];
6059 void *Mem = Context.Allocate(sizeof(CXXBaseSpecifier) * NumBases);
6060 CXXBaseSpecifier *Bases = new (Mem) CXXBaseSpecifier [NumBases];
6061 for (unsigned I = 0; I != NumBases; ++I)
6062 Bases[I] = ReadCXXBaseSpecifier(*Loc.F, Record, Idx);
6063 return Bases;
6064}
6065
6066serialization::DeclID
6067ASTReader::getGlobalDeclID(ModuleFile &F, LocalDeclID LocalID) const {
6068 if (LocalID < NUM_PREDEF_DECL_IDS)
6069 return LocalID;
6070
6071 ContinuousRangeMap<uint32_t, int, 2>::iterator I
6072 = F.DeclRemap.find(LocalID - NUM_PREDEF_DECL_IDS);
6073 assert(I != F.DeclRemap.end() && "Invalid index into decl index remap");
6074
6075 return LocalID + I->second;
6076}
6077
6078bool ASTReader::isDeclIDFromModule(serialization::GlobalDeclID ID,
6079 ModuleFile &M) const {
Richard Smithfe620d22015-03-05 23:24:12 +00006080 // Predefined decls aren't from any module.
6081 if (ID < NUM_PREDEF_DECL_IDS)
6082 return false;
6083
Richard Smithbcda1a92015-07-12 23:51:20 +00006084 return ID - NUM_PREDEF_DECL_IDS >= M.BaseDeclID &&
6085 ID - NUM_PREDEF_DECL_IDS < M.BaseDeclID + M.LocalNumDecls;
Guy Benyei11169dd2012-12-18 14:30:41 +00006086}
6087
Douglas Gregor9f782892013-01-21 15:25:38 +00006088ModuleFile *ASTReader::getOwningModuleFile(const Decl *D) {
Guy Benyei11169dd2012-12-18 14:30:41 +00006089 if (!D->isFromASTFile())
Craig Toppera13603a2014-05-22 05:54:18 +00006090 return nullptr;
Guy Benyei11169dd2012-12-18 14:30:41 +00006091 GlobalDeclMapType::const_iterator I = GlobalDeclMap.find(D->getGlobalID());
6092 assert(I != GlobalDeclMap.end() && "Corrupted global declaration map");
6093 return I->second;
6094}
6095
6096SourceLocation ASTReader::getSourceLocationForDeclID(GlobalDeclID ID) {
6097 if (ID < NUM_PREDEF_DECL_IDS)
6098 return SourceLocation();
Richard Smithcd45dbc2014-04-19 03:48:30 +00006099
Guy Benyei11169dd2012-12-18 14:30:41 +00006100 unsigned Index = ID - NUM_PREDEF_DECL_IDS;
6101
6102 if (Index > DeclsLoaded.size()) {
6103 Error("declaration ID out-of-range for AST file");
6104 return SourceLocation();
6105 }
Richard Smithcd45dbc2014-04-19 03:48:30 +00006106
Guy Benyei11169dd2012-12-18 14:30:41 +00006107 if (Decl *D = DeclsLoaded[Index])
6108 return D->getLocation();
6109
6110 unsigned RawLocation = 0;
6111 RecordLocation Rec = DeclCursorForID(ID, RawLocation);
6112 return ReadSourceLocation(*Rec.F, RawLocation);
6113}
6114
Richard Smithfe620d22015-03-05 23:24:12 +00006115static Decl *getPredefinedDecl(ASTContext &Context, PredefinedDeclIDs ID) {
6116 switch (ID) {
6117 case PREDEF_DECL_NULL_ID:
6118 return nullptr;
6119
6120 case PREDEF_DECL_TRANSLATION_UNIT_ID:
6121 return Context.getTranslationUnitDecl();
6122
6123 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();
6131
6132 case PREDEF_DECL_OBJC_PROTOCOL_ID:
6133 return Context.getObjCProtocolDecl();
6134
6135 case PREDEF_DECL_INT_128_ID:
6136 return Context.getInt128Decl();
6137
6138 case PREDEF_DECL_UNSIGNED_INT_128_ID:
6139 return Context.getUInt128Decl();
6140
6141 case PREDEF_DECL_OBJC_INSTANCETYPE_ID:
6142 return Context.getObjCInstanceTypeDecl();
6143
6144 case PREDEF_DECL_BUILTIN_VA_LIST_ID:
6145 return Context.getBuiltinVaListDecl();
Richard Smithf19e1272015-03-07 00:04:49 +00006146
Richard Smith9b88a4c2015-07-27 05:40:23 +00006147 case PREDEF_DECL_VA_LIST_TAG:
6148 return Context.getVaListTagDecl();
6149
Richard Smithf19e1272015-03-07 00:04:49 +00006150 case PREDEF_DECL_EXTERN_C_CONTEXT_ID:
6151 return Context.getExternCContextDecl();
Richard Smithfe620d22015-03-05 23:24:12 +00006152 }
Yaron Keren322bdad2015-03-06 07:49:14 +00006153 llvm_unreachable("PredefinedDeclIDs unknown enum value");
Richard Smithfe620d22015-03-05 23:24:12 +00006154}
6155
Richard Smithcd45dbc2014-04-19 03:48:30 +00006156Decl *ASTReader::GetExistingDecl(DeclID ID) {
6157 if (ID < NUM_PREDEF_DECL_IDS) {
Richard Smithfe620d22015-03-05 23:24:12 +00006158 Decl *D = getPredefinedDecl(Context, (PredefinedDeclIDs)ID);
6159 if (D) {
6160 // Track that we have merged the declaration with ID \p ID into the
6161 // pre-existing predefined declaration \p D.
Richard Smith5fc18a92015-07-12 23:43:21 +00006162 auto &Merged = KeyDecls[D->getCanonicalDecl()];
Richard Smithfe620d22015-03-05 23:24:12 +00006163 if (Merged.empty())
6164 Merged.push_back(ID);
Guy Benyei11169dd2012-12-18 14:30:41 +00006165 }
Richard Smithfe620d22015-03-05 23:24:12 +00006166 return D;
Guy Benyei11169dd2012-12-18 14:30:41 +00006167 }
Richard Smithcd45dbc2014-04-19 03:48:30 +00006168
Guy Benyei11169dd2012-12-18 14:30:41 +00006169 unsigned Index = ID - NUM_PREDEF_DECL_IDS;
6170
6171 if (Index >= DeclsLoaded.size()) {
6172 assert(0 && "declaration ID out-of-range for AST file");
6173 Error("declaration ID out-of-range for AST file");
Craig Toppera13603a2014-05-22 05:54:18 +00006174 return nullptr;
Guy Benyei11169dd2012-12-18 14:30:41 +00006175 }
Richard Smithcd45dbc2014-04-19 03:48:30 +00006176
6177 return DeclsLoaded[Index];
6178}
6179
6180Decl *ASTReader::GetDecl(DeclID ID) {
6181 if (ID < NUM_PREDEF_DECL_IDS)
6182 return GetExistingDecl(ID);
6183
6184 unsigned Index = ID - NUM_PREDEF_DECL_IDS;
6185
6186 if (Index >= DeclsLoaded.size()) {
6187 assert(0 && "declaration ID out-of-range for AST file");
6188 Error("declaration ID out-of-range for AST file");
Craig Toppera13603a2014-05-22 05:54:18 +00006189 return nullptr;
Richard Smithcd45dbc2014-04-19 03:48:30 +00006190 }
6191
Guy Benyei11169dd2012-12-18 14:30:41 +00006192 if (!DeclsLoaded[Index]) {
6193 ReadDeclRecord(ID);
6194 if (DeserializationListener)
6195 DeserializationListener->DeclRead(ID, DeclsLoaded[Index]);
6196 }
6197
6198 return DeclsLoaded[Index];
6199}
6200
6201DeclID ASTReader::mapGlobalIDToModuleFileGlobalID(ModuleFile &M,
6202 DeclID GlobalID) {
6203 if (GlobalID < NUM_PREDEF_DECL_IDS)
6204 return GlobalID;
6205
6206 GlobalDeclMapType::const_iterator I = GlobalDeclMap.find(GlobalID);
6207 assert(I != GlobalDeclMap.end() && "Corrupted global declaration map");
6208 ModuleFile *Owner = I->second;
6209
6210 llvm::DenseMap<ModuleFile *, serialization::DeclID>::iterator Pos
6211 = M.GlobalToLocalDeclIDs.find(Owner);
6212 if (Pos == M.GlobalToLocalDeclIDs.end())
6213 return 0;
6214
6215 return GlobalID - Owner->BaseDeclID + Pos->second;
6216}
6217
6218serialization::DeclID ASTReader::ReadDeclID(ModuleFile &F,
6219 const RecordData &Record,
6220 unsigned &Idx) {
6221 if (Idx >= Record.size()) {
6222 Error("Corrupted AST file");
6223 return 0;
6224 }
6225
6226 return getGlobalDeclID(F, Record[Idx++]);
6227}
6228
6229/// \brief Resolve the offset of a statement into a statement.
6230///
6231/// This operation will read a new statement from the external
6232/// source each time it is called, and is meant to be used via a
6233/// LazyOffsetPtr (which is used by Decls for the body of functions, etc).
6234Stmt *ASTReader::GetExternalDeclStmt(uint64_t Offset) {
6235 // Switch case IDs are per Decl.
6236 ClearSwitchCaseIDs();
6237
6238 // Offset here is a global offset across the entire chain.
6239 RecordLocation Loc = getLocalBitOffset(Offset);
6240 Loc.F->DeclsCursor.JumpToBit(Loc.Offset);
6241 return ReadStmtFromStream(*Loc.F);
6242}
6243
Richard Smith3cb15722015-08-05 22:41:45 +00006244void ASTReader::FindExternalLexicalDecls(
6245 const DeclContext *DC, llvm::function_ref<bool(Decl::Kind)> IsKindWeWant,
6246 SmallVectorImpl<Decl *> &Decls) {
Richard Smith82f8fcd2015-08-06 22:07:25 +00006247 bool PredefsVisited[NUM_PREDEF_DECL_IDS] = {};
6248
Richard Smith9ccdd932015-08-06 22:14:12 +00006249 auto Visit = [&] (ModuleFile *M, LexicalContents LexicalDecls) {
Richard Smith82f8fcd2015-08-06 22:07:25 +00006250 assert(LexicalDecls.size() % 2 == 0 && "expected an even number of entries");
6251 for (int I = 0, N = LexicalDecls.size(); I != N; I += 2) {
6252 auto K = (Decl::Kind)+LexicalDecls[I];
6253 if (!IsKindWeWant(K))
6254 continue;
6255
6256 auto ID = (serialization::DeclID)+LexicalDecls[I + 1];
6257
6258 // Don't add predefined declarations to the lexical context more
6259 // than once.
6260 if (ID < NUM_PREDEF_DECL_IDS) {
6261 if (PredefsVisited[ID])
6262 continue;
6263
6264 PredefsVisited[ID] = true;
6265 }
6266
6267 if (Decl *D = GetLocalDecl(*M, ID)) {
Richard Smith2317a3e2015-08-11 21:21:20 +00006268 assert(D->getKind() == K && "wrong kind for lexical decl");
Richard Smith82f8fcd2015-08-06 22:07:25 +00006269 if (!DC->isDeclInLexicalTraversal(D))
6270 Decls.push_back(D);
6271 }
6272 }
6273 };
6274
6275 if (isa<TranslationUnitDecl>(DC)) {
6276 for (auto Lexical : TULexicalDecls)
6277 Visit(Lexical.first, Lexical.second);
6278 } else {
6279 auto I = LexicalDecls.find(DC);
6280 if (I != LexicalDecls.end())
Richard Smith9c9173d2015-08-11 22:00:24 +00006281 Visit(I->second.first, I->second.second);
Richard Smith82f8fcd2015-08-06 22:07:25 +00006282 }
6283
Guy Benyei11169dd2012-12-18 14:30:41 +00006284 ++NumLexicalDeclContextsRead;
Guy Benyei11169dd2012-12-18 14:30:41 +00006285}
6286
6287namespace {
6288
6289class DeclIDComp {
6290 ASTReader &Reader;
6291 ModuleFile &Mod;
6292
6293public:
6294 DeclIDComp(ASTReader &Reader, ModuleFile &M) : Reader(Reader), Mod(M) {}
6295
6296 bool operator()(LocalDeclID L, LocalDeclID R) const {
6297 SourceLocation LHS = getLocation(L);
6298 SourceLocation RHS = getLocation(R);
6299 return Reader.getSourceManager().isBeforeInTranslationUnit(LHS, RHS);
6300 }
6301
6302 bool operator()(SourceLocation LHS, LocalDeclID R) const {
6303 SourceLocation RHS = getLocation(R);
6304 return Reader.getSourceManager().isBeforeInTranslationUnit(LHS, RHS);
6305 }
6306
6307 bool operator()(LocalDeclID L, SourceLocation RHS) const {
6308 SourceLocation LHS = getLocation(L);
6309 return Reader.getSourceManager().isBeforeInTranslationUnit(LHS, RHS);
6310 }
6311
6312 SourceLocation getLocation(LocalDeclID ID) const {
6313 return Reader.getSourceManager().getFileLoc(
6314 Reader.getSourceLocationForDeclID(Reader.getGlobalDeclID(Mod, ID)));
6315 }
6316};
6317
Alexander Kornienkoab9db512015-06-22 23:07:51 +00006318}
Guy Benyei11169dd2012-12-18 14:30:41 +00006319
6320void ASTReader::FindFileRegionDecls(FileID File,
6321 unsigned Offset, unsigned Length,
6322 SmallVectorImpl<Decl *> &Decls) {
6323 SourceManager &SM = getSourceManager();
6324
6325 llvm::DenseMap<FileID, FileDeclsInfo>::iterator I = FileDeclIDs.find(File);
6326 if (I == FileDeclIDs.end())
6327 return;
6328
6329 FileDeclsInfo &DInfo = I->second;
6330 if (DInfo.Decls.empty())
6331 return;
6332
6333 SourceLocation
6334 BeginLoc = SM.getLocForStartOfFile(File).getLocWithOffset(Offset);
6335 SourceLocation EndLoc = BeginLoc.getLocWithOffset(Length);
6336
6337 DeclIDComp DIDComp(*this, *DInfo.Mod);
6338 ArrayRef<serialization::LocalDeclID>::iterator
6339 BeginIt = std::lower_bound(DInfo.Decls.begin(), DInfo.Decls.end(),
6340 BeginLoc, DIDComp);
6341 if (BeginIt != DInfo.Decls.begin())
6342 --BeginIt;
6343
6344 // If we are pointing at a top-level decl inside an objc container, we need
6345 // to backtrack until we find it otherwise we will fail to report that the
6346 // region overlaps with an objc container.
6347 while (BeginIt != DInfo.Decls.begin() &&
6348 GetDecl(getGlobalDeclID(*DInfo.Mod, *BeginIt))
6349 ->isTopLevelDeclInObjCContainer())
6350 --BeginIt;
6351
6352 ArrayRef<serialization::LocalDeclID>::iterator
6353 EndIt = std::upper_bound(DInfo.Decls.begin(), DInfo.Decls.end(),
6354 EndLoc, DIDComp);
6355 if (EndIt != DInfo.Decls.end())
6356 ++EndIt;
6357
6358 for (ArrayRef<serialization::LocalDeclID>::iterator
6359 DIt = BeginIt; DIt != EndIt; ++DIt)
6360 Decls.push_back(GetDecl(getGlobalDeclID(*DInfo.Mod, *DIt)));
6361}
6362
Richard Smith3b637412015-07-14 18:42:41 +00006363/// \brief Retrieve the "definitive" module file for the definition of the
6364/// given declaration context, if there is one.
6365///
6366/// The "definitive" module file is the only place where we need to look to
6367/// find information about the declarations within the given declaration
6368/// context. For example, C++ and Objective-C classes, C structs/unions, and
6369/// Objective-C protocols, categories, and extensions are all defined in a
6370/// single place in the source code, so they have definitive module files
6371/// associated with them. C++ namespaces, on the other hand, can have
6372/// definitions in multiple different module files.
6373///
6374/// Note: this needs to be kept in sync with ASTWriter::AddedVisibleDecl's
6375/// NDEBUG checking.
6376static ModuleFile *getDefinitiveModuleFileFor(const DeclContext *DC,
6377 ASTReader &Reader) {
6378 if (const DeclContext *DefDC = getDefinitiveDeclContext(DC))
6379 return Reader.getOwningModuleFile(cast<Decl>(DefDC));
6380
6381 return nullptr;
6382}
6383
Guy Benyei11169dd2012-12-18 14:30:41 +00006384namespace {
6385 /// \brief ModuleFile visitor used to perform name lookup into a
6386 /// declaration context.
6387 class DeclContextNameLookupVisitor {
6388 ASTReader &Reader;
Richard Smithf13c68d2015-08-06 21:05:21 +00006389 const DeclContext *Context;
Guy Benyei11169dd2012-12-18 14:30:41 +00006390 DeclarationName Name;
Richard Smith3b637412015-07-14 18:42:41 +00006391 ASTDeclContextNameLookupTrait::DeclNameKey NameKey;
6392 unsigned NameHash;
Guy Benyei11169dd2012-12-18 14:30:41 +00006393 SmallVectorImpl<NamedDecl *> &Decls;
Richard Smith52874ec2015-02-13 20:17:14 +00006394 llvm::SmallPtrSetImpl<NamedDecl *> &DeclSet;
Guy Benyei11169dd2012-12-18 14:30:41 +00006395
6396 public:
Richard Smith8c913ec2014-08-14 02:21:01 +00006397 DeclContextNameLookupVisitor(ASTReader &Reader,
Richard Smithf13c68d2015-08-06 21:05:21 +00006398 const DeclContext *Context,
Guy Benyei11169dd2012-12-18 14:30:41 +00006399 DeclarationName Name,
Richard Smith52874ec2015-02-13 20:17:14 +00006400 SmallVectorImpl<NamedDecl *> &Decls,
6401 llvm::SmallPtrSetImpl<NamedDecl *> &DeclSet)
Richard Smithf13c68d2015-08-06 21:05:21 +00006402 : Reader(Reader), Context(Context), Name(Name),
Richard Smith3b637412015-07-14 18:42:41 +00006403 NameKey(ASTDeclContextNameLookupTrait::GetInternalKey(Name)),
6404 NameHash(ASTDeclContextNameLookupTrait::ComputeHash(NameKey)),
6405 Decls(Decls), DeclSet(DeclSet) {}
Guy Benyei11169dd2012-12-18 14:30:41 +00006406
Benjamin Kramer9a9efba2015-07-25 12:14:04 +00006407 bool operator()(ModuleFile &M) {
Guy Benyei11169dd2012-12-18 14:30:41 +00006408 // Check whether we have any visible declaration information for
6409 // this context in this module.
Richard Smithf13c68d2015-08-06 21:05:21 +00006410 auto Info = M.DeclContextInfos.find(Context);
6411 if (Info == M.DeclContextInfos.end() || !Info->second.NameLookupTableData)
Guy Benyei11169dd2012-12-18 14:30:41 +00006412 return false;
Richard Smith8c913ec2014-08-14 02:21:01 +00006413
Guy Benyei11169dd2012-12-18 14:30:41 +00006414 // Look for this name within this module.
Richard Smith52e3fba2014-03-11 07:17:35 +00006415 ASTDeclContextNameLookupTable *LookupTable =
Richard Smithf13c68d2015-08-06 21:05:21 +00006416 Info->second.NameLookupTableData;
Benjamin Kramer9a9efba2015-07-25 12:14:04 +00006417 ASTDeclContextNameLookupTable::iterator Pos =
Richard Smithbdf2d932015-07-30 03:37:16 +00006418 LookupTable->find_hashed(NameKey, NameHash);
Guy Benyei11169dd2012-12-18 14:30:41 +00006419 if (Pos == LookupTable->end())
6420 return false;
6421
6422 bool FoundAnything = false;
6423 ASTDeclContextNameLookupTrait::data_type Data = *Pos;
6424 for (; Data.first != Data.second; ++Data.first) {
Richard Smithbdf2d932015-07-30 03:37:16 +00006425 NamedDecl *ND = Reader.GetLocalDeclAs<NamedDecl>(M, *Data.first);
Guy Benyei11169dd2012-12-18 14:30:41 +00006426 if (!ND)
6427 continue;
6428
Richard Smithbdf2d932015-07-30 03:37:16 +00006429 if (ND->getDeclName() != Name) {
Guy Benyei11169dd2012-12-18 14:30:41 +00006430 // A name might be null because the decl's redeclarable part is
6431 // currently read before reading its name. The lookup is triggered by
6432 // building that decl (likely indirectly), and so it is later in the
6433 // sense of "already existing" and can be ignored here.
Richard Smith8c913ec2014-08-14 02:21:01 +00006434 // FIXME: This should not happen; deserializing declarations should
6435 // not perform lookups since that can lead to deserialization cycles.
Guy Benyei11169dd2012-12-18 14:30:41 +00006436 continue;
6437 }
Richard Smith8c913ec2014-08-14 02:21:01 +00006438
Guy Benyei11169dd2012-12-18 14:30:41 +00006439 // Record this declaration.
6440 FoundAnything = true;
Richard Smithbdf2d932015-07-30 03:37:16 +00006441 if (DeclSet.insert(ND).second)
6442 Decls.push_back(ND);
Guy Benyei11169dd2012-12-18 14:30:41 +00006443 }
6444
6445 return FoundAnything;
6446 }
6447 };
Alexander Kornienkoab9db512015-06-22 23:07:51 +00006448}
Guy Benyei11169dd2012-12-18 14:30:41 +00006449
Richard Smith9ce12e32013-02-07 03:30:24 +00006450bool
Guy Benyei11169dd2012-12-18 14:30:41 +00006451ASTReader::FindExternalVisibleDeclsByName(const DeclContext *DC,
6452 DeclarationName Name) {
6453 assert(DC->hasExternalVisibleStorage() &&
6454 "DeclContext has no visible decls in storage");
6455 if (!Name)
Richard Smith9ce12e32013-02-07 03:30:24 +00006456 return false;
Guy Benyei11169dd2012-12-18 14:30:41 +00006457
Richard Smith8c913ec2014-08-14 02:21:01 +00006458 Deserializing LookupResults(this);
6459
Guy Benyei11169dd2012-12-18 14:30:41 +00006460 SmallVector<NamedDecl *, 64> Decls;
Richard Smith52874ec2015-02-13 20:17:14 +00006461 llvm::SmallPtrSet<NamedDecl*, 64> DeclSet;
Richard Smith8c913ec2014-08-14 02:21:01 +00006462
Richard Smithf13c68d2015-08-06 21:05:21 +00006463 DeclContextNameLookupVisitor Visitor(*this, DC, Name, Decls, DeclSet);
Richard Smith8c913ec2014-08-14 02:21:01 +00006464
Richard Smithf13c68d2015-08-06 21:05:21 +00006465 // If we can definitively determine which module file to look into,
6466 // only look there. Otherwise, look in all module files.
6467 if (ModuleFile *Definitive = getDefinitiveModuleFileFor(DC, *this))
6468 Visitor(*Definitive);
6469 else
6470 ModuleMgr.visit(Visitor);
Richard Smithcd45dbc2014-04-19 03:48:30 +00006471
Guy Benyei11169dd2012-12-18 14:30:41 +00006472 ++NumVisibleDeclContextsRead;
6473 SetExternalVisibleDeclsForName(DC, Name, Decls);
Richard Smith9ce12e32013-02-07 03:30:24 +00006474 return !Decls.empty();
Guy Benyei11169dd2012-12-18 14:30:41 +00006475}
6476
6477namespace {
6478 /// \brief ModuleFile visitor used to retrieve all visible names in a
6479 /// declaration context.
6480 class DeclContextAllNamesVisitor {
6481 ASTReader &Reader;
Dmitri Gribenkof8579502013-01-12 19:30:44 +00006482 SmallVectorImpl<const DeclContext *> &Contexts;
Craig Topper3598eb72013-07-05 04:43:31 +00006483 DeclsMap &Decls;
Richard Smith52874ec2015-02-13 20:17:14 +00006484 llvm::SmallPtrSet<NamedDecl *, 256> DeclSet;
Argyrios Kyrtzidis2810e9d2012-12-19 22:21:18 +00006485 bool VisitAll;
Guy Benyei11169dd2012-12-18 14:30:41 +00006486
6487 public:
6488 DeclContextAllNamesVisitor(ASTReader &Reader,
6489 SmallVectorImpl<const DeclContext *> &Contexts,
Craig Topper3598eb72013-07-05 04:43:31 +00006490 DeclsMap &Decls, bool VisitAll)
Argyrios Kyrtzidis2810e9d2012-12-19 22:21:18 +00006491 : Reader(Reader), Contexts(Contexts), Decls(Decls), VisitAll(VisitAll) { }
Guy Benyei11169dd2012-12-18 14:30:41 +00006492
Benjamin Kramer9a9efba2015-07-25 12:14:04 +00006493 bool operator()(ModuleFile &M) {
Guy Benyei11169dd2012-12-18 14:30:41 +00006494 // Check whether we have any visible declaration information for
6495 // this context in this module.
6496 ModuleFile::DeclContextInfosMap::iterator Info;
6497 bool FoundInfo = false;
Richard Smithbdf2d932015-07-30 03:37:16 +00006498 for (unsigned I = 0, N = Contexts.size(); I != N; ++I) {
6499 Info = M.DeclContextInfos.find(Contexts[I]);
Guy Benyei11169dd2012-12-18 14:30:41 +00006500 if (Info != M.DeclContextInfos.end() &&
6501 Info->second.NameLookupTableData) {
6502 FoundInfo = true;
6503 break;
6504 }
6505 }
6506
6507 if (!FoundInfo)
6508 return false;
6509
Richard Smith52e3fba2014-03-11 07:17:35 +00006510 ASTDeclContextNameLookupTable *LookupTable =
Guy Benyei11169dd2012-12-18 14:30:41 +00006511 Info->second.NameLookupTableData;
6512 bool FoundAnything = false;
6513 for (ASTDeclContextNameLookupTable::data_iterator
Douglas Gregor5e306b12013-01-23 22:38:11 +00006514 I = LookupTable->data_begin(), E = LookupTable->data_end();
6515 I != E;
6516 ++I) {
Guy Benyei11169dd2012-12-18 14:30:41 +00006517 ASTDeclContextNameLookupTrait::data_type Data = *I;
6518 for (; Data.first != Data.second; ++Data.first) {
Richard Smithbdf2d932015-07-30 03:37:16 +00006519 NamedDecl *ND = Reader.GetLocalDeclAs<NamedDecl>(M, *Data.first);
Guy Benyei11169dd2012-12-18 14:30:41 +00006520 if (!ND)
6521 continue;
6522
6523 // Record this declaration.
6524 FoundAnything = true;
Richard Smithbdf2d932015-07-30 03:37:16 +00006525 if (DeclSet.insert(ND).second)
6526 Decls[ND->getDeclName()].push_back(ND);
Guy Benyei11169dd2012-12-18 14:30:41 +00006527 }
6528 }
6529
Richard Smithbdf2d932015-07-30 03:37:16 +00006530 return FoundAnything && !VisitAll;
Guy Benyei11169dd2012-12-18 14:30:41 +00006531 }
6532 };
Alexander Kornienkoab9db512015-06-22 23:07:51 +00006533}
Guy Benyei11169dd2012-12-18 14:30:41 +00006534
6535void ASTReader::completeVisibleDeclsMap(const DeclContext *DC) {
6536 if (!DC->hasExternalVisibleStorage())
6537 return;
Craig Topper79be4cd2013-07-05 04:33:53 +00006538 DeclsMap Decls;
Guy Benyei11169dd2012-12-18 14:30:41 +00006539
6540 // Compute the declaration contexts we need to look into. Multiple such
6541 // declaration contexts occur when two declaration contexts from disjoint
6542 // modules get merged, e.g., when two namespaces with the same name are
6543 // independently defined in separate modules.
6544 SmallVector<const DeclContext *, 2> Contexts;
6545 Contexts.push_back(DC);
6546
6547 if (DC->isNamespace()) {
Richard Smith5fc18a92015-07-12 23:43:21 +00006548 KeyDeclsMap::iterator Key =
6549 KeyDecls.find(const_cast<Decl *>(cast<Decl>(DC)));
6550 if (Key != KeyDecls.end()) {
6551 for (unsigned I = 0, N = Key->second.size(); I != N; ++I)
6552 Contexts.push_back(cast<DeclContext>(GetDecl(Key->second[I])));
Guy Benyei11169dd2012-12-18 14:30:41 +00006553 }
6554 }
6555
Argyrios Kyrtzidis2810e9d2012-12-19 22:21:18 +00006556 DeclContextAllNamesVisitor Visitor(*this, Contexts, Decls,
6557 /*VisitAll=*/DC->isFileContext());
Benjamin Kramer9a9efba2015-07-25 12:14:04 +00006558 ModuleMgr.visit(Visitor);
Guy Benyei11169dd2012-12-18 14:30:41 +00006559 ++NumVisibleDeclContextsRead;
6560
Craig Topper79be4cd2013-07-05 04:33:53 +00006561 for (DeclsMap::iterator I = Decls.begin(), E = Decls.end(); I != E; ++I) {
Guy Benyei11169dd2012-12-18 14:30:41 +00006562 SetExternalVisibleDeclsForName(DC, I->first, I->second);
6563 }
6564 const_cast<DeclContext *>(DC)->setHasExternalVisibleStorage(false);
6565}
6566
6567/// \brief Under non-PCH compilation the consumer receives the objc methods
6568/// before receiving the implementation, and codegen depends on this.
6569/// We simulate this by deserializing and passing to consumer the methods of the
6570/// implementation before passing the deserialized implementation decl.
6571static void PassObjCImplDeclToConsumer(ObjCImplDecl *ImplD,
6572 ASTConsumer *Consumer) {
6573 assert(ImplD && Consumer);
6574
Aaron Ballmanaff18c02014-03-13 19:03:34 +00006575 for (auto *I : ImplD->methods())
6576 Consumer->HandleInterestingDecl(DeclGroupRef(I));
Guy Benyei11169dd2012-12-18 14:30:41 +00006577
6578 Consumer->HandleInterestingDecl(DeclGroupRef(ImplD));
6579}
6580
6581void ASTReader::PassInterestingDeclsToConsumer() {
6582 assert(Consumer);
Richard Smith04d05b52014-03-23 00:27:18 +00006583
6584 if (PassingDeclsToConsumer)
6585 return;
6586
6587 // Guard variable to avoid recursively redoing the process of passing
6588 // decls to consumer.
6589 SaveAndRestore<bool> GuardPassingDeclsToConsumer(PassingDeclsToConsumer,
6590 true);
6591
Richard Smith9e2341d2015-03-23 03:25:59 +00006592 // Ensure that we've loaded all potentially-interesting declarations
6593 // that need to be eagerly loaded.
6594 for (auto ID : EagerlyDeserializedDecls)
6595 GetDecl(ID);
6596 EagerlyDeserializedDecls.clear();
6597
Guy Benyei11169dd2012-12-18 14:30:41 +00006598 while (!InterestingDecls.empty()) {
6599 Decl *D = InterestingDecls.front();
6600 InterestingDecls.pop_front();
6601
6602 PassInterestingDeclToConsumer(D);
6603 }
6604}
6605
6606void ASTReader::PassInterestingDeclToConsumer(Decl *D) {
6607 if (ObjCImplDecl *ImplD = dyn_cast<ObjCImplDecl>(D))
6608 PassObjCImplDeclToConsumer(ImplD, Consumer);
6609 else
6610 Consumer->HandleInterestingDecl(DeclGroupRef(D));
6611}
6612
6613void ASTReader::StartTranslationUnit(ASTConsumer *Consumer) {
6614 this->Consumer = Consumer;
6615
Richard Smith9e2341d2015-03-23 03:25:59 +00006616 if (Consumer)
6617 PassInterestingDeclsToConsumer();
Richard Smith7f330cd2015-03-18 01:42:29 +00006618
6619 if (DeserializationListener)
6620 DeserializationListener->ReaderInitialized(this);
Guy Benyei11169dd2012-12-18 14:30:41 +00006621}
6622
6623void ASTReader::PrintStats() {
6624 std::fprintf(stderr, "*** AST File Statistics:\n");
6625
6626 unsigned NumTypesLoaded
6627 = TypesLoaded.size() - std::count(TypesLoaded.begin(), TypesLoaded.end(),
6628 QualType());
6629 unsigned NumDeclsLoaded
6630 = DeclsLoaded.size() - std::count(DeclsLoaded.begin(), DeclsLoaded.end(),
Craig Toppera13603a2014-05-22 05:54:18 +00006631 (Decl *)nullptr);
Guy Benyei11169dd2012-12-18 14:30:41 +00006632 unsigned NumIdentifiersLoaded
6633 = IdentifiersLoaded.size() - std::count(IdentifiersLoaded.begin(),
6634 IdentifiersLoaded.end(),
Craig Toppera13603a2014-05-22 05:54:18 +00006635 (IdentifierInfo *)nullptr);
Guy Benyei11169dd2012-12-18 14:30:41 +00006636 unsigned NumMacrosLoaded
6637 = MacrosLoaded.size() - std::count(MacrosLoaded.begin(),
6638 MacrosLoaded.end(),
Craig Toppera13603a2014-05-22 05:54:18 +00006639 (MacroInfo *)nullptr);
Guy Benyei11169dd2012-12-18 14:30:41 +00006640 unsigned NumSelectorsLoaded
6641 = SelectorsLoaded.size() - std::count(SelectorsLoaded.begin(),
6642 SelectorsLoaded.end(),
6643 Selector());
6644
6645 if (unsigned TotalNumSLocEntries = getTotalNumSLocs())
6646 std::fprintf(stderr, " %u/%u source location entries read (%f%%)\n",
6647 NumSLocEntriesRead, TotalNumSLocEntries,
6648 ((float)NumSLocEntriesRead/TotalNumSLocEntries * 100));
6649 if (!TypesLoaded.empty())
6650 std::fprintf(stderr, " %u/%u types read (%f%%)\n",
6651 NumTypesLoaded, (unsigned)TypesLoaded.size(),
6652 ((float)NumTypesLoaded/TypesLoaded.size() * 100));
6653 if (!DeclsLoaded.empty())
6654 std::fprintf(stderr, " %u/%u declarations read (%f%%)\n",
6655 NumDeclsLoaded, (unsigned)DeclsLoaded.size(),
6656 ((float)NumDeclsLoaded/DeclsLoaded.size() * 100));
6657 if (!IdentifiersLoaded.empty())
6658 std::fprintf(stderr, " %u/%u identifiers read (%f%%)\n",
6659 NumIdentifiersLoaded, (unsigned)IdentifiersLoaded.size(),
6660 ((float)NumIdentifiersLoaded/IdentifiersLoaded.size() * 100));
6661 if (!MacrosLoaded.empty())
6662 std::fprintf(stderr, " %u/%u macros read (%f%%)\n",
6663 NumMacrosLoaded, (unsigned)MacrosLoaded.size(),
6664 ((float)NumMacrosLoaded/MacrosLoaded.size() * 100));
6665 if (!SelectorsLoaded.empty())
6666 std::fprintf(stderr, " %u/%u selectors read (%f%%)\n",
6667 NumSelectorsLoaded, (unsigned)SelectorsLoaded.size(),
6668 ((float)NumSelectorsLoaded/SelectorsLoaded.size() * 100));
6669 if (TotalNumStatements)
6670 std::fprintf(stderr, " %u/%u statements read (%f%%)\n",
6671 NumStatementsRead, TotalNumStatements,
6672 ((float)NumStatementsRead/TotalNumStatements * 100));
6673 if (TotalNumMacros)
6674 std::fprintf(stderr, " %u/%u macros read (%f%%)\n",
6675 NumMacrosRead, TotalNumMacros,
6676 ((float)NumMacrosRead/TotalNumMacros * 100));
6677 if (TotalLexicalDeclContexts)
6678 std::fprintf(stderr, " %u/%u lexical declcontexts read (%f%%)\n",
6679 NumLexicalDeclContextsRead, TotalLexicalDeclContexts,
6680 ((float)NumLexicalDeclContextsRead/TotalLexicalDeclContexts
6681 * 100));
6682 if (TotalVisibleDeclContexts)
6683 std::fprintf(stderr, " %u/%u visible declcontexts read (%f%%)\n",
6684 NumVisibleDeclContextsRead, TotalVisibleDeclContexts,
6685 ((float)NumVisibleDeclContextsRead/TotalVisibleDeclContexts
6686 * 100));
6687 if (TotalNumMethodPoolEntries) {
6688 std::fprintf(stderr, " %u/%u method pool entries read (%f%%)\n",
6689 NumMethodPoolEntriesRead, TotalNumMethodPoolEntries,
6690 ((float)NumMethodPoolEntriesRead/TotalNumMethodPoolEntries
6691 * 100));
Guy Benyei11169dd2012-12-18 14:30:41 +00006692 }
Douglas Gregorad2f7a52013-01-28 17:54:36 +00006693 if (NumMethodPoolLookups) {
6694 std::fprintf(stderr, " %u/%u method pool lookups succeeded (%f%%)\n",
6695 NumMethodPoolHits, NumMethodPoolLookups,
6696 ((float)NumMethodPoolHits/NumMethodPoolLookups * 100.0));
6697 }
6698 if (NumMethodPoolTableLookups) {
6699 std::fprintf(stderr, " %u/%u method pool table lookups succeeded (%f%%)\n",
6700 NumMethodPoolTableHits, NumMethodPoolTableLookups,
6701 ((float)NumMethodPoolTableHits/NumMethodPoolTableLookups
6702 * 100.0));
6703 }
6704
Douglas Gregor00a50f72013-01-25 00:38:33 +00006705 if (NumIdentifierLookupHits) {
6706 std::fprintf(stderr,
6707 " %u / %u identifier table lookups succeeded (%f%%)\n",
6708 NumIdentifierLookupHits, NumIdentifierLookups,
6709 (double)NumIdentifierLookupHits*100.0/NumIdentifierLookups);
6710 }
6711
Douglas Gregore060e572013-01-25 01:03:03 +00006712 if (GlobalIndex) {
6713 std::fprintf(stderr, "\n");
6714 GlobalIndex->printStats();
6715 }
6716
Guy Benyei11169dd2012-12-18 14:30:41 +00006717 std::fprintf(stderr, "\n");
6718 dump();
6719 std::fprintf(stderr, "\n");
6720}
6721
6722template<typename Key, typename ModuleFile, unsigned InitialCapacity>
6723static void
6724dumpModuleIDMap(StringRef Name,
6725 const ContinuousRangeMap<Key, ModuleFile *,
6726 InitialCapacity> &Map) {
6727 if (Map.begin() == Map.end())
6728 return;
6729
6730 typedef ContinuousRangeMap<Key, ModuleFile *, InitialCapacity> MapType;
6731 llvm::errs() << Name << ":\n";
6732 for (typename MapType::const_iterator I = Map.begin(), IEnd = Map.end();
6733 I != IEnd; ++I) {
6734 llvm::errs() << " " << I->first << " -> " << I->second->FileName
6735 << "\n";
6736 }
6737}
6738
6739void ASTReader::dump() {
6740 llvm::errs() << "*** PCH/ModuleFile Remappings:\n";
6741 dumpModuleIDMap("Global bit offset map", GlobalBitOffsetsMap);
6742 dumpModuleIDMap("Global source location entry map", GlobalSLocEntryMap);
6743 dumpModuleIDMap("Global type map", GlobalTypeMap);
6744 dumpModuleIDMap("Global declaration map", GlobalDeclMap);
6745 dumpModuleIDMap("Global identifier map", GlobalIdentifierMap);
6746 dumpModuleIDMap("Global macro map", GlobalMacroMap);
6747 dumpModuleIDMap("Global submodule map", GlobalSubmoduleMap);
6748 dumpModuleIDMap("Global selector map", GlobalSelectorMap);
6749 dumpModuleIDMap("Global preprocessed entity map",
6750 GlobalPreprocessedEntityMap);
6751
6752 llvm::errs() << "\n*** PCH/Modules Loaded:";
6753 for (ModuleManager::ModuleConstIterator M = ModuleMgr.begin(),
6754 MEnd = ModuleMgr.end();
6755 M != MEnd; ++M)
6756 (*M)->dump();
6757}
6758
6759/// Return the amount of memory used by memory buffers, breaking down
6760/// by heap-backed versus mmap'ed memory.
6761void ASTReader::getMemoryBufferSizes(MemoryBufferSizes &sizes) const {
6762 for (ModuleConstIterator I = ModuleMgr.begin(),
6763 E = ModuleMgr.end(); I != E; ++I) {
6764 if (llvm::MemoryBuffer *buf = (*I)->Buffer.get()) {
6765 size_t bytes = buf->getBufferSize();
6766 switch (buf->getBufferKind()) {
6767 case llvm::MemoryBuffer::MemoryBuffer_Malloc:
6768 sizes.malloc_bytes += bytes;
6769 break;
6770 case llvm::MemoryBuffer::MemoryBuffer_MMap:
6771 sizes.mmap_bytes += bytes;
6772 break;
6773 }
6774 }
6775 }
6776}
6777
6778void ASTReader::InitializeSema(Sema &S) {
6779 SemaObj = &S;
6780 S.addExternalSource(this);
6781
6782 // Makes sure any declarations that were deserialized "too early"
6783 // still get added to the identifier's declaration chains.
Ben Langmuir5418f402014-09-10 21:29:41 +00006784 for (uint64_t ID : PreloadedDeclIDs) {
6785 NamedDecl *D = cast<NamedDecl>(GetDecl(ID));
6786 pushExternalDeclIntoScope(D, D->getDeclName());
Guy Benyei11169dd2012-12-18 14:30:41 +00006787 }
Ben Langmuir5418f402014-09-10 21:29:41 +00006788 PreloadedDeclIDs.clear();
Guy Benyei11169dd2012-12-18 14:30:41 +00006789
Richard Smith3d8e97e2013-10-18 06:54:39 +00006790 // FIXME: What happens if these are changed by a module import?
Guy Benyei11169dd2012-12-18 14:30:41 +00006791 if (!FPPragmaOptions.empty()) {
6792 assert(FPPragmaOptions.size() == 1 && "Wrong number of FP_PRAGMA_OPTIONS");
6793 SemaObj->FPFeatures.fp_contract = FPPragmaOptions[0];
6794 }
6795
Richard Smith3d8e97e2013-10-18 06:54:39 +00006796 // FIXME: What happens if these are changed by a module import?
Guy Benyei11169dd2012-12-18 14:30:41 +00006797 if (!OpenCLExtensions.empty()) {
6798 unsigned I = 0;
6799#define OPENCLEXT(nm) SemaObj->OpenCLFeatures.nm = OpenCLExtensions[I++];
6800#include "clang/Basic/OpenCLExtensions.def"
6801
6802 assert(OpenCLExtensions.size() == I && "Wrong number of OPENCL_EXTENSIONS");
6803 }
Richard Smith3d8e97e2013-10-18 06:54:39 +00006804
6805 UpdateSema();
6806}
6807
6808void ASTReader::UpdateSema() {
6809 assert(SemaObj && "no Sema to update");
6810
6811 // Load the offsets of the declarations that Sema references.
6812 // They will be lazily deserialized when needed.
6813 if (!SemaDeclRefs.empty()) {
6814 assert(SemaDeclRefs.size() % 2 == 0);
6815 for (unsigned I = 0; I != SemaDeclRefs.size(); I += 2) {
6816 if (!SemaObj->StdNamespace)
6817 SemaObj->StdNamespace = SemaDeclRefs[I];
6818 if (!SemaObj->StdBadAlloc)
6819 SemaObj->StdBadAlloc = SemaDeclRefs[I+1];
6820 }
6821 SemaDeclRefs.clear();
6822 }
Dario Domizioli13a0a382014-05-23 12:13:25 +00006823
6824 // Update the state of 'pragma clang optimize'. Use the same API as if we had
6825 // encountered the pragma in the source.
6826 if(OptimizeOffPragmaLocation.isValid())
6827 SemaObj->ActOnPragmaOptimize(/* IsOn = */ false, OptimizeOffPragmaLocation);
Guy Benyei11169dd2012-12-18 14:30:41 +00006828}
6829
Richard Smitha8d5b6a2015-07-17 19:51:03 +00006830IdentifierInfo *ASTReader::get(StringRef Name) {
Guy Benyei11169dd2012-12-18 14:30:41 +00006831 // Note that we are loading an identifier.
6832 Deserializing AnIdentifier(this);
Douglas Gregore060e572013-01-25 01:03:03 +00006833
Douglas Gregor7211ac12013-01-25 23:32:03 +00006834 IdentifierLookupVisitor Visitor(Name, /*PriorGeneration=*/0,
Douglas Gregor00a50f72013-01-25 00:38:33 +00006835 NumIdentifierLookups,
6836 NumIdentifierLookupHits);
Richard Smith33e0f7e2015-07-22 02:08:40 +00006837
6838 // We don't need to do identifier table lookups in C++ modules (we preload
6839 // all interesting declarations, and don't need to use the scope for name
6840 // lookups). Perform the lookup in PCH files, though, since we don't build
6841 // a complete initial identifier table if we're carrying on from a PCH.
6842 if (Context.getLangOpts().CPlusPlus) {
6843 for (auto F : ModuleMgr.pch_modules())
Benjamin Kramer9a9efba2015-07-25 12:14:04 +00006844 if (Visitor(*F))
Richard Smith33e0f7e2015-07-22 02:08:40 +00006845 break;
6846 } else {
6847 // If there is a global index, look there first to determine which modules
6848 // provably do not have any results for this identifier.
6849 GlobalModuleIndex::HitSet Hits;
6850 GlobalModuleIndex::HitSet *HitsPtr = nullptr;
6851 if (!loadGlobalIndex()) {
6852 if (GlobalIndex->lookupIdentifier(Name, Hits)) {
6853 HitsPtr = &Hits;
6854 }
6855 }
6856
Benjamin Kramer9a9efba2015-07-25 12:14:04 +00006857 ModuleMgr.visit(Visitor, HitsPtr);
Richard Smith33e0f7e2015-07-22 02:08:40 +00006858 }
6859
Guy Benyei11169dd2012-12-18 14:30:41 +00006860 IdentifierInfo *II = Visitor.getIdentifierInfo();
6861 markIdentifierUpToDate(II);
6862 return II;
6863}
6864
6865namespace clang {
6866 /// \brief An identifier-lookup iterator that enumerates all of the
6867 /// identifiers stored within a set of AST files.
6868 class ASTIdentifierIterator : public IdentifierIterator {
6869 /// \brief The AST reader whose identifiers are being enumerated.
6870 const ASTReader &Reader;
6871
6872 /// \brief The current index into the chain of AST files stored in
6873 /// the AST reader.
6874 unsigned Index;
6875
6876 /// \brief The current position within the identifier lookup table
6877 /// of the current AST file.
6878 ASTIdentifierLookupTable::key_iterator Current;
6879
6880 /// \brief The end position within the identifier lookup table of
6881 /// the current AST file.
6882 ASTIdentifierLookupTable::key_iterator End;
6883
6884 public:
6885 explicit ASTIdentifierIterator(const ASTReader &Reader);
6886
Craig Topper3e89dfe2014-03-13 02:13:41 +00006887 StringRef Next() override;
Guy Benyei11169dd2012-12-18 14:30:41 +00006888 };
Alexander Kornienkoab9db512015-06-22 23:07:51 +00006889}
Guy Benyei11169dd2012-12-18 14:30:41 +00006890
6891ASTIdentifierIterator::ASTIdentifierIterator(const ASTReader &Reader)
6892 : Reader(Reader), Index(Reader.ModuleMgr.size() - 1) {
6893 ASTIdentifierLookupTable *IdTable
6894 = (ASTIdentifierLookupTable *)Reader.ModuleMgr[Index].IdentifierLookupTable;
6895 Current = IdTable->key_begin();
6896 End = IdTable->key_end();
6897}
6898
6899StringRef ASTIdentifierIterator::Next() {
6900 while (Current == End) {
6901 // If we have exhausted all of our AST files, we're done.
6902 if (Index == 0)
6903 return StringRef();
6904
6905 --Index;
6906 ASTIdentifierLookupTable *IdTable
6907 = (ASTIdentifierLookupTable *)Reader.ModuleMgr[Index].
6908 IdentifierLookupTable;
6909 Current = IdTable->key_begin();
6910 End = IdTable->key_end();
6911 }
6912
6913 // We have any identifiers remaining in the current AST file; return
6914 // the next one.
Douglas Gregorbfd73d72013-01-23 18:53:14 +00006915 StringRef Result = *Current;
Guy Benyei11169dd2012-12-18 14:30:41 +00006916 ++Current;
Douglas Gregorbfd73d72013-01-23 18:53:14 +00006917 return Result;
Guy Benyei11169dd2012-12-18 14:30:41 +00006918}
6919
Argyrios Kyrtzidis9aca3c62013-04-17 22:10:55 +00006920IdentifierIterator *ASTReader::getIdentifiers() {
6921 if (!loadGlobalIndex())
6922 return GlobalIndex->createIdentifierIterator();
6923
Guy Benyei11169dd2012-12-18 14:30:41 +00006924 return new ASTIdentifierIterator(*this);
6925}
6926
6927namespace clang { namespace serialization {
6928 class ReadMethodPoolVisitor {
6929 ASTReader &Reader;
6930 Selector Sel;
6931 unsigned PriorGeneration;
Argyrios Kyrtzidisd3da6e02013-04-17 00:08:58 +00006932 unsigned InstanceBits;
6933 unsigned FactoryBits;
Nico Weberff4b35e2014-12-27 22:14:15 +00006934 bool InstanceHasMoreThanOneDecl;
6935 bool FactoryHasMoreThanOneDecl;
Dmitri Gribenkof8579502013-01-12 19:30:44 +00006936 SmallVector<ObjCMethodDecl *, 4> InstanceMethods;
6937 SmallVector<ObjCMethodDecl *, 4> FactoryMethods;
Guy Benyei11169dd2012-12-18 14:30:41 +00006938
6939 public:
Nico Weber2e0c8f72014-12-27 03:58:08 +00006940 ReadMethodPoolVisitor(ASTReader &Reader, Selector Sel,
Guy Benyei11169dd2012-12-18 14:30:41 +00006941 unsigned PriorGeneration)
Nico Weber2e0c8f72014-12-27 03:58:08 +00006942 : Reader(Reader), Sel(Sel), PriorGeneration(PriorGeneration),
Nico Weberff4b35e2014-12-27 22:14:15 +00006943 InstanceBits(0), FactoryBits(0), InstanceHasMoreThanOneDecl(false),
6944 FactoryHasMoreThanOneDecl(false) {}
Nico Weber2e0c8f72014-12-27 03:58:08 +00006945
Benjamin Kramer9a9efba2015-07-25 12:14:04 +00006946 bool operator()(ModuleFile &M) {
Guy Benyei11169dd2012-12-18 14:30:41 +00006947 if (!M.SelectorLookupTable)
6948 return false;
6949
6950 // If we've already searched this module file, skip it now.
Richard Smithbdf2d932015-07-30 03:37:16 +00006951 if (M.Generation <= PriorGeneration)
Guy Benyei11169dd2012-12-18 14:30:41 +00006952 return true;
6953
Richard Smithbdf2d932015-07-30 03:37:16 +00006954 ++Reader.NumMethodPoolTableLookups;
Guy Benyei11169dd2012-12-18 14:30:41 +00006955 ASTSelectorLookupTable *PoolTable
6956 = (ASTSelectorLookupTable*)M.SelectorLookupTable;
Richard Smithbdf2d932015-07-30 03:37:16 +00006957 ASTSelectorLookupTable::iterator Pos = PoolTable->find(Sel);
Guy Benyei11169dd2012-12-18 14:30:41 +00006958 if (Pos == PoolTable->end())
6959 return false;
Douglas Gregorad2f7a52013-01-28 17:54:36 +00006960
Richard Smithbdf2d932015-07-30 03:37:16 +00006961 ++Reader.NumMethodPoolTableHits;
6962 ++Reader.NumSelectorsRead;
Guy Benyei11169dd2012-12-18 14:30:41 +00006963 // FIXME: Not quite happy with the statistics here. We probably should
6964 // disable this tracking when called via LoadSelector.
6965 // Also, should entries without methods count as misses?
Richard Smithbdf2d932015-07-30 03:37:16 +00006966 ++Reader.NumMethodPoolEntriesRead;
Guy Benyei11169dd2012-12-18 14:30:41 +00006967 ASTSelectorLookupTrait::data_type Data = *Pos;
Richard Smithbdf2d932015-07-30 03:37:16 +00006968 if (Reader.DeserializationListener)
6969 Reader.DeserializationListener->SelectorRead(Data.ID, Sel);
Benjamin Kramer9a9efba2015-07-25 12:14:04 +00006970
Richard Smithbdf2d932015-07-30 03:37:16 +00006971 InstanceMethods.append(Data.Instance.begin(), Data.Instance.end());
6972 FactoryMethods.append(Data.Factory.begin(), Data.Factory.end());
6973 InstanceBits = Data.InstanceBits;
6974 FactoryBits = Data.FactoryBits;
6975 InstanceHasMoreThanOneDecl = Data.InstanceHasMoreThanOneDecl;
6976 FactoryHasMoreThanOneDecl = Data.FactoryHasMoreThanOneDecl;
Guy Benyei11169dd2012-12-18 14:30:41 +00006977 return true;
6978 }
6979
6980 /// \brief Retrieve the instance methods found by this visitor.
6981 ArrayRef<ObjCMethodDecl *> getInstanceMethods() const {
6982 return InstanceMethods;
6983 }
6984
6985 /// \brief Retrieve the instance methods found by this visitor.
6986 ArrayRef<ObjCMethodDecl *> getFactoryMethods() const {
6987 return FactoryMethods;
6988 }
Argyrios Kyrtzidisd3da6e02013-04-17 00:08:58 +00006989
6990 unsigned getInstanceBits() const { return InstanceBits; }
6991 unsigned getFactoryBits() const { return FactoryBits; }
Nico Weberff4b35e2014-12-27 22:14:15 +00006992 bool instanceHasMoreThanOneDecl() const {
6993 return InstanceHasMoreThanOneDecl;
6994 }
6995 bool factoryHasMoreThanOneDecl() const { return FactoryHasMoreThanOneDecl; }
Guy Benyei11169dd2012-12-18 14:30:41 +00006996 };
Alexander Kornienkoab9db512015-06-22 23:07:51 +00006997} } // end namespace clang::serialization
Guy Benyei11169dd2012-12-18 14:30:41 +00006998
6999/// \brief Add the given set of methods to the method list.
7000static void addMethodsToPool(Sema &S, ArrayRef<ObjCMethodDecl *> Methods,
7001 ObjCMethodList &List) {
7002 for (unsigned I = 0, N = Methods.size(); I != N; ++I) {
7003 S.addMethodToGlobalList(&List, Methods[I]);
7004 }
7005}
7006
7007void ASTReader::ReadMethodPool(Selector Sel) {
7008 // Get the selector generation and update it to the current generation.
7009 unsigned &Generation = SelectorGeneration[Sel];
7010 unsigned PriorGeneration = Generation;
Richard Smith053f6c62014-05-16 23:01:30 +00007011 Generation = getGeneration();
Guy Benyei11169dd2012-12-18 14:30:41 +00007012
7013 // Search for methods defined with this selector.
Douglas Gregorad2f7a52013-01-28 17:54:36 +00007014 ++NumMethodPoolLookups;
Guy Benyei11169dd2012-12-18 14:30:41 +00007015 ReadMethodPoolVisitor Visitor(*this, Sel, PriorGeneration);
Benjamin Kramer9a9efba2015-07-25 12:14:04 +00007016 ModuleMgr.visit(Visitor);
7017
Guy Benyei11169dd2012-12-18 14:30:41 +00007018 if (Visitor.getInstanceMethods().empty() &&
Douglas Gregorad2f7a52013-01-28 17:54:36 +00007019 Visitor.getFactoryMethods().empty())
Guy Benyei11169dd2012-12-18 14:30:41 +00007020 return;
Douglas Gregorad2f7a52013-01-28 17:54:36 +00007021
7022 ++NumMethodPoolHits;
7023
Guy Benyei11169dd2012-12-18 14:30:41 +00007024 if (!getSema())
7025 return;
7026
7027 Sema &S = *getSema();
7028 Sema::GlobalMethodPool::iterator Pos
7029 = S.MethodPool.insert(std::make_pair(Sel, Sema::GlobalMethods())).first;
Ben Langmuira0c32e92015-01-12 19:27:00 +00007030
Argyrios Kyrtzidisd3da6e02013-04-17 00:08:58 +00007031 Pos->second.first.setBits(Visitor.getInstanceBits());
Nico Weberff4b35e2014-12-27 22:14:15 +00007032 Pos->second.first.setHasMoreThanOneDecl(Visitor.instanceHasMoreThanOneDecl());
Argyrios Kyrtzidisd3da6e02013-04-17 00:08:58 +00007033 Pos->second.second.setBits(Visitor.getFactoryBits());
Nico Weberff4b35e2014-12-27 22:14:15 +00007034 Pos->second.second.setHasMoreThanOneDecl(Visitor.factoryHasMoreThanOneDecl());
Ben Langmuira0c32e92015-01-12 19:27:00 +00007035
7036 // Add methods to the global pool *after* setting hasMoreThanOneDecl, since
7037 // when building a module we keep every method individually and may need to
7038 // update hasMoreThanOneDecl as we add the methods.
7039 addMethodsToPool(S, Visitor.getInstanceMethods(), Pos->second.first);
7040 addMethodsToPool(S, Visitor.getFactoryMethods(), Pos->second.second);
Guy Benyei11169dd2012-12-18 14:30:41 +00007041}
7042
7043void ASTReader::ReadKnownNamespaces(
7044 SmallVectorImpl<NamespaceDecl *> &Namespaces) {
7045 Namespaces.clear();
7046
7047 for (unsigned I = 0, N = KnownNamespaces.size(); I != N; ++I) {
7048 if (NamespaceDecl *Namespace
7049 = dyn_cast_or_null<NamespaceDecl>(GetDecl(KnownNamespaces[I])))
7050 Namespaces.push_back(Namespace);
7051 }
7052}
7053
Nick Lewycky9c7eb1d2013-02-01 08:13:20 +00007054void ASTReader::ReadUndefinedButUsed(
Nick Lewyckyf0f56162013-01-31 03:23:57 +00007055 llvm::DenseMap<NamedDecl*, SourceLocation> &Undefined) {
Nick Lewycky9c7eb1d2013-02-01 08:13:20 +00007056 for (unsigned Idx = 0, N = UndefinedButUsed.size(); Idx != N;) {
7057 NamedDecl *D = cast<NamedDecl>(GetDecl(UndefinedButUsed[Idx++]));
Nick Lewycky8334af82013-01-26 00:35:08 +00007058 SourceLocation Loc =
Nick Lewycky9c7eb1d2013-02-01 08:13:20 +00007059 SourceLocation::getFromRawEncoding(UndefinedButUsed[Idx++]);
Nick Lewycky8334af82013-01-26 00:35:08 +00007060 Undefined.insert(std::make_pair(D, Loc));
7061 }
7062}
Nick Lewycky8334af82013-01-26 00:35:08 +00007063
Ismail Pazarbasie5768d12015-05-18 19:59:11 +00007064void ASTReader::ReadMismatchingDeleteExpressions(llvm::MapVector<
7065 FieldDecl *, llvm::SmallVector<std::pair<SourceLocation, bool>, 4>> &
7066 Exprs) {
7067 for (unsigned Idx = 0, N = DelayedDeleteExprs.size(); Idx != N;) {
7068 FieldDecl *FD = cast<FieldDecl>(GetDecl(DelayedDeleteExprs[Idx++]));
7069 uint64_t Count = DelayedDeleteExprs[Idx++];
7070 for (uint64_t C = 0; C < Count; ++C) {
7071 SourceLocation DeleteLoc =
7072 SourceLocation::getFromRawEncoding(DelayedDeleteExprs[Idx++]);
7073 const bool IsArrayForm = DelayedDeleteExprs[Idx++];
7074 Exprs[FD].push_back(std::make_pair(DeleteLoc, IsArrayForm));
7075 }
7076 }
7077}
7078
Guy Benyei11169dd2012-12-18 14:30:41 +00007079void ASTReader::ReadTentativeDefinitions(
7080 SmallVectorImpl<VarDecl *> &TentativeDefs) {
7081 for (unsigned I = 0, N = TentativeDefinitions.size(); I != N; ++I) {
7082 VarDecl *Var = dyn_cast_or_null<VarDecl>(GetDecl(TentativeDefinitions[I]));
7083 if (Var)
7084 TentativeDefs.push_back(Var);
7085 }
7086 TentativeDefinitions.clear();
7087}
7088
7089void ASTReader::ReadUnusedFileScopedDecls(
7090 SmallVectorImpl<const DeclaratorDecl *> &Decls) {
7091 for (unsigned I = 0, N = UnusedFileScopedDecls.size(); I != N; ++I) {
7092 DeclaratorDecl *D
7093 = dyn_cast_or_null<DeclaratorDecl>(GetDecl(UnusedFileScopedDecls[I]));
7094 if (D)
7095 Decls.push_back(D);
7096 }
7097 UnusedFileScopedDecls.clear();
7098}
7099
7100void ASTReader::ReadDelegatingConstructors(
7101 SmallVectorImpl<CXXConstructorDecl *> &Decls) {
7102 for (unsigned I = 0, N = DelegatingCtorDecls.size(); I != N; ++I) {
7103 CXXConstructorDecl *D
7104 = dyn_cast_or_null<CXXConstructorDecl>(GetDecl(DelegatingCtorDecls[I]));
7105 if (D)
7106 Decls.push_back(D);
7107 }
7108 DelegatingCtorDecls.clear();
7109}
7110
7111void ASTReader::ReadExtVectorDecls(SmallVectorImpl<TypedefNameDecl *> &Decls) {
7112 for (unsigned I = 0, N = ExtVectorDecls.size(); I != N; ++I) {
7113 TypedefNameDecl *D
7114 = dyn_cast_or_null<TypedefNameDecl>(GetDecl(ExtVectorDecls[I]));
7115 if (D)
7116 Decls.push_back(D);
7117 }
7118 ExtVectorDecls.clear();
7119}
7120
Nico Weber72889432014-09-06 01:25:55 +00007121void ASTReader::ReadUnusedLocalTypedefNameCandidates(
7122 llvm::SmallSetVector<const TypedefNameDecl *, 4> &Decls) {
7123 for (unsigned I = 0, N = UnusedLocalTypedefNameCandidates.size(); I != N;
7124 ++I) {
7125 TypedefNameDecl *D = dyn_cast_or_null<TypedefNameDecl>(
7126 GetDecl(UnusedLocalTypedefNameCandidates[I]));
7127 if (D)
7128 Decls.insert(D);
7129 }
7130 UnusedLocalTypedefNameCandidates.clear();
7131}
7132
Guy Benyei11169dd2012-12-18 14:30:41 +00007133void ASTReader::ReadReferencedSelectors(
7134 SmallVectorImpl<std::pair<Selector, SourceLocation> > &Sels) {
7135 if (ReferencedSelectorsData.empty())
7136 return;
7137
7138 // If there are @selector references added them to its pool. This is for
7139 // implementation of -Wselector.
7140 unsigned int DataSize = ReferencedSelectorsData.size()-1;
7141 unsigned I = 0;
7142 while (I < DataSize) {
7143 Selector Sel = DecodeSelector(ReferencedSelectorsData[I++]);
7144 SourceLocation SelLoc
7145 = SourceLocation::getFromRawEncoding(ReferencedSelectorsData[I++]);
7146 Sels.push_back(std::make_pair(Sel, SelLoc));
7147 }
7148 ReferencedSelectorsData.clear();
7149}
7150
7151void ASTReader::ReadWeakUndeclaredIdentifiers(
7152 SmallVectorImpl<std::pair<IdentifierInfo *, WeakInfo> > &WeakIDs) {
7153 if (WeakUndeclaredIdentifiers.empty())
7154 return;
7155
7156 for (unsigned I = 0, N = WeakUndeclaredIdentifiers.size(); I < N; /*none*/) {
7157 IdentifierInfo *WeakId
7158 = DecodeIdentifierInfo(WeakUndeclaredIdentifiers[I++]);
7159 IdentifierInfo *AliasId
7160 = DecodeIdentifierInfo(WeakUndeclaredIdentifiers[I++]);
7161 SourceLocation Loc
7162 = SourceLocation::getFromRawEncoding(WeakUndeclaredIdentifiers[I++]);
7163 bool Used = WeakUndeclaredIdentifiers[I++];
7164 WeakInfo WI(AliasId, Loc);
7165 WI.setUsed(Used);
7166 WeakIDs.push_back(std::make_pair(WeakId, WI));
7167 }
7168 WeakUndeclaredIdentifiers.clear();
7169}
7170
7171void ASTReader::ReadUsedVTables(SmallVectorImpl<ExternalVTableUse> &VTables) {
7172 for (unsigned Idx = 0, N = VTableUses.size(); Idx < N; /* In loop */) {
7173 ExternalVTableUse VT;
7174 VT.Record = dyn_cast_or_null<CXXRecordDecl>(GetDecl(VTableUses[Idx++]));
7175 VT.Location = SourceLocation::getFromRawEncoding(VTableUses[Idx++]);
7176 VT.DefinitionRequired = VTableUses[Idx++];
7177 VTables.push_back(VT);
7178 }
7179
7180 VTableUses.clear();
7181}
7182
7183void ASTReader::ReadPendingInstantiations(
7184 SmallVectorImpl<std::pair<ValueDecl *, SourceLocation> > &Pending) {
7185 for (unsigned Idx = 0, N = PendingInstantiations.size(); Idx < N;) {
7186 ValueDecl *D = cast<ValueDecl>(GetDecl(PendingInstantiations[Idx++]));
7187 SourceLocation Loc
7188 = SourceLocation::getFromRawEncoding(PendingInstantiations[Idx++]);
7189
7190 Pending.push_back(std::make_pair(D, Loc));
7191 }
7192 PendingInstantiations.clear();
7193}
7194
Richard Smithe40f2ba2013-08-07 21:41:30 +00007195void ASTReader::ReadLateParsedTemplates(
Chandler Carruth52cee4d2015-03-26 09:08:15 +00007196 llvm::MapVector<const FunctionDecl *, LateParsedTemplate *> &LPTMap) {
Richard Smithe40f2ba2013-08-07 21:41:30 +00007197 for (unsigned Idx = 0, N = LateParsedTemplates.size(); Idx < N;
7198 /* In loop */) {
7199 FunctionDecl *FD = cast<FunctionDecl>(GetDecl(LateParsedTemplates[Idx++]));
7200
7201 LateParsedTemplate *LT = new LateParsedTemplate;
7202 LT->D = GetDecl(LateParsedTemplates[Idx++]);
7203
7204 ModuleFile *F = getOwningModuleFile(LT->D);
7205 assert(F && "No module");
7206
7207 unsigned TokN = LateParsedTemplates[Idx++];
7208 LT->Toks.reserve(TokN);
7209 for (unsigned T = 0; T < TokN; ++T)
7210 LT->Toks.push_back(ReadToken(*F, LateParsedTemplates, Idx));
7211
Chandler Carruth52cee4d2015-03-26 09:08:15 +00007212 LPTMap.insert(std::make_pair(FD, LT));
Richard Smithe40f2ba2013-08-07 21:41:30 +00007213 }
7214
7215 LateParsedTemplates.clear();
7216}
7217
Guy Benyei11169dd2012-12-18 14:30:41 +00007218void ASTReader::LoadSelector(Selector Sel) {
7219 // It would be complicated to avoid reading the methods anyway. So don't.
7220 ReadMethodPool(Sel);
7221}
7222
7223void ASTReader::SetIdentifierInfo(IdentifierID ID, IdentifierInfo *II) {
7224 assert(ID && "Non-zero identifier ID required");
7225 assert(ID <= IdentifiersLoaded.size() && "identifier ID out of range");
7226 IdentifiersLoaded[ID - 1] = II;
7227 if (DeserializationListener)
7228 DeserializationListener->IdentifierRead(ID, II);
7229}
7230
7231/// \brief Set the globally-visible declarations associated with the given
7232/// identifier.
7233///
7234/// If the AST reader is currently in a state where the given declaration IDs
7235/// cannot safely be resolved, they are queued until it is safe to resolve
7236/// them.
7237///
7238/// \param II an IdentifierInfo that refers to one or more globally-visible
7239/// declarations.
7240///
7241/// \param DeclIDs the set of declaration IDs with the name @p II that are
7242/// visible at global scope.
7243///
Douglas Gregor6168bd22013-02-18 15:53:43 +00007244/// \param Decls if non-null, this vector will be populated with the set of
7245/// deserialized declarations. These declarations will not be pushed into
7246/// scope.
Guy Benyei11169dd2012-12-18 14:30:41 +00007247void
7248ASTReader::SetGloballyVisibleDecls(IdentifierInfo *II,
7249 const SmallVectorImpl<uint32_t> &DeclIDs,
Douglas Gregor6168bd22013-02-18 15:53:43 +00007250 SmallVectorImpl<Decl *> *Decls) {
7251 if (NumCurrentElementsDeserializing && !Decls) {
7252 PendingIdentifierInfos[II].append(DeclIDs.begin(), DeclIDs.end());
Guy Benyei11169dd2012-12-18 14:30:41 +00007253 return;
7254 }
7255
7256 for (unsigned I = 0, N = DeclIDs.size(); I != N; ++I) {
Ben Langmuir5418f402014-09-10 21:29:41 +00007257 if (!SemaObj) {
Guy Benyei11169dd2012-12-18 14:30:41 +00007258 // Queue this declaration so that it will be added to the
7259 // translation unit scope and identifier's declaration chain
7260 // once a Sema object is known.
Ben Langmuir5418f402014-09-10 21:29:41 +00007261 PreloadedDeclIDs.push_back(DeclIDs[I]);
7262 continue;
Guy Benyei11169dd2012-12-18 14:30:41 +00007263 }
Ben Langmuir5418f402014-09-10 21:29:41 +00007264
7265 NamedDecl *D = cast<NamedDecl>(GetDecl(DeclIDs[I]));
7266
7267 // If we're simply supposed to record the declarations, do so now.
7268 if (Decls) {
7269 Decls->push_back(D);
7270 continue;
7271 }
7272
7273 // Introduce this declaration into the translation-unit scope
7274 // and add it to the declaration chain for this identifier, so
7275 // that (unqualified) name lookup will find it.
7276 pushExternalDeclIntoScope(D, II);
Guy Benyei11169dd2012-12-18 14:30:41 +00007277 }
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
Adrian Prantl15bcf702015-06-30 17:39:43 +00007398ExternalASTSource::ASTSourceDescriptor
7399ASTReader::getSourceDescriptor(const Module &M) {
7400 StringRef Dir, Filename;
7401 if (M.Directory)
7402 Dir = M.Directory->getName();
7403 if (auto *File = M.getASTFile())
7404 Filename = File->getName();
7405 return ASTReader::ASTSourceDescriptor{
7406 M.getFullModuleName(), Dir, Filename,
7407 M.Signature
7408 };
7409}
7410
7411llvm::Optional<ExternalASTSource::ASTSourceDescriptor>
7412ASTReader::getSourceDescriptor(unsigned ID) {
7413 if (const Module *M = getSubmodule(ID))
7414 return getSourceDescriptor(*M);
7415
7416 // If there is only a single PCH, return it instead.
7417 // Chained PCH are not suported.
7418 if (ModuleMgr.size() == 1) {
7419 ModuleFile &MF = ModuleMgr.getPrimaryModule();
7420 return ASTReader::ASTSourceDescriptor{
7421 MF.OriginalSourceFileName, MF.OriginalDir,
7422 MF.FileName,
7423 MF.Signature
7424 };
7425 }
7426 return None;
7427}
7428
Guy Benyei11169dd2012-12-18 14:30:41 +00007429Selector ASTReader::getLocalSelector(ModuleFile &M, unsigned LocalID) {
7430 return DecodeSelector(getGlobalSelectorID(M, LocalID));
7431}
7432
7433Selector ASTReader::DecodeSelector(serialization::SelectorID ID) {
7434 if (ID == 0)
7435 return Selector();
7436
7437 if (ID > SelectorsLoaded.size()) {
7438 Error("selector ID out of range in AST file");
7439 return Selector();
7440 }
7441
Craig Toppera13603a2014-05-22 05:54:18 +00007442 if (SelectorsLoaded[ID - 1].getAsOpaquePtr() == nullptr) {
Guy Benyei11169dd2012-12-18 14:30:41 +00007443 // Load this selector from the selector table.
7444 GlobalSelectorMapType::iterator I = GlobalSelectorMap.find(ID);
7445 assert(I != GlobalSelectorMap.end() && "Corrupted global selector map");
7446 ModuleFile &M = *I->second;
7447 ASTSelectorLookupTrait Trait(*this, M);
7448 unsigned Idx = ID - M.BaseSelectorID - NUM_PREDEF_SELECTOR_IDS;
7449 SelectorsLoaded[ID - 1] =
7450 Trait.ReadKey(M.SelectorLookupTableData + M.SelectorOffsets[Idx], 0);
7451 if (DeserializationListener)
7452 DeserializationListener->SelectorRead(ID, SelectorsLoaded[ID - 1]);
7453 }
7454
7455 return SelectorsLoaded[ID - 1];
7456}
7457
7458Selector ASTReader::GetExternalSelector(serialization::SelectorID ID) {
7459 return DecodeSelector(ID);
7460}
7461
7462uint32_t ASTReader::GetNumExternalSelectors() {
7463 // ID 0 (the null selector) is considered an external selector.
7464 return getTotalNumSelectors() + 1;
7465}
7466
7467serialization::SelectorID
7468ASTReader::getGlobalSelectorID(ModuleFile &M, unsigned LocalID) const {
7469 if (LocalID < NUM_PREDEF_SELECTOR_IDS)
7470 return LocalID;
7471
7472 ContinuousRangeMap<uint32_t, int, 2>::iterator I
7473 = M.SelectorRemap.find(LocalID - NUM_PREDEF_SELECTOR_IDS);
7474 assert(I != M.SelectorRemap.end()
7475 && "Invalid index into selector index remap");
7476
7477 return LocalID + I->second;
7478}
7479
7480DeclarationName
7481ASTReader::ReadDeclarationName(ModuleFile &F,
7482 const RecordData &Record, unsigned &Idx) {
7483 DeclarationName::NameKind Kind = (DeclarationName::NameKind)Record[Idx++];
7484 switch (Kind) {
7485 case DeclarationName::Identifier:
Douglas Gregorc8a992f2013-01-21 16:52:34 +00007486 return DeclarationName(GetIdentifierInfo(F, Record, Idx));
Guy Benyei11169dd2012-12-18 14:30:41 +00007487
7488 case DeclarationName::ObjCZeroArgSelector:
7489 case DeclarationName::ObjCOneArgSelector:
7490 case DeclarationName::ObjCMultiArgSelector:
7491 return DeclarationName(ReadSelector(F, Record, Idx));
7492
7493 case DeclarationName::CXXConstructorName:
7494 return Context.DeclarationNames.getCXXConstructorName(
7495 Context.getCanonicalType(readType(F, Record, Idx)));
7496
7497 case DeclarationName::CXXDestructorName:
7498 return Context.DeclarationNames.getCXXDestructorName(
7499 Context.getCanonicalType(readType(F, Record, Idx)));
7500
7501 case DeclarationName::CXXConversionFunctionName:
7502 return Context.DeclarationNames.getCXXConversionFunctionName(
7503 Context.getCanonicalType(readType(F, Record, Idx)));
7504
7505 case DeclarationName::CXXOperatorName:
7506 return Context.DeclarationNames.getCXXOperatorName(
7507 (OverloadedOperatorKind)Record[Idx++]);
7508
7509 case DeclarationName::CXXLiteralOperatorName:
7510 return Context.DeclarationNames.getCXXLiteralOperatorName(
7511 GetIdentifierInfo(F, Record, Idx));
7512
7513 case DeclarationName::CXXUsingDirective:
7514 return DeclarationName::getUsingDirectiveName();
7515 }
7516
7517 llvm_unreachable("Invalid NameKind!");
7518}
7519
7520void ASTReader::ReadDeclarationNameLoc(ModuleFile &F,
7521 DeclarationNameLoc &DNLoc,
7522 DeclarationName Name,
7523 const RecordData &Record, unsigned &Idx) {
7524 switch (Name.getNameKind()) {
7525 case DeclarationName::CXXConstructorName:
7526 case DeclarationName::CXXDestructorName:
7527 case DeclarationName::CXXConversionFunctionName:
7528 DNLoc.NamedType.TInfo = GetTypeSourceInfo(F, Record, Idx);
7529 break;
7530
7531 case DeclarationName::CXXOperatorName:
7532 DNLoc.CXXOperatorName.BeginOpNameLoc
7533 = ReadSourceLocation(F, Record, Idx).getRawEncoding();
7534 DNLoc.CXXOperatorName.EndOpNameLoc
7535 = ReadSourceLocation(F, Record, Idx).getRawEncoding();
7536 break;
7537
7538 case DeclarationName::CXXLiteralOperatorName:
7539 DNLoc.CXXLiteralOperatorName.OpNameLoc
7540 = ReadSourceLocation(F, Record, Idx).getRawEncoding();
7541 break;
7542
7543 case DeclarationName::Identifier:
7544 case DeclarationName::ObjCZeroArgSelector:
7545 case DeclarationName::ObjCOneArgSelector:
7546 case DeclarationName::ObjCMultiArgSelector:
7547 case DeclarationName::CXXUsingDirective:
7548 break;
7549 }
7550}
7551
7552void ASTReader::ReadDeclarationNameInfo(ModuleFile &F,
7553 DeclarationNameInfo &NameInfo,
7554 const RecordData &Record, unsigned &Idx) {
7555 NameInfo.setName(ReadDeclarationName(F, Record, Idx));
7556 NameInfo.setLoc(ReadSourceLocation(F, Record, Idx));
7557 DeclarationNameLoc DNLoc;
7558 ReadDeclarationNameLoc(F, DNLoc, NameInfo.getName(), Record, Idx);
7559 NameInfo.setInfo(DNLoc);
7560}
7561
7562void ASTReader::ReadQualifierInfo(ModuleFile &F, QualifierInfo &Info,
7563 const RecordData &Record, unsigned &Idx) {
7564 Info.QualifierLoc = ReadNestedNameSpecifierLoc(F, Record, Idx);
7565 unsigned NumTPLists = Record[Idx++];
7566 Info.NumTemplParamLists = NumTPLists;
7567 if (NumTPLists) {
7568 Info.TemplParamLists = new (Context) TemplateParameterList*[NumTPLists];
7569 for (unsigned i=0; i != NumTPLists; ++i)
7570 Info.TemplParamLists[i] = ReadTemplateParameterList(F, Record, Idx);
7571 }
7572}
7573
7574TemplateName
7575ASTReader::ReadTemplateName(ModuleFile &F, const RecordData &Record,
7576 unsigned &Idx) {
7577 TemplateName::NameKind Kind = (TemplateName::NameKind)Record[Idx++];
7578 switch (Kind) {
7579 case TemplateName::Template:
7580 return TemplateName(ReadDeclAs<TemplateDecl>(F, Record, Idx));
7581
7582 case TemplateName::OverloadedTemplate: {
7583 unsigned size = Record[Idx++];
7584 UnresolvedSet<8> Decls;
7585 while (size--)
7586 Decls.addDecl(ReadDeclAs<NamedDecl>(F, Record, Idx));
7587
7588 return Context.getOverloadedTemplateName(Decls.begin(), Decls.end());
7589 }
7590
7591 case TemplateName::QualifiedTemplate: {
7592 NestedNameSpecifier *NNS = ReadNestedNameSpecifier(F, Record, Idx);
7593 bool hasTemplKeyword = Record[Idx++];
7594 TemplateDecl *Template = ReadDeclAs<TemplateDecl>(F, Record, Idx);
7595 return Context.getQualifiedTemplateName(NNS, hasTemplKeyword, Template);
7596 }
7597
7598 case TemplateName::DependentTemplate: {
7599 NestedNameSpecifier *NNS = ReadNestedNameSpecifier(F, Record, Idx);
7600 if (Record[Idx++]) // isIdentifier
7601 return Context.getDependentTemplateName(NNS,
7602 GetIdentifierInfo(F, Record,
7603 Idx));
7604 return Context.getDependentTemplateName(NNS,
7605 (OverloadedOperatorKind)Record[Idx++]);
7606 }
7607
7608 case TemplateName::SubstTemplateTemplateParm: {
7609 TemplateTemplateParmDecl *param
7610 = ReadDeclAs<TemplateTemplateParmDecl>(F, Record, Idx);
7611 if (!param) return TemplateName();
7612 TemplateName replacement = ReadTemplateName(F, Record, Idx);
7613 return Context.getSubstTemplateTemplateParm(param, replacement);
7614 }
7615
7616 case TemplateName::SubstTemplateTemplateParmPack: {
7617 TemplateTemplateParmDecl *Param
7618 = ReadDeclAs<TemplateTemplateParmDecl>(F, Record, Idx);
7619 if (!Param)
7620 return TemplateName();
7621
7622 TemplateArgument ArgPack = ReadTemplateArgument(F, Record, Idx);
7623 if (ArgPack.getKind() != TemplateArgument::Pack)
7624 return TemplateName();
7625
7626 return Context.getSubstTemplateTemplateParmPack(Param, ArgPack);
7627 }
7628 }
7629
7630 llvm_unreachable("Unhandled template name kind!");
7631}
7632
Richard Smith2bb3c342015-08-09 01:05:31 +00007633TemplateArgument ASTReader::ReadTemplateArgument(ModuleFile &F,
7634 const RecordData &Record,
7635 unsigned &Idx,
7636 bool Canonicalize) {
7637 if (Canonicalize) {
7638 // The caller wants a canonical template argument. Sometimes the AST only
7639 // wants template arguments in canonical form (particularly as the template
7640 // argument lists of template specializations) so ensure we preserve that
7641 // canonical form across serialization.
7642 TemplateArgument Arg = ReadTemplateArgument(F, Record, Idx, false);
7643 return Context.getCanonicalTemplateArgument(Arg);
7644 }
7645
Guy Benyei11169dd2012-12-18 14:30:41 +00007646 TemplateArgument::ArgKind Kind = (TemplateArgument::ArgKind)Record[Idx++];
7647 switch (Kind) {
7648 case TemplateArgument::Null:
7649 return TemplateArgument();
7650 case TemplateArgument::Type:
7651 return TemplateArgument(readType(F, Record, Idx));
7652 case TemplateArgument::Declaration: {
7653 ValueDecl *D = ReadDeclAs<ValueDecl>(F, Record, Idx);
David Blaikie0f62c8d2014-10-16 04:21:25 +00007654 return TemplateArgument(D, readType(F, Record, Idx));
Guy Benyei11169dd2012-12-18 14:30:41 +00007655 }
7656 case TemplateArgument::NullPtr:
7657 return TemplateArgument(readType(F, Record, Idx), /*isNullPtr*/true);
7658 case TemplateArgument::Integral: {
7659 llvm::APSInt Value = ReadAPSInt(Record, Idx);
7660 QualType T = readType(F, Record, Idx);
7661 return TemplateArgument(Context, Value, T);
7662 }
7663 case TemplateArgument::Template:
7664 return TemplateArgument(ReadTemplateName(F, Record, Idx));
7665 case TemplateArgument::TemplateExpansion: {
7666 TemplateName Name = ReadTemplateName(F, Record, Idx);
David Blaikie05785d12013-02-20 22:23:23 +00007667 Optional<unsigned> NumTemplateExpansions;
Guy Benyei11169dd2012-12-18 14:30:41 +00007668 if (unsigned NumExpansions = Record[Idx++])
7669 NumTemplateExpansions = NumExpansions - 1;
7670 return TemplateArgument(Name, NumTemplateExpansions);
7671 }
7672 case TemplateArgument::Expression:
7673 return TemplateArgument(ReadExpr(F));
7674 case TemplateArgument::Pack: {
7675 unsigned NumArgs = Record[Idx++];
7676 TemplateArgument *Args = new (Context) TemplateArgument[NumArgs];
7677 for (unsigned I = 0; I != NumArgs; ++I)
7678 Args[I] = ReadTemplateArgument(F, Record, Idx);
Benjamin Kramercce63472015-08-05 09:40:22 +00007679 return TemplateArgument(llvm::makeArrayRef(Args, NumArgs));
Guy Benyei11169dd2012-12-18 14:30:41 +00007680 }
7681 }
7682
7683 llvm_unreachable("Unhandled template argument kind!");
7684}
7685
7686TemplateParameterList *
7687ASTReader::ReadTemplateParameterList(ModuleFile &F,
7688 const RecordData &Record, unsigned &Idx) {
7689 SourceLocation TemplateLoc = ReadSourceLocation(F, Record, Idx);
7690 SourceLocation LAngleLoc = ReadSourceLocation(F, Record, Idx);
7691 SourceLocation RAngleLoc = ReadSourceLocation(F, Record, Idx);
7692
7693 unsigned NumParams = Record[Idx++];
7694 SmallVector<NamedDecl *, 16> Params;
7695 Params.reserve(NumParams);
7696 while (NumParams--)
7697 Params.push_back(ReadDeclAs<NamedDecl>(F, Record, Idx));
7698
7699 TemplateParameterList* TemplateParams =
7700 TemplateParameterList::Create(Context, TemplateLoc, LAngleLoc,
7701 Params.data(), Params.size(), RAngleLoc);
7702 return TemplateParams;
7703}
7704
7705void
7706ASTReader::
Craig Topper5603df42013-07-05 19:34:19 +00007707ReadTemplateArgumentList(SmallVectorImpl<TemplateArgument> &TemplArgs,
Guy Benyei11169dd2012-12-18 14:30:41 +00007708 ModuleFile &F, const RecordData &Record,
Richard Smith2bb3c342015-08-09 01:05:31 +00007709 unsigned &Idx, bool Canonicalize) {
Guy Benyei11169dd2012-12-18 14:30:41 +00007710 unsigned NumTemplateArgs = Record[Idx++];
7711 TemplArgs.reserve(NumTemplateArgs);
7712 while (NumTemplateArgs--)
Richard Smith2bb3c342015-08-09 01:05:31 +00007713 TemplArgs.push_back(ReadTemplateArgument(F, Record, Idx, Canonicalize));
Guy Benyei11169dd2012-12-18 14:30:41 +00007714}
7715
7716/// \brief Read a UnresolvedSet structure.
Richard Smitha4ba74c2013-08-30 04:46:40 +00007717void ASTReader::ReadUnresolvedSet(ModuleFile &F, LazyASTUnresolvedSet &Set,
Guy Benyei11169dd2012-12-18 14:30:41 +00007718 const RecordData &Record, unsigned &Idx) {
7719 unsigned NumDecls = Record[Idx++];
7720 Set.reserve(Context, NumDecls);
7721 while (NumDecls--) {
Richard Smitha4ba74c2013-08-30 04:46:40 +00007722 DeclID ID = ReadDeclID(F, Record, Idx);
Guy Benyei11169dd2012-12-18 14:30:41 +00007723 AccessSpecifier AS = (AccessSpecifier)Record[Idx++];
Richard Smitha4ba74c2013-08-30 04:46:40 +00007724 Set.addLazyDecl(Context, ID, AS);
Guy Benyei11169dd2012-12-18 14:30:41 +00007725 }
7726}
7727
7728CXXBaseSpecifier
7729ASTReader::ReadCXXBaseSpecifier(ModuleFile &F,
7730 const RecordData &Record, unsigned &Idx) {
7731 bool isVirtual = static_cast<bool>(Record[Idx++]);
7732 bool isBaseOfClass = static_cast<bool>(Record[Idx++]);
7733 AccessSpecifier AS = static_cast<AccessSpecifier>(Record[Idx++]);
7734 bool inheritConstructors = static_cast<bool>(Record[Idx++]);
7735 TypeSourceInfo *TInfo = GetTypeSourceInfo(F, Record, Idx);
7736 SourceRange Range = ReadSourceRange(F, Record, Idx);
7737 SourceLocation EllipsisLoc = ReadSourceLocation(F, Record, Idx);
7738 CXXBaseSpecifier Result(Range, isVirtual, isBaseOfClass, AS, TInfo,
7739 EllipsisLoc);
7740 Result.setInheritConstructors(inheritConstructors);
7741 return Result;
7742}
7743
Richard Smithc2bb8182015-03-24 06:36:48 +00007744CXXCtorInitializer **
Guy Benyei11169dd2012-12-18 14:30:41 +00007745ASTReader::ReadCXXCtorInitializers(ModuleFile &F, const RecordData &Record,
7746 unsigned &Idx) {
Guy Benyei11169dd2012-12-18 14:30:41 +00007747 unsigned NumInitializers = Record[Idx++];
Richard Smithc2bb8182015-03-24 06:36:48 +00007748 assert(NumInitializers && "wrote ctor initializers but have no inits");
7749 auto **CtorInitializers = new (Context) CXXCtorInitializer*[NumInitializers];
7750 for (unsigned i = 0; i != NumInitializers; ++i) {
7751 TypeSourceInfo *TInfo = nullptr;
7752 bool IsBaseVirtual = false;
7753 FieldDecl *Member = nullptr;
7754 IndirectFieldDecl *IndirectMember = nullptr;
Guy Benyei11169dd2012-12-18 14:30:41 +00007755
Richard Smithc2bb8182015-03-24 06:36:48 +00007756 CtorInitializerType Type = (CtorInitializerType)Record[Idx++];
7757 switch (Type) {
7758 case CTOR_INITIALIZER_BASE:
7759 TInfo = GetTypeSourceInfo(F, Record, Idx);
7760 IsBaseVirtual = Record[Idx++];
7761 break;
Guy Benyei11169dd2012-12-18 14:30:41 +00007762
Richard Smithc2bb8182015-03-24 06:36:48 +00007763 case CTOR_INITIALIZER_DELEGATING:
7764 TInfo = GetTypeSourceInfo(F, Record, Idx);
7765 break;
Guy Benyei11169dd2012-12-18 14:30:41 +00007766
Richard Smithc2bb8182015-03-24 06:36:48 +00007767 case CTOR_INITIALIZER_MEMBER:
7768 Member = ReadDeclAs<FieldDecl>(F, Record, Idx);
7769 break;
Guy Benyei11169dd2012-12-18 14:30:41 +00007770
Richard Smithc2bb8182015-03-24 06:36:48 +00007771 case CTOR_INITIALIZER_INDIRECT_MEMBER:
7772 IndirectMember = ReadDeclAs<IndirectFieldDecl>(F, Record, Idx);
7773 break;
Guy Benyei11169dd2012-12-18 14:30:41 +00007774 }
Richard Smithc2bb8182015-03-24 06:36:48 +00007775
7776 SourceLocation MemberOrEllipsisLoc = ReadSourceLocation(F, Record, Idx);
7777 Expr *Init = ReadExpr(F);
7778 SourceLocation LParenLoc = ReadSourceLocation(F, Record, Idx);
7779 SourceLocation RParenLoc = ReadSourceLocation(F, Record, Idx);
7780 bool IsWritten = Record[Idx++];
7781 unsigned SourceOrderOrNumArrayIndices;
7782 SmallVector<VarDecl *, 8> Indices;
7783 if (IsWritten) {
7784 SourceOrderOrNumArrayIndices = Record[Idx++];
7785 } else {
7786 SourceOrderOrNumArrayIndices = Record[Idx++];
7787 Indices.reserve(SourceOrderOrNumArrayIndices);
7788 for (unsigned i=0; i != SourceOrderOrNumArrayIndices; ++i)
7789 Indices.push_back(ReadDeclAs<VarDecl>(F, Record, Idx));
7790 }
7791
7792 CXXCtorInitializer *BOMInit;
7793 if (Type == CTOR_INITIALIZER_BASE) {
7794 BOMInit = new (Context)
7795 CXXCtorInitializer(Context, TInfo, IsBaseVirtual, LParenLoc, Init,
7796 RParenLoc, MemberOrEllipsisLoc);
7797 } else if (Type == CTOR_INITIALIZER_DELEGATING) {
7798 BOMInit = new (Context)
7799 CXXCtorInitializer(Context, TInfo, LParenLoc, Init, RParenLoc);
7800 } else if (IsWritten) {
7801 if (Member)
7802 BOMInit = new (Context) CXXCtorInitializer(
7803 Context, Member, MemberOrEllipsisLoc, LParenLoc, Init, RParenLoc);
7804 else
7805 BOMInit = new (Context)
7806 CXXCtorInitializer(Context, IndirectMember, MemberOrEllipsisLoc,
7807 LParenLoc, Init, RParenLoc);
7808 } else {
7809 if (IndirectMember) {
7810 assert(Indices.empty() && "Indirect field improperly initialized");
7811 BOMInit = new (Context)
7812 CXXCtorInitializer(Context, IndirectMember, MemberOrEllipsisLoc,
7813 LParenLoc, Init, RParenLoc);
7814 } else {
7815 BOMInit = CXXCtorInitializer::Create(
7816 Context, Member, MemberOrEllipsisLoc, LParenLoc, Init, RParenLoc,
7817 Indices.data(), Indices.size());
7818 }
7819 }
7820
7821 if (IsWritten)
7822 BOMInit->setSourceOrder(SourceOrderOrNumArrayIndices);
7823 CtorInitializers[i] = BOMInit;
Guy Benyei11169dd2012-12-18 14:30:41 +00007824 }
7825
Richard Smithc2bb8182015-03-24 06:36:48 +00007826 return CtorInitializers;
Guy Benyei11169dd2012-12-18 14:30:41 +00007827}
7828
7829NestedNameSpecifier *
7830ASTReader::ReadNestedNameSpecifier(ModuleFile &F,
7831 const RecordData &Record, unsigned &Idx) {
7832 unsigned N = Record[Idx++];
Craig Toppera13603a2014-05-22 05:54:18 +00007833 NestedNameSpecifier *NNS = nullptr, *Prev = nullptr;
Guy Benyei11169dd2012-12-18 14:30:41 +00007834 for (unsigned I = 0; I != N; ++I) {
7835 NestedNameSpecifier::SpecifierKind Kind
7836 = (NestedNameSpecifier::SpecifierKind)Record[Idx++];
7837 switch (Kind) {
7838 case NestedNameSpecifier::Identifier: {
7839 IdentifierInfo *II = GetIdentifierInfo(F, Record, Idx);
7840 NNS = NestedNameSpecifier::Create(Context, Prev, II);
7841 break;
7842 }
7843
7844 case NestedNameSpecifier::Namespace: {
7845 NamespaceDecl *NS = ReadDeclAs<NamespaceDecl>(F, Record, Idx);
7846 NNS = NestedNameSpecifier::Create(Context, Prev, NS);
7847 break;
7848 }
7849
7850 case NestedNameSpecifier::NamespaceAlias: {
7851 NamespaceAliasDecl *Alias =ReadDeclAs<NamespaceAliasDecl>(F, Record, Idx);
7852 NNS = NestedNameSpecifier::Create(Context, Prev, Alias);
7853 break;
7854 }
7855
7856 case NestedNameSpecifier::TypeSpec:
7857 case NestedNameSpecifier::TypeSpecWithTemplate: {
7858 const Type *T = readType(F, Record, Idx).getTypePtrOrNull();
7859 if (!T)
Craig Toppera13603a2014-05-22 05:54:18 +00007860 return nullptr;
7861
Guy Benyei11169dd2012-12-18 14:30:41 +00007862 bool Template = Record[Idx++];
7863 NNS = NestedNameSpecifier::Create(Context, Prev, Template, T);
7864 break;
7865 }
7866
7867 case NestedNameSpecifier::Global: {
7868 NNS = NestedNameSpecifier::GlobalSpecifier(Context);
7869 // No associated value, and there can't be a prefix.
7870 break;
7871 }
Nikola Smiljanic67860242014-09-26 00:28:20 +00007872
7873 case NestedNameSpecifier::Super: {
7874 CXXRecordDecl *RD = ReadDeclAs<CXXRecordDecl>(F, Record, Idx);
7875 NNS = NestedNameSpecifier::SuperSpecifier(Context, RD);
7876 break;
7877 }
Guy Benyei11169dd2012-12-18 14:30:41 +00007878 }
7879 Prev = NNS;
7880 }
7881 return NNS;
7882}
7883
7884NestedNameSpecifierLoc
7885ASTReader::ReadNestedNameSpecifierLoc(ModuleFile &F, const RecordData &Record,
7886 unsigned &Idx) {
7887 unsigned N = Record[Idx++];
7888 NestedNameSpecifierLocBuilder Builder;
7889 for (unsigned I = 0; I != N; ++I) {
7890 NestedNameSpecifier::SpecifierKind Kind
7891 = (NestedNameSpecifier::SpecifierKind)Record[Idx++];
7892 switch (Kind) {
7893 case NestedNameSpecifier::Identifier: {
7894 IdentifierInfo *II = GetIdentifierInfo(F, Record, Idx);
7895 SourceRange Range = ReadSourceRange(F, Record, Idx);
7896 Builder.Extend(Context, II, Range.getBegin(), Range.getEnd());
7897 break;
7898 }
7899
7900 case NestedNameSpecifier::Namespace: {
7901 NamespaceDecl *NS = ReadDeclAs<NamespaceDecl>(F, Record, Idx);
7902 SourceRange Range = ReadSourceRange(F, Record, Idx);
7903 Builder.Extend(Context, NS, Range.getBegin(), Range.getEnd());
7904 break;
7905 }
7906
7907 case NestedNameSpecifier::NamespaceAlias: {
7908 NamespaceAliasDecl *Alias =ReadDeclAs<NamespaceAliasDecl>(F, Record, Idx);
7909 SourceRange Range = ReadSourceRange(F, Record, Idx);
7910 Builder.Extend(Context, Alias, Range.getBegin(), Range.getEnd());
7911 break;
7912 }
7913
7914 case NestedNameSpecifier::TypeSpec:
7915 case NestedNameSpecifier::TypeSpecWithTemplate: {
7916 bool Template = Record[Idx++];
7917 TypeSourceInfo *T = GetTypeSourceInfo(F, Record, Idx);
7918 if (!T)
7919 return NestedNameSpecifierLoc();
7920 SourceLocation ColonColonLoc = ReadSourceLocation(F, Record, Idx);
7921
7922 // FIXME: 'template' keyword location not saved anywhere, so we fake it.
7923 Builder.Extend(Context,
7924 Template? T->getTypeLoc().getBeginLoc() : SourceLocation(),
7925 T->getTypeLoc(), ColonColonLoc);
7926 break;
7927 }
7928
7929 case NestedNameSpecifier::Global: {
7930 SourceLocation ColonColonLoc = ReadSourceLocation(F, Record, Idx);
7931 Builder.MakeGlobal(Context, ColonColonLoc);
7932 break;
7933 }
Nikola Smiljanic67860242014-09-26 00:28:20 +00007934
7935 case NestedNameSpecifier::Super: {
7936 CXXRecordDecl *RD = ReadDeclAs<CXXRecordDecl>(F, Record, Idx);
7937 SourceRange Range = ReadSourceRange(F, Record, Idx);
7938 Builder.MakeSuper(Context, RD, Range.getBegin(), Range.getEnd());
7939 break;
7940 }
Guy Benyei11169dd2012-12-18 14:30:41 +00007941 }
7942 }
Nikola Smiljanic67860242014-09-26 00:28:20 +00007943
Guy Benyei11169dd2012-12-18 14:30:41 +00007944 return Builder.getWithLocInContext(Context);
7945}
7946
7947SourceRange
7948ASTReader::ReadSourceRange(ModuleFile &F, const RecordData &Record,
7949 unsigned &Idx) {
7950 SourceLocation beg = ReadSourceLocation(F, Record, Idx);
7951 SourceLocation end = ReadSourceLocation(F, Record, Idx);
7952 return SourceRange(beg, end);
7953}
7954
7955/// \brief Read an integral value
7956llvm::APInt ASTReader::ReadAPInt(const RecordData &Record, unsigned &Idx) {
7957 unsigned BitWidth = Record[Idx++];
7958 unsigned NumWords = llvm::APInt::getNumWords(BitWidth);
7959 llvm::APInt Result(BitWidth, NumWords, &Record[Idx]);
7960 Idx += NumWords;
7961 return Result;
7962}
7963
7964/// \brief Read a signed integral value
7965llvm::APSInt ASTReader::ReadAPSInt(const RecordData &Record, unsigned &Idx) {
7966 bool isUnsigned = Record[Idx++];
7967 return llvm::APSInt(ReadAPInt(Record, Idx), isUnsigned);
7968}
7969
7970/// \brief Read a floating-point value
Tim Northover178723a2013-01-22 09:46:51 +00007971llvm::APFloat ASTReader::ReadAPFloat(const RecordData &Record,
7972 const llvm::fltSemantics &Sem,
7973 unsigned &Idx) {
7974 return llvm::APFloat(Sem, ReadAPInt(Record, Idx));
Guy Benyei11169dd2012-12-18 14:30:41 +00007975}
7976
7977// \brief Read a string
7978std::string ASTReader::ReadString(const RecordData &Record, unsigned &Idx) {
7979 unsigned Len = Record[Idx++];
7980 std::string Result(Record.data() + Idx, Record.data() + Idx + Len);
7981 Idx += Len;
7982 return Result;
7983}
7984
Richard Smith7ed1bc92014-12-05 22:42:13 +00007985std::string ASTReader::ReadPath(ModuleFile &F, const RecordData &Record,
7986 unsigned &Idx) {
7987 std::string Filename = ReadString(Record, Idx);
7988 ResolveImportedPath(F, Filename);
7989 return Filename;
7990}
7991
Guy Benyei11169dd2012-12-18 14:30:41 +00007992VersionTuple ASTReader::ReadVersionTuple(const RecordData &Record,
7993 unsigned &Idx) {
7994 unsigned Major = Record[Idx++];
7995 unsigned Minor = Record[Idx++];
7996 unsigned Subminor = Record[Idx++];
7997 if (Minor == 0)
7998 return VersionTuple(Major);
7999 if (Subminor == 0)
8000 return VersionTuple(Major, Minor - 1);
8001 return VersionTuple(Major, Minor - 1, Subminor - 1);
8002}
8003
8004CXXTemporary *ASTReader::ReadCXXTemporary(ModuleFile &F,
8005 const RecordData &Record,
8006 unsigned &Idx) {
8007 CXXDestructorDecl *Decl = ReadDeclAs<CXXDestructorDecl>(F, Record, Idx);
8008 return CXXTemporary::Create(Context, Decl);
8009}
8010
8011DiagnosticBuilder ASTReader::Diag(unsigned DiagID) {
Argyrios Kyrtzidisdc9fdaf2013-05-24 05:44:08 +00008012 return Diag(CurrentImportLoc, DiagID);
Guy Benyei11169dd2012-12-18 14:30:41 +00008013}
8014
8015DiagnosticBuilder ASTReader::Diag(SourceLocation Loc, unsigned DiagID) {
8016 return Diags.Report(Loc, DiagID);
8017}
8018
8019/// \brief Retrieve the identifier table associated with the
8020/// preprocessor.
8021IdentifierTable &ASTReader::getIdentifierTable() {
8022 return PP.getIdentifierTable();
8023}
8024
8025/// \brief Record that the given ID maps to the given switch-case
8026/// statement.
8027void ASTReader::RecordSwitchCaseID(SwitchCase *SC, unsigned ID) {
Craig Toppera13603a2014-05-22 05:54:18 +00008028 assert((*CurrSwitchCaseStmts)[ID] == nullptr &&
Guy Benyei11169dd2012-12-18 14:30:41 +00008029 "Already have a SwitchCase with this ID");
8030 (*CurrSwitchCaseStmts)[ID] = SC;
8031}
8032
8033/// \brief Retrieve the switch-case statement with the given ID.
8034SwitchCase *ASTReader::getSwitchCaseWithID(unsigned ID) {
Craig Toppera13603a2014-05-22 05:54:18 +00008035 assert((*CurrSwitchCaseStmts)[ID] != nullptr && "No SwitchCase with this ID");
Guy Benyei11169dd2012-12-18 14:30:41 +00008036 return (*CurrSwitchCaseStmts)[ID];
8037}
8038
8039void ASTReader::ClearSwitchCaseIDs() {
8040 CurrSwitchCaseStmts->clear();
8041}
8042
8043void ASTReader::ReadComments() {
8044 std::vector<RawComment *> Comments;
Chris Lattner7fb3bef2013-01-20 00:56:42 +00008045 for (SmallVectorImpl<std::pair<BitstreamCursor,
Guy Benyei11169dd2012-12-18 14:30:41 +00008046 serialization::ModuleFile *> >::iterator
8047 I = CommentsCursors.begin(),
8048 E = CommentsCursors.end();
8049 I != E; ++I) {
Dmitri Gribenko9ee0e302014-03-27 15:40:39 +00008050 Comments.clear();
Chris Lattner7fb3bef2013-01-20 00:56:42 +00008051 BitstreamCursor &Cursor = I->first;
Guy Benyei11169dd2012-12-18 14:30:41 +00008052 serialization::ModuleFile &F = *I->second;
8053 SavedStreamPosition SavedPosition(Cursor);
8054
8055 RecordData Record;
8056 while (true) {
Chris Lattner7fb3bef2013-01-20 00:56:42 +00008057 llvm::BitstreamEntry Entry =
8058 Cursor.advanceSkippingSubblocks(BitstreamCursor::AF_DontPopBlockAtEnd);
Dmitri Gribenko9ee0e302014-03-27 15:40:39 +00008059
Chris Lattner7fb3bef2013-01-20 00:56:42 +00008060 switch (Entry.Kind) {
8061 case llvm::BitstreamEntry::SubBlock: // Handled for us already.
8062 case llvm::BitstreamEntry::Error:
8063 Error("malformed block record in AST file");
8064 return;
8065 case llvm::BitstreamEntry::EndBlock:
8066 goto NextCursor;
8067 case llvm::BitstreamEntry::Record:
8068 // The interesting case.
Guy Benyei11169dd2012-12-18 14:30:41 +00008069 break;
Guy Benyei11169dd2012-12-18 14:30:41 +00008070 }
8071
8072 // Read a record.
8073 Record.clear();
Chris Lattner0e6c9402013-01-20 02:38:54 +00008074 switch ((CommentRecordTypes)Cursor.readRecord(Entry.ID, Record)) {
Guy Benyei11169dd2012-12-18 14:30:41 +00008075 case COMMENTS_RAW_COMMENT: {
8076 unsigned Idx = 0;
8077 SourceRange SR = ReadSourceRange(F, Record, Idx);
8078 RawComment::CommentKind Kind =
8079 (RawComment::CommentKind) Record[Idx++];
8080 bool IsTrailingComment = Record[Idx++];
8081 bool IsAlmostTrailingComment = Record[Idx++];
Dmitri Gribenkoa7d16ce2013-04-10 15:35:17 +00008082 Comments.push_back(new (Context) RawComment(
8083 SR, Kind, IsTrailingComment, IsAlmostTrailingComment,
8084 Context.getLangOpts().CommentOpts.ParseAllComments));
Guy Benyei11169dd2012-12-18 14:30:41 +00008085 break;
8086 }
8087 }
8088 }
Dmitri Gribenko9ee0e302014-03-27 15:40:39 +00008089 NextCursor:
8090 Context.Comments.addDeserializedComments(Comments);
Guy Benyei11169dd2012-12-18 14:30:41 +00008091 }
Guy Benyei11169dd2012-12-18 14:30:41 +00008092}
8093
Richard Smithcd45dbc2014-04-19 03:48:30 +00008094std::string ASTReader::getOwningModuleNameForDiagnostic(const Decl *D) {
8095 // If we know the owning module, use it.
Richard Smith42413142015-05-15 20:05:43 +00008096 if (Module *M = D->getImportedOwningModule())
Richard Smithcd45dbc2014-04-19 03:48:30 +00008097 return M->getFullModuleName();
8098
8099 // Otherwise, use the name of the top-level module the decl is within.
8100 if (ModuleFile *M = getOwningModuleFile(D))
8101 return M->ModuleName;
8102
8103 // Not from a module.
8104 return "";
8105}
8106
Guy Benyei11169dd2012-12-18 14:30:41 +00008107void ASTReader::finishPendingActions() {
Richard Smith851072e2014-05-19 20:59:20 +00008108 while (!PendingIdentifierInfos.empty() ||
8109 !PendingIncompleteDeclChains.empty() || !PendingDeclChains.empty() ||
Richard Smith2b9e3e32013-10-18 06:05:18 +00008110 !PendingMacroIDs.empty() || !PendingDeclContextInfos.empty() ||
Richard Smitha0ce9c42014-07-29 23:23:27 +00008111 !PendingUpdateRecords.empty()) {
Guy Benyei11169dd2012-12-18 14:30:41 +00008112 // If any identifiers with corresponding top-level declarations have
8113 // been loaded, load those declarations now.
Craig Topper79be4cd2013-07-05 04:33:53 +00008114 typedef llvm::DenseMap<IdentifierInfo *, SmallVector<Decl *, 2> >
8115 TopLevelDeclsMap;
8116 TopLevelDeclsMap TopLevelDecls;
8117
Guy Benyei11169dd2012-12-18 14:30:41 +00008118 while (!PendingIdentifierInfos.empty()) {
Douglas Gregor6168bd22013-02-18 15:53:43 +00008119 IdentifierInfo *II = PendingIdentifierInfos.back().first;
Richard Smithf0ae3c2d2014-03-28 17:31:23 +00008120 SmallVector<uint32_t, 4> DeclIDs =
8121 std::move(PendingIdentifierInfos.back().second);
Douglas Gregorcb15f082013-02-19 18:26:28 +00008122 PendingIdentifierInfos.pop_back();
Douglas Gregor6168bd22013-02-18 15:53:43 +00008123
8124 SetGloballyVisibleDecls(II, DeclIDs, &TopLevelDecls[II]);
Guy Benyei11169dd2012-12-18 14:30:41 +00008125 }
Richard Smithf0ae3c2d2014-03-28 17:31:23 +00008126
Richard Smith851072e2014-05-19 20:59:20 +00008127 // For each decl chain that we wanted to complete while deserializing, mark
8128 // it as "still needs to be completed".
8129 for (unsigned I = 0; I != PendingIncompleteDeclChains.size(); ++I) {
8130 markIncompleteDeclChain(PendingIncompleteDeclChains[I]);
8131 }
8132 PendingIncompleteDeclChains.clear();
8133
Guy Benyei11169dd2012-12-18 14:30:41 +00008134 // Load pending declaration chains.
Richard Smithd8a83712015-08-22 01:47:18 +00008135 for (unsigned I = 0; I != PendingDeclChains.size(); ++I)
Richard Smithd61d4ac2015-08-22 20:13:39 +00008136 loadPendingDeclChain(PendingDeclChains[I].first, PendingDeclChains[I].second);
Guy Benyei11169dd2012-12-18 14:30:41 +00008137 PendingDeclChains.clear();
8138
Douglas Gregor6168bd22013-02-18 15:53:43 +00008139 // Make the most recent of the top-level declarations visible.
Craig Topper79be4cd2013-07-05 04:33:53 +00008140 for (TopLevelDeclsMap::iterator TLD = TopLevelDecls.begin(),
8141 TLDEnd = TopLevelDecls.end(); TLD != TLDEnd; ++TLD) {
Douglas Gregor6168bd22013-02-18 15:53:43 +00008142 IdentifierInfo *II = TLD->first;
8143 for (unsigned I = 0, N = TLD->second.size(); I != N; ++I) {
Argyrios Kyrtzidise5edbf92013-04-26 21:33:35 +00008144 pushExternalDeclIntoScope(cast<NamedDecl>(TLD->second[I]), II);
Douglas Gregor6168bd22013-02-18 15:53:43 +00008145 }
8146 }
8147
Guy Benyei11169dd2012-12-18 14:30:41 +00008148 // Load any pending macro definitions.
8149 for (unsigned I = 0; I != PendingMacroIDs.size(); ++I) {
Argyrios Kyrtzidiseb663da2013-03-22 21:12:57 +00008150 IdentifierInfo *II = PendingMacroIDs.begin()[I].first;
8151 SmallVector<PendingMacroInfo, 2> GlobalIDs;
8152 GlobalIDs.swap(PendingMacroIDs.begin()[I].second);
8153 // Initialize the macro history from chained-PCHs ahead of module imports.
Richard Smith49f906a2014-03-01 00:08:04 +00008154 for (unsigned IDIdx = 0, NumIDs = GlobalIDs.size(); IDIdx != NumIDs;
Argyrios Kyrtzidis719736c2013-01-19 03:14:56 +00008155 ++IDIdx) {
Argyrios Kyrtzidiseb663da2013-03-22 21:12:57 +00008156 const PendingMacroInfo &Info = GlobalIDs[IDIdx];
Richard Smithe842a472014-10-22 02:05:46 +00008157 if (Info.M->Kind != MK_ImplicitModule &&
8158 Info.M->Kind != MK_ExplicitModule)
Argyrios Kyrtzidiseb663da2013-03-22 21:12:57 +00008159 resolvePendingMacro(II, Info);
8160 }
8161 // Handle module imports.
Richard Smith49f906a2014-03-01 00:08:04 +00008162 for (unsigned IDIdx = 0, NumIDs = GlobalIDs.size(); IDIdx != NumIDs;
Argyrios Kyrtzidiseb663da2013-03-22 21:12:57 +00008163 ++IDIdx) {
8164 const PendingMacroInfo &Info = GlobalIDs[IDIdx];
Richard Smithe842a472014-10-22 02:05:46 +00008165 if (Info.M->Kind == MK_ImplicitModule ||
8166 Info.M->Kind == MK_ExplicitModule)
Argyrios Kyrtzidiseb663da2013-03-22 21:12:57 +00008167 resolvePendingMacro(II, Info);
Guy Benyei11169dd2012-12-18 14:30:41 +00008168 }
8169 }
8170 PendingMacroIDs.clear();
Argyrios Kyrtzidis83a6e3b2013-02-16 00:48:59 +00008171
8172 // Wire up the DeclContexts for Decls that we delayed setting until
8173 // recursive loading is completed.
8174 while (!PendingDeclContextInfos.empty()) {
8175 PendingDeclContextInfo Info = PendingDeclContextInfos.front();
8176 PendingDeclContextInfos.pop_front();
8177 DeclContext *SemaDC = cast<DeclContext>(GetDecl(Info.SemaDC));
8178 DeclContext *LexicalDC = cast<DeclContext>(GetDecl(Info.LexicalDC));
8179 Info.D->setDeclContextsImpl(SemaDC, LexicalDC, getContext());
8180 }
Richard Smith2b9e3e32013-10-18 06:05:18 +00008181
Richard Smithd1c46742014-04-30 02:24:17 +00008182 // Perform any pending declaration updates.
Richard Smithd6db68c2014-08-07 20:58:41 +00008183 while (!PendingUpdateRecords.empty()) {
Richard Smithd1c46742014-04-30 02:24:17 +00008184 auto Update = PendingUpdateRecords.pop_back_val();
8185 ReadingKindTracker ReadingKind(Read_Decl, *this);
8186 loadDeclUpdateRecords(Update.first, Update.second);
8187 }
Guy Benyei11169dd2012-12-18 14:30:41 +00008188 }
Richard Smith8a639892015-01-24 01:07:20 +00008189
8190 // At this point, all update records for loaded decls are in place, so any
8191 // fake class definitions should have become real.
8192 assert(PendingFakeDefinitionData.empty() &&
8193 "faked up a class definition but never saw the real one");
8194
Guy Benyei11169dd2012-12-18 14:30:41 +00008195 // If we deserialized any C++ or Objective-C class definitions, any
8196 // Objective-C protocol definitions, or any redeclarable templates, make sure
8197 // that all redeclarations point to the definitions. Note that this can only
8198 // happen now, after the redeclaration chains have been fully wired.
Craig Topperc6914d02014-08-25 04:15:02 +00008199 for (Decl *D : PendingDefinitions) {
8200 if (TagDecl *TD = dyn_cast<TagDecl>(D)) {
Richard Smith5b21db82014-04-23 18:20:42 +00008201 if (const TagType *TagT = dyn_cast<TagType>(TD->getTypeForDecl())) {
Guy Benyei11169dd2012-12-18 14:30:41 +00008202 // Make sure that the TagType points at the definition.
8203 const_cast<TagType*>(TagT)->decl = TD;
8204 }
Richard Smith8ce51082015-03-11 01:44:51 +00008205
Craig Topperc6914d02014-08-25 04:15:02 +00008206 if (auto RD = dyn_cast<CXXRecordDecl>(D)) {
Richard Smith8ce51082015-03-11 01:44:51 +00008207 for (auto *R = getMostRecentExistingDecl(RD); R;
8208 R = R->getPreviousDecl()) {
8209 assert((R == D) ==
8210 cast<CXXRecordDecl>(R)->isThisDeclarationADefinition() &&
Richard Smith2c381642014-08-27 23:11:59 +00008211 "declaration thinks it's the definition but it isn't");
Aaron Ballman86c93902014-03-06 23:45:36 +00008212 cast<CXXRecordDecl>(R)->DefinitionData = RD->DefinitionData;
Richard Smith2c381642014-08-27 23:11:59 +00008213 }
Guy Benyei11169dd2012-12-18 14:30:41 +00008214 }
8215
8216 continue;
8217 }
Richard Smith8ce51082015-03-11 01:44:51 +00008218
Craig Topperc6914d02014-08-25 04:15:02 +00008219 if (auto ID = dyn_cast<ObjCInterfaceDecl>(D)) {
Guy Benyei11169dd2012-12-18 14:30:41 +00008220 // Make sure that the ObjCInterfaceType points at the definition.
8221 const_cast<ObjCInterfaceType *>(cast<ObjCInterfaceType>(ID->TypeForDecl))
8222 ->Decl = ID;
Richard Smith8ce51082015-03-11 01:44:51 +00008223
8224 for (auto *R = getMostRecentExistingDecl(ID); R; R = R->getPreviousDecl())
8225 cast<ObjCInterfaceDecl>(R)->Data = ID->Data;
8226
Guy Benyei11169dd2012-12-18 14:30:41 +00008227 continue;
8228 }
Richard Smith8ce51082015-03-11 01:44:51 +00008229
Craig Topperc6914d02014-08-25 04:15:02 +00008230 if (auto PD = dyn_cast<ObjCProtocolDecl>(D)) {
Richard Smith8ce51082015-03-11 01:44:51 +00008231 for (auto *R = getMostRecentExistingDecl(PD); R; R = R->getPreviousDecl())
8232 cast<ObjCProtocolDecl>(R)->Data = PD->Data;
8233
Guy Benyei11169dd2012-12-18 14:30:41 +00008234 continue;
8235 }
Richard Smith8ce51082015-03-11 01:44:51 +00008236
Craig Topperc6914d02014-08-25 04:15:02 +00008237 auto RTD = cast<RedeclarableTemplateDecl>(D)->getCanonicalDecl();
Richard Smith8ce51082015-03-11 01:44:51 +00008238 for (auto *R = getMostRecentExistingDecl(RTD); R; R = R->getPreviousDecl())
8239 cast<RedeclarableTemplateDecl>(R)->Common = RTD->Common;
Guy Benyei11169dd2012-12-18 14:30:41 +00008240 }
8241 PendingDefinitions.clear();
8242
8243 // Load the bodies of any functions or methods we've encountered. We do
8244 // this now (delayed) so that we can be sure that the declaration chains
Richard Smithb9fa9962015-08-21 03:04:33 +00008245 // have been fully wired up (hasBody relies on this).
8246 // FIXME: We shouldn't require complete redeclaration chains here.
Guy Benyei11169dd2012-12-18 14:30:41 +00008247 for (PendingBodiesMap::iterator PB = PendingBodies.begin(),
8248 PBEnd = PendingBodies.end();
8249 PB != PBEnd; ++PB) {
8250 if (FunctionDecl *FD = dyn_cast<FunctionDecl>(PB->first)) {
8251 // FIXME: Check for =delete/=default?
8252 // FIXME: Complain about ODR violations here?
8253 if (!getContext().getLangOpts().Modules || !FD->hasBody())
8254 FD->setLazyBody(PB->second);
8255 continue;
8256 }
8257
8258 ObjCMethodDecl *MD = cast<ObjCMethodDecl>(PB->first);
8259 if (!getContext().getLangOpts().Modules || !MD->hasBody())
8260 MD->setLazyBody(PB->second);
8261 }
8262 PendingBodies.clear();
Richard Smith42413142015-05-15 20:05:43 +00008263
8264 // Do some cleanup.
8265 for (auto *ND : PendingMergedDefinitionsToDeduplicate)
8266 getContext().deduplicateMergedDefinitonsFor(ND);
8267 PendingMergedDefinitionsToDeduplicate.clear();
Richard Smitha0ce9c42014-07-29 23:23:27 +00008268}
8269
8270void ASTReader::diagnoseOdrViolations() {
Richard Smithbb853c72014-08-13 01:23:33 +00008271 if (PendingOdrMergeFailures.empty() && PendingOdrMergeChecks.empty())
8272 return;
8273
Richard Smitha0ce9c42014-07-29 23:23:27 +00008274 // Trigger the import of the full definition of each class that had any
8275 // odr-merging problems, so we can produce better diagnostics for them.
Richard Smithbb853c72014-08-13 01:23:33 +00008276 // These updates may in turn find and diagnose some ODR failures, so take
8277 // ownership of the set first.
8278 auto OdrMergeFailures = std::move(PendingOdrMergeFailures);
8279 PendingOdrMergeFailures.clear();
8280 for (auto &Merge : OdrMergeFailures) {
Richard Smitha0ce9c42014-07-29 23:23:27 +00008281 Merge.first->buildLookup();
8282 Merge.first->decls_begin();
8283 Merge.first->bases_begin();
8284 Merge.first->vbases_begin();
8285 for (auto *RD : Merge.second) {
8286 RD->decls_begin();
8287 RD->bases_begin();
8288 RD->vbases_begin();
8289 }
8290 }
8291
8292 // For each declaration from a merged context, check that the canonical
8293 // definition of that context also contains a declaration of the same
8294 // entity.
8295 //
8296 // Caution: this loop does things that might invalidate iterators into
8297 // PendingOdrMergeChecks. Don't turn this into a range-based for loop!
8298 while (!PendingOdrMergeChecks.empty()) {
8299 NamedDecl *D = PendingOdrMergeChecks.pop_back_val();
8300
8301 // FIXME: Skip over implicit declarations for now. This matters for things
8302 // like implicitly-declared special member functions. This isn't entirely
8303 // correct; we can end up with multiple unmerged declarations of the same
8304 // implicit entity.
8305 if (D->isImplicit())
8306 continue;
8307
8308 DeclContext *CanonDef = D->getDeclContext();
Richard Smitha0ce9c42014-07-29 23:23:27 +00008309
8310 bool Found = false;
8311 const Decl *DCanon = D->getCanonicalDecl();
8312
Richard Smith01bdb7a2014-08-28 05:44:07 +00008313 for (auto RI : D->redecls()) {
8314 if (RI->getLexicalDeclContext() == CanonDef) {
8315 Found = true;
8316 break;
8317 }
8318 }
8319 if (Found)
8320 continue;
8321
Richard Smith0f4e2c42015-08-06 04:23:48 +00008322 // Quick check failed, time to do the slow thing. Note, we can't just
8323 // look up the name of D in CanonDef here, because the member that is
8324 // in CanonDef might not be found by name lookup (it might have been
8325 // replaced by a more recent declaration in the lookup table), and we
8326 // can't necessarily find it in the redeclaration chain because it might
8327 // be merely mergeable, not redeclarable.
Richard Smitha0ce9c42014-07-29 23:23:27 +00008328 llvm::SmallVector<const NamedDecl*, 4> Candidates;
Richard Smith0f4e2c42015-08-06 04:23:48 +00008329 for (auto *CanonMember : CanonDef->decls()) {
8330 if (CanonMember->getCanonicalDecl() == DCanon) {
8331 // This can happen if the declaration is merely mergeable and not
8332 // actually redeclarable (we looked for redeclarations earlier).
8333 //
8334 // FIXME: We should be able to detect this more efficiently, without
8335 // pulling in all of the members of CanonDef.
8336 Found = true;
8337 break;
Richard Smitha0ce9c42014-07-29 23:23:27 +00008338 }
Richard Smith0f4e2c42015-08-06 04:23:48 +00008339 if (auto *ND = dyn_cast<NamedDecl>(CanonMember))
8340 if (ND->getDeclName() == D->getDeclName())
8341 Candidates.push_back(ND);
Richard Smitha0ce9c42014-07-29 23:23:27 +00008342 }
8343
8344 if (!Found) {
Richard Smithd08aeb62014-08-28 01:33:39 +00008345 // The AST doesn't like TagDecls becoming invalid after they've been
8346 // completed. We only really need to mark FieldDecls as invalid here.
8347 if (!isa<TagDecl>(D))
8348 D->setInvalidDecl();
Richard Smith4ab3dbd2015-02-13 22:43:51 +00008349
8350 // Ensure we don't accidentally recursively enter deserialization while
8351 // we're producing our diagnostic.
8352 Deserializing RecursionGuard(this);
Richard Smitha0ce9c42014-07-29 23:23:27 +00008353
8354 std::string CanonDefModule =
8355 getOwningModuleNameForDiagnostic(cast<Decl>(CanonDef));
8356 Diag(D->getLocation(), diag::err_module_odr_violation_missing_decl)
8357 << D << getOwningModuleNameForDiagnostic(D)
8358 << CanonDef << CanonDefModule.empty() << CanonDefModule;
8359
8360 if (Candidates.empty())
8361 Diag(cast<Decl>(CanonDef)->getLocation(),
8362 diag::note_module_odr_violation_no_possible_decls) << D;
8363 else {
8364 for (unsigned I = 0, N = Candidates.size(); I != N; ++I)
8365 Diag(Candidates[I]->getLocation(),
8366 diag::note_module_odr_violation_possible_decl)
8367 << Candidates[I];
8368 }
8369
8370 DiagnosedOdrMergeFailures.insert(CanonDef);
8371 }
8372 }
Richard Smithcd45dbc2014-04-19 03:48:30 +00008373
Richard Smith4ab3dbd2015-02-13 22:43:51 +00008374 if (OdrMergeFailures.empty())
8375 return;
8376
8377 // Ensure we don't accidentally recursively enter deserialization while
8378 // we're producing our diagnostics.
8379 Deserializing RecursionGuard(this);
8380
Richard Smithcd45dbc2014-04-19 03:48:30 +00008381 // Issue any pending ODR-failure diagnostics.
Richard Smithbb853c72014-08-13 01:23:33 +00008382 for (auto &Merge : OdrMergeFailures) {
Richard Smitha0ce9c42014-07-29 23:23:27 +00008383 // If we've already pointed out a specific problem with this class, don't
8384 // bother issuing a general "something's different" diagnostic.
David Blaikie82e95a32014-11-19 07:49:47 +00008385 if (!DiagnosedOdrMergeFailures.insert(Merge.first).second)
Richard Smithcd45dbc2014-04-19 03:48:30 +00008386 continue;
8387
8388 bool Diagnosed = false;
8389 for (auto *RD : Merge.second) {
8390 // Multiple different declarations got merged together; tell the user
8391 // where they came from.
8392 if (Merge.first != RD) {
8393 // FIXME: Walk the definition, figure out what's different,
8394 // and diagnose that.
8395 if (!Diagnosed) {
8396 std::string Module = getOwningModuleNameForDiagnostic(Merge.first);
8397 Diag(Merge.first->getLocation(),
8398 diag::err_module_odr_violation_different_definitions)
8399 << Merge.first << Module.empty() << Module;
8400 Diagnosed = true;
8401 }
8402
8403 Diag(RD->getLocation(),
8404 diag::note_module_odr_violation_different_definitions)
8405 << getOwningModuleNameForDiagnostic(RD);
8406 }
8407 }
8408
8409 if (!Diagnosed) {
8410 // All definitions are updates to the same declaration. This happens if a
8411 // module instantiates the declaration of a class template specialization
8412 // and two or more other modules instantiate its definition.
8413 //
8414 // FIXME: Indicate which modules had instantiations of this definition.
8415 // FIXME: How can this even happen?
8416 Diag(Merge.first->getLocation(),
8417 diag::err_module_odr_violation_different_instantiations)
8418 << Merge.first;
8419 }
8420 }
Guy Benyei11169dd2012-12-18 14:30:41 +00008421}
8422
Richard Smithce18a182015-07-14 00:26:00 +00008423void ASTReader::StartedDeserializing() {
8424 if (++NumCurrentElementsDeserializing == 1 && ReadTimer.get())
8425 ReadTimer->startTimer();
8426}
8427
Guy Benyei11169dd2012-12-18 14:30:41 +00008428void ASTReader::FinishedDeserializing() {
8429 assert(NumCurrentElementsDeserializing &&
8430 "FinishedDeserializing not paired with StartedDeserializing");
8431 if (NumCurrentElementsDeserializing == 1) {
8432 // We decrease NumCurrentElementsDeserializing only after pending actions
8433 // are finished, to avoid recursively re-calling finishPendingActions().
8434 finishPendingActions();
8435 }
8436 --NumCurrentElementsDeserializing;
8437
Richard Smitha0ce9c42014-07-29 23:23:27 +00008438 if (NumCurrentElementsDeserializing == 0) {
Richard Smith9e2341d2015-03-23 03:25:59 +00008439 // Propagate exception specification updates along redeclaration chains.
Richard Smith7226f2a2015-03-23 19:54:56 +00008440 while (!PendingExceptionSpecUpdates.empty()) {
8441 auto Updates = std::move(PendingExceptionSpecUpdates);
8442 PendingExceptionSpecUpdates.clear();
8443 for (auto Update : Updates) {
8444 auto *FPT = Update.second->getType()->castAs<FunctionProtoType>();
Richard Smith1d0f1992015-08-19 21:09:32 +00008445 auto ESI = FPT->getExtProtoInfo().ExceptionSpec;
8446 for (auto *Redecl : Update.second->redecls())
8447 Context.adjustExceptionSpec(cast<FunctionDecl>(Redecl), ESI);
Richard Smith7226f2a2015-03-23 19:54:56 +00008448 }
Richard Smith9e2341d2015-03-23 03:25:59 +00008449 }
8450
Richard Smithce18a182015-07-14 00:26:00 +00008451 if (ReadTimer)
8452 ReadTimer->stopTimer();
8453
Richard Smith0f4e2c42015-08-06 04:23:48 +00008454 diagnoseOdrViolations();
8455
Richard Smith04d05b52014-03-23 00:27:18 +00008456 // We are not in recursive loading, so it's safe to pass the "interesting"
8457 // decls to the consumer.
Richard Smitha0ce9c42014-07-29 23:23:27 +00008458 if (Consumer)
8459 PassInterestingDeclsToConsumer();
Guy Benyei11169dd2012-12-18 14:30:41 +00008460 }
8461}
8462
Argyrios Kyrtzidise5edbf92013-04-26 21:33:35 +00008463void ASTReader::pushExternalDeclIntoScope(NamedDecl *D, DeclarationName Name) {
Richard Smith9e2341d2015-03-23 03:25:59 +00008464 if (IdentifierInfo *II = Name.getAsIdentifierInfo()) {
8465 // Remove any fake results before adding any real ones.
8466 auto It = PendingFakeLookupResults.find(II);
8467 if (It != PendingFakeLookupResults.end()) {
Richard Smitha534a312015-07-21 23:54:07 +00008468 for (auto *ND : It->second)
Richard Smith9e2341d2015-03-23 03:25:59 +00008469 SemaObj->IdResolver.RemoveDecl(ND);
Ben Langmuireb8bd2d2015-04-10 22:25:42 +00008470 // FIXME: this works around module+PCH performance issue.
8471 // Rather than erase the result from the map, which is O(n), just clear
8472 // the vector of NamedDecls.
8473 It->second.clear();
Richard Smith9e2341d2015-03-23 03:25:59 +00008474 }
8475 }
Argyrios Kyrtzidise5edbf92013-04-26 21:33:35 +00008476
8477 if (SemaObj->IdResolver.tryAddTopLevelDecl(D, Name) && SemaObj->TUScope) {
8478 SemaObj->TUScope->AddDecl(D);
8479 } else if (SemaObj->TUScope) {
8480 // Adding the decl to IdResolver may have failed because it was already in
8481 // (even though it was not added in scope). If it is already in, make sure
8482 // it gets in the scope as well.
8483 if (std::find(SemaObj->IdResolver.begin(Name),
8484 SemaObj->IdResolver.end(), D) != SemaObj->IdResolver.end())
8485 SemaObj->TUScope->AddDecl(D);
8486 }
8487}
8488
Adrian Prantlbb165fb2015-06-20 18:53:08 +00008489ASTReader::ASTReader(Preprocessor &PP, ASTContext &Context,
Adrian Prantlfb2398d2015-07-17 01:19:54 +00008490 const PCHContainerReader &PCHContainerRdr,
Adrian Prantlbb165fb2015-06-20 18:53:08 +00008491 StringRef isysroot, bool DisableValidation,
8492 bool AllowASTWithCompilerErrors,
Nico Weber824285e2014-05-08 04:26:47 +00008493 bool AllowConfigurationMismatch, bool ValidateSystemInputs,
Richard Smithce18a182015-07-14 00:26:00 +00008494 bool UseGlobalIndex,
8495 std::unique_ptr<llvm::Timer> ReadTimer)
Craig Toppera13603a2014-05-22 05:54:18 +00008496 : Listener(new PCHValidator(PP, *this)), DeserializationListener(nullptr),
Nico Weber824285e2014-05-08 04:26:47 +00008497 OwnsDeserializationListener(false), SourceMgr(PP.getSourceManager()),
Adrian Prantlfb2398d2015-07-17 01:19:54 +00008498 FileMgr(PP.getFileManager()), PCHContainerRdr(PCHContainerRdr),
Adrian Prantlbb165fb2015-06-20 18:53:08 +00008499 Diags(PP.getDiagnostics()), SemaObj(nullptr), PP(PP), Context(Context),
Adrian Prantlfb2398d2015-07-17 01:19:54 +00008500 Consumer(nullptr), ModuleMgr(PP.getFileManager(), PCHContainerRdr),
Richard Smithce18a182015-07-14 00:26:00 +00008501 ReadTimer(std::move(ReadTimer)),
Adrian Prantlbb165fb2015-06-20 18:53:08 +00008502 isysroot(isysroot), DisableValidation(DisableValidation),
Nico Weber824285e2014-05-08 04:26:47 +00008503 AllowASTWithCompilerErrors(AllowASTWithCompilerErrors),
8504 AllowConfigurationMismatch(AllowConfigurationMismatch),
8505 ValidateSystemInputs(ValidateSystemInputs),
8506 UseGlobalIndex(UseGlobalIndex), TriedLoadingGlobalIndex(false),
Adrian Prantlbb165fb2015-06-20 18:53:08 +00008507 CurrSwitchCaseStmts(&SwitchCaseStmts), NumSLocEntriesRead(0),
8508 TotalNumSLocEntries(0), NumStatementsRead(0), TotalNumStatements(0),
8509 NumMacrosRead(0), TotalNumMacros(0), NumIdentifierLookups(0),
8510 NumIdentifierLookupHits(0), NumSelectorsRead(0),
Nico Weber824285e2014-05-08 04:26:47 +00008511 NumMethodPoolEntriesRead(0), NumMethodPoolLookups(0),
8512 NumMethodPoolHits(0), NumMethodPoolTableLookups(0),
8513 NumMethodPoolTableHits(0), TotalNumMethodPoolEntries(0),
8514 NumLexicalDeclContextsRead(0), TotalLexicalDeclContexts(0),
8515 NumVisibleDeclContextsRead(0), TotalVisibleDeclContexts(0),
8516 TotalModulesSizeInBits(0), NumCurrentElementsDeserializing(0),
Richard Smithc2bb8182015-03-24 06:36:48 +00008517 PassingDeclsToConsumer(false), ReadingKind(Read_None) {
Guy Benyei11169dd2012-12-18 14:30:41 +00008518 SourceMgr.setExternalSLocEntrySource(this);
8519}
8520
8521ASTReader::~ASTReader() {
Nico Weber824285e2014-05-08 04:26:47 +00008522 if (OwnsDeserializationListener)
8523 delete DeserializationListener;
Guy Benyei11169dd2012-12-18 14:30:41 +00008524}