blob: 7c94ca435deb8c5b0cac902691860a78faba635a [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;
5829 }
5830
5831 assert(!T.isNull() && "Unknown predefined type");
5832 return T.withFastQualifiers(FastQuals);
5833 }
5834
5835 Index -= NUM_PREDEF_TYPE_IDS;
5836 assert(Index < TypesLoaded.size() && "Type index out-of-range");
5837 if (TypesLoaded[Index].isNull()) {
5838 TypesLoaded[Index] = readTypeRecord(Index);
5839 if (TypesLoaded[Index].isNull())
5840 return QualType();
5841
5842 TypesLoaded[Index]->setFromAST();
5843 if (DeserializationListener)
5844 DeserializationListener->TypeRead(TypeIdx::fromTypeID(ID),
5845 TypesLoaded[Index]);
5846 }
5847
5848 return TypesLoaded[Index].withFastQualifiers(FastQuals);
5849}
5850
5851QualType ASTReader::getLocalType(ModuleFile &F, unsigned LocalID) {
5852 return GetType(getGlobalTypeID(F, LocalID));
5853}
5854
5855serialization::TypeID
5856ASTReader::getGlobalTypeID(ModuleFile &F, unsigned LocalID) const {
5857 unsigned FastQuals = LocalID & Qualifiers::FastMask;
5858 unsigned LocalIndex = LocalID >> Qualifiers::FastWidth;
5859
5860 if (LocalIndex < NUM_PREDEF_TYPE_IDS)
5861 return LocalID;
5862
5863 ContinuousRangeMap<uint32_t, int, 2>::iterator I
5864 = F.TypeRemap.find(LocalIndex - NUM_PREDEF_TYPE_IDS);
5865 assert(I != F.TypeRemap.end() && "Invalid index into type index remap");
5866
5867 unsigned GlobalIndex = LocalIndex + I->second;
5868 return (GlobalIndex << Qualifiers::FastWidth) | FastQuals;
5869}
5870
5871TemplateArgumentLocInfo
5872ASTReader::GetTemplateArgumentLocInfo(ModuleFile &F,
5873 TemplateArgument::ArgKind Kind,
5874 const RecordData &Record,
5875 unsigned &Index) {
5876 switch (Kind) {
5877 case TemplateArgument::Expression:
5878 return ReadExpr(F);
5879 case TemplateArgument::Type:
5880 return GetTypeSourceInfo(F, Record, Index);
5881 case TemplateArgument::Template: {
5882 NestedNameSpecifierLoc QualifierLoc = ReadNestedNameSpecifierLoc(F, Record,
5883 Index);
5884 SourceLocation TemplateNameLoc = ReadSourceLocation(F, Record, Index);
5885 return TemplateArgumentLocInfo(QualifierLoc, TemplateNameLoc,
5886 SourceLocation());
5887 }
5888 case TemplateArgument::TemplateExpansion: {
5889 NestedNameSpecifierLoc QualifierLoc = ReadNestedNameSpecifierLoc(F, Record,
5890 Index);
5891 SourceLocation TemplateNameLoc = ReadSourceLocation(F, Record, Index);
5892 SourceLocation EllipsisLoc = ReadSourceLocation(F, Record, Index);
5893 return TemplateArgumentLocInfo(QualifierLoc, TemplateNameLoc,
5894 EllipsisLoc);
5895 }
5896 case TemplateArgument::Null:
5897 case TemplateArgument::Integral:
5898 case TemplateArgument::Declaration:
5899 case TemplateArgument::NullPtr:
5900 case TemplateArgument::Pack:
5901 // FIXME: Is this right?
5902 return TemplateArgumentLocInfo();
5903 }
5904 llvm_unreachable("unexpected template argument loc");
5905}
5906
5907TemplateArgumentLoc
5908ASTReader::ReadTemplateArgumentLoc(ModuleFile &F,
5909 const RecordData &Record, unsigned &Index) {
5910 TemplateArgument Arg = ReadTemplateArgument(F, Record, Index);
5911
5912 if (Arg.getKind() == TemplateArgument::Expression) {
5913 if (Record[Index++]) // bool InfoHasSameExpr.
5914 return TemplateArgumentLoc(Arg, TemplateArgumentLocInfo(Arg.getAsExpr()));
5915 }
5916 return TemplateArgumentLoc(Arg, GetTemplateArgumentLocInfo(F, Arg.getKind(),
5917 Record, Index));
5918}
5919
Enea Zaffanella6dbe1872013-08-10 07:24:53 +00005920const ASTTemplateArgumentListInfo*
5921ASTReader::ReadASTTemplateArgumentListInfo(ModuleFile &F,
5922 const RecordData &Record,
5923 unsigned &Index) {
5924 SourceLocation LAngleLoc = ReadSourceLocation(F, Record, Index);
5925 SourceLocation RAngleLoc = ReadSourceLocation(F, Record, Index);
5926 unsigned NumArgsAsWritten = Record[Index++];
5927 TemplateArgumentListInfo TemplArgsInfo(LAngleLoc, RAngleLoc);
5928 for (unsigned i = 0; i != NumArgsAsWritten; ++i)
5929 TemplArgsInfo.addArgument(ReadTemplateArgumentLoc(F, Record, Index));
5930 return ASTTemplateArgumentListInfo::Create(getContext(), TemplArgsInfo);
5931}
5932
Guy Benyei11169dd2012-12-18 14:30:41 +00005933Decl *ASTReader::GetExternalDecl(uint32_t ID) {
5934 return GetDecl(ID);
5935}
5936
Richard Smith50895422015-01-31 03:04:55 +00005937template<typename TemplateSpecializationDecl>
5938static void completeRedeclChainForTemplateSpecialization(Decl *D) {
5939 if (auto *TSD = dyn_cast<TemplateSpecializationDecl>(D))
5940 TSD->getSpecializedTemplate()->LoadLazySpecializations();
5941}
5942
Richard Smith053f6c62014-05-16 23:01:30 +00005943void ASTReader::CompleteRedeclChain(const Decl *D) {
Richard Smith851072e2014-05-19 20:59:20 +00005944 if (NumCurrentElementsDeserializing) {
5945 // We arrange to not care about the complete redeclaration chain while we're
5946 // deserializing. Just remember that the AST has marked this one as complete
5947 // but that it's not actually complete yet, so we know we still need to
5948 // complete it later.
5949 PendingIncompleteDeclChains.push_back(const_cast<Decl*>(D));
5950 return;
5951 }
5952
Richard Smith053f6c62014-05-16 23:01:30 +00005953 const DeclContext *DC = D->getDeclContext()->getRedeclContext();
5954
Richard Smith053f6c62014-05-16 23:01:30 +00005955 // If this is a named declaration, complete it by looking it up
5956 // within its context.
5957 //
Richard Smith01bdb7a2014-08-28 05:44:07 +00005958 // FIXME: Merging a function definition should merge
Richard Smith053f6c62014-05-16 23:01:30 +00005959 // all mergeable entities within it.
5960 if (isa<TranslationUnitDecl>(DC) || isa<NamespaceDecl>(DC) ||
5961 isa<CXXRecordDecl>(DC) || isa<EnumDecl>(DC)) {
5962 if (DeclarationName Name = cast<NamedDecl>(D)->getDeclName()) {
Richard Smitha534a312015-07-21 23:54:07 +00005963 if (!getContext().getLangOpts().CPlusPlus &&
5964 isa<TranslationUnitDecl>(DC)) {
Richard Smith053f6c62014-05-16 23:01:30 +00005965 // Outside of C++, we don't have a lookup table for the TU, so update
Richard Smitha534a312015-07-21 23:54:07 +00005966 // the identifier instead. (For C++ modules, we don't store decls
5967 // in the serialized identifier table, so we do the lookup in the TU.)
5968 auto *II = Name.getAsIdentifierInfo();
5969 assert(II && "non-identifier name in C?");
Richard Smith053f6c62014-05-16 23:01:30 +00005970 if (II->isOutOfDate())
5971 updateOutOfDateIdentifier(*II);
5972 } else
5973 DC->lookup(Name);
Richard Smith01bdb7a2014-08-28 05:44:07 +00005974 } else if (needsAnonymousDeclarationNumber(cast<NamedDecl>(D))) {
Richard Smith3cb15722015-08-05 22:41:45 +00005975 // Find all declarations of this kind from the relevant context.
5976 for (auto *DCDecl : cast<Decl>(D->getLexicalDeclContext())->redecls()) {
5977 auto *DC = cast<DeclContext>(DCDecl);
5978 SmallVector<Decl*, 8> Decls;
5979 FindExternalLexicalDecls(
5980 DC, [&](Decl::Kind K) { return K == D->getKind(); }, Decls);
5981 }
Richard Smith053f6c62014-05-16 23:01:30 +00005982 }
5983 }
Richard Smith50895422015-01-31 03:04:55 +00005984
5985 if (auto *CTSD = dyn_cast<ClassTemplateSpecializationDecl>(D))
5986 CTSD->getSpecializedTemplate()->LoadLazySpecializations();
5987 if (auto *VTSD = dyn_cast<VarTemplateSpecializationDecl>(D))
5988 VTSD->getSpecializedTemplate()->LoadLazySpecializations();
5989 if (auto *FD = dyn_cast<FunctionDecl>(D)) {
5990 if (auto *Template = FD->getPrimaryTemplate())
5991 Template->LoadLazySpecializations();
5992 }
Richard Smith053f6c62014-05-16 23:01:30 +00005993}
5994
Richard Smithc2bb8182015-03-24 06:36:48 +00005995uint64_t ASTReader::ReadCXXCtorInitializersRef(ModuleFile &M,
5996 const RecordData &Record,
5997 unsigned &Idx) {
5998 if (Idx >= Record.size() || Record[Idx] > M.LocalNumCXXCtorInitializers) {
5999 Error("malformed AST file: missing C++ ctor initializers");
6000 return 0;
6001 }
6002
6003 unsigned LocalID = Record[Idx++];
6004 return getGlobalBitOffset(M, M.CXXCtorInitializersOffsets[LocalID - 1]);
6005}
6006
6007CXXCtorInitializer **
6008ASTReader::GetExternalCXXCtorInitializers(uint64_t Offset) {
6009 RecordLocation Loc = getLocalBitOffset(Offset);
6010 BitstreamCursor &Cursor = Loc.F->DeclsCursor;
6011 SavedStreamPosition SavedPosition(Cursor);
6012 Cursor.JumpToBit(Loc.Offset);
6013 ReadingKindTracker ReadingKind(Read_Decl, *this);
6014
6015 RecordData Record;
6016 unsigned Code = Cursor.ReadCode();
6017 unsigned RecCode = Cursor.readRecord(Code, Record);
6018 if (RecCode != DECL_CXX_CTOR_INITIALIZERS) {
6019 Error("malformed AST file: missing C++ ctor initializers");
6020 return nullptr;
6021 }
6022
6023 unsigned Idx = 0;
6024 return ReadCXXCtorInitializers(*Loc.F, Record, Idx);
6025}
6026
Richard Smithcd45dbc2014-04-19 03:48:30 +00006027uint64_t ASTReader::readCXXBaseSpecifiers(ModuleFile &M,
6028 const RecordData &Record,
6029 unsigned &Idx) {
6030 if (Idx >= Record.size() || Record[Idx] > M.LocalNumCXXBaseSpecifiers) {
6031 Error("malformed AST file: missing C++ base specifier");
Guy Benyei11169dd2012-12-18 14:30:41 +00006032 return 0;
Richard Smithcd45dbc2014-04-19 03:48:30 +00006033 }
6034
Guy Benyei11169dd2012-12-18 14:30:41 +00006035 unsigned LocalID = Record[Idx++];
6036 return getGlobalBitOffset(M, M.CXXBaseSpecifiersOffsets[LocalID - 1]);
6037}
6038
6039CXXBaseSpecifier *ASTReader::GetExternalCXXBaseSpecifiers(uint64_t Offset) {
6040 RecordLocation Loc = getLocalBitOffset(Offset);
Chris Lattner7fb3bef2013-01-20 00:56:42 +00006041 BitstreamCursor &Cursor = Loc.F->DeclsCursor;
Guy Benyei11169dd2012-12-18 14:30:41 +00006042 SavedStreamPosition SavedPosition(Cursor);
6043 Cursor.JumpToBit(Loc.Offset);
6044 ReadingKindTracker ReadingKind(Read_Decl, *this);
6045 RecordData Record;
6046 unsigned Code = Cursor.ReadCode();
Chris Lattner0e6c9402013-01-20 02:38:54 +00006047 unsigned RecCode = Cursor.readRecord(Code, Record);
Guy Benyei11169dd2012-12-18 14:30:41 +00006048 if (RecCode != DECL_CXX_BASE_SPECIFIERS) {
Richard Smithcd45dbc2014-04-19 03:48:30 +00006049 Error("malformed AST file: missing C++ base specifiers");
Craig Toppera13603a2014-05-22 05:54:18 +00006050 return nullptr;
Guy Benyei11169dd2012-12-18 14:30:41 +00006051 }
6052
6053 unsigned Idx = 0;
6054 unsigned NumBases = Record[Idx++];
6055 void *Mem = Context.Allocate(sizeof(CXXBaseSpecifier) * NumBases);
6056 CXXBaseSpecifier *Bases = new (Mem) CXXBaseSpecifier [NumBases];
6057 for (unsigned I = 0; I != NumBases; ++I)
6058 Bases[I] = ReadCXXBaseSpecifier(*Loc.F, Record, Idx);
6059 return Bases;
6060}
6061
6062serialization::DeclID
6063ASTReader::getGlobalDeclID(ModuleFile &F, LocalDeclID LocalID) const {
6064 if (LocalID < NUM_PREDEF_DECL_IDS)
6065 return LocalID;
6066
6067 ContinuousRangeMap<uint32_t, int, 2>::iterator I
6068 = F.DeclRemap.find(LocalID - NUM_PREDEF_DECL_IDS);
6069 assert(I != F.DeclRemap.end() && "Invalid index into decl index remap");
6070
6071 return LocalID + I->second;
6072}
6073
6074bool ASTReader::isDeclIDFromModule(serialization::GlobalDeclID ID,
6075 ModuleFile &M) const {
Richard Smithfe620d22015-03-05 23:24:12 +00006076 // Predefined decls aren't from any module.
6077 if (ID < NUM_PREDEF_DECL_IDS)
6078 return false;
6079
Richard Smithbcda1a92015-07-12 23:51:20 +00006080 return ID - NUM_PREDEF_DECL_IDS >= M.BaseDeclID &&
6081 ID - NUM_PREDEF_DECL_IDS < M.BaseDeclID + M.LocalNumDecls;
Guy Benyei11169dd2012-12-18 14:30:41 +00006082}
6083
Douglas Gregor9f782892013-01-21 15:25:38 +00006084ModuleFile *ASTReader::getOwningModuleFile(const Decl *D) {
Guy Benyei11169dd2012-12-18 14:30:41 +00006085 if (!D->isFromASTFile())
Craig Toppera13603a2014-05-22 05:54:18 +00006086 return nullptr;
Guy Benyei11169dd2012-12-18 14:30:41 +00006087 GlobalDeclMapType::const_iterator I = GlobalDeclMap.find(D->getGlobalID());
6088 assert(I != GlobalDeclMap.end() && "Corrupted global declaration map");
6089 return I->second;
6090}
6091
6092SourceLocation ASTReader::getSourceLocationForDeclID(GlobalDeclID ID) {
6093 if (ID < NUM_PREDEF_DECL_IDS)
6094 return SourceLocation();
Richard Smithcd45dbc2014-04-19 03:48:30 +00006095
Guy Benyei11169dd2012-12-18 14:30:41 +00006096 unsigned Index = ID - NUM_PREDEF_DECL_IDS;
6097
6098 if (Index > DeclsLoaded.size()) {
6099 Error("declaration ID out-of-range for AST file");
6100 return SourceLocation();
6101 }
Richard Smithcd45dbc2014-04-19 03:48:30 +00006102
Guy Benyei11169dd2012-12-18 14:30:41 +00006103 if (Decl *D = DeclsLoaded[Index])
6104 return D->getLocation();
6105
6106 unsigned RawLocation = 0;
6107 RecordLocation Rec = DeclCursorForID(ID, RawLocation);
6108 return ReadSourceLocation(*Rec.F, RawLocation);
6109}
6110
Richard Smithfe620d22015-03-05 23:24:12 +00006111static Decl *getPredefinedDecl(ASTContext &Context, PredefinedDeclIDs ID) {
6112 switch (ID) {
6113 case PREDEF_DECL_NULL_ID:
6114 return nullptr;
6115
6116 case PREDEF_DECL_TRANSLATION_UNIT_ID:
6117 return Context.getTranslationUnitDecl();
6118
6119 case PREDEF_DECL_OBJC_ID_ID:
6120 return Context.getObjCIdDecl();
6121
6122 case PREDEF_DECL_OBJC_SEL_ID:
6123 return Context.getObjCSelDecl();
6124
6125 case PREDEF_DECL_OBJC_CLASS_ID:
6126 return Context.getObjCClassDecl();
6127
6128 case PREDEF_DECL_OBJC_PROTOCOL_ID:
6129 return Context.getObjCProtocolDecl();
6130
6131 case PREDEF_DECL_INT_128_ID:
6132 return Context.getInt128Decl();
6133
6134 case PREDEF_DECL_UNSIGNED_INT_128_ID:
6135 return Context.getUInt128Decl();
6136
6137 case PREDEF_DECL_OBJC_INSTANCETYPE_ID:
6138 return Context.getObjCInstanceTypeDecl();
6139
6140 case PREDEF_DECL_BUILTIN_VA_LIST_ID:
6141 return Context.getBuiltinVaListDecl();
Richard Smithf19e1272015-03-07 00:04:49 +00006142
Richard Smith9b88a4c2015-07-27 05:40:23 +00006143 case PREDEF_DECL_VA_LIST_TAG:
6144 return Context.getVaListTagDecl();
6145
Richard Smithf19e1272015-03-07 00:04:49 +00006146 case PREDEF_DECL_EXTERN_C_CONTEXT_ID:
6147 return Context.getExternCContextDecl();
Richard Smithfe620d22015-03-05 23:24:12 +00006148 }
Yaron Keren322bdad2015-03-06 07:49:14 +00006149 llvm_unreachable("PredefinedDeclIDs unknown enum value");
Richard Smithfe620d22015-03-05 23:24:12 +00006150}
6151
Richard Smithcd45dbc2014-04-19 03:48:30 +00006152Decl *ASTReader::GetExistingDecl(DeclID ID) {
6153 if (ID < NUM_PREDEF_DECL_IDS) {
Richard Smithfe620d22015-03-05 23:24:12 +00006154 Decl *D = getPredefinedDecl(Context, (PredefinedDeclIDs)ID);
6155 if (D) {
6156 // Track that we have merged the declaration with ID \p ID into the
6157 // pre-existing predefined declaration \p D.
Richard Smith5fc18a92015-07-12 23:43:21 +00006158 auto &Merged = KeyDecls[D->getCanonicalDecl()];
Richard Smithfe620d22015-03-05 23:24:12 +00006159 if (Merged.empty())
6160 Merged.push_back(ID);
Guy Benyei11169dd2012-12-18 14:30:41 +00006161 }
Richard Smithfe620d22015-03-05 23:24:12 +00006162 return D;
Guy Benyei11169dd2012-12-18 14:30:41 +00006163 }
Richard Smithcd45dbc2014-04-19 03:48:30 +00006164
Guy Benyei11169dd2012-12-18 14:30:41 +00006165 unsigned Index = ID - NUM_PREDEF_DECL_IDS;
6166
6167 if (Index >= DeclsLoaded.size()) {
6168 assert(0 && "declaration ID out-of-range for AST file");
6169 Error("declaration ID out-of-range for AST file");
Craig Toppera13603a2014-05-22 05:54:18 +00006170 return nullptr;
Guy Benyei11169dd2012-12-18 14:30:41 +00006171 }
Richard Smithcd45dbc2014-04-19 03:48:30 +00006172
6173 return DeclsLoaded[Index];
6174}
6175
6176Decl *ASTReader::GetDecl(DeclID ID) {
6177 if (ID < NUM_PREDEF_DECL_IDS)
6178 return GetExistingDecl(ID);
6179
6180 unsigned Index = ID - NUM_PREDEF_DECL_IDS;
6181
6182 if (Index >= DeclsLoaded.size()) {
6183 assert(0 && "declaration ID out-of-range for AST file");
6184 Error("declaration ID out-of-range for AST file");
Craig Toppera13603a2014-05-22 05:54:18 +00006185 return nullptr;
Richard Smithcd45dbc2014-04-19 03:48:30 +00006186 }
6187
Guy Benyei11169dd2012-12-18 14:30:41 +00006188 if (!DeclsLoaded[Index]) {
6189 ReadDeclRecord(ID);
6190 if (DeserializationListener)
6191 DeserializationListener->DeclRead(ID, DeclsLoaded[Index]);
6192 }
6193
6194 return DeclsLoaded[Index];
6195}
6196
6197DeclID ASTReader::mapGlobalIDToModuleFileGlobalID(ModuleFile &M,
6198 DeclID GlobalID) {
6199 if (GlobalID < NUM_PREDEF_DECL_IDS)
6200 return GlobalID;
6201
6202 GlobalDeclMapType::const_iterator I = GlobalDeclMap.find(GlobalID);
6203 assert(I != GlobalDeclMap.end() && "Corrupted global declaration map");
6204 ModuleFile *Owner = I->second;
6205
6206 llvm::DenseMap<ModuleFile *, serialization::DeclID>::iterator Pos
6207 = M.GlobalToLocalDeclIDs.find(Owner);
6208 if (Pos == M.GlobalToLocalDeclIDs.end())
6209 return 0;
6210
6211 return GlobalID - Owner->BaseDeclID + Pos->second;
6212}
6213
6214serialization::DeclID ASTReader::ReadDeclID(ModuleFile &F,
6215 const RecordData &Record,
6216 unsigned &Idx) {
6217 if (Idx >= Record.size()) {
6218 Error("Corrupted AST file");
6219 return 0;
6220 }
6221
6222 return getGlobalDeclID(F, Record[Idx++]);
6223}
6224
6225/// \brief Resolve the offset of a statement into a statement.
6226///
6227/// This operation will read a new statement from the external
6228/// source each time it is called, and is meant to be used via a
6229/// LazyOffsetPtr (which is used by Decls for the body of functions, etc).
6230Stmt *ASTReader::GetExternalDeclStmt(uint64_t Offset) {
6231 // Switch case IDs are per Decl.
6232 ClearSwitchCaseIDs();
6233
6234 // Offset here is a global offset across the entire chain.
6235 RecordLocation Loc = getLocalBitOffset(Offset);
6236 Loc.F->DeclsCursor.JumpToBit(Loc.Offset);
6237 return ReadStmtFromStream(*Loc.F);
6238}
6239
Richard Smith3cb15722015-08-05 22:41:45 +00006240void ASTReader::FindExternalLexicalDecls(
6241 const DeclContext *DC, llvm::function_ref<bool(Decl::Kind)> IsKindWeWant,
6242 SmallVectorImpl<Decl *> &Decls) {
Richard Smith82f8fcd2015-08-06 22:07:25 +00006243 bool PredefsVisited[NUM_PREDEF_DECL_IDS] = {};
6244
Richard Smith9ccdd932015-08-06 22:14:12 +00006245 auto Visit = [&] (ModuleFile *M, LexicalContents LexicalDecls) {
Richard Smith82f8fcd2015-08-06 22:07:25 +00006246 assert(LexicalDecls.size() % 2 == 0 && "expected an even number of entries");
6247 for (int I = 0, N = LexicalDecls.size(); I != N; I += 2) {
6248 auto K = (Decl::Kind)+LexicalDecls[I];
6249 if (!IsKindWeWant(K))
6250 continue;
6251
6252 auto ID = (serialization::DeclID)+LexicalDecls[I + 1];
6253
6254 // Don't add predefined declarations to the lexical context more
6255 // than once.
6256 if (ID < NUM_PREDEF_DECL_IDS) {
6257 if (PredefsVisited[ID])
6258 continue;
6259
6260 PredefsVisited[ID] = true;
6261 }
6262
6263 if (Decl *D = GetLocalDecl(*M, ID)) {
Richard Smith2317a3e2015-08-11 21:21:20 +00006264 assert(D->getKind() == K && "wrong kind for lexical decl");
Richard Smith82f8fcd2015-08-06 22:07:25 +00006265 if (!DC->isDeclInLexicalTraversal(D))
6266 Decls.push_back(D);
6267 }
6268 }
6269 };
6270
6271 if (isa<TranslationUnitDecl>(DC)) {
6272 for (auto Lexical : TULexicalDecls)
6273 Visit(Lexical.first, Lexical.second);
6274 } else {
6275 auto I = LexicalDecls.find(DC);
6276 if (I != LexicalDecls.end())
Richard Smith9c9173d2015-08-11 22:00:24 +00006277 Visit(I->second.first, I->second.second);
Richard Smith82f8fcd2015-08-06 22:07:25 +00006278 }
6279
Guy Benyei11169dd2012-12-18 14:30:41 +00006280 ++NumLexicalDeclContextsRead;
Guy Benyei11169dd2012-12-18 14:30:41 +00006281}
6282
6283namespace {
6284
6285class DeclIDComp {
6286 ASTReader &Reader;
6287 ModuleFile &Mod;
6288
6289public:
6290 DeclIDComp(ASTReader &Reader, ModuleFile &M) : Reader(Reader), Mod(M) {}
6291
6292 bool operator()(LocalDeclID L, LocalDeclID R) const {
6293 SourceLocation LHS = getLocation(L);
6294 SourceLocation RHS = getLocation(R);
6295 return Reader.getSourceManager().isBeforeInTranslationUnit(LHS, RHS);
6296 }
6297
6298 bool operator()(SourceLocation LHS, LocalDeclID R) const {
6299 SourceLocation RHS = getLocation(R);
6300 return Reader.getSourceManager().isBeforeInTranslationUnit(LHS, RHS);
6301 }
6302
6303 bool operator()(LocalDeclID L, SourceLocation RHS) const {
6304 SourceLocation LHS = getLocation(L);
6305 return Reader.getSourceManager().isBeforeInTranslationUnit(LHS, RHS);
6306 }
6307
6308 SourceLocation getLocation(LocalDeclID ID) const {
6309 return Reader.getSourceManager().getFileLoc(
6310 Reader.getSourceLocationForDeclID(Reader.getGlobalDeclID(Mod, ID)));
6311 }
6312};
6313
Alexander Kornienkoab9db512015-06-22 23:07:51 +00006314}
Guy Benyei11169dd2012-12-18 14:30:41 +00006315
6316void ASTReader::FindFileRegionDecls(FileID File,
6317 unsigned Offset, unsigned Length,
6318 SmallVectorImpl<Decl *> &Decls) {
6319 SourceManager &SM = getSourceManager();
6320
6321 llvm::DenseMap<FileID, FileDeclsInfo>::iterator I = FileDeclIDs.find(File);
6322 if (I == FileDeclIDs.end())
6323 return;
6324
6325 FileDeclsInfo &DInfo = I->second;
6326 if (DInfo.Decls.empty())
6327 return;
6328
6329 SourceLocation
6330 BeginLoc = SM.getLocForStartOfFile(File).getLocWithOffset(Offset);
6331 SourceLocation EndLoc = BeginLoc.getLocWithOffset(Length);
6332
6333 DeclIDComp DIDComp(*this, *DInfo.Mod);
6334 ArrayRef<serialization::LocalDeclID>::iterator
6335 BeginIt = std::lower_bound(DInfo.Decls.begin(), DInfo.Decls.end(),
6336 BeginLoc, DIDComp);
6337 if (BeginIt != DInfo.Decls.begin())
6338 --BeginIt;
6339
6340 // If we are pointing at a top-level decl inside an objc container, we need
6341 // to backtrack until we find it otherwise we will fail to report that the
6342 // region overlaps with an objc container.
6343 while (BeginIt != DInfo.Decls.begin() &&
6344 GetDecl(getGlobalDeclID(*DInfo.Mod, *BeginIt))
6345 ->isTopLevelDeclInObjCContainer())
6346 --BeginIt;
6347
6348 ArrayRef<serialization::LocalDeclID>::iterator
6349 EndIt = std::upper_bound(DInfo.Decls.begin(), DInfo.Decls.end(),
6350 EndLoc, DIDComp);
6351 if (EndIt != DInfo.Decls.end())
6352 ++EndIt;
6353
6354 for (ArrayRef<serialization::LocalDeclID>::iterator
6355 DIt = BeginIt; DIt != EndIt; ++DIt)
6356 Decls.push_back(GetDecl(getGlobalDeclID(*DInfo.Mod, *DIt)));
6357}
6358
Richard Smith3b637412015-07-14 18:42:41 +00006359/// \brief Retrieve the "definitive" module file for the definition of the
6360/// given declaration context, if there is one.
6361///
6362/// The "definitive" module file is the only place where we need to look to
6363/// find information about the declarations within the given declaration
6364/// context. For example, C++ and Objective-C classes, C structs/unions, and
6365/// Objective-C protocols, categories, and extensions are all defined in a
6366/// single place in the source code, so they have definitive module files
6367/// associated with them. C++ namespaces, on the other hand, can have
6368/// definitions in multiple different module files.
6369///
6370/// Note: this needs to be kept in sync with ASTWriter::AddedVisibleDecl's
6371/// NDEBUG checking.
6372static ModuleFile *getDefinitiveModuleFileFor(const DeclContext *DC,
6373 ASTReader &Reader) {
6374 if (const DeclContext *DefDC = getDefinitiveDeclContext(DC))
6375 return Reader.getOwningModuleFile(cast<Decl>(DefDC));
6376
6377 return nullptr;
6378}
6379
Guy Benyei11169dd2012-12-18 14:30:41 +00006380namespace {
6381 /// \brief ModuleFile visitor used to perform name lookup into a
6382 /// declaration context.
6383 class DeclContextNameLookupVisitor {
6384 ASTReader &Reader;
Richard Smithf13c68d2015-08-06 21:05:21 +00006385 const DeclContext *Context;
Guy Benyei11169dd2012-12-18 14:30:41 +00006386 DeclarationName Name;
Richard Smith3b637412015-07-14 18:42:41 +00006387 ASTDeclContextNameLookupTrait::DeclNameKey NameKey;
6388 unsigned NameHash;
Guy Benyei11169dd2012-12-18 14:30:41 +00006389 SmallVectorImpl<NamedDecl *> &Decls;
Richard Smith52874ec2015-02-13 20:17:14 +00006390 llvm::SmallPtrSetImpl<NamedDecl *> &DeclSet;
Guy Benyei11169dd2012-12-18 14:30:41 +00006391
6392 public:
Richard Smith8c913ec2014-08-14 02:21:01 +00006393 DeclContextNameLookupVisitor(ASTReader &Reader,
Richard Smithf13c68d2015-08-06 21:05:21 +00006394 const DeclContext *Context,
Guy Benyei11169dd2012-12-18 14:30:41 +00006395 DeclarationName Name,
Richard Smith52874ec2015-02-13 20:17:14 +00006396 SmallVectorImpl<NamedDecl *> &Decls,
6397 llvm::SmallPtrSetImpl<NamedDecl *> &DeclSet)
Richard Smithf13c68d2015-08-06 21:05:21 +00006398 : Reader(Reader), Context(Context), Name(Name),
Richard Smith3b637412015-07-14 18:42:41 +00006399 NameKey(ASTDeclContextNameLookupTrait::GetInternalKey(Name)),
6400 NameHash(ASTDeclContextNameLookupTrait::ComputeHash(NameKey)),
6401 Decls(Decls), DeclSet(DeclSet) {}
Guy Benyei11169dd2012-12-18 14:30:41 +00006402
Benjamin Kramer9a9efba2015-07-25 12:14:04 +00006403 bool operator()(ModuleFile &M) {
Guy Benyei11169dd2012-12-18 14:30:41 +00006404 // Check whether we have any visible declaration information for
6405 // this context in this module.
Richard Smithf13c68d2015-08-06 21:05:21 +00006406 auto Info = M.DeclContextInfos.find(Context);
6407 if (Info == M.DeclContextInfos.end() || !Info->second.NameLookupTableData)
Guy Benyei11169dd2012-12-18 14:30:41 +00006408 return false;
Richard Smith8c913ec2014-08-14 02:21:01 +00006409
Guy Benyei11169dd2012-12-18 14:30:41 +00006410 // Look for this name within this module.
Richard Smith52e3fba2014-03-11 07:17:35 +00006411 ASTDeclContextNameLookupTable *LookupTable =
Richard Smithf13c68d2015-08-06 21:05:21 +00006412 Info->second.NameLookupTableData;
Benjamin Kramer9a9efba2015-07-25 12:14:04 +00006413 ASTDeclContextNameLookupTable::iterator Pos =
Richard Smithbdf2d932015-07-30 03:37:16 +00006414 LookupTable->find_hashed(NameKey, NameHash);
Guy Benyei11169dd2012-12-18 14:30:41 +00006415 if (Pos == LookupTable->end())
6416 return false;
6417
6418 bool FoundAnything = false;
6419 ASTDeclContextNameLookupTrait::data_type Data = *Pos;
6420 for (; Data.first != Data.second; ++Data.first) {
Richard Smithbdf2d932015-07-30 03:37:16 +00006421 NamedDecl *ND = Reader.GetLocalDeclAs<NamedDecl>(M, *Data.first);
Guy Benyei11169dd2012-12-18 14:30:41 +00006422 if (!ND)
6423 continue;
6424
Richard Smithbdf2d932015-07-30 03:37:16 +00006425 if (ND->getDeclName() != Name) {
Guy Benyei11169dd2012-12-18 14:30:41 +00006426 // A name might be null because the decl's redeclarable part is
6427 // currently read before reading its name. The lookup is triggered by
6428 // building that decl (likely indirectly), and so it is later in the
6429 // sense of "already existing" and can be ignored here.
Richard Smith8c913ec2014-08-14 02:21:01 +00006430 // FIXME: This should not happen; deserializing declarations should
6431 // not perform lookups since that can lead to deserialization cycles.
Guy Benyei11169dd2012-12-18 14:30:41 +00006432 continue;
6433 }
Richard Smith8c913ec2014-08-14 02:21:01 +00006434
Guy Benyei11169dd2012-12-18 14:30:41 +00006435 // Record this declaration.
6436 FoundAnything = true;
Richard Smithbdf2d932015-07-30 03:37:16 +00006437 if (DeclSet.insert(ND).second)
6438 Decls.push_back(ND);
Guy Benyei11169dd2012-12-18 14:30:41 +00006439 }
6440
6441 return FoundAnything;
6442 }
6443 };
Alexander Kornienkoab9db512015-06-22 23:07:51 +00006444}
Guy Benyei11169dd2012-12-18 14:30:41 +00006445
Richard Smith9ce12e32013-02-07 03:30:24 +00006446bool
Guy Benyei11169dd2012-12-18 14:30:41 +00006447ASTReader::FindExternalVisibleDeclsByName(const DeclContext *DC,
6448 DeclarationName Name) {
6449 assert(DC->hasExternalVisibleStorage() &&
6450 "DeclContext has no visible decls in storage");
6451 if (!Name)
Richard Smith9ce12e32013-02-07 03:30:24 +00006452 return false;
Guy Benyei11169dd2012-12-18 14:30:41 +00006453
Richard Smith8c913ec2014-08-14 02:21:01 +00006454 Deserializing LookupResults(this);
6455
Guy Benyei11169dd2012-12-18 14:30:41 +00006456 SmallVector<NamedDecl *, 64> Decls;
Richard Smith52874ec2015-02-13 20:17:14 +00006457 llvm::SmallPtrSet<NamedDecl*, 64> DeclSet;
Richard Smith8c913ec2014-08-14 02:21:01 +00006458
Richard Smithf13c68d2015-08-06 21:05:21 +00006459 DeclContextNameLookupVisitor Visitor(*this, DC, Name, Decls, DeclSet);
Richard Smith8c913ec2014-08-14 02:21:01 +00006460
Richard Smithf13c68d2015-08-06 21:05:21 +00006461 // If we can definitively determine which module file to look into,
6462 // only look there. Otherwise, look in all module files.
6463 if (ModuleFile *Definitive = getDefinitiveModuleFileFor(DC, *this))
6464 Visitor(*Definitive);
6465 else
6466 ModuleMgr.visit(Visitor);
Richard Smithcd45dbc2014-04-19 03:48:30 +00006467
Guy Benyei11169dd2012-12-18 14:30:41 +00006468 ++NumVisibleDeclContextsRead;
6469 SetExternalVisibleDeclsForName(DC, Name, Decls);
Richard Smith9ce12e32013-02-07 03:30:24 +00006470 return !Decls.empty();
Guy Benyei11169dd2012-12-18 14:30:41 +00006471}
6472
6473namespace {
6474 /// \brief ModuleFile visitor used to retrieve all visible names in a
6475 /// declaration context.
6476 class DeclContextAllNamesVisitor {
6477 ASTReader &Reader;
Dmitri Gribenkof8579502013-01-12 19:30:44 +00006478 SmallVectorImpl<const DeclContext *> &Contexts;
Craig Topper3598eb72013-07-05 04:43:31 +00006479 DeclsMap &Decls;
Richard Smith52874ec2015-02-13 20:17:14 +00006480 llvm::SmallPtrSet<NamedDecl *, 256> DeclSet;
Argyrios Kyrtzidis2810e9d2012-12-19 22:21:18 +00006481 bool VisitAll;
Guy Benyei11169dd2012-12-18 14:30:41 +00006482
6483 public:
6484 DeclContextAllNamesVisitor(ASTReader &Reader,
6485 SmallVectorImpl<const DeclContext *> &Contexts,
Craig Topper3598eb72013-07-05 04:43:31 +00006486 DeclsMap &Decls, bool VisitAll)
Argyrios Kyrtzidis2810e9d2012-12-19 22:21:18 +00006487 : Reader(Reader), Contexts(Contexts), Decls(Decls), VisitAll(VisitAll) { }
Guy Benyei11169dd2012-12-18 14:30:41 +00006488
Benjamin Kramer9a9efba2015-07-25 12:14:04 +00006489 bool operator()(ModuleFile &M) {
Guy Benyei11169dd2012-12-18 14:30:41 +00006490 // Check whether we have any visible declaration information for
6491 // this context in this module.
6492 ModuleFile::DeclContextInfosMap::iterator Info;
6493 bool FoundInfo = false;
Richard Smithbdf2d932015-07-30 03:37:16 +00006494 for (unsigned I = 0, N = Contexts.size(); I != N; ++I) {
6495 Info = M.DeclContextInfos.find(Contexts[I]);
Guy Benyei11169dd2012-12-18 14:30:41 +00006496 if (Info != M.DeclContextInfos.end() &&
6497 Info->second.NameLookupTableData) {
6498 FoundInfo = true;
6499 break;
6500 }
6501 }
6502
6503 if (!FoundInfo)
6504 return false;
6505
Richard Smith52e3fba2014-03-11 07:17:35 +00006506 ASTDeclContextNameLookupTable *LookupTable =
Guy Benyei11169dd2012-12-18 14:30:41 +00006507 Info->second.NameLookupTableData;
6508 bool FoundAnything = false;
6509 for (ASTDeclContextNameLookupTable::data_iterator
Douglas Gregor5e306b12013-01-23 22:38:11 +00006510 I = LookupTable->data_begin(), E = LookupTable->data_end();
6511 I != E;
6512 ++I) {
Guy Benyei11169dd2012-12-18 14:30:41 +00006513 ASTDeclContextNameLookupTrait::data_type Data = *I;
6514 for (; Data.first != Data.second; ++Data.first) {
Richard Smithbdf2d932015-07-30 03:37:16 +00006515 NamedDecl *ND = Reader.GetLocalDeclAs<NamedDecl>(M, *Data.first);
Guy Benyei11169dd2012-12-18 14:30:41 +00006516 if (!ND)
6517 continue;
6518
6519 // Record this declaration.
6520 FoundAnything = true;
Richard Smithbdf2d932015-07-30 03:37:16 +00006521 if (DeclSet.insert(ND).second)
6522 Decls[ND->getDeclName()].push_back(ND);
Guy Benyei11169dd2012-12-18 14:30:41 +00006523 }
6524 }
6525
Richard Smithbdf2d932015-07-30 03:37:16 +00006526 return FoundAnything && !VisitAll;
Guy Benyei11169dd2012-12-18 14:30:41 +00006527 }
6528 };
Alexander Kornienkoab9db512015-06-22 23:07:51 +00006529}
Guy Benyei11169dd2012-12-18 14:30:41 +00006530
6531void ASTReader::completeVisibleDeclsMap(const DeclContext *DC) {
6532 if (!DC->hasExternalVisibleStorage())
6533 return;
Craig Topper79be4cd2013-07-05 04:33:53 +00006534 DeclsMap Decls;
Guy Benyei11169dd2012-12-18 14:30:41 +00006535
6536 // Compute the declaration contexts we need to look into. Multiple such
6537 // declaration contexts occur when two declaration contexts from disjoint
6538 // modules get merged, e.g., when two namespaces with the same name are
6539 // independently defined in separate modules.
6540 SmallVector<const DeclContext *, 2> Contexts;
6541 Contexts.push_back(DC);
6542
6543 if (DC->isNamespace()) {
Richard Smith5fc18a92015-07-12 23:43:21 +00006544 KeyDeclsMap::iterator Key =
6545 KeyDecls.find(const_cast<Decl *>(cast<Decl>(DC)));
6546 if (Key != KeyDecls.end()) {
6547 for (unsigned I = 0, N = Key->second.size(); I != N; ++I)
6548 Contexts.push_back(cast<DeclContext>(GetDecl(Key->second[I])));
Guy Benyei11169dd2012-12-18 14:30:41 +00006549 }
6550 }
6551
Argyrios Kyrtzidis2810e9d2012-12-19 22:21:18 +00006552 DeclContextAllNamesVisitor Visitor(*this, Contexts, Decls,
6553 /*VisitAll=*/DC->isFileContext());
Benjamin Kramer9a9efba2015-07-25 12:14:04 +00006554 ModuleMgr.visit(Visitor);
Guy Benyei11169dd2012-12-18 14:30:41 +00006555 ++NumVisibleDeclContextsRead;
6556
Craig Topper79be4cd2013-07-05 04:33:53 +00006557 for (DeclsMap::iterator I = Decls.begin(), E = Decls.end(); I != E; ++I) {
Guy Benyei11169dd2012-12-18 14:30:41 +00006558 SetExternalVisibleDeclsForName(DC, I->first, I->second);
6559 }
6560 const_cast<DeclContext *>(DC)->setHasExternalVisibleStorage(false);
6561}
6562
6563/// \brief Under non-PCH compilation the consumer receives the objc methods
6564/// before receiving the implementation, and codegen depends on this.
6565/// We simulate this by deserializing and passing to consumer the methods of the
6566/// implementation before passing the deserialized implementation decl.
6567static void PassObjCImplDeclToConsumer(ObjCImplDecl *ImplD,
6568 ASTConsumer *Consumer) {
6569 assert(ImplD && Consumer);
6570
Aaron Ballmanaff18c02014-03-13 19:03:34 +00006571 for (auto *I : ImplD->methods())
6572 Consumer->HandleInterestingDecl(DeclGroupRef(I));
Guy Benyei11169dd2012-12-18 14:30:41 +00006573
6574 Consumer->HandleInterestingDecl(DeclGroupRef(ImplD));
6575}
6576
6577void ASTReader::PassInterestingDeclsToConsumer() {
6578 assert(Consumer);
Richard Smith04d05b52014-03-23 00:27:18 +00006579
6580 if (PassingDeclsToConsumer)
6581 return;
6582
6583 // Guard variable to avoid recursively redoing the process of passing
6584 // decls to consumer.
6585 SaveAndRestore<bool> GuardPassingDeclsToConsumer(PassingDeclsToConsumer,
6586 true);
6587
Richard Smith9e2341d2015-03-23 03:25:59 +00006588 // Ensure that we've loaded all potentially-interesting declarations
6589 // that need to be eagerly loaded.
6590 for (auto ID : EagerlyDeserializedDecls)
6591 GetDecl(ID);
6592 EagerlyDeserializedDecls.clear();
6593
Guy Benyei11169dd2012-12-18 14:30:41 +00006594 while (!InterestingDecls.empty()) {
6595 Decl *D = InterestingDecls.front();
6596 InterestingDecls.pop_front();
6597
6598 PassInterestingDeclToConsumer(D);
6599 }
6600}
6601
6602void ASTReader::PassInterestingDeclToConsumer(Decl *D) {
6603 if (ObjCImplDecl *ImplD = dyn_cast<ObjCImplDecl>(D))
6604 PassObjCImplDeclToConsumer(ImplD, Consumer);
6605 else
6606 Consumer->HandleInterestingDecl(DeclGroupRef(D));
6607}
6608
6609void ASTReader::StartTranslationUnit(ASTConsumer *Consumer) {
6610 this->Consumer = Consumer;
6611
Richard Smith9e2341d2015-03-23 03:25:59 +00006612 if (Consumer)
6613 PassInterestingDeclsToConsumer();
Richard Smith7f330cd2015-03-18 01:42:29 +00006614
6615 if (DeserializationListener)
6616 DeserializationListener->ReaderInitialized(this);
Guy Benyei11169dd2012-12-18 14:30:41 +00006617}
6618
6619void ASTReader::PrintStats() {
6620 std::fprintf(stderr, "*** AST File Statistics:\n");
6621
6622 unsigned NumTypesLoaded
6623 = TypesLoaded.size() - std::count(TypesLoaded.begin(), TypesLoaded.end(),
6624 QualType());
6625 unsigned NumDeclsLoaded
6626 = DeclsLoaded.size() - std::count(DeclsLoaded.begin(), DeclsLoaded.end(),
Craig Toppera13603a2014-05-22 05:54:18 +00006627 (Decl *)nullptr);
Guy Benyei11169dd2012-12-18 14:30:41 +00006628 unsigned NumIdentifiersLoaded
6629 = IdentifiersLoaded.size() - std::count(IdentifiersLoaded.begin(),
6630 IdentifiersLoaded.end(),
Craig Toppera13603a2014-05-22 05:54:18 +00006631 (IdentifierInfo *)nullptr);
Guy Benyei11169dd2012-12-18 14:30:41 +00006632 unsigned NumMacrosLoaded
6633 = MacrosLoaded.size() - std::count(MacrosLoaded.begin(),
6634 MacrosLoaded.end(),
Craig Toppera13603a2014-05-22 05:54:18 +00006635 (MacroInfo *)nullptr);
Guy Benyei11169dd2012-12-18 14:30:41 +00006636 unsigned NumSelectorsLoaded
6637 = SelectorsLoaded.size() - std::count(SelectorsLoaded.begin(),
6638 SelectorsLoaded.end(),
6639 Selector());
6640
6641 if (unsigned TotalNumSLocEntries = getTotalNumSLocs())
6642 std::fprintf(stderr, " %u/%u source location entries read (%f%%)\n",
6643 NumSLocEntriesRead, TotalNumSLocEntries,
6644 ((float)NumSLocEntriesRead/TotalNumSLocEntries * 100));
6645 if (!TypesLoaded.empty())
6646 std::fprintf(stderr, " %u/%u types read (%f%%)\n",
6647 NumTypesLoaded, (unsigned)TypesLoaded.size(),
6648 ((float)NumTypesLoaded/TypesLoaded.size() * 100));
6649 if (!DeclsLoaded.empty())
6650 std::fprintf(stderr, " %u/%u declarations read (%f%%)\n",
6651 NumDeclsLoaded, (unsigned)DeclsLoaded.size(),
6652 ((float)NumDeclsLoaded/DeclsLoaded.size() * 100));
6653 if (!IdentifiersLoaded.empty())
6654 std::fprintf(stderr, " %u/%u identifiers read (%f%%)\n",
6655 NumIdentifiersLoaded, (unsigned)IdentifiersLoaded.size(),
6656 ((float)NumIdentifiersLoaded/IdentifiersLoaded.size() * 100));
6657 if (!MacrosLoaded.empty())
6658 std::fprintf(stderr, " %u/%u macros read (%f%%)\n",
6659 NumMacrosLoaded, (unsigned)MacrosLoaded.size(),
6660 ((float)NumMacrosLoaded/MacrosLoaded.size() * 100));
6661 if (!SelectorsLoaded.empty())
6662 std::fprintf(stderr, " %u/%u selectors read (%f%%)\n",
6663 NumSelectorsLoaded, (unsigned)SelectorsLoaded.size(),
6664 ((float)NumSelectorsLoaded/SelectorsLoaded.size() * 100));
6665 if (TotalNumStatements)
6666 std::fprintf(stderr, " %u/%u statements read (%f%%)\n",
6667 NumStatementsRead, TotalNumStatements,
6668 ((float)NumStatementsRead/TotalNumStatements * 100));
6669 if (TotalNumMacros)
6670 std::fprintf(stderr, " %u/%u macros read (%f%%)\n",
6671 NumMacrosRead, TotalNumMacros,
6672 ((float)NumMacrosRead/TotalNumMacros * 100));
6673 if (TotalLexicalDeclContexts)
6674 std::fprintf(stderr, " %u/%u lexical declcontexts read (%f%%)\n",
6675 NumLexicalDeclContextsRead, TotalLexicalDeclContexts,
6676 ((float)NumLexicalDeclContextsRead/TotalLexicalDeclContexts
6677 * 100));
6678 if (TotalVisibleDeclContexts)
6679 std::fprintf(stderr, " %u/%u visible declcontexts read (%f%%)\n",
6680 NumVisibleDeclContextsRead, TotalVisibleDeclContexts,
6681 ((float)NumVisibleDeclContextsRead/TotalVisibleDeclContexts
6682 * 100));
6683 if (TotalNumMethodPoolEntries) {
6684 std::fprintf(stderr, " %u/%u method pool entries read (%f%%)\n",
6685 NumMethodPoolEntriesRead, TotalNumMethodPoolEntries,
6686 ((float)NumMethodPoolEntriesRead/TotalNumMethodPoolEntries
6687 * 100));
Guy Benyei11169dd2012-12-18 14:30:41 +00006688 }
Douglas Gregorad2f7a52013-01-28 17:54:36 +00006689 if (NumMethodPoolLookups) {
6690 std::fprintf(stderr, " %u/%u method pool lookups succeeded (%f%%)\n",
6691 NumMethodPoolHits, NumMethodPoolLookups,
6692 ((float)NumMethodPoolHits/NumMethodPoolLookups * 100.0));
6693 }
6694 if (NumMethodPoolTableLookups) {
6695 std::fprintf(stderr, " %u/%u method pool table lookups succeeded (%f%%)\n",
6696 NumMethodPoolTableHits, NumMethodPoolTableLookups,
6697 ((float)NumMethodPoolTableHits/NumMethodPoolTableLookups
6698 * 100.0));
6699 }
6700
Douglas Gregor00a50f72013-01-25 00:38:33 +00006701 if (NumIdentifierLookupHits) {
6702 std::fprintf(stderr,
6703 " %u / %u identifier table lookups succeeded (%f%%)\n",
6704 NumIdentifierLookupHits, NumIdentifierLookups,
6705 (double)NumIdentifierLookupHits*100.0/NumIdentifierLookups);
6706 }
6707
Douglas Gregore060e572013-01-25 01:03:03 +00006708 if (GlobalIndex) {
6709 std::fprintf(stderr, "\n");
6710 GlobalIndex->printStats();
6711 }
6712
Guy Benyei11169dd2012-12-18 14:30:41 +00006713 std::fprintf(stderr, "\n");
6714 dump();
6715 std::fprintf(stderr, "\n");
6716}
6717
6718template<typename Key, typename ModuleFile, unsigned InitialCapacity>
6719static void
6720dumpModuleIDMap(StringRef Name,
6721 const ContinuousRangeMap<Key, ModuleFile *,
6722 InitialCapacity> &Map) {
6723 if (Map.begin() == Map.end())
6724 return;
6725
6726 typedef ContinuousRangeMap<Key, ModuleFile *, InitialCapacity> MapType;
6727 llvm::errs() << Name << ":\n";
6728 for (typename MapType::const_iterator I = Map.begin(), IEnd = Map.end();
6729 I != IEnd; ++I) {
6730 llvm::errs() << " " << I->first << " -> " << I->second->FileName
6731 << "\n";
6732 }
6733}
6734
6735void ASTReader::dump() {
6736 llvm::errs() << "*** PCH/ModuleFile Remappings:\n";
6737 dumpModuleIDMap("Global bit offset map", GlobalBitOffsetsMap);
6738 dumpModuleIDMap("Global source location entry map", GlobalSLocEntryMap);
6739 dumpModuleIDMap("Global type map", GlobalTypeMap);
6740 dumpModuleIDMap("Global declaration map", GlobalDeclMap);
6741 dumpModuleIDMap("Global identifier map", GlobalIdentifierMap);
6742 dumpModuleIDMap("Global macro map", GlobalMacroMap);
6743 dumpModuleIDMap("Global submodule map", GlobalSubmoduleMap);
6744 dumpModuleIDMap("Global selector map", GlobalSelectorMap);
6745 dumpModuleIDMap("Global preprocessed entity map",
6746 GlobalPreprocessedEntityMap);
6747
6748 llvm::errs() << "\n*** PCH/Modules Loaded:";
6749 for (ModuleManager::ModuleConstIterator M = ModuleMgr.begin(),
6750 MEnd = ModuleMgr.end();
6751 M != MEnd; ++M)
6752 (*M)->dump();
6753}
6754
6755/// Return the amount of memory used by memory buffers, breaking down
6756/// by heap-backed versus mmap'ed memory.
6757void ASTReader::getMemoryBufferSizes(MemoryBufferSizes &sizes) const {
6758 for (ModuleConstIterator I = ModuleMgr.begin(),
6759 E = ModuleMgr.end(); I != E; ++I) {
6760 if (llvm::MemoryBuffer *buf = (*I)->Buffer.get()) {
6761 size_t bytes = buf->getBufferSize();
6762 switch (buf->getBufferKind()) {
6763 case llvm::MemoryBuffer::MemoryBuffer_Malloc:
6764 sizes.malloc_bytes += bytes;
6765 break;
6766 case llvm::MemoryBuffer::MemoryBuffer_MMap:
6767 sizes.mmap_bytes += bytes;
6768 break;
6769 }
6770 }
6771 }
6772}
6773
6774void ASTReader::InitializeSema(Sema &S) {
6775 SemaObj = &S;
6776 S.addExternalSource(this);
6777
6778 // Makes sure any declarations that were deserialized "too early"
6779 // still get added to the identifier's declaration chains.
Ben Langmuir5418f402014-09-10 21:29:41 +00006780 for (uint64_t ID : PreloadedDeclIDs) {
6781 NamedDecl *D = cast<NamedDecl>(GetDecl(ID));
6782 pushExternalDeclIntoScope(D, D->getDeclName());
Guy Benyei11169dd2012-12-18 14:30:41 +00006783 }
Ben Langmuir5418f402014-09-10 21:29:41 +00006784 PreloadedDeclIDs.clear();
Guy Benyei11169dd2012-12-18 14:30:41 +00006785
Richard Smith3d8e97e2013-10-18 06:54:39 +00006786 // FIXME: What happens if these are changed by a module import?
Guy Benyei11169dd2012-12-18 14:30:41 +00006787 if (!FPPragmaOptions.empty()) {
6788 assert(FPPragmaOptions.size() == 1 && "Wrong number of FP_PRAGMA_OPTIONS");
6789 SemaObj->FPFeatures.fp_contract = FPPragmaOptions[0];
6790 }
6791
Richard Smith3d8e97e2013-10-18 06:54:39 +00006792 // FIXME: What happens if these are changed by a module import?
Guy Benyei11169dd2012-12-18 14:30:41 +00006793 if (!OpenCLExtensions.empty()) {
6794 unsigned I = 0;
6795#define OPENCLEXT(nm) SemaObj->OpenCLFeatures.nm = OpenCLExtensions[I++];
6796#include "clang/Basic/OpenCLExtensions.def"
6797
6798 assert(OpenCLExtensions.size() == I && "Wrong number of OPENCL_EXTENSIONS");
6799 }
Richard Smith3d8e97e2013-10-18 06:54:39 +00006800
6801 UpdateSema();
6802}
6803
6804void ASTReader::UpdateSema() {
6805 assert(SemaObj && "no Sema to update");
6806
6807 // Load the offsets of the declarations that Sema references.
6808 // They will be lazily deserialized when needed.
6809 if (!SemaDeclRefs.empty()) {
6810 assert(SemaDeclRefs.size() % 2 == 0);
6811 for (unsigned I = 0; I != SemaDeclRefs.size(); I += 2) {
6812 if (!SemaObj->StdNamespace)
6813 SemaObj->StdNamespace = SemaDeclRefs[I];
6814 if (!SemaObj->StdBadAlloc)
6815 SemaObj->StdBadAlloc = SemaDeclRefs[I+1];
6816 }
6817 SemaDeclRefs.clear();
6818 }
Dario Domizioli13a0a382014-05-23 12:13:25 +00006819
6820 // Update the state of 'pragma clang optimize'. Use the same API as if we had
6821 // encountered the pragma in the source.
6822 if(OptimizeOffPragmaLocation.isValid())
6823 SemaObj->ActOnPragmaOptimize(/* IsOn = */ false, OptimizeOffPragmaLocation);
Guy Benyei11169dd2012-12-18 14:30:41 +00006824}
6825
Richard Smitha8d5b6a2015-07-17 19:51:03 +00006826IdentifierInfo *ASTReader::get(StringRef Name) {
Guy Benyei11169dd2012-12-18 14:30:41 +00006827 // Note that we are loading an identifier.
6828 Deserializing AnIdentifier(this);
Douglas Gregore060e572013-01-25 01:03:03 +00006829
Douglas Gregor7211ac12013-01-25 23:32:03 +00006830 IdentifierLookupVisitor Visitor(Name, /*PriorGeneration=*/0,
Douglas Gregor00a50f72013-01-25 00:38:33 +00006831 NumIdentifierLookups,
6832 NumIdentifierLookupHits);
Richard Smith33e0f7e2015-07-22 02:08:40 +00006833
6834 // We don't need to do identifier table lookups in C++ modules (we preload
6835 // all interesting declarations, and don't need to use the scope for name
6836 // lookups). Perform the lookup in PCH files, though, since we don't build
6837 // a complete initial identifier table if we're carrying on from a PCH.
6838 if (Context.getLangOpts().CPlusPlus) {
6839 for (auto F : ModuleMgr.pch_modules())
Benjamin Kramer9a9efba2015-07-25 12:14:04 +00006840 if (Visitor(*F))
Richard Smith33e0f7e2015-07-22 02:08:40 +00006841 break;
6842 } else {
6843 // If there is a global index, look there first to determine which modules
6844 // provably do not have any results for this identifier.
6845 GlobalModuleIndex::HitSet Hits;
6846 GlobalModuleIndex::HitSet *HitsPtr = nullptr;
6847 if (!loadGlobalIndex()) {
6848 if (GlobalIndex->lookupIdentifier(Name, Hits)) {
6849 HitsPtr = &Hits;
6850 }
6851 }
6852
Benjamin Kramer9a9efba2015-07-25 12:14:04 +00006853 ModuleMgr.visit(Visitor, HitsPtr);
Richard Smith33e0f7e2015-07-22 02:08:40 +00006854 }
6855
Guy Benyei11169dd2012-12-18 14:30:41 +00006856 IdentifierInfo *II = Visitor.getIdentifierInfo();
6857 markIdentifierUpToDate(II);
6858 return II;
6859}
6860
6861namespace clang {
6862 /// \brief An identifier-lookup iterator that enumerates all of the
6863 /// identifiers stored within a set of AST files.
6864 class ASTIdentifierIterator : public IdentifierIterator {
6865 /// \brief The AST reader whose identifiers are being enumerated.
6866 const ASTReader &Reader;
6867
6868 /// \brief The current index into the chain of AST files stored in
6869 /// the AST reader.
6870 unsigned Index;
6871
6872 /// \brief The current position within the identifier lookup table
6873 /// of the current AST file.
6874 ASTIdentifierLookupTable::key_iterator Current;
6875
6876 /// \brief The end position within the identifier lookup table of
6877 /// the current AST file.
6878 ASTIdentifierLookupTable::key_iterator End;
6879
6880 public:
6881 explicit ASTIdentifierIterator(const ASTReader &Reader);
6882
Craig Topper3e89dfe2014-03-13 02:13:41 +00006883 StringRef Next() override;
Guy Benyei11169dd2012-12-18 14:30:41 +00006884 };
Alexander Kornienkoab9db512015-06-22 23:07:51 +00006885}
Guy Benyei11169dd2012-12-18 14:30:41 +00006886
6887ASTIdentifierIterator::ASTIdentifierIterator(const ASTReader &Reader)
6888 : Reader(Reader), Index(Reader.ModuleMgr.size() - 1) {
6889 ASTIdentifierLookupTable *IdTable
6890 = (ASTIdentifierLookupTable *)Reader.ModuleMgr[Index].IdentifierLookupTable;
6891 Current = IdTable->key_begin();
6892 End = IdTable->key_end();
6893}
6894
6895StringRef ASTIdentifierIterator::Next() {
6896 while (Current == End) {
6897 // If we have exhausted all of our AST files, we're done.
6898 if (Index == 0)
6899 return StringRef();
6900
6901 --Index;
6902 ASTIdentifierLookupTable *IdTable
6903 = (ASTIdentifierLookupTable *)Reader.ModuleMgr[Index].
6904 IdentifierLookupTable;
6905 Current = IdTable->key_begin();
6906 End = IdTable->key_end();
6907 }
6908
6909 // We have any identifiers remaining in the current AST file; return
6910 // the next one.
Douglas Gregorbfd73d72013-01-23 18:53:14 +00006911 StringRef Result = *Current;
Guy Benyei11169dd2012-12-18 14:30:41 +00006912 ++Current;
Douglas Gregorbfd73d72013-01-23 18:53:14 +00006913 return Result;
Guy Benyei11169dd2012-12-18 14:30:41 +00006914}
6915
Argyrios Kyrtzidis9aca3c62013-04-17 22:10:55 +00006916IdentifierIterator *ASTReader::getIdentifiers() {
6917 if (!loadGlobalIndex())
6918 return GlobalIndex->createIdentifierIterator();
6919
Guy Benyei11169dd2012-12-18 14:30:41 +00006920 return new ASTIdentifierIterator(*this);
6921}
6922
6923namespace clang { namespace serialization {
6924 class ReadMethodPoolVisitor {
6925 ASTReader &Reader;
6926 Selector Sel;
6927 unsigned PriorGeneration;
Argyrios Kyrtzidisd3da6e02013-04-17 00:08:58 +00006928 unsigned InstanceBits;
6929 unsigned FactoryBits;
Nico Weberff4b35e2014-12-27 22:14:15 +00006930 bool InstanceHasMoreThanOneDecl;
6931 bool FactoryHasMoreThanOneDecl;
Dmitri Gribenkof8579502013-01-12 19:30:44 +00006932 SmallVector<ObjCMethodDecl *, 4> InstanceMethods;
6933 SmallVector<ObjCMethodDecl *, 4> FactoryMethods;
Guy Benyei11169dd2012-12-18 14:30:41 +00006934
6935 public:
Nico Weber2e0c8f72014-12-27 03:58:08 +00006936 ReadMethodPoolVisitor(ASTReader &Reader, Selector Sel,
Guy Benyei11169dd2012-12-18 14:30:41 +00006937 unsigned PriorGeneration)
Nico Weber2e0c8f72014-12-27 03:58:08 +00006938 : Reader(Reader), Sel(Sel), PriorGeneration(PriorGeneration),
Nico Weberff4b35e2014-12-27 22:14:15 +00006939 InstanceBits(0), FactoryBits(0), InstanceHasMoreThanOneDecl(false),
6940 FactoryHasMoreThanOneDecl(false) {}
Nico Weber2e0c8f72014-12-27 03:58:08 +00006941
Benjamin Kramer9a9efba2015-07-25 12:14:04 +00006942 bool operator()(ModuleFile &M) {
Guy Benyei11169dd2012-12-18 14:30:41 +00006943 if (!M.SelectorLookupTable)
6944 return false;
6945
6946 // If we've already searched this module file, skip it now.
Richard Smithbdf2d932015-07-30 03:37:16 +00006947 if (M.Generation <= PriorGeneration)
Guy Benyei11169dd2012-12-18 14:30:41 +00006948 return true;
6949
Richard Smithbdf2d932015-07-30 03:37:16 +00006950 ++Reader.NumMethodPoolTableLookups;
Guy Benyei11169dd2012-12-18 14:30:41 +00006951 ASTSelectorLookupTable *PoolTable
6952 = (ASTSelectorLookupTable*)M.SelectorLookupTable;
Richard Smithbdf2d932015-07-30 03:37:16 +00006953 ASTSelectorLookupTable::iterator Pos = PoolTable->find(Sel);
Guy Benyei11169dd2012-12-18 14:30:41 +00006954 if (Pos == PoolTable->end())
6955 return false;
Douglas Gregorad2f7a52013-01-28 17:54:36 +00006956
Richard Smithbdf2d932015-07-30 03:37:16 +00006957 ++Reader.NumMethodPoolTableHits;
6958 ++Reader.NumSelectorsRead;
Guy Benyei11169dd2012-12-18 14:30:41 +00006959 // FIXME: Not quite happy with the statistics here. We probably should
6960 // disable this tracking when called via LoadSelector.
6961 // Also, should entries without methods count as misses?
Richard Smithbdf2d932015-07-30 03:37:16 +00006962 ++Reader.NumMethodPoolEntriesRead;
Guy Benyei11169dd2012-12-18 14:30:41 +00006963 ASTSelectorLookupTrait::data_type Data = *Pos;
Richard Smithbdf2d932015-07-30 03:37:16 +00006964 if (Reader.DeserializationListener)
6965 Reader.DeserializationListener->SelectorRead(Data.ID, Sel);
Benjamin Kramer9a9efba2015-07-25 12:14:04 +00006966
Richard Smithbdf2d932015-07-30 03:37:16 +00006967 InstanceMethods.append(Data.Instance.begin(), Data.Instance.end());
6968 FactoryMethods.append(Data.Factory.begin(), Data.Factory.end());
6969 InstanceBits = Data.InstanceBits;
6970 FactoryBits = Data.FactoryBits;
6971 InstanceHasMoreThanOneDecl = Data.InstanceHasMoreThanOneDecl;
6972 FactoryHasMoreThanOneDecl = Data.FactoryHasMoreThanOneDecl;
Guy Benyei11169dd2012-12-18 14:30:41 +00006973 return true;
6974 }
6975
6976 /// \brief Retrieve the instance methods found by this visitor.
6977 ArrayRef<ObjCMethodDecl *> getInstanceMethods() const {
6978 return InstanceMethods;
6979 }
6980
6981 /// \brief Retrieve the instance methods found by this visitor.
6982 ArrayRef<ObjCMethodDecl *> getFactoryMethods() const {
6983 return FactoryMethods;
6984 }
Argyrios Kyrtzidisd3da6e02013-04-17 00:08:58 +00006985
6986 unsigned getInstanceBits() const { return InstanceBits; }
6987 unsigned getFactoryBits() const { return FactoryBits; }
Nico Weberff4b35e2014-12-27 22:14:15 +00006988 bool instanceHasMoreThanOneDecl() const {
6989 return InstanceHasMoreThanOneDecl;
6990 }
6991 bool factoryHasMoreThanOneDecl() const { return FactoryHasMoreThanOneDecl; }
Guy Benyei11169dd2012-12-18 14:30:41 +00006992 };
Alexander Kornienkoab9db512015-06-22 23:07:51 +00006993} } // end namespace clang::serialization
Guy Benyei11169dd2012-12-18 14:30:41 +00006994
6995/// \brief Add the given set of methods to the method list.
6996static void addMethodsToPool(Sema &S, ArrayRef<ObjCMethodDecl *> Methods,
6997 ObjCMethodList &List) {
6998 for (unsigned I = 0, N = Methods.size(); I != N; ++I) {
6999 S.addMethodToGlobalList(&List, Methods[I]);
7000 }
7001}
7002
7003void ASTReader::ReadMethodPool(Selector Sel) {
7004 // Get the selector generation and update it to the current generation.
7005 unsigned &Generation = SelectorGeneration[Sel];
7006 unsigned PriorGeneration = Generation;
Richard Smith053f6c62014-05-16 23:01:30 +00007007 Generation = getGeneration();
Guy Benyei11169dd2012-12-18 14:30:41 +00007008
7009 // Search for methods defined with this selector.
Douglas Gregorad2f7a52013-01-28 17:54:36 +00007010 ++NumMethodPoolLookups;
Guy Benyei11169dd2012-12-18 14:30:41 +00007011 ReadMethodPoolVisitor Visitor(*this, Sel, PriorGeneration);
Benjamin Kramer9a9efba2015-07-25 12:14:04 +00007012 ModuleMgr.visit(Visitor);
7013
Guy Benyei11169dd2012-12-18 14:30:41 +00007014 if (Visitor.getInstanceMethods().empty() &&
Douglas Gregorad2f7a52013-01-28 17:54:36 +00007015 Visitor.getFactoryMethods().empty())
Guy Benyei11169dd2012-12-18 14:30:41 +00007016 return;
Douglas Gregorad2f7a52013-01-28 17:54:36 +00007017
7018 ++NumMethodPoolHits;
7019
Guy Benyei11169dd2012-12-18 14:30:41 +00007020 if (!getSema())
7021 return;
7022
7023 Sema &S = *getSema();
7024 Sema::GlobalMethodPool::iterator Pos
7025 = S.MethodPool.insert(std::make_pair(Sel, Sema::GlobalMethods())).first;
Ben Langmuira0c32e92015-01-12 19:27:00 +00007026
Argyrios Kyrtzidisd3da6e02013-04-17 00:08:58 +00007027 Pos->second.first.setBits(Visitor.getInstanceBits());
Nico Weberff4b35e2014-12-27 22:14:15 +00007028 Pos->second.first.setHasMoreThanOneDecl(Visitor.instanceHasMoreThanOneDecl());
Argyrios Kyrtzidisd3da6e02013-04-17 00:08:58 +00007029 Pos->second.second.setBits(Visitor.getFactoryBits());
Nico Weberff4b35e2014-12-27 22:14:15 +00007030 Pos->second.second.setHasMoreThanOneDecl(Visitor.factoryHasMoreThanOneDecl());
Ben Langmuira0c32e92015-01-12 19:27:00 +00007031
7032 // Add methods to the global pool *after* setting hasMoreThanOneDecl, since
7033 // when building a module we keep every method individually and may need to
7034 // update hasMoreThanOneDecl as we add the methods.
7035 addMethodsToPool(S, Visitor.getInstanceMethods(), Pos->second.first);
7036 addMethodsToPool(S, Visitor.getFactoryMethods(), Pos->second.second);
Guy Benyei11169dd2012-12-18 14:30:41 +00007037}
7038
7039void ASTReader::ReadKnownNamespaces(
7040 SmallVectorImpl<NamespaceDecl *> &Namespaces) {
7041 Namespaces.clear();
7042
7043 for (unsigned I = 0, N = KnownNamespaces.size(); I != N; ++I) {
7044 if (NamespaceDecl *Namespace
7045 = dyn_cast_or_null<NamespaceDecl>(GetDecl(KnownNamespaces[I])))
7046 Namespaces.push_back(Namespace);
7047 }
7048}
7049
Nick Lewycky9c7eb1d2013-02-01 08:13:20 +00007050void ASTReader::ReadUndefinedButUsed(
Nick Lewyckyf0f56162013-01-31 03:23:57 +00007051 llvm::DenseMap<NamedDecl*, SourceLocation> &Undefined) {
Nick Lewycky9c7eb1d2013-02-01 08:13:20 +00007052 for (unsigned Idx = 0, N = UndefinedButUsed.size(); Idx != N;) {
7053 NamedDecl *D = cast<NamedDecl>(GetDecl(UndefinedButUsed[Idx++]));
Nick Lewycky8334af82013-01-26 00:35:08 +00007054 SourceLocation Loc =
Nick Lewycky9c7eb1d2013-02-01 08:13:20 +00007055 SourceLocation::getFromRawEncoding(UndefinedButUsed[Idx++]);
Nick Lewycky8334af82013-01-26 00:35:08 +00007056 Undefined.insert(std::make_pair(D, Loc));
7057 }
7058}
Nick Lewycky8334af82013-01-26 00:35:08 +00007059
Ismail Pazarbasie5768d12015-05-18 19:59:11 +00007060void ASTReader::ReadMismatchingDeleteExpressions(llvm::MapVector<
7061 FieldDecl *, llvm::SmallVector<std::pair<SourceLocation, bool>, 4>> &
7062 Exprs) {
7063 for (unsigned Idx = 0, N = DelayedDeleteExprs.size(); Idx != N;) {
7064 FieldDecl *FD = cast<FieldDecl>(GetDecl(DelayedDeleteExprs[Idx++]));
7065 uint64_t Count = DelayedDeleteExprs[Idx++];
7066 for (uint64_t C = 0; C < Count; ++C) {
7067 SourceLocation DeleteLoc =
7068 SourceLocation::getFromRawEncoding(DelayedDeleteExprs[Idx++]);
7069 const bool IsArrayForm = DelayedDeleteExprs[Idx++];
7070 Exprs[FD].push_back(std::make_pair(DeleteLoc, IsArrayForm));
7071 }
7072 }
7073}
7074
Guy Benyei11169dd2012-12-18 14:30:41 +00007075void ASTReader::ReadTentativeDefinitions(
7076 SmallVectorImpl<VarDecl *> &TentativeDefs) {
7077 for (unsigned I = 0, N = TentativeDefinitions.size(); I != N; ++I) {
7078 VarDecl *Var = dyn_cast_or_null<VarDecl>(GetDecl(TentativeDefinitions[I]));
7079 if (Var)
7080 TentativeDefs.push_back(Var);
7081 }
7082 TentativeDefinitions.clear();
7083}
7084
7085void ASTReader::ReadUnusedFileScopedDecls(
7086 SmallVectorImpl<const DeclaratorDecl *> &Decls) {
7087 for (unsigned I = 0, N = UnusedFileScopedDecls.size(); I != N; ++I) {
7088 DeclaratorDecl *D
7089 = dyn_cast_or_null<DeclaratorDecl>(GetDecl(UnusedFileScopedDecls[I]));
7090 if (D)
7091 Decls.push_back(D);
7092 }
7093 UnusedFileScopedDecls.clear();
7094}
7095
7096void ASTReader::ReadDelegatingConstructors(
7097 SmallVectorImpl<CXXConstructorDecl *> &Decls) {
7098 for (unsigned I = 0, N = DelegatingCtorDecls.size(); I != N; ++I) {
7099 CXXConstructorDecl *D
7100 = dyn_cast_or_null<CXXConstructorDecl>(GetDecl(DelegatingCtorDecls[I]));
7101 if (D)
7102 Decls.push_back(D);
7103 }
7104 DelegatingCtorDecls.clear();
7105}
7106
7107void ASTReader::ReadExtVectorDecls(SmallVectorImpl<TypedefNameDecl *> &Decls) {
7108 for (unsigned I = 0, N = ExtVectorDecls.size(); I != N; ++I) {
7109 TypedefNameDecl *D
7110 = dyn_cast_or_null<TypedefNameDecl>(GetDecl(ExtVectorDecls[I]));
7111 if (D)
7112 Decls.push_back(D);
7113 }
7114 ExtVectorDecls.clear();
7115}
7116
Nico Weber72889432014-09-06 01:25:55 +00007117void ASTReader::ReadUnusedLocalTypedefNameCandidates(
7118 llvm::SmallSetVector<const TypedefNameDecl *, 4> &Decls) {
7119 for (unsigned I = 0, N = UnusedLocalTypedefNameCandidates.size(); I != N;
7120 ++I) {
7121 TypedefNameDecl *D = dyn_cast_or_null<TypedefNameDecl>(
7122 GetDecl(UnusedLocalTypedefNameCandidates[I]));
7123 if (D)
7124 Decls.insert(D);
7125 }
7126 UnusedLocalTypedefNameCandidates.clear();
7127}
7128
Guy Benyei11169dd2012-12-18 14:30:41 +00007129void ASTReader::ReadReferencedSelectors(
7130 SmallVectorImpl<std::pair<Selector, SourceLocation> > &Sels) {
7131 if (ReferencedSelectorsData.empty())
7132 return;
7133
7134 // If there are @selector references added them to its pool. This is for
7135 // implementation of -Wselector.
7136 unsigned int DataSize = ReferencedSelectorsData.size()-1;
7137 unsigned I = 0;
7138 while (I < DataSize) {
7139 Selector Sel = DecodeSelector(ReferencedSelectorsData[I++]);
7140 SourceLocation SelLoc
7141 = SourceLocation::getFromRawEncoding(ReferencedSelectorsData[I++]);
7142 Sels.push_back(std::make_pair(Sel, SelLoc));
7143 }
7144 ReferencedSelectorsData.clear();
7145}
7146
7147void ASTReader::ReadWeakUndeclaredIdentifiers(
7148 SmallVectorImpl<std::pair<IdentifierInfo *, WeakInfo> > &WeakIDs) {
7149 if (WeakUndeclaredIdentifiers.empty())
7150 return;
7151
7152 for (unsigned I = 0, N = WeakUndeclaredIdentifiers.size(); I < N; /*none*/) {
7153 IdentifierInfo *WeakId
7154 = DecodeIdentifierInfo(WeakUndeclaredIdentifiers[I++]);
7155 IdentifierInfo *AliasId
7156 = DecodeIdentifierInfo(WeakUndeclaredIdentifiers[I++]);
7157 SourceLocation Loc
7158 = SourceLocation::getFromRawEncoding(WeakUndeclaredIdentifiers[I++]);
7159 bool Used = WeakUndeclaredIdentifiers[I++];
7160 WeakInfo WI(AliasId, Loc);
7161 WI.setUsed(Used);
7162 WeakIDs.push_back(std::make_pair(WeakId, WI));
7163 }
7164 WeakUndeclaredIdentifiers.clear();
7165}
7166
7167void ASTReader::ReadUsedVTables(SmallVectorImpl<ExternalVTableUse> &VTables) {
7168 for (unsigned Idx = 0, N = VTableUses.size(); Idx < N; /* In loop */) {
7169 ExternalVTableUse VT;
7170 VT.Record = dyn_cast_or_null<CXXRecordDecl>(GetDecl(VTableUses[Idx++]));
7171 VT.Location = SourceLocation::getFromRawEncoding(VTableUses[Idx++]);
7172 VT.DefinitionRequired = VTableUses[Idx++];
7173 VTables.push_back(VT);
7174 }
7175
7176 VTableUses.clear();
7177}
7178
7179void ASTReader::ReadPendingInstantiations(
7180 SmallVectorImpl<std::pair<ValueDecl *, SourceLocation> > &Pending) {
7181 for (unsigned Idx = 0, N = PendingInstantiations.size(); Idx < N;) {
7182 ValueDecl *D = cast<ValueDecl>(GetDecl(PendingInstantiations[Idx++]));
7183 SourceLocation Loc
7184 = SourceLocation::getFromRawEncoding(PendingInstantiations[Idx++]);
7185
7186 Pending.push_back(std::make_pair(D, Loc));
7187 }
7188 PendingInstantiations.clear();
7189}
7190
Richard Smithe40f2ba2013-08-07 21:41:30 +00007191void ASTReader::ReadLateParsedTemplates(
Chandler Carruth52cee4d2015-03-26 09:08:15 +00007192 llvm::MapVector<const FunctionDecl *, LateParsedTemplate *> &LPTMap) {
Richard Smithe40f2ba2013-08-07 21:41:30 +00007193 for (unsigned Idx = 0, N = LateParsedTemplates.size(); Idx < N;
7194 /* In loop */) {
7195 FunctionDecl *FD = cast<FunctionDecl>(GetDecl(LateParsedTemplates[Idx++]));
7196
7197 LateParsedTemplate *LT = new LateParsedTemplate;
7198 LT->D = GetDecl(LateParsedTemplates[Idx++]);
7199
7200 ModuleFile *F = getOwningModuleFile(LT->D);
7201 assert(F && "No module");
7202
7203 unsigned TokN = LateParsedTemplates[Idx++];
7204 LT->Toks.reserve(TokN);
7205 for (unsigned T = 0; T < TokN; ++T)
7206 LT->Toks.push_back(ReadToken(*F, LateParsedTemplates, Idx));
7207
Chandler Carruth52cee4d2015-03-26 09:08:15 +00007208 LPTMap.insert(std::make_pair(FD, LT));
Richard Smithe40f2ba2013-08-07 21:41:30 +00007209 }
7210
7211 LateParsedTemplates.clear();
7212}
7213
Guy Benyei11169dd2012-12-18 14:30:41 +00007214void ASTReader::LoadSelector(Selector Sel) {
7215 // It would be complicated to avoid reading the methods anyway. So don't.
7216 ReadMethodPool(Sel);
7217}
7218
7219void ASTReader::SetIdentifierInfo(IdentifierID ID, IdentifierInfo *II) {
7220 assert(ID && "Non-zero identifier ID required");
7221 assert(ID <= IdentifiersLoaded.size() && "identifier ID out of range");
7222 IdentifiersLoaded[ID - 1] = II;
7223 if (DeserializationListener)
7224 DeserializationListener->IdentifierRead(ID, II);
7225}
7226
7227/// \brief Set the globally-visible declarations associated with the given
7228/// identifier.
7229///
7230/// If the AST reader is currently in a state where the given declaration IDs
7231/// cannot safely be resolved, they are queued until it is safe to resolve
7232/// them.
7233///
7234/// \param II an IdentifierInfo that refers to one or more globally-visible
7235/// declarations.
7236///
7237/// \param DeclIDs the set of declaration IDs with the name @p II that are
7238/// visible at global scope.
7239///
Douglas Gregor6168bd22013-02-18 15:53:43 +00007240/// \param Decls if non-null, this vector will be populated with the set of
7241/// deserialized declarations. These declarations will not be pushed into
7242/// scope.
Guy Benyei11169dd2012-12-18 14:30:41 +00007243void
7244ASTReader::SetGloballyVisibleDecls(IdentifierInfo *II,
7245 const SmallVectorImpl<uint32_t> &DeclIDs,
Douglas Gregor6168bd22013-02-18 15:53:43 +00007246 SmallVectorImpl<Decl *> *Decls) {
7247 if (NumCurrentElementsDeserializing && !Decls) {
7248 PendingIdentifierInfos[II].append(DeclIDs.begin(), DeclIDs.end());
Guy Benyei11169dd2012-12-18 14:30:41 +00007249 return;
7250 }
7251
7252 for (unsigned I = 0, N = DeclIDs.size(); I != N; ++I) {
Ben Langmuir5418f402014-09-10 21:29:41 +00007253 if (!SemaObj) {
Guy Benyei11169dd2012-12-18 14:30:41 +00007254 // Queue this declaration so that it will be added to the
7255 // translation unit scope and identifier's declaration chain
7256 // once a Sema object is known.
Ben Langmuir5418f402014-09-10 21:29:41 +00007257 PreloadedDeclIDs.push_back(DeclIDs[I]);
7258 continue;
Guy Benyei11169dd2012-12-18 14:30:41 +00007259 }
Ben Langmuir5418f402014-09-10 21:29:41 +00007260
7261 NamedDecl *D = cast<NamedDecl>(GetDecl(DeclIDs[I]));
7262
7263 // If we're simply supposed to record the declarations, do so now.
7264 if (Decls) {
7265 Decls->push_back(D);
7266 continue;
7267 }
7268
7269 // Introduce this declaration into the translation-unit scope
7270 // and add it to the declaration chain for this identifier, so
7271 // that (unqualified) name lookup will find it.
7272 pushExternalDeclIntoScope(D, II);
Guy Benyei11169dd2012-12-18 14:30:41 +00007273 }
7274}
7275
Douglas Gregorc8a992f2013-01-21 16:52:34 +00007276IdentifierInfo *ASTReader::DecodeIdentifierInfo(IdentifierID ID) {
Guy Benyei11169dd2012-12-18 14:30:41 +00007277 if (ID == 0)
Craig Toppera13603a2014-05-22 05:54:18 +00007278 return nullptr;
Guy Benyei11169dd2012-12-18 14:30:41 +00007279
7280 if (IdentifiersLoaded.empty()) {
7281 Error("no identifier table in AST file");
Craig Toppera13603a2014-05-22 05:54:18 +00007282 return nullptr;
Guy Benyei11169dd2012-12-18 14:30:41 +00007283 }
7284
7285 ID -= 1;
7286 if (!IdentifiersLoaded[ID]) {
7287 GlobalIdentifierMapType::iterator I = GlobalIdentifierMap.find(ID + 1);
7288 assert(I != GlobalIdentifierMap.end() && "Corrupted global identifier map");
7289 ModuleFile *M = I->second;
7290 unsigned Index = ID - M->BaseIdentifierID;
7291 const char *Str = M->IdentifierTableData + M->IdentifierOffsets[Index];
7292
7293 // All of the strings in the AST file are preceded by a 16-bit length.
7294 // Extract that 16-bit length to avoid having to execute strlen().
7295 // NOTE: 'StrLenPtr' is an 'unsigned char*' so that we load bytes as
7296 // unsigned integers. This is important to avoid integer overflow when
7297 // we cast them to 'unsigned'.
7298 const unsigned char *StrLenPtr = (const unsigned char*) Str - 2;
7299 unsigned StrLen = (((unsigned) StrLenPtr[0])
7300 | (((unsigned) StrLenPtr[1]) << 8)) - 1;
Douglas Gregorc8a992f2013-01-21 16:52:34 +00007301 IdentifiersLoaded[ID]
7302 = &PP.getIdentifierTable().get(StringRef(Str, StrLen));
Guy Benyei11169dd2012-12-18 14:30:41 +00007303 if (DeserializationListener)
7304 DeserializationListener->IdentifierRead(ID + 1, IdentifiersLoaded[ID]);
7305 }
7306
7307 return IdentifiersLoaded[ID];
7308}
7309
Douglas Gregorc8a992f2013-01-21 16:52:34 +00007310IdentifierInfo *ASTReader::getLocalIdentifier(ModuleFile &M, unsigned LocalID) {
7311 return DecodeIdentifierInfo(getGlobalIdentifierID(M, LocalID));
Guy Benyei11169dd2012-12-18 14:30:41 +00007312}
7313
7314IdentifierID ASTReader::getGlobalIdentifierID(ModuleFile &M, unsigned LocalID) {
7315 if (LocalID < NUM_PREDEF_IDENT_IDS)
7316 return LocalID;
7317
7318 ContinuousRangeMap<uint32_t, int, 2>::iterator I
7319 = M.IdentifierRemap.find(LocalID - NUM_PREDEF_IDENT_IDS);
7320 assert(I != M.IdentifierRemap.end()
7321 && "Invalid index into identifier index remap");
7322
7323 return LocalID + I->second;
7324}
7325
Argyrios Kyrtzidiseb663da2013-03-22 21:12:57 +00007326MacroInfo *ASTReader::getMacro(MacroID ID) {
Guy Benyei11169dd2012-12-18 14:30:41 +00007327 if (ID == 0)
Craig Toppera13603a2014-05-22 05:54:18 +00007328 return nullptr;
Guy Benyei11169dd2012-12-18 14:30:41 +00007329
7330 if (MacrosLoaded.empty()) {
7331 Error("no macro table in AST file");
Craig Toppera13603a2014-05-22 05:54:18 +00007332 return nullptr;
Guy Benyei11169dd2012-12-18 14:30:41 +00007333 }
7334
7335 ID -= NUM_PREDEF_MACRO_IDS;
7336 if (!MacrosLoaded[ID]) {
7337 GlobalMacroMapType::iterator I
7338 = GlobalMacroMap.find(ID + NUM_PREDEF_MACRO_IDS);
7339 assert(I != GlobalMacroMap.end() && "Corrupted global macro map");
7340 ModuleFile *M = I->second;
7341 unsigned Index = ID - M->BaseMacroID;
Argyrios Kyrtzidiseb663da2013-03-22 21:12:57 +00007342 MacrosLoaded[ID] = ReadMacroRecord(*M, M->MacroOffsets[Index]);
7343
7344 if (DeserializationListener)
7345 DeserializationListener->MacroRead(ID + NUM_PREDEF_MACRO_IDS,
7346 MacrosLoaded[ID]);
Guy Benyei11169dd2012-12-18 14:30:41 +00007347 }
7348
7349 return MacrosLoaded[ID];
7350}
7351
7352MacroID ASTReader::getGlobalMacroID(ModuleFile &M, unsigned LocalID) {
7353 if (LocalID < NUM_PREDEF_MACRO_IDS)
7354 return LocalID;
7355
7356 ContinuousRangeMap<uint32_t, int, 2>::iterator I
7357 = M.MacroRemap.find(LocalID - NUM_PREDEF_MACRO_IDS);
7358 assert(I != M.MacroRemap.end() && "Invalid index into macro index remap");
7359
7360 return LocalID + I->second;
7361}
7362
7363serialization::SubmoduleID
7364ASTReader::getGlobalSubmoduleID(ModuleFile &M, unsigned LocalID) {
7365 if (LocalID < NUM_PREDEF_SUBMODULE_IDS)
7366 return LocalID;
7367
7368 ContinuousRangeMap<uint32_t, int, 2>::iterator I
7369 = M.SubmoduleRemap.find(LocalID - NUM_PREDEF_SUBMODULE_IDS);
7370 assert(I != M.SubmoduleRemap.end()
7371 && "Invalid index into submodule index remap");
7372
7373 return LocalID + I->second;
7374}
7375
7376Module *ASTReader::getSubmodule(SubmoduleID GlobalID) {
7377 if (GlobalID < NUM_PREDEF_SUBMODULE_IDS) {
7378 assert(GlobalID == 0 && "Unhandled global submodule ID");
Craig Toppera13603a2014-05-22 05:54:18 +00007379 return nullptr;
Guy Benyei11169dd2012-12-18 14:30:41 +00007380 }
7381
7382 if (GlobalID > SubmodulesLoaded.size()) {
7383 Error("submodule ID out of range in AST file");
Craig Toppera13603a2014-05-22 05:54:18 +00007384 return nullptr;
Guy Benyei11169dd2012-12-18 14:30:41 +00007385 }
7386
7387 return SubmodulesLoaded[GlobalID - NUM_PREDEF_SUBMODULE_IDS];
7388}
Douglas Gregorc147b0b2013-01-12 01:29:50 +00007389
7390Module *ASTReader::getModule(unsigned ID) {
7391 return getSubmodule(ID);
7392}
7393
Adrian Prantl15bcf702015-06-30 17:39:43 +00007394ExternalASTSource::ASTSourceDescriptor
7395ASTReader::getSourceDescriptor(const Module &M) {
7396 StringRef Dir, Filename;
7397 if (M.Directory)
7398 Dir = M.Directory->getName();
7399 if (auto *File = M.getASTFile())
7400 Filename = File->getName();
7401 return ASTReader::ASTSourceDescriptor{
7402 M.getFullModuleName(), Dir, Filename,
7403 M.Signature
7404 };
7405}
7406
7407llvm::Optional<ExternalASTSource::ASTSourceDescriptor>
7408ASTReader::getSourceDescriptor(unsigned ID) {
7409 if (const Module *M = getSubmodule(ID))
7410 return getSourceDescriptor(*M);
7411
7412 // If there is only a single PCH, return it instead.
7413 // Chained PCH are not suported.
7414 if (ModuleMgr.size() == 1) {
7415 ModuleFile &MF = ModuleMgr.getPrimaryModule();
7416 return ASTReader::ASTSourceDescriptor{
7417 MF.OriginalSourceFileName, MF.OriginalDir,
7418 MF.FileName,
7419 MF.Signature
7420 };
7421 }
7422 return None;
7423}
7424
Guy Benyei11169dd2012-12-18 14:30:41 +00007425Selector ASTReader::getLocalSelector(ModuleFile &M, unsigned LocalID) {
7426 return DecodeSelector(getGlobalSelectorID(M, LocalID));
7427}
7428
7429Selector ASTReader::DecodeSelector(serialization::SelectorID ID) {
7430 if (ID == 0)
7431 return Selector();
7432
7433 if (ID > SelectorsLoaded.size()) {
7434 Error("selector ID out of range in AST file");
7435 return Selector();
7436 }
7437
Craig Toppera13603a2014-05-22 05:54:18 +00007438 if (SelectorsLoaded[ID - 1].getAsOpaquePtr() == nullptr) {
Guy Benyei11169dd2012-12-18 14:30:41 +00007439 // Load this selector from the selector table.
7440 GlobalSelectorMapType::iterator I = GlobalSelectorMap.find(ID);
7441 assert(I != GlobalSelectorMap.end() && "Corrupted global selector map");
7442 ModuleFile &M = *I->second;
7443 ASTSelectorLookupTrait Trait(*this, M);
7444 unsigned Idx = ID - M.BaseSelectorID - NUM_PREDEF_SELECTOR_IDS;
7445 SelectorsLoaded[ID - 1] =
7446 Trait.ReadKey(M.SelectorLookupTableData + M.SelectorOffsets[Idx], 0);
7447 if (DeserializationListener)
7448 DeserializationListener->SelectorRead(ID, SelectorsLoaded[ID - 1]);
7449 }
7450
7451 return SelectorsLoaded[ID - 1];
7452}
7453
7454Selector ASTReader::GetExternalSelector(serialization::SelectorID ID) {
7455 return DecodeSelector(ID);
7456}
7457
7458uint32_t ASTReader::GetNumExternalSelectors() {
7459 // ID 0 (the null selector) is considered an external selector.
7460 return getTotalNumSelectors() + 1;
7461}
7462
7463serialization::SelectorID
7464ASTReader::getGlobalSelectorID(ModuleFile &M, unsigned LocalID) const {
7465 if (LocalID < NUM_PREDEF_SELECTOR_IDS)
7466 return LocalID;
7467
7468 ContinuousRangeMap<uint32_t, int, 2>::iterator I
7469 = M.SelectorRemap.find(LocalID - NUM_PREDEF_SELECTOR_IDS);
7470 assert(I != M.SelectorRemap.end()
7471 && "Invalid index into selector index remap");
7472
7473 return LocalID + I->second;
7474}
7475
7476DeclarationName
7477ASTReader::ReadDeclarationName(ModuleFile &F,
7478 const RecordData &Record, unsigned &Idx) {
7479 DeclarationName::NameKind Kind = (DeclarationName::NameKind)Record[Idx++];
7480 switch (Kind) {
7481 case DeclarationName::Identifier:
Douglas Gregorc8a992f2013-01-21 16:52:34 +00007482 return DeclarationName(GetIdentifierInfo(F, Record, Idx));
Guy Benyei11169dd2012-12-18 14:30:41 +00007483
7484 case DeclarationName::ObjCZeroArgSelector:
7485 case DeclarationName::ObjCOneArgSelector:
7486 case DeclarationName::ObjCMultiArgSelector:
7487 return DeclarationName(ReadSelector(F, Record, Idx));
7488
7489 case DeclarationName::CXXConstructorName:
7490 return Context.DeclarationNames.getCXXConstructorName(
7491 Context.getCanonicalType(readType(F, Record, Idx)));
7492
7493 case DeclarationName::CXXDestructorName:
7494 return Context.DeclarationNames.getCXXDestructorName(
7495 Context.getCanonicalType(readType(F, Record, Idx)));
7496
7497 case DeclarationName::CXXConversionFunctionName:
7498 return Context.DeclarationNames.getCXXConversionFunctionName(
7499 Context.getCanonicalType(readType(F, Record, Idx)));
7500
7501 case DeclarationName::CXXOperatorName:
7502 return Context.DeclarationNames.getCXXOperatorName(
7503 (OverloadedOperatorKind)Record[Idx++]);
7504
7505 case DeclarationName::CXXLiteralOperatorName:
7506 return Context.DeclarationNames.getCXXLiteralOperatorName(
7507 GetIdentifierInfo(F, Record, Idx));
7508
7509 case DeclarationName::CXXUsingDirective:
7510 return DeclarationName::getUsingDirectiveName();
7511 }
7512
7513 llvm_unreachable("Invalid NameKind!");
7514}
7515
7516void ASTReader::ReadDeclarationNameLoc(ModuleFile &F,
7517 DeclarationNameLoc &DNLoc,
7518 DeclarationName Name,
7519 const RecordData &Record, unsigned &Idx) {
7520 switch (Name.getNameKind()) {
7521 case DeclarationName::CXXConstructorName:
7522 case DeclarationName::CXXDestructorName:
7523 case DeclarationName::CXXConversionFunctionName:
7524 DNLoc.NamedType.TInfo = GetTypeSourceInfo(F, Record, Idx);
7525 break;
7526
7527 case DeclarationName::CXXOperatorName:
7528 DNLoc.CXXOperatorName.BeginOpNameLoc
7529 = ReadSourceLocation(F, Record, Idx).getRawEncoding();
7530 DNLoc.CXXOperatorName.EndOpNameLoc
7531 = ReadSourceLocation(F, Record, Idx).getRawEncoding();
7532 break;
7533
7534 case DeclarationName::CXXLiteralOperatorName:
7535 DNLoc.CXXLiteralOperatorName.OpNameLoc
7536 = ReadSourceLocation(F, Record, Idx).getRawEncoding();
7537 break;
7538
7539 case DeclarationName::Identifier:
7540 case DeclarationName::ObjCZeroArgSelector:
7541 case DeclarationName::ObjCOneArgSelector:
7542 case DeclarationName::ObjCMultiArgSelector:
7543 case DeclarationName::CXXUsingDirective:
7544 break;
7545 }
7546}
7547
7548void ASTReader::ReadDeclarationNameInfo(ModuleFile &F,
7549 DeclarationNameInfo &NameInfo,
7550 const RecordData &Record, unsigned &Idx) {
7551 NameInfo.setName(ReadDeclarationName(F, Record, Idx));
7552 NameInfo.setLoc(ReadSourceLocation(F, Record, Idx));
7553 DeclarationNameLoc DNLoc;
7554 ReadDeclarationNameLoc(F, DNLoc, NameInfo.getName(), Record, Idx);
7555 NameInfo.setInfo(DNLoc);
7556}
7557
7558void ASTReader::ReadQualifierInfo(ModuleFile &F, QualifierInfo &Info,
7559 const RecordData &Record, unsigned &Idx) {
7560 Info.QualifierLoc = ReadNestedNameSpecifierLoc(F, Record, Idx);
7561 unsigned NumTPLists = Record[Idx++];
7562 Info.NumTemplParamLists = NumTPLists;
7563 if (NumTPLists) {
7564 Info.TemplParamLists = new (Context) TemplateParameterList*[NumTPLists];
7565 for (unsigned i=0; i != NumTPLists; ++i)
7566 Info.TemplParamLists[i] = ReadTemplateParameterList(F, Record, Idx);
7567 }
7568}
7569
7570TemplateName
7571ASTReader::ReadTemplateName(ModuleFile &F, const RecordData &Record,
7572 unsigned &Idx) {
7573 TemplateName::NameKind Kind = (TemplateName::NameKind)Record[Idx++];
7574 switch (Kind) {
7575 case TemplateName::Template:
7576 return TemplateName(ReadDeclAs<TemplateDecl>(F, Record, Idx));
7577
7578 case TemplateName::OverloadedTemplate: {
7579 unsigned size = Record[Idx++];
7580 UnresolvedSet<8> Decls;
7581 while (size--)
7582 Decls.addDecl(ReadDeclAs<NamedDecl>(F, Record, Idx));
7583
7584 return Context.getOverloadedTemplateName(Decls.begin(), Decls.end());
7585 }
7586
7587 case TemplateName::QualifiedTemplate: {
7588 NestedNameSpecifier *NNS = ReadNestedNameSpecifier(F, Record, Idx);
7589 bool hasTemplKeyword = Record[Idx++];
7590 TemplateDecl *Template = ReadDeclAs<TemplateDecl>(F, Record, Idx);
7591 return Context.getQualifiedTemplateName(NNS, hasTemplKeyword, Template);
7592 }
7593
7594 case TemplateName::DependentTemplate: {
7595 NestedNameSpecifier *NNS = ReadNestedNameSpecifier(F, Record, Idx);
7596 if (Record[Idx++]) // isIdentifier
7597 return Context.getDependentTemplateName(NNS,
7598 GetIdentifierInfo(F, Record,
7599 Idx));
7600 return Context.getDependentTemplateName(NNS,
7601 (OverloadedOperatorKind)Record[Idx++]);
7602 }
7603
7604 case TemplateName::SubstTemplateTemplateParm: {
7605 TemplateTemplateParmDecl *param
7606 = ReadDeclAs<TemplateTemplateParmDecl>(F, Record, Idx);
7607 if (!param) return TemplateName();
7608 TemplateName replacement = ReadTemplateName(F, Record, Idx);
7609 return Context.getSubstTemplateTemplateParm(param, replacement);
7610 }
7611
7612 case TemplateName::SubstTemplateTemplateParmPack: {
7613 TemplateTemplateParmDecl *Param
7614 = ReadDeclAs<TemplateTemplateParmDecl>(F, Record, Idx);
7615 if (!Param)
7616 return TemplateName();
7617
7618 TemplateArgument ArgPack = ReadTemplateArgument(F, Record, Idx);
7619 if (ArgPack.getKind() != TemplateArgument::Pack)
7620 return TemplateName();
7621
7622 return Context.getSubstTemplateTemplateParmPack(Param, ArgPack);
7623 }
7624 }
7625
7626 llvm_unreachable("Unhandled template name kind!");
7627}
7628
Richard Smith2bb3c342015-08-09 01:05:31 +00007629TemplateArgument ASTReader::ReadTemplateArgument(ModuleFile &F,
7630 const RecordData &Record,
7631 unsigned &Idx,
7632 bool Canonicalize) {
7633 if (Canonicalize) {
7634 // The caller wants a canonical template argument. Sometimes the AST only
7635 // wants template arguments in canonical form (particularly as the template
7636 // argument lists of template specializations) so ensure we preserve that
7637 // canonical form across serialization.
7638 TemplateArgument Arg = ReadTemplateArgument(F, Record, Idx, false);
7639 return Context.getCanonicalTemplateArgument(Arg);
7640 }
7641
Guy Benyei11169dd2012-12-18 14:30:41 +00007642 TemplateArgument::ArgKind Kind = (TemplateArgument::ArgKind)Record[Idx++];
7643 switch (Kind) {
7644 case TemplateArgument::Null:
7645 return TemplateArgument();
7646 case TemplateArgument::Type:
7647 return TemplateArgument(readType(F, Record, Idx));
7648 case TemplateArgument::Declaration: {
7649 ValueDecl *D = ReadDeclAs<ValueDecl>(F, Record, Idx);
David Blaikie0f62c8d2014-10-16 04:21:25 +00007650 return TemplateArgument(D, readType(F, Record, Idx));
Guy Benyei11169dd2012-12-18 14:30:41 +00007651 }
7652 case TemplateArgument::NullPtr:
7653 return TemplateArgument(readType(F, Record, Idx), /*isNullPtr*/true);
7654 case TemplateArgument::Integral: {
7655 llvm::APSInt Value = ReadAPSInt(Record, Idx);
7656 QualType T = readType(F, Record, Idx);
7657 return TemplateArgument(Context, Value, T);
7658 }
7659 case TemplateArgument::Template:
7660 return TemplateArgument(ReadTemplateName(F, Record, Idx));
7661 case TemplateArgument::TemplateExpansion: {
7662 TemplateName Name = ReadTemplateName(F, Record, Idx);
David Blaikie05785d12013-02-20 22:23:23 +00007663 Optional<unsigned> NumTemplateExpansions;
Guy Benyei11169dd2012-12-18 14:30:41 +00007664 if (unsigned NumExpansions = Record[Idx++])
7665 NumTemplateExpansions = NumExpansions - 1;
7666 return TemplateArgument(Name, NumTemplateExpansions);
7667 }
7668 case TemplateArgument::Expression:
7669 return TemplateArgument(ReadExpr(F));
7670 case TemplateArgument::Pack: {
7671 unsigned NumArgs = Record[Idx++];
7672 TemplateArgument *Args = new (Context) TemplateArgument[NumArgs];
7673 for (unsigned I = 0; I != NumArgs; ++I)
7674 Args[I] = ReadTemplateArgument(F, Record, Idx);
Benjamin Kramercce63472015-08-05 09:40:22 +00007675 return TemplateArgument(llvm::makeArrayRef(Args, NumArgs));
Guy Benyei11169dd2012-12-18 14:30:41 +00007676 }
7677 }
7678
7679 llvm_unreachable("Unhandled template argument kind!");
7680}
7681
7682TemplateParameterList *
7683ASTReader::ReadTemplateParameterList(ModuleFile &F,
7684 const RecordData &Record, unsigned &Idx) {
7685 SourceLocation TemplateLoc = ReadSourceLocation(F, Record, Idx);
7686 SourceLocation LAngleLoc = ReadSourceLocation(F, Record, Idx);
7687 SourceLocation RAngleLoc = ReadSourceLocation(F, Record, Idx);
7688
7689 unsigned NumParams = Record[Idx++];
7690 SmallVector<NamedDecl *, 16> Params;
7691 Params.reserve(NumParams);
7692 while (NumParams--)
7693 Params.push_back(ReadDeclAs<NamedDecl>(F, Record, Idx));
7694
7695 TemplateParameterList* TemplateParams =
7696 TemplateParameterList::Create(Context, TemplateLoc, LAngleLoc,
7697 Params.data(), Params.size(), RAngleLoc);
7698 return TemplateParams;
7699}
7700
7701void
7702ASTReader::
Craig Topper5603df42013-07-05 19:34:19 +00007703ReadTemplateArgumentList(SmallVectorImpl<TemplateArgument> &TemplArgs,
Guy Benyei11169dd2012-12-18 14:30:41 +00007704 ModuleFile &F, const RecordData &Record,
Richard Smith2bb3c342015-08-09 01:05:31 +00007705 unsigned &Idx, bool Canonicalize) {
Guy Benyei11169dd2012-12-18 14:30:41 +00007706 unsigned NumTemplateArgs = Record[Idx++];
7707 TemplArgs.reserve(NumTemplateArgs);
7708 while (NumTemplateArgs--)
Richard Smith2bb3c342015-08-09 01:05:31 +00007709 TemplArgs.push_back(ReadTemplateArgument(F, Record, Idx, Canonicalize));
Guy Benyei11169dd2012-12-18 14:30:41 +00007710}
7711
7712/// \brief Read a UnresolvedSet structure.
Richard Smitha4ba74c2013-08-30 04:46:40 +00007713void ASTReader::ReadUnresolvedSet(ModuleFile &F, LazyASTUnresolvedSet &Set,
Guy Benyei11169dd2012-12-18 14:30:41 +00007714 const RecordData &Record, unsigned &Idx) {
7715 unsigned NumDecls = Record[Idx++];
7716 Set.reserve(Context, NumDecls);
7717 while (NumDecls--) {
Richard Smitha4ba74c2013-08-30 04:46:40 +00007718 DeclID ID = ReadDeclID(F, Record, Idx);
Guy Benyei11169dd2012-12-18 14:30:41 +00007719 AccessSpecifier AS = (AccessSpecifier)Record[Idx++];
Richard Smitha4ba74c2013-08-30 04:46:40 +00007720 Set.addLazyDecl(Context, ID, AS);
Guy Benyei11169dd2012-12-18 14:30:41 +00007721 }
7722}
7723
7724CXXBaseSpecifier
7725ASTReader::ReadCXXBaseSpecifier(ModuleFile &F,
7726 const RecordData &Record, unsigned &Idx) {
7727 bool isVirtual = static_cast<bool>(Record[Idx++]);
7728 bool isBaseOfClass = static_cast<bool>(Record[Idx++]);
7729 AccessSpecifier AS = static_cast<AccessSpecifier>(Record[Idx++]);
7730 bool inheritConstructors = static_cast<bool>(Record[Idx++]);
7731 TypeSourceInfo *TInfo = GetTypeSourceInfo(F, Record, Idx);
7732 SourceRange Range = ReadSourceRange(F, Record, Idx);
7733 SourceLocation EllipsisLoc = ReadSourceLocation(F, Record, Idx);
7734 CXXBaseSpecifier Result(Range, isVirtual, isBaseOfClass, AS, TInfo,
7735 EllipsisLoc);
7736 Result.setInheritConstructors(inheritConstructors);
7737 return Result;
7738}
7739
Richard Smithc2bb8182015-03-24 06:36:48 +00007740CXXCtorInitializer **
Guy Benyei11169dd2012-12-18 14:30:41 +00007741ASTReader::ReadCXXCtorInitializers(ModuleFile &F, const RecordData &Record,
7742 unsigned &Idx) {
Guy Benyei11169dd2012-12-18 14:30:41 +00007743 unsigned NumInitializers = Record[Idx++];
Richard Smithc2bb8182015-03-24 06:36:48 +00007744 assert(NumInitializers && "wrote ctor initializers but have no inits");
7745 auto **CtorInitializers = new (Context) CXXCtorInitializer*[NumInitializers];
7746 for (unsigned i = 0; i != NumInitializers; ++i) {
7747 TypeSourceInfo *TInfo = nullptr;
7748 bool IsBaseVirtual = false;
7749 FieldDecl *Member = nullptr;
7750 IndirectFieldDecl *IndirectMember = nullptr;
Guy Benyei11169dd2012-12-18 14:30:41 +00007751
Richard Smithc2bb8182015-03-24 06:36:48 +00007752 CtorInitializerType Type = (CtorInitializerType)Record[Idx++];
7753 switch (Type) {
7754 case CTOR_INITIALIZER_BASE:
7755 TInfo = GetTypeSourceInfo(F, Record, Idx);
7756 IsBaseVirtual = Record[Idx++];
7757 break;
Guy Benyei11169dd2012-12-18 14:30:41 +00007758
Richard Smithc2bb8182015-03-24 06:36:48 +00007759 case CTOR_INITIALIZER_DELEGATING:
7760 TInfo = GetTypeSourceInfo(F, Record, Idx);
7761 break;
Guy Benyei11169dd2012-12-18 14:30:41 +00007762
Richard Smithc2bb8182015-03-24 06:36:48 +00007763 case CTOR_INITIALIZER_MEMBER:
7764 Member = ReadDeclAs<FieldDecl>(F, Record, Idx);
7765 break;
Guy Benyei11169dd2012-12-18 14:30:41 +00007766
Richard Smithc2bb8182015-03-24 06:36:48 +00007767 case CTOR_INITIALIZER_INDIRECT_MEMBER:
7768 IndirectMember = ReadDeclAs<IndirectFieldDecl>(F, Record, Idx);
7769 break;
Guy Benyei11169dd2012-12-18 14:30:41 +00007770 }
Richard Smithc2bb8182015-03-24 06:36:48 +00007771
7772 SourceLocation MemberOrEllipsisLoc = ReadSourceLocation(F, Record, Idx);
7773 Expr *Init = ReadExpr(F);
7774 SourceLocation LParenLoc = ReadSourceLocation(F, Record, Idx);
7775 SourceLocation RParenLoc = ReadSourceLocation(F, Record, Idx);
7776 bool IsWritten = Record[Idx++];
7777 unsigned SourceOrderOrNumArrayIndices;
7778 SmallVector<VarDecl *, 8> Indices;
7779 if (IsWritten) {
7780 SourceOrderOrNumArrayIndices = Record[Idx++];
7781 } else {
7782 SourceOrderOrNumArrayIndices = Record[Idx++];
7783 Indices.reserve(SourceOrderOrNumArrayIndices);
7784 for (unsigned i=0; i != SourceOrderOrNumArrayIndices; ++i)
7785 Indices.push_back(ReadDeclAs<VarDecl>(F, Record, Idx));
7786 }
7787
7788 CXXCtorInitializer *BOMInit;
7789 if (Type == CTOR_INITIALIZER_BASE) {
7790 BOMInit = new (Context)
7791 CXXCtorInitializer(Context, TInfo, IsBaseVirtual, LParenLoc, Init,
7792 RParenLoc, MemberOrEllipsisLoc);
7793 } else if (Type == CTOR_INITIALIZER_DELEGATING) {
7794 BOMInit = new (Context)
7795 CXXCtorInitializer(Context, TInfo, LParenLoc, Init, RParenLoc);
7796 } else if (IsWritten) {
7797 if (Member)
7798 BOMInit = new (Context) CXXCtorInitializer(
7799 Context, Member, MemberOrEllipsisLoc, LParenLoc, Init, RParenLoc);
7800 else
7801 BOMInit = new (Context)
7802 CXXCtorInitializer(Context, IndirectMember, MemberOrEllipsisLoc,
7803 LParenLoc, Init, RParenLoc);
7804 } else {
7805 if (IndirectMember) {
7806 assert(Indices.empty() && "Indirect field improperly initialized");
7807 BOMInit = new (Context)
7808 CXXCtorInitializer(Context, IndirectMember, MemberOrEllipsisLoc,
7809 LParenLoc, Init, RParenLoc);
7810 } else {
7811 BOMInit = CXXCtorInitializer::Create(
7812 Context, Member, MemberOrEllipsisLoc, LParenLoc, Init, RParenLoc,
7813 Indices.data(), Indices.size());
7814 }
7815 }
7816
7817 if (IsWritten)
7818 BOMInit->setSourceOrder(SourceOrderOrNumArrayIndices);
7819 CtorInitializers[i] = BOMInit;
Guy Benyei11169dd2012-12-18 14:30:41 +00007820 }
7821
Richard Smithc2bb8182015-03-24 06:36:48 +00007822 return CtorInitializers;
Guy Benyei11169dd2012-12-18 14:30:41 +00007823}
7824
7825NestedNameSpecifier *
7826ASTReader::ReadNestedNameSpecifier(ModuleFile &F,
7827 const RecordData &Record, unsigned &Idx) {
7828 unsigned N = Record[Idx++];
Craig Toppera13603a2014-05-22 05:54:18 +00007829 NestedNameSpecifier *NNS = nullptr, *Prev = nullptr;
Guy Benyei11169dd2012-12-18 14:30:41 +00007830 for (unsigned I = 0; I != N; ++I) {
7831 NestedNameSpecifier::SpecifierKind Kind
7832 = (NestedNameSpecifier::SpecifierKind)Record[Idx++];
7833 switch (Kind) {
7834 case NestedNameSpecifier::Identifier: {
7835 IdentifierInfo *II = GetIdentifierInfo(F, Record, Idx);
7836 NNS = NestedNameSpecifier::Create(Context, Prev, II);
7837 break;
7838 }
7839
7840 case NestedNameSpecifier::Namespace: {
7841 NamespaceDecl *NS = ReadDeclAs<NamespaceDecl>(F, Record, Idx);
7842 NNS = NestedNameSpecifier::Create(Context, Prev, NS);
7843 break;
7844 }
7845
7846 case NestedNameSpecifier::NamespaceAlias: {
7847 NamespaceAliasDecl *Alias =ReadDeclAs<NamespaceAliasDecl>(F, Record, Idx);
7848 NNS = NestedNameSpecifier::Create(Context, Prev, Alias);
7849 break;
7850 }
7851
7852 case NestedNameSpecifier::TypeSpec:
7853 case NestedNameSpecifier::TypeSpecWithTemplate: {
7854 const Type *T = readType(F, Record, Idx).getTypePtrOrNull();
7855 if (!T)
Craig Toppera13603a2014-05-22 05:54:18 +00007856 return nullptr;
7857
Guy Benyei11169dd2012-12-18 14:30:41 +00007858 bool Template = Record[Idx++];
7859 NNS = NestedNameSpecifier::Create(Context, Prev, Template, T);
7860 break;
7861 }
7862
7863 case NestedNameSpecifier::Global: {
7864 NNS = NestedNameSpecifier::GlobalSpecifier(Context);
7865 // No associated value, and there can't be a prefix.
7866 break;
7867 }
Nikola Smiljanic67860242014-09-26 00:28:20 +00007868
7869 case NestedNameSpecifier::Super: {
7870 CXXRecordDecl *RD = ReadDeclAs<CXXRecordDecl>(F, Record, Idx);
7871 NNS = NestedNameSpecifier::SuperSpecifier(Context, RD);
7872 break;
7873 }
Guy Benyei11169dd2012-12-18 14:30:41 +00007874 }
7875 Prev = NNS;
7876 }
7877 return NNS;
7878}
7879
7880NestedNameSpecifierLoc
7881ASTReader::ReadNestedNameSpecifierLoc(ModuleFile &F, const RecordData &Record,
7882 unsigned &Idx) {
7883 unsigned N = Record[Idx++];
7884 NestedNameSpecifierLocBuilder Builder;
7885 for (unsigned I = 0; I != N; ++I) {
7886 NestedNameSpecifier::SpecifierKind Kind
7887 = (NestedNameSpecifier::SpecifierKind)Record[Idx++];
7888 switch (Kind) {
7889 case NestedNameSpecifier::Identifier: {
7890 IdentifierInfo *II = GetIdentifierInfo(F, Record, Idx);
7891 SourceRange Range = ReadSourceRange(F, Record, Idx);
7892 Builder.Extend(Context, II, Range.getBegin(), Range.getEnd());
7893 break;
7894 }
7895
7896 case NestedNameSpecifier::Namespace: {
7897 NamespaceDecl *NS = ReadDeclAs<NamespaceDecl>(F, Record, Idx);
7898 SourceRange Range = ReadSourceRange(F, Record, Idx);
7899 Builder.Extend(Context, NS, Range.getBegin(), Range.getEnd());
7900 break;
7901 }
7902
7903 case NestedNameSpecifier::NamespaceAlias: {
7904 NamespaceAliasDecl *Alias =ReadDeclAs<NamespaceAliasDecl>(F, Record, Idx);
7905 SourceRange Range = ReadSourceRange(F, Record, Idx);
7906 Builder.Extend(Context, Alias, Range.getBegin(), Range.getEnd());
7907 break;
7908 }
7909
7910 case NestedNameSpecifier::TypeSpec:
7911 case NestedNameSpecifier::TypeSpecWithTemplate: {
7912 bool Template = Record[Idx++];
7913 TypeSourceInfo *T = GetTypeSourceInfo(F, Record, Idx);
7914 if (!T)
7915 return NestedNameSpecifierLoc();
7916 SourceLocation ColonColonLoc = ReadSourceLocation(F, Record, Idx);
7917
7918 // FIXME: 'template' keyword location not saved anywhere, so we fake it.
7919 Builder.Extend(Context,
7920 Template? T->getTypeLoc().getBeginLoc() : SourceLocation(),
7921 T->getTypeLoc(), ColonColonLoc);
7922 break;
7923 }
7924
7925 case NestedNameSpecifier::Global: {
7926 SourceLocation ColonColonLoc = ReadSourceLocation(F, Record, Idx);
7927 Builder.MakeGlobal(Context, ColonColonLoc);
7928 break;
7929 }
Nikola Smiljanic67860242014-09-26 00:28:20 +00007930
7931 case NestedNameSpecifier::Super: {
7932 CXXRecordDecl *RD = ReadDeclAs<CXXRecordDecl>(F, Record, Idx);
7933 SourceRange Range = ReadSourceRange(F, Record, Idx);
7934 Builder.MakeSuper(Context, RD, Range.getBegin(), Range.getEnd());
7935 break;
7936 }
Guy Benyei11169dd2012-12-18 14:30:41 +00007937 }
7938 }
Nikola Smiljanic67860242014-09-26 00:28:20 +00007939
Guy Benyei11169dd2012-12-18 14:30:41 +00007940 return Builder.getWithLocInContext(Context);
7941}
7942
7943SourceRange
7944ASTReader::ReadSourceRange(ModuleFile &F, const RecordData &Record,
7945 unsigned &Idx) {
7946 SourceLocation beg = ReadSourceLocation(F, Record, Idx);
7947 SourceLocation end = ReadSourceLocation(F, Record, Idx);
7948 return SourceRange(beg, end);
7949}
7950
7951/// \brief Read an integral value
7952llvm::APInt ASTReader::ReadAPInt(const RecordData &Record, unsigned &Idx) {
7953 unsigned BitWidth = Record[Idx++];
7954 unsigned NumWords = llvm::APInt::getNumWords(BitWidth);
7955 llvm::APInt Result(BitWidth, NumWords, &Record[Idx]);
7956 Idx += NumWords;
7957 return Result;
7958}
7959
7960/// \brief Read a signed integral value
7961llvm::APSInt ASTReader::ReadAPSInt(const RecordData &Record, unsigned &Idx) {
7962 bool isUnsigned = Record[Idx++];
7963 return llvm::APSInt(ReadAPInt(Record, Idx), isUnsigned);
7964}
7965
7966/// \brief Read a floating-point value
Tim Northover178723a2013-01-22 09:46:51 +00007967llvm::APFloat ASTReader::ReadAPFloat(const RecordData &Record,
7968 const llvm::fltSemantics &Sem,
7969 unsigned &Idx) {
7970 return llvm::APFloat(Sem, ReadAPInt(Record, Idx));
Guy Benyei11169dd2012-12-18 14:30:41 +00007971}
7972
7973// \brief Read a string
7974std::string ASTReader::ReadString(const RecordData &Record, unsigned &Idx) {
7975 unsigned Len = Record[Idx++];
7976 std::string Result(Record.data() + Idx, Record.data() + Idx + Len);
7977 Idx += Len;
7978 return Result;
7979}
7980
Richard Smith7ed1bc92014-12-05 22:42:13 +00007981std::string ASTReader::ReadPath(ModuleFile &F, const RecordData &Record,
7982 unsigned &Idx) {
7983 std::string Filename = ReadString(Record, Idx);
7984 ResolveImportedPath(F, Filename);
7985 return Filename;
7986}
7987
Guy Benyei11169dd2012-12-18 14:30:41 +00007988VersionTuple ASTReader::ReadVersionTuple(const RecordData &Record,
7989 unsigned &Idx) {
7990 unsigned Major = Record[Idx++];
7991 unsigned Minor = Record[Idx++];
7992 unsigned Subminor = Record[Idx++];
7993 if (Minor == 0)
7994 return VersionTuple(Major);
7995 if (Subminor == 0)
7996 return VersionTuple(Major, Minor - 1);
7997 return VersionTuple(Major, Minor - 1, Subminor - 1);
7998}
7999
8000CXXTemporary *ASTReader::ReadCXXTemporary(ModuleFile &F,
8001 const RecordData &Record,
8002 unsigned &Idx) {
8003 CXXDestructorDecl *Decl = ReadDeclAs<CXXDestructorDecl>(F, Record, Idx);
8004 return CXXTemporary::Create(Context, Decl);
8005}
8006
8007DiagnosticBuilder ASTReader::Diag(unsigned DiagID) {
Argyrios Kyrtzidisdc9fdaf2013-05-24 05:44:08 +00008008 return Diag(CurrentImportLoc, DiagID);
Guy Benyei11169dd2012-12-18 14:30:41 +00008009}
8010
8011DiagnosticBuilder ASTReader::Diag(SourceLocation Loc, unsigned DiagID) {
8012 return Diags.Report(Loc, DiagID);
8013}
8014
8015/// \brief Retrieve the identifier table associated with the
8016/// preprocessor.
8017IdentifierTable &ASTReader::getIdentifierTable() {
8018 return PP.getIdentifierTable();
8019}
8020
8021/// \brief Record that the given ID maps to the given switch-case
8022/// statement.
8023void ASTReader::RecordSwitchCaseID(SwitchCase *SC, unsigned ID) {
Craig Toppera13603a2014-05-22 05:54:18 +00008024 assert((*CurrSwitchCaseStmts)[ID] == nullptr &&
Guy Benyei11169dd2012-12-18 14:30:41 +00008025 "Already have a SwitchCase with this ID");
8026 (*CurrSwitchCaseStmts)[ID] = SC;
8027}
8028
8029/// \brief Retrieve the switch-case statement with the given ID.
8030SwitchCase *ASTReader::getSwitchCaseWithID(unsigned ID) {
Craig Toppera13603a2014-05-22 05:54:18 +00008031 assert((*CurrSwitchCaseStmts)[ID] != nullptr && "No SwitchCase with this ID");
Guy Benyei11169dd2012-12-18 14:30:41 +00008032 return (*CurrSwitchCaseStmts)[ID];
8033}
8034
8035void ASTReader::ClearSwitchCaseIDs() {
8036 CurrSwitchCaseStmts->clear();
8037}
8038
8039void ASTReader::ReadComments() {
8040 std::vector<RawComment *> Comments;
Chris Lattner7fb3bef2013-01-20 00:56:42 +00008041 for (SmallVectorImpl<std::pair<BitstreamCursor,
Guy Benyei11169dd2012-12-18 14:30:41 +00008042 serialization::ModuleFile *> >::iterator
8043 I = CommentsCursors.begin(),
8044 E = CommentsCursors.end();
8045 I != E; ++I) {
Dmitri Gribenko9ee0e302014-03-27 15:40:39 +00008046 Comments.clear();
Chris Lattner7fb3bef2013-01-20 00:56:42 +00008047 BitstreamCursor &Cursor = I->first;
Guy Benyei11169dd2012-12-18 14:30:41 +00008048 serialization::ModuleFile &F = *I->second;
8049 SavedStreamPosition SavedPosition(Cursor);
8050
8051 RecordData Record;
8052 while (true) {
Chris Lattner7fb3bef2013-01-20 00:56:42 +00008053 llvm::BitstreamEntry Entry =
8054 Cursor.advanceSkippingSubblocks(BitstreamCursor::AF_DontPopBlockAtEnd);
Dmitri Gribenko9ee0e302014-03-27 15:40:39 +00008055
Chris Lattner7fb3bef2013-01-20 00:56:42 +00008056 switch (Entry.Kind) {
8057 case llvm::BitstreamEntry::SubBlock: // Handled for us already.
8058 case llvm::BitstreamEntry::Error:
8059 Error("malformed block record in AST file");
8060 return;
8061 case llvm::BitstreamEntry::EndBlock:
8062 goto NextCursor;
8063 case llvm::BitstreamEntry::Record:
8064 // The interesting case.
Guy Benyei11169dd2012-12-18 14:30:41 +00008065 break;
Guy Benyei11169dd2012-12-18 14:30:41 +00008066 }
8067
8068 // Read a record.
8069 Record.clear();
Chris Lattner0e6c9402013-01-20 02:38:54 +00008070 switch ((CommentRecordTypes)Cursor.readRecord(Entry.ID, Record)) {
Guy Benyei11169dd2012-12-18 14:30:41 +00008071 case COMMENTS_RAW_COMMENT: {
8072 unsigned Idx = 0;
8073 SourceRange SR = ReadSourceRange(F, Record, Idx);
8074 RawComment::CommentKind Kind =
8075 (RawComment::CommentKind) Record[Idx++];
8076 bool IsTrailingComment = Record[Idx++];
8077 bool IsAlmostTrailingComment = Record[Idx++];
Dmitri Gribenkoa7d16ce2013-04-10 15:35:17 +00008078 Comments.push_back(new (Context) RawComment(
8079 SR, Kind, IsTrailingComment, IsAlmostTrailingComment,
8080 Context.getLangOpts().CommentOpts.ParseAllComments));
Guy Benyei11169dd2012-12-18 14:30:41 +00008081 break;
8082 }
8083 }
8084 }
Dmitri Gribenko9ee0e302014-03-27 15:40:39 +00008085 NextCursor:
8086 Context.Comments.addDeserializedComments(Comments);
Guy Benyei11169dd2012-12-18 14:30:41 +00008087 }
Guy Benyei11169dd2012-12-18 14:30:41 +00008088}
8089
Richard Smithcd45dbc2014-04-19 03:48:30 +00008090std::string ASTReader::getOwningModuleNameForDiagnostic(const Decl *D) {
8091 // If we know the owning module, use it.
Richard Smith42413142015-05-15 20:05:43 +00008092 if (Module *M = D->getImportedOwningModule())
Richard Smithcd45dbc2014-04-19 03:48:30 +00008093 return M->getFullModuleName();
8094
8095 // Otherwise, use the name of the top-level module the decl is within.
8096 if (ModuleFile *M = getOwningModuleFile(D))
8097 return M->ModuleName;
8098
8099 // Not from a module.
8100 return "";
8101}
8102
Guy Benyei11169dd2012-12-18 14:30:41 +00008103void ASTReader::finishPendingActions() {
Richard Smith851072e2014-05-19 20:59:20 +00008104 while (!PendingIdentifierInfos.empty() ||
8105 !PendingIncompleteDeclChains.empty() || !PendingDeclChains.empty() ||
Richard Smith2b9e3e32013-10-18 06:05:18 +00008106 !PendingMacroIDs.empty() || !PendingDeclContextInfos.empty() ||
Richard Smitha0ce9c42014-07-29 23:23:27 +00008107 !PendingUpdateRecords.empty()) {
Guy Benyei11169dd2012-12-18 14:30:41 +00008108 // If any identifiers with corresponding top-level declarations have
8109 // been loaded, load those declarations now.
Craig Topper79be4cd2013-07-05 04:33:53 +00008110 typedef llvm::DenseMap<IdentifierInfo *, SmallVector<Decl *, 2> >
8111 TopLevelDeclsMap;
8112 TopLevelDeclsMap TopLevelDecls;
8113
Guy Benyei11169dd2012-12-18 14:30:41 +00008114 while (!PendingIdentifierInfos.empty()) {
Douglas Gregor6168bd22013-02-18 15:53:43 +00008115 IdentifierInfo *II = PendingIdentifierInfos.back().first;
Richard Smithf0ae3c2d2014-03-28 17:31:23 +00008116 SmallVector<uint32_t, 4> DeclIDs =
8117 std::move(PendingIdentifierInfos.back().second);
Douglas Gregorcb15f082013-02-19 18:26:28 +00008118 PendingIdentifierInfos.pop_back();
Douglas Gregor6168bd22013-02-18 15:53:43 +00008119
8120 SetGloballyVisibleDecls(II, DeclIDs, &TopLevelDecls[II]);
Guy Benyei11169dd2012-12-18 14:30:41 +00008121 }
Richard Smithf0ae3c2d2014-03-28 17:31:23 +00008122
Richard Smith851072e2014-05-19 20:59:20 +00008123 // For each decl chain that we wanted to complete while deserializing, mark
8124 // it as "still needs to be completed".
8125 for (unsigned I = 0; I != PendingIncompleteDeclChains.size(); ++I) {
8126 markIncompleteDeclChain(PendingIncompleteDeclChains[I]);
8127 }
8128 PendingIncompleteDeclChains.clear();
8129
Guy Benyei11169dd2012-12-18 14:30:41 +00008130 // Load pending declaration chains.
Richard Smithd8a83712015-08-22 01:47:18 +00008131 for (unsigned I = 0; I != PendingDeclChains.size(); ++I)
Richard Smithd61d4ac2015-08-22 20:13:39 +00008132 loadPendingDeclChain(PendingDeclChains[I].first, PendingDeclChains[I].second);
Guy Benyei11169dd2012-12-18 14:30:41 +00008133 PendingDeclChains.clear();
8134
Douglas Gregor6168bd22013-02-18 15:53:43 +00008135 // Make the most recent of the top-level declarations visible.
Craig Topper79be4cd2013-07-05 04:33:53 +00008136 for (TopLevelDeclsMap::iterator TLD = TopLevelDecls.begin(),
8137 TLDEnd = TopLevelDecls.end(); TLD != TLDEnd; ++TLD) {
Douglas Gregor6168bd22013-02-18 15:53:43 +00008138 IdentifierInfo *II = TLD->first;
8139 for (unsigned I = 0, N = TLD->second.size(); I != N; ++I) {
Argyrios Kyrtzidise5edbf92013-04-26 21:33:35 +00008140 pushExternalDeclIntoScope(cast<NamedDecl>(TLD->second[I]), II);
Douglas Gregor6168bd22013-02-18 15:53:43 +00008141 }
8142 }
8143
Guy Benyei11169dd2012-12-18 14:30:41 +00008144 // Load any pending macro definitions.
8145 for (unsigned I = 0; I != PendingMacroIDs.size(); ++I) {
Argyrios Kyrtzidiseb663da2013-03-22 21:12:57 +00008146 IdentifierInfo *II = PendingMacroIDs.begin()[I].first;
8147 SmallVector<PendingMacroInfo, 2> GlobalIDs;
8148 GlobalIDs.swap(PendingMacroIDs.begin()[I].second);
8149 // Initialize the macro history from chained-PCHs ahead of module imports.
Richard Smith49f906a2014-03-01 00:08:04 +00008150 for (unsigned IDIdx = 0, NumIDs = GlobalIDs.size(); IDIdx != NumIDs;
Argyrios Kyrtzidis719736c2013-01-19 03:14:56 +00008151 ++IDIdx) {
Argyrios Kyrtzidiseb663da2013-03-22 21:12:57 +00008152 const PendingMacroInfo &Info = GlobalIDs[IDIdx];
Richard Smithe842a472014-10-22 02:05:46 +00008153 if (Info.M->Kind != MK_ImplicitModule &&
8154 Info.M->Kind != MK_ExplicitModule)
Argyrios Kyrtzidiseb663da2013-03-22 21:12:57 +00008155 resolvePendingMacro(II, Info);
8156 }
8157 // Handle module imports.
Richard Smith49f906a2014-03-01 00:08:04 +00008158 for (unsigned IDIdx = 0, NumIDs = GlobalIDs.size(); IDIdx != NumIDs;
Argyrios Kyrtzidiseb663da2013-03-22 21:12:57 +00008159 ++IDIdx) {
8160 const PendingMacroInfo &Info = GlobalIDs[IDIdx];
Richard Smithe842a472014-10-22 02:05:46 +00008161 if (Info.M->Kind == MK_ImplicitModule ||
8162 Info.M->Kind == MK_ExplicitModule)
Argyrios Kyrtzidiseb663da2013-03-22 21:12:57 +00008163 resolvePendingMacro(II, Info);
Guy Benyei11169dd2012-12-18 14:30:41 +00008164 }
8165 }
8166 PendingMacroIDs.clear();
Argyrios Kyrtzidis83a6e3b2013-02-16 00:48:59 +00008167
8168 // Wire up the DeclContexts for Decls that we delayed setting until
8169 // recursive loading is completed.
8170 while (!PendingDeclContextInfos.empty()) {
8171 PendingDeclContextInfo Info = PendingDeclContextInfos.front();
8172 PendingDeclContextInfos.pop_front();
8173 DeclContext *SemaDC = cast<DeclContext>(GetDecl(Info.SemaDC));
8174 DeclContext *LexicalDC = cast<DeclContext>(GetDecl(Info.LexicalDC));
8175 Info.D->setDeclContextsImpl(SemaDC, LexicalDC, getContext());
8176 }
Richard Smith2b9e3e32013-10-18 06:05:18 +00008177
Richard Smithd1c46742014-04-30 02:24:17 +00008178 // Perform any pending declaration updates.
Richard Smithd6db68c2014-08-07 20:58:41 +00008179 while (!PendingUpdateRecords.empty()) {
Richard Smithd1c46742014-04-30 02:24:17 +00008180 auto Update = PendingUpdateRecords.pop_back_val();
8181 ReadingKindTracker ReadingKind(Read_Decl, *this);
8182 loadDeclUpdateRecords(Update.first, Update.second);
8183 }
Guy Benyei11169dd2012-12-18 14:30:41 +00008184 }
Richard Smith8a639892015-01-24 01:07:20 +00008185
8186 // At this point, all update records for loaded decls are in place, so any
8187 // fake class definitions should have become real.
8188 assert(PendingFakeDefinitionData.empty() &&
8189 "faked up a class definition but never saw the real one");
8190
Guy Benyei11169dd2012-12-18 14:30:41 +00008191 // If we deserialized any C++ or Objective-C class definitions, any
8192 // Objective-C protocol definitions, or any redeclarable templates, make sure
8193 // that all redeclarations point to the definitions. Note that this can only
8194 // happen now, after the redeclaration chains have been fully wired.
Craig Topperc6914d02014-08-25 04:15:02 +00008195 for (Decl *D : PendingDefinitions) {
8196 if (TagDecl *TD = dyn_cast<TagDecl>(D)) {
Richard Smith5b21db82014-04-23 18:20:42 +00008197 if (const TagType *TagT = dyn_cast<TagType>(TD->getTypeForDecl())) {
Guy Benyei11169dd2012-12-18 14:30:41 +00008198 // Make sure that the TagType points at the definition.
8199 const_cast<TagType*>(TagT)->decl = TD;
8200 }
Richard Smith8ce51082015-03-11 01:44:51 +00008201
Craig Topperc6914d02014-08-25 04:15:02 +00008202 if (auto RD = dyn_cast<CXXRecordDecl>(D)) {
Richard Smith8ce51082015-03-11 01:44:51 +00008203 for (auto *R = getMostRecentExistingDecl(RD); R;
8204 R = R->getPreviousDecl()) {
8205 assert((R == D) ==
8206 cast<CXXRecordDecl>(R)->isThisDeclarationADefinition() &&
Richard Smith2c381642014-08-27 23:11:59 +00008207 "declaration thinks it's the definition but it isn't");
Aaron Ballman86c93902014-03-06 23:45:36 +00008208 cast<CXXRecordDecl>(R)->DefinitionData = RD->DefinitionData;
Richard Smith2c381642014-08-27 23:11:59 +00008209 }
Guy Benyei11169dd2012-12-18 14:30:41 +00008210 }
8211
8212 continue;
8213 }
Richard Smith8ce51082015-03-11 01:44:51 +00008214
Craig Topperc6914d02014-08-25 04:15:02 +00008215 if (auto ID = dyn_cast<ObjCInterfaceDecl>(D)) {
Guy Benyei11169dd2012-12-18 14:30:41 +00008216 // Make sure that the ObjCInterfaceType points at the definition.
8217 const_cast<ObjCInterfaceType *>(cast<ObjCInterfaceType>(ID->TypeForDecl))
8218 ->Decl = ID;
Richard Smith8ce51082015-03-11 01:44:51 +00008219
8220 for (auto *R = getMostRecentExistingDecl(ID); R; R = R->getPreviousDecl())
8221 cast<ObjCInterfaceDecl>(R)->Data = ID->Data;
8222
Guy Benyei11169dd2012-12-18 14:30:41 +00008223 continue;
8224 }
Richard Smith8ce51082015-03-11 01:44:51 +00008225
Craig Topperc6914d02014-08-25 04:15:02 +00008226 if (auto PD = dyn_cast<ObjCProtocolDecl>(D)) {
Richard Smith8ce51082015-03-11 01:44:51 +00008227 for (auto *R = getMostRecentExistingDecl(PD); R; R = R->getPreviousDecl())
8228 cast<ObjCProtocolDecl>(R)->Data = PD->Data;
8229
Guy Benyei11169dd2012-12-18 14:30:41 +00008230 continue;
8231 }
Richard Smith8ce51082015-03-11 01:44:51 +00008232
Craig Topperc6914d02014-08-25 04:15:02 +00008233 auto RTD = cast<RedeclarableTemplateDecl>(D)->getCanonicalDecl();
Richard Smith8ce51082015-03-11 01:44:51 +00008234 for (auto *R = getMostRecentExistingDecl(RTD); R; R = R->getPreviousDecl())
8235 cast<RedeclarableTemplateDecl>(R)->Common = RTD->Common;
Guy Benyei11169dd2012-12-18 14:30:41 +00008236 }
8237 PendingDefinitions.clear();
8238
8239 // Load the bodies of any functions or methods we've encountered. We do
8240 // this now (delayed) so that we can be sure that the declaration chains
Richard Smithb9fa9962015-08-21 03:04:33 +00008241 // have been fully wired up (hasBody relies on this).
8242 // FIXME: We shouldn't require complete redeclaration chains here.
Guy Benyei11169dd2012-12-18 14:30:41 +00008243 for (PendingBodiesMap::iterator PB = PendingBodies.begin(),
8244 PBEnd = PendingBodies.end();
8245 PB != PBEnd; ++PB) {
8246 if (FunctionDecl *FD = dyn_cast<FunctionDecl>(PB->first)) {
8247 // FIXME: Check for =delete/=default?
8248 // FIXME: Complain about ODR violations here?
8249 if (!getContext().getLangOpts().Modules || !FD->hasBody())
8250 FD->setLazyBody(PB->second);
8251 continue;
8252 }
8253
8254 ObjCMethodDecl *MD = cast<ObjCMethodDecl>(PB->first);
8255 if (!getContext().getLangOpts().Modules || !MD->hasBody())
8256 MD->setLazyBody(PB->second);
8257 }
8258 PendingBodies.clear();
Richard Smith42413142015-05-15 20:05:43 +00008259
8260 // Do some cleanup.
8261 for (auto *ND : PendingMergedDefinitionsToDeduplicate)
8262 getContext().deduplicateMergedDefinitonsFor(ND);
8263 PendingMergedDefinitionsToDeduplicate.clear();
Richard Smitha0ce9c42014-07-29 23:23:27 +00008264}
8265
8266void ASTReader::diagnoseOdrViolations() {
Richard Smithbb853c72014-08-13 01:23:33 +00008267 if (PendingOdrMergeFailures.empty() && PendingOdrMergeChecks.empty())
8268 return;
8269
Richard Smitha0ce9c42014-07-29 23:23:27 +00008270 // Trigger the import of the full definition of each class that had any
8271 // odr-merging problems, so we can produce better diagnostics for them.
Richard Smithbb853c72014-08-13 01:23:33 +00008272 // These updates may in turn find and diagnose some ODR failures, so take
8273 // ownership of the set first.
8274 auto OdrMergeFailures = std::move(PendingOdrMergeFailures);
8275 PendingOdrMergeFailures.clear();
8276 for (auto &Merge : OdrMergeFailures) {
Richard Smitha0ce9c42014-07-29 23:23:27 +00008277 Merge.first->buildLookup();
8278 Merge.first->decls_begin();
8279 Merge.first->bases_begin();
8280 Merge.first->vbases_begin();
8281 for (auto *RD : Merge.second) {
8282 RD->decls_begin();
8283 RD->bases_begin();
8284 RD->vbases_begin();
8285 }
8286 }
8287
8288 // For each declaration from a merged context, check that the canonical
8289 // definition of that context also contains a declaration of the same
8290 // entity.
8291 //
8292 // Caution: this loop does things that might invalidate iterators into
8293 // PendingOdrMergeChecks. Don't turn this into a range-based for loop!
8294 while (!PendingOdrMergeChecks.empty()) {
8295 NamedDecl *D = PendingOdrMergeChecks.pop_back_val();
8296
8297 // FIXME: Skip over implicit declarations for now. This matters for things
8298 // like implicitly-declared special member functions. This isn't entirely
8299 // correct; we can end up with multiple unmerged declarations of the same
8300 // implicit entity.
8301 if (D->isImplicit())
8302 continue;
8303
8304 DeclContext *CanonDef = D->getDeclContext();
Richard Smitha0ce9c42014-07-29 23:23:27 +00008305
8306 bool Found = false;
8307 const Decl *DCanon = D->getCanonicalDecl();
8308
Richard Smith01bdb7a2014-08-28 05:44:07 +00008309 for (auto RI : D->redecls()) {
8310 if (RI->getLexicalDeclContext() == CanonDef) {
8311 Found = true;
8312 break;
8313 }
8314 }
8315 if (Found)
8316 continue;
8317
Richard Smith0f4e2c42015-08-06 04:23:48 +00008318 // Quick check failed, time to do the slow thing. Note, we can't just
8319 // look up the name of D in CanonDef here, because the member that is
8320 // in CanonDef might not be found by name lookup (it might have been
8321 // replaced by a more recent declaration in the lookup table), and we
8322 // can't necessarily find it in the redeclaration chain because it might
8323 // be merely mergeable, not redeclarable.
Richard Smitha0ce9c42014-07-29 23:23:27 +00008324 llvm::SmallVector<const NamedDecl*, 4> Candidates;
Richard Smith0f4e2c42015-08-06 04:23:48 +00008325 for (auto *CanonMember : CanonDef->decls()) {
8326 if (CanonMember->getCanonicalDecl() == DCanon) {
8327 // This can happen if the declaration is merely mergeable and not
8328 // actually redeclarable (we looked for redeclarations earlier).
8329 //
8330 // FIXME: We should be able to detect this more efficiently, without
8331 // pulling in all of the members of CanonDef.
8332 Found = true;
8333 break;
Richard Smitha0ce9c42014-07-29 23:23:27 +00008334 }
Richard Smith0f4e2c42015-08-06 04:23:48 +00008335 if (auto *ND = dyn_cast<NamedDecl>(CanonMember))
8336 if (ND->getDeclName() == D->getDeclName())
8337 Candidates.push_back(ND);
Richard Smitha0ce9c42014-07-29 23:23:27 +00008338 }
8339
8340 if (!Found) {
Richard Smithd08aeb62014-08-28 01:33:39 +00008341 // The AST doesn't like TagDecls becoming invalid after they've been
8342 // completed. We only really need to mark FieldDecls as invalid here.
8343 if (!isa<TagDecl>(D))
8344 D->setInvalidDecl();
Richard Smith4ab3dbd2015-02-13 22:43:51 +00008345
8346 // Ensure we don't accidentally recursively enter deserialization while
8347 // we're producing our diagnostic.
8348 Deserializing RecursionGuard(this);
Richard Smitha0ce9c42014-07-29 23:23:27 +00008349
8350 std::string CanonDefModule =
8351 getOwningModuleNameForDiagnostic(cast<Decl>(CanonDef));
8352 Diag(D->getLocation(), diag::err_module_odr_violation_missing_decl)
8353 << D << getOwningModuleNameForDiagnostic(D)
8354 << CanonDef << CanonDefModule.empty() << CanonDefModule;
8355
8356 if (Candidates.empty())
8357 Diag(cast<Decl>(CanonDef)->getLocation(),
8358 diag::note_module_odr_violation_no_possible_decls) << D;
8359 else {
8360 for (unsigned I = 0, N = Candidates.size(); I != N; ++I)
8361 Diag(Candidates[I]->getLocation(),
8362 diag::note_module_odr_violation_possible_decl)
8363 << Candidates[I];
8364 }
8365
8366 DiagnosedOdrMergeFailures.insert(CanonDef);
8367 }
8368 }
Richard Smithcd45dbc2014-04-19 03:48:30 +00008369
Richard Smith4ab3dbd2015-02-13 22:43:51 +00008370 if (OdrMergeFailures.empty())
8371 return;
8372
8373 // Ensure we don't accidentally recursively enter deserialization while
8374 // we're producing our diagnostics.
8375 Deserializing RecursionGuard(this);
8376
Richard Smithcd45dbc2014-04-19 03:48:30 +00008377 // Issue any pending ODR-failure diagnostics.
Richard Smithbb853c72014-08-13 01:23:33 +00008378 for (auto &Merge : OdrMergeFailures) {
Richard Smitha0ce9c42014-07-29 23:23:27 +00008379 // If we've already pointed out a specific problem with this class, don't
8380 // bother issuing a general "something's different" diagnostic.
David Blaikie82e95a32014-11-19 07:49:47 +00008381 if (!DiagnosedOdrMergeFailures.insert(Merge.first).second)
Richard Smithcd45dbc2014-04-19 03:48:30 +00008382 continue;
8383
8384 bool Diagnosed = false;
8385 for (auto *RD : Merge.second) {
8386 // Multiple different declarations got merged together; tell the user
8387 // where they came from.
8388 if (Merge.first != RD) {
8389 // FIXME: Walk the definition, figure out what's different,
8390 // and diagnose that.
8391 if (!Diagnosed) {
8392 std::string Module = getOwningModuleNameForDiagnostic(Merge.first);
8393 Diag(Merge.first->getLocation(),
8394 diag::err_module_odr_violation_different_definitions)
8395 << Merge.first << Module.empty() << Module;
8396 Diagnosed = true;
8397 }
8398
8399 Diag(RD->getLocation(),
8400 diag::note_module_odr_violation_different_definitions)
8401 << getOwningModuleNameForDiagnostic(RD);
8402 }
8403 }
8404
8405 if (!Diagnosed) {
8406 // All definitions are updates to the same declaration. This happens if a
8407 // module instantiates the declaration of a class template specialization
8408 // and two or more other modules instantiate its definition.
8409 //
8410 // FIXME: Indicate which modules had instantiations of this definition.
8411 // FIXME: How can this even happen?
8412 Diag(Merge.first->getLocation(),
8413 diag::err_module_odr_violation_different_instantiations)
8414 << Merge.first;
8415 }
8416 }
Guy Benyei11169dd2012-12-18 14:30:41 +00008417}
8418
Richard Smithce18a182015-07-14 00:26:00 +00008419void ASTReader::StartedDeserializing() {
8420 if (++NumCurrentElementsDeserializing == 1 && ReadTimer.get())
8421 ReadTimer->startTimer();
8422}
8423
Guy Benyei11169dd2012-12-18 14:30:41 +00008424void ASTReader::FinishedDeserializing() {
8425 assert(NumCurrentElementsDeserializing &&
8426 "FinishedDeserializing not paired with StartedDeserializing");
8427 if (NumCurrentElementsDeserializing == 1) {
8428 // We decrease NumCurrentElementsDeserializing only after pending actions
8429 // are finished, to avoid recursively re-calling finishPendingActions().
8430 finishPendingActions();
8431 }
8432 --NumCurrentElementsDeserializing;
8433
Richard Smitha0ce9c42014-07-29 23:23:27 +00008434 if (NumCurrentElementsDeserializing == 0) {
Richard Smith9e2341d2015-03-23 03:25:59 +00008435 // Propagate exception specification updates along redeclaration chains.
Richard Smith7226f2a2015-03-23 19:54:56 +00008436 while (!PendingExceptionSpecUpdates.empty()) {
8437 auto Updates = std::move(PendingExceptionSpecUpdates);
8438 PendingExceptionSpecUpdates.clear();
8439 for (auto Update : Updates) {
8440 auto *FPT = Update.second->getType()->castAs<FunctionProtoType>();
Richard Smith1d0f1992015-08-19 21:09:32 +00008441 auto ESI = FPT->getExtProtoInfo().ExceptionSpec;
8442 for (auto *Redecl : Update.second->redecls())
8443 Context.adjustExceptionSpec(cast<FunctionDecl>(Redecl), ESI);
Richard Smith7226f2a2015-03-23 19:54:56 +00008444 }
Richard Smith9e2341d2015-03-23 03:25:59 +00008445 }
8446
Richard Smithce18a182015-07-14 00:26:00 +00008447 if (ReadTimer)
8448 ReadTimer->stopTimer();
8449
Richard Smith0f4e2c42015-08-06 04:23:48 +00008450 diagnoseOdrViolations();
8451
Richard Smith04d05b52014-03-23 00:27:18 +00008452 // We are not in recursive loading, so it's safe to pass the "interesting"
8453 // decls to the consumer.
Richard Smitha0ce9c42014-07-29 23:23:27 +00008454 if (Consumer)
8455 PassInterestingDeclsToConsumer();
Guy Benyei11169dd2012-12-18 14:30:41 +00008456 }
8457}
8458
Argyrios Kyrtzidise5edbf92013-04-26 21:33:35 +00008459void ASTReader::pushExternalDeclIntoScope(NamedDecl *D, DeclarationName Name) {
Richard Smith9e2341d2015-03-23 03:25:59 +00008460 if (IdentifierInfo *II = Name.getAsIdentifierInfo()) {
8461 // Remove any fake results before adding any real ones.
8462 auto It = PendingFakeLookupResults.find(II);
8463 if (It != PendingFakeLookupResults.end()) {
Richard Smitha534a312015-07-21 23:54:07 +00008464 for (auto *ND : It->second)
Richard Smith9e2341d2015-03-23 03:25:59 +00008465 SemaObj->IdResolver.RemoveDecl(ND);
Ben Langmuireb8bd2d2015-04-10 22:25:42 +00008466 // FIXME: this works around module+PCH performance issue.
8467 // Rather than erase the result from the map, which is O(n), just clear
8468 // the vector of NamedDecls.
8469 It->second.clear();
Richard Smith9e2341d2015-03-23 03:25:59 +00008470 }
8471 }
Argyrios Kyrtzidise5edbf92013-04-26 21:33:35 +00008472
8473 if (SemaObj->IdResolver.tryAddTopLevelDecl(D, Name) && SemaObj->TUScope) {
8474 SemaObj->TUScope->AddDecl(D);
8475 } else if (SemaObj->TUScope) {
8476 // Adding the decl to IdResolver may have failed because it was already in
8477 // (even though it was not added in scope). If it is already in, make sure
8478 // it gets in the scope as well.
8479 if (std::find(SemaObj->IdResolver.begin(Name),
8480 SemaObj->IdResolver.end(), D) != SemaObj->IdResolver.end())
8481 SemaObj->TUScope->AddDecl(D);
8482 }
8483}
8484
Adrian Prantlbb165fb2015-06-20 18:53:08 +00008485ASTReader::ASTReader(Preprocessor &PP, ASTContext &Context,
Adrian Prantlfb2398d2015-07-17 01:19:54 +00008486 const PCHContainerReader &PCHContainerRdr,
Adrian Prantlbb165fb2015-06-20 18:53:08 +00008487 StringRef isysroot, bool DisableValidation,
8488 bool AllowASTWithCompilerErrors,
Nico Weber824285e2014-05-08 04:26:47 +00008489 bool AllowConfigurationMismatch, bool ValidateSystemInputs,
Richard Smithce18a182015-07-14 00:26:00 +00008490 bool UseGlobalIndex,
8491 std::unique_ptr<llvm::Timer> ReadTimer)
Craig Toppera13603a2014-05-22 05:54:18 +00008492 : Listener(new PCHValidator(PP, *this)), DeserializationListener(nullptr),
Nico Weber824285e2014-05-08 04:26:47 +00008493 OwnsDeserializationListener(false), SourceMgr(PP.getSourceManager()),
Adrian Prantlfb2398d2015-07-17 01:19:54 +00008494 FileMgr(PP.getFileManager()), PCHContainerRdr(PCHContainerRdr),
Adrian Prantlbb165fb2015-06-20 18:53:08 +00008495 Diags(PP.getDiagnostics()), SemaObj(nullptr), PP(PP), Context(Context),
Adrian Prantlfb2398d2015-07-17 01:19:54 +00008496 Consumer(nullptr), ModuleMgr(PP.getFileManager(), PCHContainerRdr),
Richard Smithce18a182015-07-14 00:26:00 +00008497 ReadTimer(std::move(ReadTimer)),
Adrian Prantlbb165fb2015-06-20 18:53:08 +00008498 isysroot(isysroot), DisableValidation(DisableValidation),
Nico Weber824285e2014-05-08 04:26:47 +00008499 AllowASTWithCompilerErrors(AllowASTWithCompilerErrors),
8500 AllowConfigurationMismatch(AllowConfigurationMismatch),
8501 ValidateSystemInputs(ValidateSystemInputs),
8502 UseGlobalIndex(UseGlobalIndex), TriedLoadingGlobalIndex(false),
Adrian Prantlbb165fb2015-06-20 18:53:08 +00008503 CurrSwitchCaseStmts(&SwitchCaseStmts), NumSLocEntriesRead(0),
8504 TotalNumSLocEntries(0), NumStatementsRead(0), TotalNumStatements(0),
8505 NumMacrosRead(0), TotalNumMacros(0), NumIdentifierLookups(0),
8506 NumIdentifierLookupHits(0), NumSelectorsRead(0),
Nico Weber824285e2014-05-08 04:26:47 +00008507 NumMethodPoolEntriesRead(0), NumMethodPoolLookups(0),
8508 NumMethodPoolHits(0), NumMethodPoolTableLookups(0),
8509 NumMethodPoolTableHits(0), TotalNumMethodPoolEntries(0),
8510 NumLexicalDeclContextsRead(0), TotalLexicalDeclContexts(0),
8511 NumVisibleDeclContextsRead(0), TotalVisibleDeclContexts(0),
8512 TotalModulesSizeInBits(0), NumCurrentElementsDeserializing(0),
Richard Smithc2bb8182015-03-24 06:36:48 +00008513 PassingDeclsToConsumer(false), ReadingKind(Read_None) {
Guy Benyei11169dd2012-12-18 14:30:41 +00008514 SourceMgr.setExternalSLocEntrySource(this);
8515}
8516
8517ASTReader::~ASTReader() {
Nico Weber824285e2014-05-08 04:26:47 +00008518 if (OwnsDeserializationListener)
8519 delete DeserializationListener;
Guy Benyei11169dd2012-12-18 14:30:41 +00008520}