blob: 985d68e348ec08eed0141477b4a6893d4c6cf686 [file] [log] [blame]
Eugene Zelenkoe95e7d52016-09-07 21:53:17 +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"
Eugene Zelenkoe95e7d52016-09-07 21:53:17 +000019#include "clang/AST/ASTMutationListener.h"
20#include "clang/AST/ASTUnresolvedSet.h"
21#include "clang/AST/Decl.h"
22#include "clang/AST/DeclCXX.h"
23#include "clang/AST/DeclGroup.h"
24#include "clang/AST/DeclObjC.h"
Guy Benyei11169dd2012-12-18 14:30:41 +000025#include "clang/AST/DeclTemplate.h"
26#include "clang/AST/Expr.h"
27#include "clang/AST/ExprCXX.h"
28#include "clang/AST/NestedNameSpecifier.h"
Eugene Zelenkoe95e7d52016-09-07 21:53:17 +000029#include "clang/AST/RawCommentList.h"
Guy Benyei11169dd2012-12-18 14:30:41 +000030#include "clang/AST/Type.h"
31#include "clang/AST/TypeLocVisitor.h"
Eugene Zelenkoe95e7d52016-09-07 21:53:17 +000032#include "clang/AST/UnresolvedSet.h"
33#include "clang/Basic/CommentOptions.h"
Benjamin Kramerf3ca26982014-05-10 16:31:55 +000034#include "clang/Basic/DiagnosticOptions.h"
Eugene Zelenkoe95e7d52016-09-07 21:53:17 +000035#include "clang/Basic/ExceptionSpecificationType.h"
Guy Benyei11169dd2012-12-18 14:30:41 +000036#include "clang/Basic/FileManager.h"
Eugene Zelenkoe95e7d52016-09-07 21:53:17 +000037#include "clang/Basic/FileSystemOptions.h"
38#include "clang/Basic/LangOptions.h"
39#include "clang/Basic/ObjCRuntime.h"
40#include "clang/Basic/OperatorKinds.h"
41#include "clang/Basic/Sanitizers.h"
Guy Benyei11169dd2012-12-18 14:30:41 +000042#include "clang/Basic/SourceManager.h"
43#include "clang/Basic/SourceManagerInternals.h"
Eugene Zelenkoe95e7d52016-09-07 21:53:17 +000044#include "clang/Basic/Specifiers.h"
Guy Benyei11169dd2012-12-18 14:30:41 +000045#include "clang/Basic/TargetInfo.h"
46#include "clang/Basic/TargetOptions.h"
Eugene Zelenkoe95e7d52016-09-07 21:53:17 +000047#include "clang/Basic/TokenKinds.h"
Guy Benyei11169dd2012-12-18 14:30:41 +000048#include "clang/Basic/Version.h"
49#include "clang/Basic/VersionTuple.h"
Eugene Zelenkoe95e7d52016-09-07 21:53:17 +000050#include "clang/Frontend/PCHContainerOperations.h"
Guy Benyei11169dd2012-12-18 14:30:41 +000051#include "clang/Lex/HeaderSearch.h"
52#include "clang/Lex/HeaderSearchOptions.h"
53#include "clang/Lex/MacroInfo.h"
Eugene Zelenkoe95e7d52016-09-07 21:53:17 +000054#include "clang/Lex/ModuleMap.h"
Guy Benyei11169dd2012-12-18 14:30:41 +000055#include "clang/Lex/PreprocessingRecord.h"
56#include "clang/Lex/Preprocessor.h"
57#include "clang/Lex/PreprocessorOptions.h"
58#include "clang/Sema/Scope.h"
59#include "clang/Sema/Sema.h"
Eugene Zelenkoe95e7d52016-09-07 21:53:17 +000060#include "clang/Sema/Weak.h"
Guy Benyei11169dd2012-12-18 14:30:41 +000061#include "clang/Serialization/ASTDeserializationListener.h"
Douglas Gregore060e572013-01-25 01:03:03 +000062#include "clang/Serialization/GlobalModuleIndex.h"
Guy Benyei11169dd2012-12-18 14:30:41 +000063#include "clang/Serialization/ModuleManager.h"
64#include "clang/Serialization/SerializationDiagnostic.h"
Eugene Zelenkoe95e7d52016-09-07 21:53:17 +000065#include "llvm/ADT/APFloat.h"
66#include "llvm/ADT/APInt.h"
67#include "llvm/ADT/APSInt.h"
Argyrios Kyrtzidis5c2a3452013-03-06 18:12:47 +000068#include "llvm/ADT/Hashing.h"
Eugene Zelenkoe95e7d52016-09-07 21:53:17 +000069#include "llvm/ADT/SmallString.h"
Guy Benyei11169dd2012-12-18 14:30:41 +000070#include "llvm/ADT/StringExtras.h"
Eugene Zelenkoe95e7d52016-09-07 21:53:17 +000071#include "llvm/ADT/Triple.h"
Guy Benyei11169dd2012-12-18 14:30:41 +000072#include "llvm/Bitcode/BitstreamReader.h"
Richard Smithaada85c2016-02-06 02:06:43 +000073#include "llvm/Support/Compression.h"
Eugene Zelenkoe95e7d52016-09-07 21:53:17 +000074#include "llvm/Support/Compiler.h"
George Rimarc39f5492017-01-17 15:45:31 +000075#include "llvm/Support/Error.h"
Guy Benyei11169dd2012-12-18 14:30:41 +000076#include "llvm/Support/ErrorHandling.h"
77#include "llvm/Support/FileSystem.h"
78#include "llvm/Support/MemoryBuffer.h"
79#include "llvm/Support/Path.h"
80#include "llvm/Support/SaveAndRestore.h"
Dmitri Gribenkof430da42014-02-12 10:33:14 +000081#include "llvm/Support/raw_ostream.h"
Guy Benyei11169dd2012-12-18 14:30:41 +000082#include <algorithm>
Eugene Zelenkoe95e7d52016-09-07 21:53:17 +000083#include <cassert>
84#include <cstdint>
Chris Lattner91f373e2013-01-20 00:57:52 +000085#include <cstdio>
Eugene Zelenkoe95e7d52016-09-07 21:53:17 +000086#include <cstring>
87#include <ctime>
Guy Benyei11169dd2012-12-18 14:30:41 +000088#include <iterator>
Eugene Zelenkoe95e7d52016-09-07 21:53:17 +000089#include <limits>
90#include <map>
91#include <memory>
92#include <new>
93#include <string>
Rafael Espindola8a8e5542014-06-12 17:19:42 +000094#include <system_error>
Eugene Zelenkoe95e7d52016-09-07 21:53:17 +000095#include <tuple>
96#include <utility>
97#include <vector>
Guy Benyei11169dd2012-12-18 14:30:41 +000098
99using namespace clang;
100using namespace clang::serialization;
101using namespace clang::serialization::reader;
Chris Lattner7fb3bef2013-01-20 00:56:42 +0000102using llvm::BitstreamCursor;
Guy Benyei11169dd2012-12-18 14:30:41 +0000103
Ben Langmuircb69b572014-03-07 06:40:32 +0000104//===----------------------------------------------------------------------===//
105// ChainedASTReaderListener implementation
106//===----------------------------------------------------------------------===//
107
108bool
109ChainedASTReaderListener::ReadFullVersionInformation(StringRef FullVersion) {
110 return First->ReadFullVersionInformation(FullVersion) ||
111 Second->ReadFullVersionInformation(FullVersion);
112}
Eugene Zelenkoe95e7d52016-09-07 21:53:17 +0000113
Ben Langmuir4f5212a2014-04-14 22:12:44 +0000114void ChainedASTReaderListener::ReadModuleName(StringRef ModuleName) {
115 First->ReadModuleName(ModuleName);
116 Second->ReadModuleName(ModuleName);
117}
Eugene Zelenkoe95e7d52016-09-07 21:53:17 +0000118
Ben Langmuir4f5212a2014-04-14 22:12:44 +0000119void ChainedASTReaderListener::ReadModuleMapFile(StringRef ModuleMapPath) {
120 First->ReadModuleMapFile(ModuleMapPath);
121 Second->ReadModuleMapFile(ModuleMapPath);
122}
Eugene Zelenkoe95e7d52016-09-07 21:53:17 +0000123
Richard Smith1e2cf0d2014-10-31 02:28:58 +0000124bool
125ChainedASTReaderListener::ReadLanguageOptions(const LangOptions &LangOpts,
126 bool Complain,
127 bool AllowCompatibleDifferences) {
128 return First->ReadLanguageOptions(LangOpts, Complain,
129 AllowCompatibleDifferences) ||
130 Second->ReadLanguageOptions(LangOpts, Complain,
131 AllowCompatibleDifferences);
Ben Langmuircb69b572014-03-07 06:40:32 +0000132}
Eugene Zelenkoe95e7d52016-09-07 21:53:17 +0000133
Chandler Carruth0d745bc2015-03-14 04:47:43 +0000134bool ChainedASTReaderListener::ReadTargetOptions(
135 const TargetOptions &TargetOpts, bool Complain,
136 bool AllowCompatibleDifferences) {
137 return First->ReadTargetOptions(TargetOpts, Complain,
138 AllowCompatibleDifferences) ||
139 Second->ReadTargetOptions(TargetOpts, Complain,
140 AllowCompatibleDifferences);
Ben Langmuircb69b572014-03-07 06:40:32 +0000141}
Eugene Zelenkoe95e7d52016-09-07 21:53:17 +0000142
Ben Langmuircb69b572014-03-07 06:40:32 +0000143bool ChainedASTReaderListener::ReadDiagnosticOptions(
Ben Langmuirb92de022014-04-29 16:25:26 +0000144 IntrusiveRefCntPtr<DiagnosticOptions> DiagOpts, bool Complain) {
Ben Langmuircb69b572014-03-07 06:40:32 +0000145 return First->ReadDiagnosticOptions(DiagOpts, Complain) ||
146 Second->ReadDiagnosticOptions(DiagOpts, Complain);
147}
Eugene Zelenkoe95e7d52016-09-07 21:53:17 +0000148
Ben Langmuircb69b572014-03-07 06:40:32 +0000149bool
150ChainedASTReaderListener::ReadFileSystemOptions(const FileSystemOptions &FSOpts,
151 bool Complain) {
152 return First->ReadFileSystemOptions(FSOpts, Complain) ||
153 Second->ReadFileSystemOptions(FSOpts, Complain);
154}
155
156bool ChainedASTReaderListener::ReadHeaderSearchOptions(
Argyrios Kyrtzidisbd0b6512015-02-19 20:12:20 +0000157 const HeaderSearchOptions &HSOpts, StringRef SpecificModuleCachePath,
158 bool Complain) {
159 return First->ReadHeaderSearchOptions(HSOpts, SpecificModuleCachePath,
160 Complain) ||
161 Second->ReadHeaderSearchOptions(HSOpts, SpecificModuleCachePath,
162 Complain);
Ben Langmuircb69b572014-03-07 06:40:32 +0000163}
Eugene Zelenkoe95e7d52016-09-07 21:53:17 +0000164
Ben Langmuircb69b572014-03-07 06:40:32 +0000165bool ChainedASTReaderListener::ReadPreprocessorOptions(
166 const PreprocessorOptions &PPOpts, bool Complain,
167 std::string &SuggestedPredefines) {
168 return First->ReadPreprocessorOptions(PPOpts, Complain,
169 SuggestedPredefines) ||
170 Second->ReadPreprocessorOptions(PPOpts, Complain, SuggestedPredefines);
171}
172void ChainedASTReaderListener::ReadCounter(const serialization::ModuleFile &M,
173 unsigned Value) {
174 First->ReadCounter(M, Value);
175 Second->ReadCounter(M, Value);
176}
177bool ChainedASTReaderListener::needsInputFileVisitation() {
178 return First->needsInputFileVisitation() ||
179 Second->needsInputFileVisitation();
180}
181bool ChainedASTReaderListener::needsSystemInputFileVisitation() {
182 return First->needsSystemInputFileVisitation() ||
183 Second->needsSystemInputFileVisitation();
184}
Richard Smith216a3bd2015-08-13 17:57:10 +0000185void ChainedASTReaderListener::visitModuleFile(StringRef Filename,
186 ModuleKind Kind) {
187 First->visitModuleFile(Filename, Kind);
188 Second->visitModuleFile(Filename, Kind);
Argyrios Kyrtzidis6d0753d2014-03-14 03:07:38 +0000189}
Eugene Zelenkoe95e7d52016-09-07 21:53:17 +0000190
Ben Langmuircb69b572014-03-07 06:40:32 +0000191bool ChainedASTReaderListener::visitInputFile(StringRef Filename,
Argyrios Kyrtzidis68ccbe02014-03-14 02:26:31 +0000192 bool isSystem,
Richard Smith216a3bd2015-08-13 17:57:10 +0000193 bool isOverridden,
194 bool isExplicitModule) {
Justin Bognerc65a66d2014-05-22 06:04:59 +0000195 bool Continue = false;
196 if (First->needsInputFileVisitation() &&
197 (!isSystem || First->needsSystemInputFileVisitation()))
Richard Smith216a3bd2015-08-13 17:57:10 +0000198 Continue |= First->visitInputFile(Filename, isSystem, isOverridden,
199 isExplicitModule);
Justin Bognerc65a66d2014-05-22 06:04:59 +0000200 if (Second->needsInputFileVisitation() &&
201 (!isSystem || Second->needsSystemInputFileVisitation()))
Richard Smith216a3bd2015-08-13 17:57:10 +0000202 Continue |= Second->visitInputFile(Filename, isSystem, isOverridden,
203 isExplicitModule);
Justin Bognerc65a66d2014-05-22 06:04:59 +0000204 return Continue;
Ben Langmuircb69b572014-03-07 06:40:32 +0000205}
206
Douglas Gregor6623e1f2015-11-03 18:33:07 +0000207void ChainedASTReaderListener::readModuleFileExtension(
208 const ModuleFileExtensionMetadata &Metadata) {
209 First->readModuleFileExtension(Metadata);
210 Second->readModuleFileExtension(Metadata);
211}
212
Guy Benyei11169dd2012-12-18 14:30:41 +0000213//===----------------------------------------------------------------------===//
214// PCH validator implementation
215//===----------------------------------------------------------------------===//
216
Angel Garcia Gomez637d1e62015-10-20 13:23:58 +0000217ASTReaderListener::~ASTReaderListener() {}
Guy Benyei11169dd2012-12-18 14:30:41 +0000218
219/// \brief Compare the given set of language options against an existing set of
220/// language options.
221///
222/// \param Diags If non-NULL, diagnostics will be emitted via this engine.
Richard Smith1e2cf0d2014-10-31 02:28:58 +0000223/// \param AllowCompatibleDifferences If true, differences between compatible
224/// language options will be permitted.
Guy Benyei11169dd2012-12-18 14:30:41 +0000225///
226/// \returns true if the languagae options mis-match, false otherwise.
227static bool checkLanguageOptions(const LangOptions &LangOpts,
228 const LangOptions &ExistingLangOpts,
Richard Smith1e2cf0d2014-10-31 02:28:58 +0000229 DiagnosticsEngine *Diags,
230 bool AllowCompatibleDifferences = true) {
Guy Benyei11169dd2012-12-18 14:30:41 +0000231#define LANGOPT(Name, Bits, Default, Description) \
232 if (ExistingLangOpts.Name != LangOpts.Name) { \
233 if (Diags) \
234 Diags->Report(diag::err_pch_langopt_mismatch) \
235 << Description << LangOpts.Name << ExistingLangOpts.Name; \
236 return true; \
237 }
238
239#define VALUE_LANGOPT(Name, Bits, Default, Description) \
240 if (ExistingLangOpts.Name != LangOpts.Name) { \
241 if (Diags) \
242 Diags->Report(diag::err_pch_langopt_value_mismatch) \
243 << Description; \
244 return true; \
245 }
246
247#define ENUM_LANGOPT(Name, Type, Bits, Default, Description) \
248 if (ExistingLangOpts.get##Name() != LangOpts.get##Name()) { \
249 if (Diags) \
250 Diags->Report(diag::err_pch_langopt_value_mismatch) \
251 << Description; \
252 return true; \
253 }
254
Richard Smith1e2cf0d2014-10-31 02:28:58 +0000255#define COMPATIBLE_LANGOPT(Name, Bits, Default, Description) \
256 if (!AllowCompatibleDifferences) \
257 LANGOPT(Name, Bits, Default, Description)
258
259#define COMPATIBLE_ENUM_LANGOPT(Name, Bits, Default, Description) \
260 if (!AllowCompatibleDifferences) \
261 ENUM_LANGOPT(Name, Bits, Default, Description)
262
Richard Smitha1ddf5e2016-04-07 20:47:37 +0000263#define COMPATIBLE_VALUE_LANGOPT(Name, Bits, Default, Description) \
264 if (!AllowCompatibleDifferences) \
265 VALUE_LANGOPT(Name, Bits, Default, Description)
266
Guy Benyei11169dd2012-12-18 14:30:41 +0000267#define BENIGN_LANGOPT(Name, Bits, Default, Description)
268#define BENIGN_ENUM_LANGOPT(Name, Type, Bits, Default, Description)
Richard Smitha1ddf5e2016-04-07 20:47:37 +0000269#define BENIGN_VALUE_LANGOPT(Name, Type, Bits, Default, Description)
Guy Benyei11169dd2012-12-18 14:30:41 +0000270#include "clang/Basic/LangOptions.def"
271
Ben Langmuircd98cb72015-06-23 18:20:18 +0000272 if (ExistingLangOpts.ModuleFeatures != LangOpts.ModuleFeatures) {
273 if (Diags)
274 Diags->Report(diag::err_pch_langopt_value_mismatch) << "module features";
275 return true;
276 }
277
Guy Benyei11169dd2012-12-18 14:30:41 +0000278 if (ExistingLangOpts.ObjCRuntime != LangOpts.ObjCRuntime) {
279 if (Diags)
280 Diags->Report(diag::err_pch_langopt_value_mismatch)
281 << "target Objective-C runtime";
282 return true;
283 }
284
Dmitri Gribenkoacf2e782013-02-22 14:21:27 +0000285 if (ExistingLangOpts.CommentOpts.BlockCommandNames !=
286 LangOpts.CommentOpts.BlockCommandNames) {
287 if (Diags)
288 Diags->Report(diag::err_pch_langopt_value_mismatch)
289 << "block command names";
290 return true;
291 }
292
Guy Benyei11169dd2012-12-18 14:30:41 +0000293 return false;
294}
295
296/// \brief Compare the given set of target options against an existing set of
297/// target options.
298///
299/// \param Diags If non-NULL, diagnostics will be emitted via this engine.
300///
301/// \returns true if the target options mis-match, false otherwise.
302static bool checkTargetOptions(const TargetOptions &TargetOpts,
303 const TargetOptions &ExistingTargetOpts,
Chandler Carruth0d745bc2015-03-14 04:47:43 +0000304 DiagnosticsEngine *Diags,
305 bool AllowCompatibleDifferences = true) {
Guy Benyei11169dd2012-12-18 14:30:41 +0000306#define CHECK_TARGET_OPT(Field, Name) \
307 if (TargetOpts.Field != ExistingTargetOpts.Field) { \
308 if (Diags) \
309 Diags->Report(diag::err_pch_targetopt_mismatch) \
310 << Name << TargetOpts.Field << ExistingTargetOpts.Field; \
311 return true; \
312 }
313
Chandler Carruth0d745bc2015-03-14 04:47:43 +0000314 // The triple and ABI must match exactly.
Guy Benyei11169dd2012-12-18 14:30:41 +0000315 CHECK_TARGET_OPT(Triple, "target");
Guy Benyei11169dd2012-12-18 14:30:41 +0000316 CHECK_TARGET_OPT(ABI, "target ABI");
Chandler Carruth0d745bc2015-03-14 04:47:43 +0000317
318 // We can tolerate different CPUs in many cases, notably when one CPU
319 // supports a strict superset of another. When allowing compatible
320 // differences skip this check.
321 if (!AllowCompatibleDifferences)
322 CHECK_TARGET_OPT(CPU, "target CPU");
323
Guy Benyei11169dd2012-12-18 14:30:41 +0000324#undef CHECK_TARGET_OPT
325
326 // Compare feature sets.
327 SmallVector<StringRef, 4> ExistingFeatures(
328 ExistingTargetOpts.FeaturesAsWritten.begin(),
329 ExistingTargetOpts.FeaturesAsWritten.end());
330 SmallVector<StringRef, 4> ReadFeatures(TargetOpts.FeaturesAsWritten.begin(),
331 TargetOpts.FeaturesAsWritten.end());
332 std::sort(ExistingFeatures.begin(), ExistingFeatures.end());
333 std::sort(ReadFeatures.begin(), ReadFeatures.end());
334
Chandler Carruth0d745bc2015-03-14 04:47:43 +0000335 // We compute the set difference in both directions explicitly so that we can
336 // diagnose the differences differently.
337 SmallVector<StringRef, 4> UnmatchedExistingFeatures, UnmatchedReadFeatures;
338 std::set_difference(
339 ExistingFeatures.begin(), ExistingFeatures.end(), ReadFeatures.begin(),
340 ReadFeatures.end(), std::back_inserter(UnmatchedExistingFeatures));
341 std::set_difference(ReadFeatures.begin(), ReadFeatures.end(),
342 ExistingFeatures.begin(), ExistingFeatures.end(),
343 std::back_inserter(UnmatchedReadFeatures));
Guy Benyei11169dd2012-12-18 14:30:41 +0000344
Chandler Carruth0d745bc2015-03-14 04:47:43 +0000345 // If we are allowing compatible differences and the read feature set is
346 // a strict subset of the existing feature set, there is nothing to diagnose.
347 if (AllowCompatibleDifferences && UnmatchedReadFeatures.empty())
348 return false;
Guy Benyei11169dd2012-12-18 14:30:41 +0000349
Chandler Carruth0d745bc2015-03-14 04:47:43 +0000350 if (Diags) {
351 for (StringRef Feature : UnmatchedReadFeatures)
Guy Benyei11169dd2012-12-18 14:30:41 +0000352 Diags->Report(diag::err_pch_targetopt_feature_mismatch)
Chandler Carruth0d745bc2015-03-14 04:47:43 +0000353 << /* is-existing-feature */ false << Feature;
354 for (StringRef Feature : UnmatchedExistingFeatures)
355 Diags->Report(diag::err_pch_targetopt_feature_mismatch)
356 << /* is-existing-feature */ true << Feature;
Guy Benyei11169dd2012-12-18 14:30:41 +0000357 }
358
Chandler Carruth0d745bc2015-03-14 04:47:43 +0000359 return !UnmatchedReadFeatures.empty() || !UnmatchedExistingFeatures.empty();
Guy Benyei11169dd2012-12-18 14:30:41 +0000360}
361
362bool
363PCHValidator::ReadLanguageOptions(const LangOptions &LangOpts,
Richard Smith1e2cf0d2014-10-31 02:28:58 +0000364 bool Complain,
365 bool AllowCompatibleDifferences) {
Guy Benyei11169dd2012-12-18 14:30:41 +0000366 const LangOptions &ExistingLangOpts = PP.getLangOpts();
367 return checkLanguageOptions(LangOpts, ExistingLangOpts,
Richard Smith1e2cf0d2014-10-31 02:28:58 +0000368 Complain ? &Reader.Diags : nullptr,
369 AllowCompatibleDifferences);
Guy Benyei11169dd2012-12-18 14:30:41 +0000370}
371
372bool PCHValidator::ReadTargetOptions(const TargetOptions &TargetOpts,
Chandler Carruth0d745bc2015-03-14 04:47:43 +0000373 bool Complain,
374 bool AllowCompatibleDifferences) {
Guy Benyei11169dd2012-12-18 14:30:41 +0000375 const TargetOptions &ExistingTargetOpts = PP.getTargetInfo().getTargetOpts();
376 return checkTargetOptions(TargetOpts, ExistingTargetOpts,
Chandler Carruth0d745bc2015-03-14 04:47:43 +0000377 Complain ? &Reader.Diags : nullptr,
378 AllowCompatibleDifferences);
Guy Benyei11169dd2012-12-18 14:30:41 +0000379}
380
381namespace {
Eugene Zelenkoe95e7d52016-09-07 21:53:17 +0000382
Guy Benyei11169dd2012-12-18 14:30:41 +0000383 typedef llvm::StringMap<std::pair<StringRef, bool /*IsUndef*/> >
384 MacroDefinitionsMap;
Craig Topper3598eb72013-07-05 04:43:31 +0000385 typedef llvm::DenseMap<DeclarationName, SmallVector<NamedDecl *, 8> >
386 DeclsMap;
Eugene Zelenkoe95e7d52016-09-07 21:53:17 +0000387
388} // end anonymous namespace
Guy Benyei11169dd2012-12-18 14:30:41 +0000389
Ben Langmuirb92de022014-04-29 16:25:26 +0000390static bool checkDiagnosticGroupMappings(DiagnosticsEngine &StoredDiags,
391 DiagnosticsEngine &Diags,
392 bool Complain) {
393 typedef DiagnosticsEngine::Level Level;
394
395 // Check current mappings for new -Werror mappings, and the stored mappings
396 // for cases that were explicitly mapped to *not* be errors that are now
397 // errors because of options like -Werror.
398 DiagnosticsEngine *MappingSources[] = { &Diags, &StoredDiags };
399
400 for (DiagnosticsEngine *MappingSource : MappingSources) {
401 for (auto DiagIDMappingPair : MappingSource->getDiagnosticMappings()) {
402 diag::kind DiagID = DiagIDMappingPair.first;
403 Level CurLevel = Diags.getDiagnosticLevel(DiagID, SourceLocation());
404 if (CurLevel < DiagnosticsEngine::Error)
405 continue; // not significant
406 Level StoredLevel =
407 StoredDiags.getDiagnosticLevel(DiagID, SourceLocation());
408 if (StoredLevel < DiagnosticsEngine::Error) {
409 if (Complain)
410 Diags.Report(diag::err_pch_diagopt_mismatch) << "-Werror=" +
411 Diags.getDiagnosticIDs()->getWarningOptionForDiag(DiagID).str();
412 return true;
413 }
414 }
415 }
416
417 return false;
418}
419
Alp Tokerac4e8e52014-06-22 21:58:33 +0000420static bool isExtHandlingFromDiagsError(DiagnosticsEngine &Diags) {
421 diag::Severity Ext = Diags.getExtensionHandlingBehavior();
422 if (Ext == diag::Severity::Warning && Diags.getWarningsAsErrors())
423 return true;
424 return Ext >= diag::Severity::Error;
Ben Langmuirb92de022014-04-29 16:25:26 +0000425}
426
427static bool checkDiagnosticMappings(DiagnosticsEngine &StoredDiags,
428 DiagnosticsEngine &Diags,
429 bool IsSystem, bool Complain) {
430 // Top-level options
431 if (IsSystem) {
432 if (Diags.getSuppressSystemWarnings())
433 return false;
434 // If -Wsystem-headers was not enabled before, be conservative
435 if (StoredDiags.getSuppressSystemWarnings()) {
436 if (Complain)
437 Diags.Report(diag::err_pch_diagopt_mismatch) << "-Wsystem-headers";
438 return true;
439 }
440 }
441
442 if (Diags.getWarningsAsErrors() && !StoredDiags.getWarningsAsErrors()) {
443 if (Complain)
444 Diags.Report(diag::err_pch_diagopt_mismatch) << "-Werror";
445 return true;
446 }
447
448 if (Diags.getWarningsAsErrors() && Diags.getEnableAllWarnings() &&
449 !StoredDiags.getEnableAllWarnings()) {
450 if (Complain)
451 Diags.Report(diag::err_pch_diagopt_mismatch) << "-Weverything -Werror";
452 return true;
453 }
454
455 if (isExtHandlingFromDiagsError(Diags) &&
456 !isExtHandlingFromDiagsError(StoredDiags)) {
457 if (Complain)
458 Diags.Report(diag::err_pch_diagopt_mismatch) << "-pedantic-errors";
459 return true;
460 }
461
462 return checkDiagnosticGroupMappings(StoredDiags, Diags, Complain);
463}
464
465bool PCHValidator::ReadDiagnosticOptions(
466 IntrusiveRefCntPtr<DiagnosticOptions> DiagOpts, bool Complain) {
467 DiagnosticsEngine &ExistingDiags = PP.getDiagnostics();
468 IntrusiveRefCntPtr<DiagnosticIDs> DiagIDs(ExistingDiags.getDiagnosticIDs());
469 IntrusiveRefCntPtr<DiagnosticsEngine> Diags(
Alp Tokerf994cef2014-07-05 03:08:06 +0000470 new DiagnosticsEngine(DiagIDs, DiagOpts.get()));
Ben Langmuirb92de022014-04-29 16:25:26 +0000471 // This should never fail, because we would have processed these options
472 // before writing them to an ASTFile.
473 ProcessWarningOptions(*Diags, *DiagOpts, /*Report*/false);
474
475 ModuleManager &ModuleMgr = Reader.getModuleManager();
476 assert(ModuleMgr.size() >= 1 && "what ASTFile is this then");
477
478 // If the original import came from a file explicitly generated by the user,
479 // don't check the diagnostic mappings.
480 // FIXME: currently this is approximated by checking whether this is not a
Richard Smithe842a472014-10-22 02:05:46 +0000481 // module import of an implicitly-loaded module file.
Ben Langmuirb92de022014-04-29 16:25:26 +0000482 // Note: ModuleMgr.rbegin() may not be the current module, but it must be in
483 // the transitive closure of its imports, since unrelated modules cannot be
484 // imported until after this module finishes validation.
Duncan P. N. Exon Smith96a06e02017-01-28 22:15:22 +0000485 ModuleFile *TopImport = &*ModuleMgr.rbegin();
Ben Langmuirb92de022014-04-29 16:25:26 +0000486 while (!TopImport->ImportedBy.empty())
487 TopImport = TopImport->ImportedBy[0];
Richard Smithe842a472014-10-22 02:05:46 +0000488 if (TopImport->Kind != MK_ImplicitModule)
Ben Langmuirb92de022014-04-29 16:25:26 +0000489 return false;
490
491 StringRef ModuleName = TopImport->ModuleName;
492 assert(!ModuleName.empty() && "diagnostic options read before module name");
493
494 Module *M = PP.getHeaderSearchInfo().lookupModule(ModuleName);
495 assert(M && "missing module");
496
497 // FIXME: if the diagnostics are incompatible, save a DiagnosticOptions that
498 // contains the union of their flags.
499 return checkDiagnosticMappings(*Diags, ExistingDiags, M->IsSystem, Complain);
500}
501
Guy Benyei11169dd2012-12-18 14:30:41 +0000502/// \brief Collect the macro definitions provided by the given preprocessor
503/// options.
Craig Toppera13603a2014-05-22 05:54:18 +0000504static void
505collectMacroDefinitions(const PreprocessorOptions &PPOpts,
506 MacroDefinitionsMap &Macros,
507 SmallVectorImpl<StringRef> *MacroNames = nullptr) {
Guy Benyei11169dd2012-12-18 14:30:41 +0000508 for (unsigned I = 0, N = PPOpts.Macros.size(); I != N; ++I) {
509 StringRef Macro = PPOpts.Macros[I].first;
510 bool IsUndef = PPOpts.Macros[I].second;
511
512 std::pair<StringRef, StringRef> MacroPair = Macro.split('=');
513 StringRef MacroName = MacroPair.first;
514 StringRef MacroBody = MacroPair.second;
515
516 // For an #undef'd macro, we only care about the name.
517 if (IsUndef) {
518 if (MacroNames && !Macros.count(MacroName))
519 MacroNames->push_back(MacroName);
520
521 Macros[MacroName] = std::make_pair("", true);
522 continue;
523 }
524
525 // For a #define'd macro, figure out the actual definition.
526 if (MacroName.size() == Macro.size())
527 MacroBody = "1";
528 else {
529 // Note: GCC drops anything following an end-of-line character.
530 StringRef::size_type End = MacroBody.find_first_of("\n\r");
531 MacroBody = MacroBody.substr(0, End);
532 }
533
534 if (MacroNames && !Macros.count(MacroName))
535 MacroNames->push_back(MacroName);
536 Macros[MacroName] = std::make_pair(MacroBody, false);
537 }
538}
Argyrios Kyrtzidisbd0b6512015-02-19 20:12:20 +0000539
Guy Benyei11169dd2012-12-18 14:30:41 +0000540/// \brief Check the preprocessor options deserialized from the control block
541/// against the preprocessor options in an existing preprocessor.
542///
543/// \param Diags If non-null, produce diagnostics for any mismatches incurred.
Yaxun Liu43712e02016-09-07 18:40:20 +0000544/// \param Validate If true, validate preprocessor options. If false, allow
545/// macros defined by \p ExistingPPOpts to override those defined by
546/// \p PPOpts in SuggestedPredefines.
Guy Benyei11169dd2012-12-18 14:30:41 +0000547static bool checkPreprocessorOptions(const PreprocessorOptions &PPOpts,
548 const PreprocessorOptions &ExistingPPOpts,
549 DiagnosticsEngine *Diags,
550 FileManager &FileMgr,
Argyrios Kyrtzidisd3afa0c2013-04-26 21:33:40 +0000551 std::string &SuggestedPredefines,
Yaxun Liu43712e02016-09-07 18:40:20 +0000552 const LangOptions &LangOpts,
553 bool Validate = true) {
Guy Benyei11169dd2012-12-18 14:30:41 +0000554 // Check macro definitions.
555 MacroDefinitionsMap ASTFileMacros;
556 collectMacroDefinitions(PPOpts, ASTFileMacros);
557 MacroDefinitionsMap ExistingMacros;
558 SmallVector<StringRef, 4> ExistingMacroNames;
559 collectMacroDefinitions(ExistingPPOpts, ExistingMacros, &ExistingMacroNames);
560
561 for (unsigned I = 0, N = ExistingMacroNames.size(); I != N; ++I) {
562 // Dig out the macro definition in the existing preprocessor options.
563 StringRef MacroName = ExistingMacroNames[I];
564 std::pair<StringRef, bool> Existing = ExistingMacros[MacroName];
565
566 // Check whether we know anything about this macro name or not.
567 llvm::StringMap<std::pair<StringRef, bool /*IsUndef*/> >::iterator Known
568 = ASTFileMacros.find(MacroName);
Yaxun Liu43712e02016-09-07 18:40:20 +0000569 if (!Validate || Known == ASTFileMacros.end()) {
Guy Benyei11169dd2012-12-18 14:30:41 +0000570 // FIXME: Check whether this identifier was referenced anywhere in the
571 // AST file. If so, we should reject the AST file. Unfortunately, this
572 // information isn't in the control block. What shall we do about it?
573
574 if (Existing.second) {
575 SuggestedPredefines += "#undef ";
576 SuggestedPredefines += MacroName.str();
577 SuggestedPredefines += '\n';
578 } else {
579 SuggestedPredefines += "#define ";
580 SuggestedPredefines += MacroName.str();
581 SuggestedPredefines += ' ';
582 SuggestedPredefines += Existing.first.str();
583 SuggestedPredefines += '\n';
584 }
585 continue;
586 }
587
588 // If the macro was defined in one but undef'd in the other, we have a
589 // conflict.
590 if (Existing.second != Known->second.second) {
591 if (Diags) {
592 Diags->Report(diag::err_pch_macro_def_undef)
593 << MacroName << Known->second.second;
594 }
595 return true;
596 }
597
598 // If the macro was #undef'd in both, or if the macro bodies are identical,
599 // it's fine.
600 if (Existing.second || Existing.first == Known->second.first)
601 continue;
602
603 // The macro bodies differ; complain.
604 if (Diags) {
605 Diags->Report(diag::err_pch_macro_def_conflict)
606 << MacroName << Known->second.first << Existing.first;
607 }
608 return true;
609 }
610
611 // Check whether we're using predefines.
Yaxun Liu43712e02016-09-07 18:40:20 +0000612 if (PPOpts.UsePredefines != ExistingPPOpts.UsePredefines && Validate) {
Guy Benyei11169dd2012-12-18 14:30:41 +0000613 if (Diags) {
614 Diags->Report(diag::err_pch_undef) << ExistingPPOpts.UsePredefines;
615 }
616 return true;
617 }
618
Argyrios Kyrtzidisd3afa0c2013-04-26 21:33:40 +0000619 // Detailed record is important since it is used for the module cache hash.
620 if (LangOpts.Modules &&
Yaxun Liu43712e02016-09-07 18:40:20 +0000621 PPOpts.DetailedRecord != ExistingPPOpts.DetailedRecord && Validate) {
Argyrios Kyrtzidisd3afa0c2013-04-26 21:33:40 +0000622 if (Diags) {
623 Diags->Report(diag::err_pch_pp_detailed_record) << PPOpts.DetailedRecord;
624 }
625 return true;
626 }
627
Guy Benyei11169dd2012-12-18 14:30:41 +0000628 // Compute the #include and #include_macros lines we need.
629 for (unsigned I = 0, N = ExistingPPOpts.Includes.size(); I != N; ++I) {
630 StringRef File = ExistingPPOpts.Includes[I];
631 if (File == ExistingPPOpts.ImplicitPCHInclude)
632 continue;
633
634 if (std::find(PPOpts.Includes.begin(), PPOpts.Includes.end(), File)
635 != PPOpts.Includes.end())
636 continue;
637
638 SuggestedPredefines += "#include \"";
Manuel Klimek9af34ae2014-08-12 08:25:57 +0000639 SuggestedPredefines += File;
Guy Benyei11169dd2012-12-18 14:30:41 +0000640 SuggestedPredefines += "\"\n";
641 }
642
643 for (unsigned I = 0, N = ExistingPPOpts.MacroIncludes.size(); I != N; ++I) {
644 StringRef File = ExistingPPOpts.MacroIncludes[I];
645 if (std::find(PPOpts.MacroIncludes.begin(), PPOpts.MacroIncludes.end(),
646 File)
647 != PPOpts.MacroIncludes.end())
648 continue;
649
650 SuggestedPredefines += "#__include_macros \"";
Manuel Klimek9af34ae2014-08-12 08:25:57 +0000651 SuggestedPredefines += File;
Guy Benyei11169dd2012-12-18 14:30:41 +0000652 SuggestedPredefines += "\"\n##\n";
653 }
654
655 return false;
656}
657
658bool PCHValidator::ReadPreprocessorOptions(const PreprocessorOptions &PPOpts,
659 bool Complain,
660 std::string &SuggestedPredefines) {
661 const PreprocessorOptions &ExistingPPOpts = PP.getPreprocessorOpts();
662
663 return checkPreprocessorOptions(PPOpts, ExistingPPOpts,
Craig Toppera13603a2014-05-22 05:54:18 +0000664 Complain? &Reader.Diags : nullptr,
Guy Benyei11169dd2012-12-18 14:30:41 +0000665 PP.getFileManager(),
Argyrios Kyrtzidisd3afa0c2013-04-26 21:33:40 +0000666 SuggestedPredefines,
667 PP.getLangOpts());
Guy Benyei11169dd2012-12-18 14:30:41 +0000668}
669
Yaxun Liu43712e02016-09-07 18:40:20 +0000670bool SimpleASTReaderListener::ReadPreprocessorOptions(
671 const PreprocessorOptions &PPOpts,
672 bool Complain,
673 std::string &SuggestedPredefines) {
674 return checkPreprocessorOptions(PPOpts,
675 PP.getPreprocessorOpts(),
676 nullptr,
677 PP.getFileManager(),
678 SuggestedPredefines,
679 PP.getLangOpts(),
680 false);
681}
682
Argyrios Kyrtzidisbd0b6512015-02-19 20:12:20 +0000683/// Check the header search options deserialized from the control block
684/// against the header search options in an existing preprocessor.
685///
686/// \param Diags If non-null, produce diagnostics for any mismatches incurred.
687static bool checkHeaderSearchOptions(const HeaderSearchOptions &HSOpts,
688 StringRef SpecificModuleCachePath,
689 StringRef ExistingModuleCachePath,
690 DiagnosticsEngine *Diags,
691 const LangOptions &LangOpts) {
692 if (LangOpts.Modules) {
693 if (SpecificModuleCachePath != ExistingModuleCachePath) {
694 if (Diags)
695 Diags->Report(diag::err_pch_modulecache_mismatch)
696 << SpecificModuleCachePath << ExistingModuleCachePath;
697 return true;
698 }
699 }
700
701 return false;
702}
703
704bool PCHValidator::ReadHeaderSearchOptions(const HeaderSearchOptions &HSOpts,
705 StringRef SpecificModuleCachePath,
706 bool Complain) {
707 return checkHeaderSearchOptions(HSOpts, SpecificModuleCachePath,
708 PP.getHeaderSearchInfo().getModuleCachePath(),
709 Complain ? &Reader.Diags : nullptr,
710 PP.getLangOpts());
711}
712
Guy Benyei11169dd2012-12-18 14:30:41 +0000713void PCHValidator::ReadCounter(const ModuleFile &M, unsigned Value) {
714 PP.setCounterValue(Value);
715}
716
717//===----------------------------------------------------------------------===//
718// AST reader implementation
719//===----------------------------------------------------------------------===//
720
Nico Weber824285e2014-05-08 04:26:47 +0000721void ASTReader::setDeserializationListener(ASTDeserializationListener *Listener,
722 bool TakeOwnership) {
Guy Benyei11169dd2012-12-18 14:30:41 +0000723 DeserializationListener = Listener;
Nico Weber824285e2014-05-08 04:26:47 +0000724 OwnsDeserializationListener = TakeOwnership;
Guy Benyei11169dd2012-12-18 14:30:41 +0000725}
726
Guy Benyei11169dd2012-12-18 14:30:41 +0000727unsigned ASTSelectorLookupTrait::ComputeHash(Selector Sel) {
728 return serialization::ComputeHash(Sel);
729}
730
Guy Benyei11169dd2012-12-18 14:30:41 +0000731std::pair<unsigned, unsigned>
732ASTSelectorLookupTrait::ReadKeyDataLength(const unsigned char*& d) {
Justin Bogner57ba0b22014-03-28 22:03:24 +0000733 using namespace llvm::support;
734 unsigned KeyLen = endian::readNext<uint16_t, little, unaligned>(d);
735 unsigned DataLen = endian::readNext<uint16_t, little, unaligned>(d);
Guy Benyei11169dd2012-12-18 14:30:41 +0000736 return std::make_pair(KeyLen, DataLen);
737}
738
David L. Jonesc4808b9e2016-12-15 20:53:26 +0000739ASTSelectorLookupTrait::internal_key_type
Guy Benyei11169dd2012-12-18 14:30:41 +0000740ASTSelectorLookupTrait::ReadKey(const unsigned char* d, unsigned) {
Justin Bogner57ba0b22014-03-28 22:03:24 +0000741 using namespace llvm::support;
Guy Benyei11169dd2012-12-18 14:30:41 +0000742 SelectorTable &SelTable = Reader.getContext().Selectors;
Justin Bogner57ba0b22014-03-28 22:03:24 +0000743 unsigned N = endian::readNext<uint16_t, little, unaligned>(d);
744 IdentifierInfo *FirstII = Reader.getLocalIdentifier(
745 F, endian::readNext<uint32_t, little, unaligned>(d));
Guy Benyei11169dd2012-12-18 14:30:41 +0000746 if (N == 0)
747 return SelTable.getNullarySelector(FirstII);
748 else if (N == 1)
749 return SelTable.getUnarySelector(FirstII);
750
751 SmallVector<IdentifierInfo *, 16> Args;
752 Args.push_back(FirstII);
753 for (unsigned I = 1; I != N; ++I)
Justin Bogner57ba0b22014-03-28 22:03:24 +0000754 Args.push_back(Reader.getLocalIdentifier(
755 F, endian::readNext<uint32_t, little, unaligned>(d)));
Guy Benyei11169dd2012-12-18 14:30:41 +0000756
757 return SelTable.getSelector(N, Args.data());
758}
759
David L. Jonesc4808b9e2016-12-15 20:53:26 +0000760ASTSelectorLookupTrait::data_type
761ASTSelectorLookupTrait::ReadData(Selector, const unsigned char* d,
Guy Benyei11169dd2012-12-18 14:30:41 +0000762 unsigned DataLen) {
Justin Bogner57ba0b22014-03-28 22:03:24 +0000763 using namespace llvm::support;
Guy Benyei11169dd2012-12-18 14:30:41 +0000764
765 data_type Result;
766
Justin Bogner57ba0b22014-03-28 22:03:24 +0000767 Result.ID = Reader.getGlobalSelectorID(
768 F, endian::readNext<uint32_t, little, unaligned>(d));
Nico Weberff4b35e2014-12-27 22:14:15 +0000769 unsigned FullInstanceBits = endian::readNext<uint16_t, little, unaligned>(d);
770 unsigned FullFactoryBits = endian::readNext<uint16_t, little, unaligned>(d);
771 Result.InstanceBits = FullInstanceBits & 0x3;
772 Result.InstanceHasMoreThanOneDecl = (FullInstanceBits >> 2) & 0x1;
773 Result.FactoryBits = FullFactoryBits & 0x3;
774 Result.FactoryHasMoreThanOneDecl = (FullFactoryBits >> 2) & 0x1;
775 unsigned NumInstanceMethods = FullInstanceBits >> 3;
776 unsigned NumFactoryMethods = FullFactoryBits >> 3;
Guy Benyei11169dd2012-12-18 14:30:41 +0000777
778 // Load instance methods
779 for (unsigned I = 0; I != NumInstanceMethods; ++I) {
Justin Bogner57ba0b22014-03-28 22:03:24 +0000780 if (ObjCMethodDecl *Method = Reader.GetLocalDeclAs<ObjCMethodDecl>(
781 F, endian::readNext<uint32_t, little, unaligned>(d)))
Guy Benyei11169dd2012-12-18 14:30:41 +0000782 Result.Instance.push_back(Method);
783 }
784
785 // Load factory methods
786 for (unsigned I = 0; I != NumFactoryMethods; ++I) {
Justin Bogner57ba0b22014-03-28 22:03:24 +0000787 if (ObjCMethodDecl *Method = Reader.GetLocalDeclAs<ObjCMethodDecl>(
788 F, endian::readNext<uint32_t, little, unaligned>(d)))
Guy Benyei11169dd2012-12-18 14:30:41 +0000789 Result.Factory.push_back(Method);
790 }
791
792 return Result;
793}
794
Douglas Gregorbfd73d72013-01-23 18:53:14 +0000795unsigned ASTIdentifierLookupTraitBase::ComputeHash(const internal_key_type& a) {
796 return llvm::HashString(a);
Guy Benyei11169dd2012-12-18 14:30:41 +0000797}
798
799std::pair<unsigned, unsigned>
Douglas Gregorbfd73d72013-01-23 18:53:14 +0000800ASTIdentifierLookupTraitBase::ReadKeyDataLength(const unsigned char*& d) {
Justin Bogner57ba0b22014-03-28 22:03:24 +0000801 using namespace llvm::support;
802 unsigned DataLen = endian::readNext<uint16_t, little, unaligned>(d);
803 unsigned KeyLen = endian::readNext<uint16_t, little, unaligned>(d);
Guy Benyei11169dd2012-12-18 14:30:41 +0000804 return std::make_pair(KeyLen, DataLen);
805}
806
Douglas Gregorbfd73d72013-01-23 18:53:14 +0000807ASTIdentifierLookupTraitBase::internal_key_type
808ASTIdentifierLookupTraitBase::ReadKey(const unsigned char* d, unsigned n) {
Guy Benyei11169dd2012-12-18 14:30:41 +0000809 assert(n >= 2 && d[n-1] == '\0');
Douglas Gregorbfd73d72013-01-23 18:53:14 +0000810 return StringRef((const char*) d, n-1);
Guy Benyei11169dd2012-12-18 14:30:41 +0000811}
812
Douglas Gregordcf25082013-02-11 18:16:18 +0000813/// \brief Whether the given identifier is "interesting".
Richard Smitha534a312015-07-21 23:54:07 +0000814static bool isInterestingIdentifier(ASTReader &Reader, IdentifierInfo &II,
815 bool IsModule) {
Richard Smithcab89802015-07-17 20:19:56 +0000816 return II.hadMacroDefinition() ||
817 II.isPoisoned() ||
Richard Smith9c254182015-07-19 21:41:12 +0000818 (IsModule ? II.hasRevertedBuiltin() : II.getObjCOrBuiltinID()) ||
Douglas Gregordcf25082013-02-11 18:16:18 +0000819 II.hasRevertedTokenIDToIdentifier() ||
Richard Smitha534a312015-07-21 23:54:07 +0000820 (!(IsModule && Reader.getContext().getLangOpts().CPlusPlus) &&
821 II.getFETokenInfo<void>());
Douglas Gregordcf25082013-02-11 18:16:18 +0000822}
823
Richard Smith76c2f2c2015-07-17 20:09:43 +0000824static bool readBit(unsigned &Bits) {
825 bool Value = Bits & 0x1;
826 Bits >>= 1;
827 return Value;
828}
829
Richard Smith79bf9202015-08-24 03:33:22 +0000830IdentID ASTIdentifierLookupTrait::ReadIdentifierID(const unsigned char *d) {
831 using namespace llvm::support;
832 unsigned RawID = endian::readNext<uint32_t, little, unaligned>(d);
833 return Reader.getGlobalIdentifierID(F, RawID >> 1);
834}
835
Richard Smitheb4b58f62016-02-05 01:40:54 +0000836static void markIdentifierFromAST(ASTReader &Reader, IdentifierInfo &II) {
837 if (!II.isFromAST()) {
838 II.setIsFromAST();
839 bool IsModule = Reader.getPreprocessor().getCurrentModule() != nullptr;
840 if (isInterestingIdentifier(Reader, II, IsModule))
841 II.setChangedSinceDeserialization();
842 }
843}
844
Guy Benyei11169dd2012-12-18 14:30:41 +0000845IdentifierInfo *ASTIdentifierLookupTrait::ReadData(const internal_key_type& k,
846 const unsigned char* d,
847 unsigned DataLen) {
Justin Bogner57ba0b22014-03-28 22:03:24 +0000848 using namespace llvm::support;
849 unsigned RawID = endian::readNext<uint32_t, little, unaligned>(d);
Guy Benyei11169dd2012-12-18 14:30:41 +0000850 bool IsInteresting = RawID & 0x01;
851
852 // Wipe out the "is interesting" bit.
853 RawID = RawID >> 1;
854
Richard Smith76c2f2c2015-07-17 20:09:43 +0000855 // Build the IdentifierInfo and link the identifier ID with it.
856 IdentifierInfo *II = KnownII;
857 if (!II) {
858 II = &Reader.getIdentifierTable().getOwn(k);
859 KnownII = II;
860 }
Richard Smitheb4b58f62016-02-05 01:40:54 +0000861 markIdentifierFromAST(Reader, *II);
Richard Smith76c2f2c2015-07-17 20:09:43 +0000862 Reader.markIdentifierUpToDate(II);
863
Guy Benyei11169dd2012-12-18 14:30:41 +0000864 IdentID ID = Reader.getGlobalIdentifierID(F, RawID);
865 if (!IsInteresting) {
Richard Smith76c2f2c2015-07-17 20:09:43 +0000866 // For uninteresting identifiers, there's nothing else to do. Just notify
867 // the reader that we've finished loading this identifier.
Guy Benyei11169dd2012-12-18 14:30:41 +0000868 Reader.SetIdentifierInfo(ID, II);
Guy Benyei11169dd2012-12-18 14:30:41 +0000869 return II;
870 }
871
Justin Bogner57ba0b22014-03-28 22:03:24 +0000872 unsigned ObjCOrBuiltinID = endian::readNext<uint16_t, little, unaligned>(d);
873 unsigned Bits = endian::readNext<uint16_t, little, unaligned>(d);
Richard Smith76c2f2c2015-07-17 20:09:43 +0000874 bool CPlusPlusOperatorKeyword = readBit(Bits);
875 bool HasRevertedTokenIDToIdentifier = readBit(Bits);
Richard Smith9c254182015-07-19 21:41:12 +0000876 bool HasRevertedBuiltin = readBit(Bits);
Richard Smith76c2f2c2015-07-17 20:09:43 +0000877 bool Poisoned = readBit(Bits);
878 bool ExtensionToken = readBit(Bits);
879 bool HadMacroDefinition = readBit(Bits);
Guy Benyei11169dd2012-12-18 14:30:41 +0000880
881 assert(Bits == 0 && "Extra bits in the identifier?");
882 DataLen -= 8;
883
Guy Benyei11169dd2012-12-18 14:30:41 +0000884 // Set or check the various bits in the IdentifierInfo structure.
885 // Token IDs are read-only.
Argyrios Kyrtzidisddee8c92013-02-27 01:13:51 +0000886 if (HasRevertedTokenIDToIdentifier && II->getTokenID() != tok::identifier)
Richard Smith9c254182015-07-19 21:41:12 +0000887 II->revertTokenIDToIdentifier();
888 if (!F.isModule())
889 II->setObjCOrBuiltinID(ObjCOrBuiltinID);
890 else if (HasRevertedBuiltin && II->getBuiltinID()) {
891 II->revertBuiltin();
892 assert((II->hasRevertedBuiltin() ||
893 II->getObjCOrBuiltinID() == ObjCOrBuiltinID) &&
894 "Incorrect ObjC keyword or builtin ID");
895 }
Guy Benyei11169dd2012-12-18 14:30:41 +0000896 assert(II->isExtensionToken() == ExtensionToken &&
897 "Incorrect extension token flag");
898 (void)ExtensionToken;
899 if (Poisoned)
900 II->setIsPoisoned(true);
901 assert(II->isCPlusPlusOperatorKeyword() == CPlusPlusOperatorKeyword &&
902 "Incorrect C++ operator keyword flag");
903 (void)CPlusPlusOperatorKeyword;
904
905 // If this identifier is a macro, deserialize the macro
906 // definition.
Richard Smith76c2f2c2015-07-17 20:09:43 +0000907 if (HadMacroDefinition) {
Justin Bogner57ba0b22014-03-28 22:03:24 +0000908 uint32_t MacroDirectivesOffset =
909 endian::readNext<uint32_t, little, unaligned>(d);
Argyrios Kyrtzidiseb663da2013-03-22 21:12:57 +0000910 DataLen -= 4;
Argyrios Kyrtzidiseb663da2013-03-22 21:12:57 +0000911
Richard Smithd7329392015-04-21 21:46:32 +0000912 Reader.addPendingMacro(II, &F, MacroDirectivesOffset);
Guy Benyei11169dd2012-12-18 14:30:41 +0000913 }
914
915 Reader.SetIdentifierInfo(ID, II);
916
917 // Read all of the declarations visible at global scope with this
918 // name.
919 if (DataLen > 0) {
920 SmallVector<uint32_t, 4> DeclIDs;
921 for (; DataLen > 0; DataLen -= 4)
Justin Bogner57ba0b22014-03-28 22:03:24 +0000922 DeclIDs.push_back(Reader.getGlobalDeclID(
923 F, endian::readNext<uint32_t, little, unaligned>(d)));
Guy Benyei11169dd2012-12-18 14:30:41 +0000924 Reader.SetGloballyVisibleDecls(II, DeclIDs);
925 }
926
927 return II;
928}
929
Richard Smitha06c7e62015-08-26 23:55:49 +0000930DeclarationNameKey::DeclarationNameKey(DeclarationName Name)
931 : Kind(Name.getNameKind()) {
932 switch (Kind) {
Guy Benyei11169dd2012-12-18 14:30:41 +0000933 case DeclarationName::Identifier:
Richard Smitha06c7e62015-08-26 23:55:49 +0000934 Data = (uint64_t)Name.getAsIdentifierInfo();
Guy Benyei11169dd2012-12-18 14:30:41 +0000935 break;
936 case DeclarationName::ObjCZeroArgSelector:
937 case DeclarationName::ObjCOneArgSelector:
938 case DeclarationName::ObjCMultiArgSelector:
Richard Smitha06c7e62015-08-26 23:55:49 +0000939 Data = (uint64_t)Name.getObjCSelector().getAsOpaquePtr();
Guy Benyei11169dd2012-12-18 14:30:41 +0000940 break;
941 case DeclarationName::CXXOperatorName:
Richard Smitha06c7e62015-08-26 23:55:49 +0000942 Data = Name.getCXXOverloadedOperator();
943 break;
944 case DeclarationName::CXXLiteralOperatorName:
945 Data = (uint64_t)Name.getCXXLiteralIdentifier();
946 break;
Richard Smith35845152017-02-07 01:37:30 +0000947 case DeclarationName::CXXDeductionGuideName:
948 Data = (uint64_t)Name.getCXXDeductionGuideTemplate()
949 ->getDeclName().getAsIdentifierInfo();
950 break;
Richard Smitha06c7e62015-08-26 23:55:49 +0000951 case DeclarationName::CXXConstructorName:
952 case DeclarationName::CXXDestructorName:
953 case DeclarationName::CXXConversionFunctionName:
954 case DeclarationName::CXXUsingDirective:
955 Data = 0;
956 break;
957 }
958}
959
960unsigned DeclarationNameKey::getHash() const {
961 llvm::FoldingSetNodeID ID;
962 ID.AddInteger(Kind);
963
964 switch (Kind) {
965 case DeclarationName::Identifier:
966 case DeclarationName::CXXLiteralOperatorName:
Richard Smith35845152017-02-07 01:37:30 +0000967 case DeclarationName::CXXDeductionGuideName:
Richard Smitha06c7e62015-08-26 23:55:49 +0000968 ID.AddString(((IdentifierInfo*)Data)->getName());
969 break;
970 case DeclarationName::ObjCZeroArgSelector:
971 case DeclarationName::ObjCOneArgSelector:
972 case DeclarationName::ObjCMultiArgSelector:
973 ID.AddInteger(serialization::ComputeHash(Selector(Data)));
974 break;
975 case DeclarationName::CXXOperatorName:
976 ID.AddInteger((OverloadedOperatorKind)Data);
Guy Benyei11169dd2012-12-18 14:30:41 +0000977 break;
978 case DeclarationName::CXXConstructorName:
979 case DeclarationName::CXXDestructorName:
980 case DeclarationName::CXXConversionFunctionName:
981 case DeclarationName::CXXUsingDirective:
982 break;
983 }
984
985 return ID.ComputeHash();
986}
987
Richard Smithd88a7f12015-09-01 20:35:42 +0000988ModuleFile *
989ASTDeclContextNameLookupTrait::ReadFileRef(const unsigned char *&d) {
990 using namespace llvm::support;
991 uint32_t ModuleFileID = endian::readNext<uint32_t, little, unaligned>(d);
992 return Reader.getLocalModuleFile(F, ModuleFileID);
993}
994
Guy Benyei11169dd2012-12-18 14:30:41 +0000995std::pair<unsigned, unsigned>
Richard Smitha06c7e62015-08-26 23:55:49 +0000996ASTDeclContextNameLookupTrait::ReadKeyDataLength(const unsigned char *&d) {
Justin Bogner57ba0b22014-03-28 22:03:24 +0000997 using namespace llvm::support;
998 unsigned KeyLen = endian::readNext<uint16_t, little, unaligned>(d);
999 unsigned DataLen = endian::readNext<uint16_t, little, unaligned>(d);
Guy Benyei11169dd2012-12-18 14:30:41 +00001000 return std::make_pair(KeyLen, DataLen);
1001}
1002
Richard Smitha06c7e62015-08-26 23:55:49 +00001003ASTDeclContextNameLookupTrait::internal_key_type
1004ASTDeclContextNameLookupTrait::ReadKey(const unsigned char *d, unsigned) {
Justin Bogner57ba0b22014-03-28 22:03:24 +00001005 using namespace llvm::support;
Guy Benyei11169dd2012-12-18 14:30:41 +00001006
Richard Smitha06c7e62015-08-26 23:55:49 +00001007 auto Kind = (DeclarationName::NameKind)*d++;
1008 uint64_t Data;
1009 switch (Kind) {
Guy Benyei11169dd2012-12-18 14:30:41 +00001010 case DeclarationName::Identifier:
Richard Smith35845152017-02-07 01:37:30 +00001011 case DeclarationName::CXXLiteralOperatorName:
1012 case DeclarationName::CXXDeductionGuideName:
Richard Smitha06c7e62015-08-26 23:55:49 +00001013 Data = (uint64_t)Reader.getLocalIdentifier(
Justin Bogner57ba0b22014-03-28 22:03:24 +00001014 F, endian::readNext<uint32_t, little, unaligned>(d));
Guy Benyei11169dd2012-12-18 14:30:41 +00001015 break;
1016 case DeclarationName::ObjCZeroArgSelector:
1017 case DeclarationName::ObjCOneArgSelector:
1018 case DeclarationName::ObjCMultiArgSelector:
Richard Smitha06c7e62015-08-26 23:55:49 +00001019 Data =
Justin Bogner57ba0b22014-03-28 22:03:24 +00001020 (uint64_t)Reader.getLocalSelector(
1021 F, endian::readNext<uint32_t, little, unaligned>(
1022 d)).getAsOpaquePtr();
Guy Benyei11169dd2012-12-18 14:30:41 +00001023 break;
1024 case DeclarationName::CXXOperatorName:
Richard Smitha06c7e62015-08-26 23:55:49 +00001025 Data = *d++; // OverloadedOperatorKind
Guy Benyei11169dd2012-12-18 14:30:41 +00001026 break;
Guy Benyei11169dd2012-12-18 14:30:41 +00001027 case DeclarationName::CXXConstructorName:
1028 case DeclarationName::CXXDestructorName:
1029 case DeclarationName::CXXConversionFunctionName:
1030 case DeclarationName::CXXUsingDirective:
Richard Smitha06c7e62015-08-26 23:55:49 +00001031 Data = 0;
Guy Benyei11169dd2012-12-18 14:30:41 +00001032 break;
1033 }
1034
Richard Smitha06c7e62015-08-26 23:55:49 +00001035 return DeclarationNameKey(Kind, Data);
Guy Benyei11169dd2012-12-18 14:30:41 +00001036}
1037
Richard Smithd88a7f12015-09-01 20:35:42 +00001038void ASTDeclContextNameLookupTrait::ReadDataInto(internal_key_type,
1039 const unsigned char *d,
1040 unsigned DataLen,
1041 data_type_builder &Val) {
Justin Bogner57ba0b22014-03-28 22:03:24 +00001042 using namespace llvm::support;
Richard Smithd88a7f12015-09-01 20:35:42 +00001043 for (unsigned NumDecls = DataLen / 4; NumDecls; --NumDecls) {
1044 uint32_t LocalID = endian::readNext<uint32_t, little, unaligned>(d);
1045 Val.insert(Reader.getGlobalDeclID(F, LocalID));
1046 }
Guy Benyei11169dd2012-12-18 14:30:41 +00001047}
1048
Richard Smith0f4e2c42015-08-06 04:23:48 +00001049bool ASTReader::ReadLexicalDeclContextStorage(ModuleFile &M,
1050 BitstreamCursor &Cursor,
1051 uint64_t Offset,
1052 DeclContext *DC) {
1053 assert(Offset != 0);
1054
Guy Benyei11169dd2012-12-18 14:30:41 +00001055 SavedStreamPosition SavedPosition(Cursor);
Richard Smith0f4e2c42015-08-06 04:23:48 +00001056 Cursor.JumpToBit(Offset);
Guy Benyei11169dd2012-12-18 14:30:41 +00001057
Richard Smith0f4e2c42015-08-06 04:23:48 +00001058 RecordData Record;
1059 StringRef Blob;
1060 unsigned Code = Cursor.ReadCode();
1061 unsigned RecCode = Cursor.readRecord(Code, Record, &Blob);
1062 if (RecCode != DECL_CONTEXT_LEXICAL) {
1063 Error("Expected lexical block");
1064 return true;
Guy Benyei11169dd2012-12-18 14:30:41 +00001065 }
1066
Richard Smith82f8fcd2015-08-06 22:07:25 +00001067 assert(!isa<TranslationUnitDecl>(DC) &&
1068 "expected a TU_UPDATE_LEXICAL record for TU");
Richard Smith9c9173d2015-08-11 22:00:24 +00001069 // If we are handling a C++ class template instantiation, we can see multiple
1070 // lexical updates for the same record. It's important that we select only one
1071 // of them, so that field numbering works properly. Just pick the first one we
1072 // see.
1073 auto &Lex = LexicalDecls[DC];
1074 if (!Lex.first) {
1075 Lex = std::make_pair(
1076 &M, llvm::makeArrayRef(
1077 reinterpret_cast<const llvm::support::unaligned_uint32_t *>(
1078 Blob.data()),
1079 Blob.size() / 4));
1080 }
Richard Smith0f4e2c42015-08-06 04:23:48 +00001081 DC->setHasExternalLexicalStorage(true);
1082 return false;
1083}
Guy Benyei11169dd2012-12-18 14:30:41 +00001084
Richard Smith0f4e2c42015-08-06 04:23:48 +00001085bool ASTReader::ReadVisibleDeclContextStorage(ModuleFile &M,
1086 BitstreamCursor &Cursor,
1087 uint64_t Offset,
1088 DeclID ID) {
1089 assert(Offset != 0);
1090
1091 SavedStreamPosition SavedPosition(Cursor);
1092 Cursor.JumpToBit(Offset);
1093
1094 RecordData Record;
1095 StringRef Blob;
1096 unsigned Code = Cursor.ReadCode();
1097 unsigned RecCode = Cursor.readRecord(Code, Record, &Blob);
1098 if (RecCode != DECL_CONTEXT_VISIBLE) {
1099 Error("Expected visible lookup table block");
1100 return true;
Guy Benyei11169dd2012-12-18 14:30:41 +00001101 }
1102
Richard Smith0f4e2c42015-08-06 04:23:48 +00001103 // We can't safely determine the primary context yet, so delay attaching the
1104 // lookup table until we're done with recursive deserialization.
Richard Smithd88a7f12015-09-01 20:35:42 +00001105 auto *Data = (const unsigned char*)Blob.data();
1106 PendingVisibleUpdates[ID].push_back(PendingVisibleUpdate{&M, Data});
Guy Benyei11169dd2012-12-18 14:30:41 +00001107 return false;
1108}
1109
Richard Smith37a93df2017-02-18 00:32:02 +00001110void ASTReader::Error(StringRef Msg) const {
Guy Benyei11169dd2012-12-18 14:30:41 +00001111 Error(diag::err_fe_pch_malformed, Msg);
Richard Smithfb1e7f72015-08-14 05:02:58 +00001112 if (Context.getLangOpts().Modules && !Diags.isDiagnosticInFlight() &&
1113 !PP.getHeaderSearchInfo().getModuleCachePath().empty()) {
Douglas Gregor940e8052013-05-10 22:15:13 +00001114 Diag(diag::note_module_cache_path)
1115 << PP.getHeaderSearchInfo().getModuleCachePath();
1116 }
Guy Benyei11169dd2012-12-18 14:30:41 +00001117}
1118
1119void ASTReader::Error(unsigned DiagID,
Richard Smith37a93df2017-02-18 00:32:02 +00001120 StringRef Arg1, StringRef Arg2) const {
Guy Benyei11169dd2012-12-18 14:30:41 +00001121 if (Diags.isDiagnosticInFlight())
1122 Diags.SetDelayedDiagnostic(DiagID, Arg1, Arg2);
1123 else
1124 Diag(DiagID) << Arg1 << Arg2;
1125}
1126
1127//===----------------------------------------------------------------------===//
1128// Source Manager Deserialization
1129//===----------------------------------------------------------------------===//
1130
1131/// \brief Read the line table in the source manager block.
1132/// \returns true if there was an error.
1133bool ASTReader::ParseLineTable(ModuleFile &F,
Richard Smith7ed1bc92014-12-05 22:42:13 +00001134 const RecordData &Record) {
Guy Benyei11169dd2012-12-18 14:30:41 +00001135 unsigned Idx = 0;
1136 LineTableInfo &LineTable = SourceMgr.getLineTable();
1137
1138 // Parse the file names
1139 std::map<int, int> FileIDs;
Richard Smith63078492015-09-01 07:41:55 +00001140 for (unsigned I = 0; Record[Idx]; ++I) {
Guy Benyei11169dd2012-12-18 14:30:41 +00001141 // Extract the file name
Richard Smith7ed1bc92014-12-05 22:42:13 +00001142 auto Filename = ReadPath(F, Record, Idx);
Guy Benyei11169dd2012-12-18 14:30:41 +00001143 FileIDs[I] = LineTable.getLineTableFilenameID(Filename);
1144 }
Richard Smith63078492015-09-01 07:41:55 +00001145 ++Idx;
Guy Benyei11169dd2012-12-18 14:30:41 +00001146
1147 // Parse the line entries
1148 std::vector<LineEntry> Entries;
1149 while (Idx < Record.size()) {
1150 int FID = Record[Idx++];
1151 assert(FID >= 0 && "Serialized line entries for non-local file.");
1152 // Remap FileID from 1-based old view.
1153 FID += F.SLocEntryBaseID - 1;
1154
1155 // Extract the line entries
1156 unsigned NumEntries = Record[Idx++];
Richard Smith63078492015-09-01 07:41:55 +00001157 assert(NumEntries && "no line entries for file ID");
Guy Benyei11169dd2012-12-18 14:30:41 +00001158 Entries.clear();
1159 Entries.reserve(NumEntries);
1160 for (unsigned I = 0; I != NumEntries; ++I) {
1161 unsigned FileOffset = Record[Idx++];
1162 unsigned LineNo = Record[Idx++];
1163 int FilenameID = FileIDs[Record[Idx++]];
1164 SrcMgr::CharacteristicKind FileKind
1165 = (SrcMgr::CharacteristicKind)Record[Idx++];
1166 unsigned IncludeOffset = Record[Idx++];
1167 Entries.push_back(LineEntry::get(FileOffset, LineNo, FilenameID,
1168 FileKind, IncludeOffset));
1169 }
1170 LineTable.AddEntry(FileID::get(FID), Entries);
1171 }
1172
1173 return false;
1174}
1175
1176/// \brief Read a source manager block
1177bool ASTReader::ReadSourceManagerBlock(ModuleFile &F) {
1178 using namespace SrcMgr;
1179
Chris Lattner7fb3bef2013-01-20 00:56:42 +00001180 BitstreamCursor &SLocEntryCursor = F.SLocEntryCursor;
Guy Benyei11169dd2012-12-18 14:30:41 +00001181
1182 // Set the source-location entry cursor to the current position in
1183 // the stream. This cursor will be used to read the contents of the
1184 // source manager block initially, and then lazily read
1185 // source-location entries as needed.
1186 SLocEntryCursor = F.Stream;
1187
1188 // The stream itself is going to skip over the source manager block.
1189 if (F.Stream.SkipBlock()) {
1190 Error("malformed block record in AST file");
1191 return true;
1192 }
1193
1194 // Enter the source manager block.
1195 if (SLocEntryCursor.EnterSubBlock(SOURCE_MANAGER_BLOCK_ID)) {
1196 Error("malformed source manager block record in AST file");
1197 return true;
1198 }
1199
1200 RecordData Record;
1201 while (true) {
Chris Lattnere7b154b2013-01-19 21:39:22 +00001202 llvm::BitstreamEntry E = SLocEntryCursor.advanceSkippingSubblocks();
David L. Jonesc4808b9e2016-12-15 20:53:26 +00001203
Chris Lattnere7b154b2013-01-19 21:39:22 +00001204 switch (E.Kind) {
1205 case llvm::BitstreamEntry::SubBlock: // Handled for us already.
1206 case llvm::BitstreamEntry::Error:
1207 Error("malformed block record in AST file");
1208 return true;
1209 case llvm::BitstreamEntry::EndBlock:
Guy Benyei11169dd2012-12-18 14:30:41 +00001210 return false;
Chris Lattnere7b154b2013-01-19 21:39:22 +00001211 case llvm::BitstreamEntry::Record:
1212 // The interesting case.
1213 break;
Guy Benyei11169dd2012-12-18 14:30:41 +00001214 }
David L. Jonesc4808b9e2016-12-15 20:53:26 +00001215
Guy Benyei11169dd2012-12-18 14:30:41 +00001216 // Read a record.
Guy Benyei11169dd2012-12-18 14:30:41 +00001217 Record.clear();
Chris Lattner15c3e7d2013-01-21 18:28:26 +00001218 StringRef Blob;
1219 switch (SLocEntryCursor.readRecord(E.ID, Record, &Blob)) {
Guy Benyei11169dd2012-12-18 14:30:41 +00001220 default: // Default behavior: ignore.
1221 break;
1222
1223 case SM_SLOC_FILE_ENTRY:
1224 case SM_SLOC_BUFFER_ENTRY:
1225 case SM_SLOC_EXPANSION_ENTRY:
1226 // Once we hit one of the source location entries, we're done.
1227 return false;
1228 }
1229 }
1230}
1231
1232/// \brief If a header file is not found at the path that we expect it to be
1233/// and the PCH file was moved from its original location, try to resolve the
1234/// file by assuming that header+PCH were moved together and the header is in
1235/// the same place relative to the PCH.
1236static std::string
1237resolveFileRelativeToOriginalDir(const std::string &Filename,
1238 const std::string &OriginalDir,
1239 const std::string &CurrDir) {
1240 assert(OriginalDir != CurrDir &&
1241 "No point trying to resolve the file if the PCH dir didn't change");
1242 using namespace llvm::sys;
1243 SmallString<128> filePath(Filename);
1244 fs::make_absolute(filePath);
1245 assert(path::is_absolute(OriginalDir));
1246 SmallString<128> currPCHPath(CurrDir);
1247
1248 path::const_iterator fileDirI = path::begin(path::parent_path(filePath)),
1249 fileDirE = path::end(path::parent_path(filePath));
1250 path::const_iterator origDirI = path::begin(OriginalDir),
1251 origDirE = path::end(OriginalDir);
1252 // Skip the common path components from filePath and OriginalDir.
1253 while (fileDirI != fileDirE && origDirI != origDirE &&
1254 *fileDirI == *origDirI) {
1255 ++fileDirI;
1256 ++origDirI;
1257 }
1258 for (; origDirI != origDirE; ++origDirI)
1259 path::append(currPCHPath, "..");
1260 path::append(currPCHPath, fileDirI, fileDirE);
1261 path::append(currPCHPath, path::filename(Filename));
1262 return currPCHPath.str();
1263}
1264
1265bool ASTReader::ReadSLocEntry(int ID) {
1266 if (ID == 0)
1267 return false;
1268
1269 if (unsigned(-ID) - 2 >= getTotalNumSLocs() || ID > 0) {
1270 Error("source location entry ID out-of-range for AST file");
1271 return true;
1272 }
1273
Richard Smithaada85c2016-02-06 02:06:43 +00001274 // Local helper to read the (possibly-compressed) buffer data following the
1275 // entry record.
1276 auto ReadBuffer = [this](
1277 BitstreamCursor &SLocEntryCursor,
1278 StringRef Name) -> std::unique_ptr<llvm::MemoryBuffer> {
1279 RecordData Record;
1280 StringRef Blob;
1281 unsigned Code = SLocEntryCursor.ReadCode();
1282 unsigned RecCode = SLocEntryCursor.readRecord(Code, Record, &Blob);
1283
1284 if (RecCode == SM_SLOC_BUFFER_BLOB_COMPRESSED) {
George Rimarc39f5492017-01-17 15:45:31 +00001285 if (!llvm::zlib::isAvailable()) {
1286 Error("zlib is not available");
1287 return nullptr;
1288 }
Richard Smithaada85c2016-02-06 02:06:43 +00001289 SmallString<0> Uncompressed;
George Rimarc39f5492017-01-17 15:45:31 +00001290 if (llvm::Error E =
1291 llvm::zlib::uncompress(Blob, Uncompressed, Record[0])) {
1292 Error("could not decompress embedded file contents: " +
1293 llvm::toString(std::move(E)));
Richard Smithaada85c2016-02-06 02:06:43 +00001294 return nullptr;
1295 }
1296 return llvm::MemoryBuffer::getMemBufferCopy(Uncompressed, Name);
1297 } else if (RecCode == SM_SLOC_BUFFER_BLOB) {
1298 return llvm::MemoryBuffer::getMemBuffer(Blob.drop_back(1), Name, true);
1299 } else {
1300 Error("AST record has invalid code");
1301 return nullptr;
1302 }
1303 };
1304
Guy Benyei11169dd2012-12-18 14:30:41 +00001305 ModuleFile *F = GlobalSLocEntryMap.find(-ID)->second;
1306 F->SLocEntryCursor.JumpToBit(F->SLocEntryOffsets[ID - F->SLocEntryBaseID]);
Chris Lattner7fb3bef2013-01-20 00:56:42 +00001307 BitstreamCursor &SLocEntryCursor = F->SLocEntryCursor;
Guy Benyei11169dd2012-12-18 14:30:41 +00001308 unsigned BaseOffset = F->SLocEntryBaseOffset;
1309
1310 ++NumSLocEntriesRead;
Chris Lattnere7b154b2013-01-19 21:39:22 +00001311 llvm::BitstreamEntry Entry = SLocEntryCursor.advance();
1312 if (Entry.Kind != llvm::BitstreamEntry::Record) {
Guy Benyei11169dd2012-12-18 14:30:41 +00001313 Error("incorrectly-formatted source location entry in AST file");
1314 return true;
1315 }
David L. Jonesc4808b9e2016-12-15 20:53:26 +00001316
Guy Benyei11169dd2012-12-18 14:30:41 +00001317 RecordData Record;
Chris Lattner0e6c9402013-01-20 02:38:54 +00001318 StringRef Blob;
1319 switch (SLocEntryCursor.readRecord(Entry.ID, Record, &Blob)) {
Guy Benyei11169dd2012-12-18 14:30:41 +00001320 default:
1321 Error("incorrectly-formatted source location entry in AST file");
1322 return true;
1323
1324 case SM_SLOC_FILE_ENTRY: {
1325 // We will detect whether a file changed and return 'Failure' for it, but
1326 // we will also try to fail gracefully by setting up the SLocEntry.
1327 unsigned InputID = Record[4];
1328 InputFile IF = getInputFile(*F, InputID);
Argyrios Kyrtzidis61c3d872013-03-01 03:26:04 +00001329 const FileEntry *File = IF.getFile();
1330 bool OverriddenBuffer = IF.isOverridden();
Guy Benyei11169dd2012-12-18 14:30:41 +00001331
Argyrios Kyrtzidis61c3d872013-03-01 03:26:04 +00001332 // Note that we only check if a File was returned. If it was out-of-date
1333 // we have complained but we will continue creating a FileID to recover
1334 // gracefully.
1335 if (!File)
Guy Benyei11169dd2012-12-18 14:30:41 +00001336 return true;
1337
1338 SourceLocation IncludeLoc = ReadSourceLocation(*F, Record[1]);
1339 if (IncludeLoc.isInvalid() && F->Kind != MK_MainFile) {
1340 // This is the module's main file.
1341 IncludeLoc = getImportLocation(F);
1342 }
1343 SrcMgr::CharacteristicKind
1344 FileCharacter = (SrcMgr::CharacteristicKind)Record[2];
1345 FileID FID = SourceMgr.createFileID(File, IncludeLoc, FileCharacter,
1346 ID, BaseOffset + Record[0]);
1347 SrcMgr::FileInfo &FileInfo =
1348 const_cast<SrcMgr::FileInfo&>(SourceMgr.getSLocEntry(FID).getFile());
1349 FileInfo.NumCreatedFIDs = Record[5];
1350 if (Record[3])
1351 FileInfo.setHasLineDirectives();
1352
1353 const DeclID *FirstDecl = F->FileSortedDecls + Record[6];
1354 unsigned NumFileDecls = Record[7];
1355 if (NumFileDecls) {
1356 assert(F->FileSortedDecls && "FILE_SORTED_DECLS not encountered yet ?");
1357 FileDeclIDs[FID] = FileDeclsInfo(F, llvm::makeArrayRef(FirstDecl,
1358 NumFileDecls));
1359 }
Richard Smithaada85c2016-02-06 02:06:43 +00001360
Guy Benyei11169dd2012-12-18 14:30:41 +00001361 const SrcMgr::ContentCache *ContentCache
1362 = SourceMgr.getOrCreateContentCache(File,
1363 /*isSystemFile=*/FileCharacter != SrcMgr::C_User);
1364 if (OverriddenBuffer && !ContentCache->BufferOverridden &&
Richard Smitha8cfffa2015-11-26 02:04:16 +00001365 ContentCache->ContentsEntry == ContentCache->OrigEntry &&
1366 !ContentCache->getRawBuffer()) {
Richard Smithaada85c2016-02-06 02:06:43 +00001367 auto Buffer = ReadBuffer(SLocEntryCursor, File->getName());
1368 if (!Buffer)
Guy Benyei11169dd2012-12-18 14:30:41 +00001369 return true;
David Blaikie49cc3182014-08-27 20:54:45 +00001370 SourceMgr.overrideFileContents(File, std::move(Buffer));
Guy Benyei11169dd2012-12-18 14:30:41 +00001371 }
1372
1373 break;
1374 }
1375
1376 case SM_SLOC_BUFFER_ENTRY: {
Chris Lattner0e6c9402013-01-20 02:38:54 +00001377 const char *Name = Blob.data();
Guy Benyei11169dd2012-12-18 14:30:41 +00001378 unsigned Offset = Record[0];
1379 SrcMgr::CharacteristicKind
1380 FileCharacter = (SrcMgr::CharacteristicKind)Record[2];
1381 SourceLocation IncludeLoc = ReadSourceLocation(*F, Record[1]);
Manman Ren11f2a472016-08-18 17:42:15 +00001382 if (IncludeLoc.isInvalid() && F->isModule()) {
Guy Benyei11169dd2012-12-18 14:30:41 +00001383 IncludeLoc = getImportLocation(F);
1384 }
Guy Benyei11169dd2012-12-18 14:30:41 +00001385
Richard Smithaada85c2016-02-06 02:06:43 +00001386 auto Buffer = ReadBuffer(SLocEntryCursor, Name);
1387 if (!Buffer)
Guy Benyei11169dd2012-12-18 14:30:41 +00001388 return true;
David Blaikie50a5f972014-08-29 07:59:55 +00001389 SourceMgr.createFileID(std::move(Buffer), FileCharacter, ID,
Rafael Espindolad87f8d72014-08-27 20:03:29 +00001390 BaseOffset + Offset, IncludeLoc);
Guy Benyei11169dd2012-12-18 14:30:41 +00001391 break;
1392 }
1393
1394 case SM_SLOC_EXPANSION_ENTRY: {
1395 SourceLocation SpellingLoc = ReadSourceLocation(*F, Record[1]);
1396 SourceMgr.createExpansionLoc(SpellingLoc,
1397 ReadSourceLocation(*F, Record[2]),
1398 ReadSourceLocation(*F, Record[3]),
1399 Record[4],
1400 ID,
1401 BaseOffset + Record[0]);
1402 break;
1403 }
1404 }
1405
1406 return false;
1407}
1408
1409std::pair<SourceLocation, StringRef> ASTReader::getModuleImportLoc(int ID) {
1410 if (ID == 0)
1411 return std::make_pair(SourceLocation(), "");
1412
1413 if (unsigned(-ID) - 2 >= getTotalNumSLocs() || ID > 0) {
1414 Error("source location entry ID out-of-range for AST file");
1415 return std::make_pair(SourceLocation(), "");
1416 }
1417
1418 // Find which module file this entry lands in.
1419 ModuleFile *M = GlobalSLocEntryMap.find(-ID)->second;
Manman Ren11f2a472016-08-18 17:42:15 +00001420 if (!M->isModule())
Guy Benyei11169dd2012-12-18 14:30:41 +00001421 return std::make_pair(SourceLocation(), "");
1422
1423 // FIXME: Can we map this down to a particular submodule? That would be
1424 // ideal.
Ben Langmuirbeee15e2014-04-14 18:00:01 +00001425 return std::make_pair(M->ImportLoc, StringRef(M->ModuleName));
Guy Benyei11169dd2012-12-18 14:30:41 +00001426}
1427
1428/// \brief Find the location where the module F is imported.
1429SourceLocation ASTReader::getImportLocation(ModuleFile *F) {
1430 if (F->ImportLoc.isValid())
1431 return F->ImportLoc;
David L. Jonesc4808b9e2016-12-15 20:53:26 +00001432
Guy Benyei11169dd2012-12-18 14:30:41 +00001433 // Otherwise we have a PCH. It's considered to be "imported" at the first
1434 // location of its includer.
1435 if (F->ImportedBy.empty() || !F->ImportedBy[0]) {
Ben Langmuirbeee15e2014-04-14 18:00:01 +00001436 // Main file is the importer.
Yaron Keren8b563662015-10-03 10:46:20 +00001437 assert(SourceMgr.getMainFileID().isValid() && "missing main file");
Ben Langmuirbeee15e2014-04-14 18:00:01 +00001438 return SourceMgr.getLocForStartOfFile(SourceMgr.getMainFileID());
Guy Benyei11169dd2012-12-18 14:30:41 +00001439 }
Guy Benyei11169dd2012-12-18 14:30:41 +00001440 return F->ImportedBy[0]->FirstLoc;
1441}
1442
1443/// ReadBlockAbbrevs - Enter a subblock of the specified BlockID with the
1444/// specified cursor. Read the abbreviations that are at the top of the block
1445/// and then leave the cursor pointing into the block.
Chris Lattner7fb3bef2013-01-20 00:56:42 +00001446bool ASTReader::ReadBlockAbbrevs(BitstreamCursor &Cursor, unsigned BlockID) {
Richard Smith0516b182015-09-08 19:40:14 +00001447 if (Cursor.EnterSubBlock(BlockID))
1448 return true;
Guy Benyei11169dd2012-12-18 14:30:41 +00001449
1450 while (true) {
1451 uint64_t Offset = Cursor.GetCurrentBitNo();
1452 unsigned Code = Cursor.ReadCode();
1453
1454 // We expect all abbrevs to be at the start of the block.
1455 if (Code != llvm::bitc::DEFINE_ABBREV) {
1456 Cursor.JumpToBit(Offset);
1457 return false;
1458 }
1459 Cursor.ReadAbbrevRecord();
1460 }
1461}
1462
Richard Smithe40f2ba2013-08-07 21:41:30 +00001463Token ASTReader::ReadToken(ModuleFile &F, const RecordDataImpl &Record,
John McCallf413f5e2013-05-03 00:10:13 +00001464 unsigned &Idx) {
1465 Token Tok;
1466 Tok.startToken();
1467 Tok.setLocation(ReadSourceLocation(F, Record, Idx));
1468 Tok.setLength(Record[Idx++]);
1469 if (IdentifierInfo *II = getLocalIdentifier(F, Record[Idx++]))
1470 Tok.setIdentifierInfo(II);
1471 Tok.setKind((tok::TokenKind)Record[Idx++]);
1472 Tok.setFlag((Token::TokenFlags)Record[Idx++]);
1473 return Tok;
1474}
1475
Argyrios Kyrtzidiseb663da2013-03-22 21:12:57 +00001476MacroInfo *ASTReader::ReadMacroRecord(ModuleFile &F, uint64_t Offset) {
Chris Lattner7fb3bef2013-01-20 00:56:42 +00001477 BitstreamCursor &Stream = F.MacroCursor;
Guy Benyei11169dd2012-12-18 14:30:41 +00001478
1479 // Keep track of where we are in the stream, then jump back there
1480 // after reading this macro.
1481 SavedStreamPosition SavedPosition(Stream);
1482
1483 Stream.JumpToBit(Offset);
1484 RecordData Record;
1485 SmallVector<IdentifierInfo*, 16> MacroArgs;
Craig Toppera13603a2014-05-22 05:54:18 +00001486 MacroInfo *Macro = nullptr;
Guy Benyei11169dd2012-12-18 14:30:41 +00001487
Guy Benyei11169dd2012-12-18 14:30:41 +00001488 while (true) {
Chris Lattnerefa77172013-01-20 00:00:22 +00001489 // Advance to the next record, but if we get to the end of the block, don't
1490 // pop it (removing all the abbreviations from the cursor) since we want to
1491 // be able to reseek within the block and read entries.
Chris Lattner7fb3bef2013-01-20 00:56:42 +00001492 unsigned Flags = BitstreamCursor::AF_DontPopBlockAtEnd;
Chris Lattnerefa77172013-01-20 00:00:22 +00001493 llvm::BitstreamEntry Entry = Stream.advanceSkippingSubblocks(Flags);
David L. Jonesc4808b9e2016-12-15 20:53:26 +00001494
Chris Lattnerefa77172013-01-20 00:00:22 +00001495 switch (Entry.Kind) {
1496 case llvm::BitstreamEntry::SubBlock: // Handled for us already.
1497 case llvm::BitstreamEntry::Error:
1498 Error("malformed block record in AST file");
Argyrios Kyrtzidiseb663da2013-03-22 21:12:57 +00001499 return Macro;
Chris Lattnerefa77172013-01-20 00:00:22 +00001500 case llvm::BitstreamEntry::EndBlock:
Argyrios Kyrtzidiseb663da2013-03-22 21:12:57 +00001501 return Macro;
Chris Lattnerefa77172013-01-20 00:00:22 +00001502 case llvm::BitstreamEntry::Record:
1503 // The interesting case.
1504 break;
Guy Benyei11169dd2012-12-18 14:30:41 +00001505 }
1506
1507 // Read a record.
Guy Benyei11169dd2012-12-18 14:30:41 +00001508 Record.clear();
1509 PreprocessorRecordTypes RecType =
Chris Lattner0e6c9402013-01-20 02:38:54 +00001510 (PreprocessorRecordTypes)Stream.readRecord(Entry.ID, Record);
Guy Benyei11169dd2012-12-18 14:30:41 +00001511 switch (RecType) {
Richard Smithd7329392015-04-21 21:46:32 +00001512 case PP_MODULE_MACRO:
Argyrios Kyrtzidiseb663da2013-03-22 21:12:57 +00001513 case PP_MACRO_DIRECTIVE_HISTORY:
1514 return Macro;
1515
Guy Benyei11169dd2012-12-18 14:30:41 +00001516 case PP_MACRO_OBJECT_LIKE:
1517 case PP_MACRO_FUNCTION_LIKE: {
1518 // If we already have a macro, that means that we've hit the end
1519 // of the definition of the macro we were looking for. We're
1520 // done.
1521 if (Macro)
Argyrios Kyrtzidiseb663da2013-03-22 21:12:57 +00001522 return Macro;
Guy Benyei11169dd2012-12-18 14:30:41 +00001523
Argyrios Kyrtzidiseb663da2013-03-22 21:12:57 +00001524 unsigned NextIndex = 1; // Skip identifier ID.
1525 SubmoduleID SubModID = getGlobalSubmoduleID(F, Record[NextIndex++]);
Guy Benyei11169dd2012-12-18 14:30:41 +00001526 SourceLocation Loc = ReadSourceLocation(F, Record, NextIndex);
Argyrios Kyrtzidiseb663da2013-03-22 21:12:57 +00001527 MacroInfo *MI = PP.AllocateDeserializedMacroInfo(Loc, SubModID);
Argyrios Kyrtzidis7572be22013-01-07 19:16:23 +00001528 MI->setDefinitionEndLoc(ReadSourceLocation(F, Record, NextIndex));
Guy Benyei11169dd2012-12-18 14:30:41 +00001529 MI->setIsUsed(Record[NextIndex++]);
Argyrios Kyrtzidis9ef53ce2014-04-09 18:21:23 +00001530 MI->setUsedForHeaderGuard(Record[NextIndex++]);
Guy Benyei11169dd2012-12-18 14:30:41 +00001531
Guy Benyei11169dd2012-12-18 14:30:41 +00001532 if (RecType == PP_MACRO_FUNCTION_LIKE) {
1533 // Decode function-like macro info.
1534 bool isC99VarArgs = Record[NextIndex++];
1535 bool isGNUVarArgs = Record[NextIndex++];
1536 bool hasCommaPasting = Record[NextIndex++];
1537 MacroArgs.clear();
1538 unsigned NumArgs = Record[NextIndex++];
1539 for (unsigned i = 0; i != NumArgs; ++i)
1540 MacroArgs.push_back(getLocalIdentifier(F, Record[NextIndex++]));
1541
1542 // Install function-like macro info.
1543 MI->setIsFunctionLike();
1544 if (isC99VarArgs) MI->setIsC99Varargs();
1545 if (isGNUVarArgs) MI->setIsGNUVarargs();
1546 if (hasCommaPasting) MI->setHasCommaPasting();
Craig Topperd96b3f92015-10-22 04:59:52 +00001547 MI->setArgumentList(MacroArgs, PP.getPreprocessorAllocator());
Guy Benyei11169dd2012-12-18 14:30:41 +00001548 }
1549
Guy Benyei11169dd2012-12-18 14:30:41 +00001550 // Remember that we saw this macro last so that we add the tokens that
1551 // form its body to it.
1552 Macro = MI;
1553
1554 if (NextIndex + 1 == Record.size() && PP.getPreprocessingRecord() &&
1555 Record[NextIndex]) {
1556 // We have a macro definition. Register the association
1557 PreprocessedEntityID
1558 GlobalID = getGlobalPreprocessedEntityID(F, Record[NextIndex]);
1559 PreprocessingRecord &PPRec = *PP.getPreprocessingRecord();
Richard Smith66a81862015-05-04 02:25:31 +00001560 PreprocessingRecord::PPEntityID PPID =
1561 PPRec.getPPEntityID(GlobalID - 1, /*isLoaded=*/true);
1562 MacroDefinitionRecord *PPDef = cast_or_null<MacroDefinitionRecord>(
1563 PPRec.getPreprocessedEntity(PPID));
Argyrios Kyrtzidis832de9f2013-02-22 18:35:59 +00001564 if (PPDef)
1565 PPRec.RegisterMacroDefinition(Macro, PPDef);
Guy Benyei11169dd2012-12-18 14:30:41 +00001566 }
1567
1568 ++NumMacrosRead;
1569 break;
1570 }
1571
1572 case PP_TOKEN: {
1573 // If we see a TOKEN before a PP_MACRO_*, then the file is
1574 // erroneous, just pretend we didn't see this.
Craig Toppera13603a2014-05-22 05:54:18 +00001575 if (!Macro) break;
Guy Benyei11169dd2012-12-18 14:30:41 +00001576
John McCallf413f5e2013-05-03 00:10:13 +00001577 unsigned Idx = 0;
1578 Token Tok = ReadToken(F, Record, Idx);
Guy Benyei11169dd2012-12-18 14:30:41 +00001579 Macro->AddTokenToBody(Tok);
1580 break;
1581 }
1582 }
1583 }
1584}
1585
David L. Jonesc4808b9e2016-12-15 20:53:26 +00001586PreprocessedEntityID
Richard Smith37a93df2017-02-18 00:32:02 +00001587ASTReader::getGlobalPreprocessedEntityID(ModuleFile &M,
1588 unsigned LocalID) const {
1589 if (!M.ModuleOffsetMap.empty())
1590 ReadModuleOffsetMap(M);
1591
David L. Jonesc4808b9e2016-12-15 20:53:26 +00001592 ContinuousRangeMap<uint32_t, int, 2>::const_iterator
Guy Benyei11169dd2012-12-18 14:30:41 +00001593 I = M.PreprocessedEntityRemap.find(LocalID - NUM_PREDEF_PP_ENTITY_IDS);
David L. Jonesc4808b9e2016-12-15 20:53:26 +00001594 assert(I != M.PreprocessedEntityRemap.end()
Guy Benyei11169dd2012-12-18 14:30:41 +00001595 && "Invalid index into preprocessed entity index remap");
David L. Jonesc4808b9e2016-12-15 20:53:26 +00001596
Guy Benyei11169dd2012-12-18 14:30:41 +00001597 return LocalID + I->second;
1598}
1599
Argyrios Kyrtzidis5c2a3452013-03-06 18:12:47 +00001600unsigned HeaderFileInfoTrait::ComputeHash(internal_key_ref ikey) {
1601 return llvm::hash_combine(ikey.Size, ikey.ModTime);
Guy Benyei11169dd2012-12-18 14:30:41 +00001602}
Richard Smith7ed1bc92014-12-05 22:42:13 +00001603
David L. Jonesc4808b9e2016-12-15 20:53:26 +00001604HeaderFileInfoTrait::internal_key_type
Argyrios Kyrtzidis5c2a3452013-03-06 18:12:47 +00001605HeaderFileInfoTrait::GetInternalKey(const FileEntry *FE) {
Richard Smithe75ee0f2015-08-17 07:13:32 +00001606 internal_key_type ikey = {FE->getSize(),
1607 M.HasTimestamps ? FE->getModificationTime() : 0,
1608 FE->getName(), /*Imported*/ false};
Argyrios Kyrtzidis5c2a3452013-03-06 18:12:47 +00001609 return ikey;
1610}
David L. Jonesc4808b9e2016-12-15 20:53:26 +00001611
Argyrios Kyrtzidis5c2a3452013-03-06 18:12:47 +00001612bool HeaderFileInfoTrait::EqualKey(internal_key_ref a, internal_key_ref b) {
Richard Smithe75ee0f2015-08-17 07:13:32 +00001613 if (a.Size != b.Size || (a.ModTime && b.ModTime && a.ModTime != b.ModTime))
Guy Benyei11169dd2012-12-18 14:30:41 +00001614 return false;
1615
Mehdi Amini004b9c72016-10-10 22:52:47 +00001616 if (llvm::sys::path::is_absolute(a.Filename) && a.Filename == b.Filename)
Argyrios Kyrtzidis5c2a3452013-03-06 18:12:47 +00001617 return true;
David L. Jonesc4808b9e2016-12-15 20:53:26 +00001618
Guy Benyei11169dd2012-12-18 14:30:41 +00001619 // Determine whether the actual files are equivalent.
Argyrios Kyrtzidis2a513e82013-03-04 20:33:40 +00001620 FileManager &FileMgr = Reader.getFileManager();
Richard Smith7ed1bc92014-12-05 22:42:13 +00001621 auto GetFile = [&](const internal_key_type &Key) -> const FileEntry* {
1622 if (!Key.Imported)
1623 return FileMgr.getFile(Key.Filename);
1624
1625 std::string Resolved = Key.Filename;
1626 Reader.ResolveImportedPath(M, Resolved);
1627 return FileMgr.getFile(Resolved);
1628 };
1629
1630 const FileEntry *FEA = GetFile(a);
1631 const FileEntry *FEB = GetFile(b);
1632 return FEA && FEA == FEB;
Guy Benyei11169dd2012-12-18 14:30:41 +00001633}
David L. Jonesc4808b9e2016-12-15 20:53:26 +00001634
Guy Benyei11169dd2012-12-18 14:30:41 +00001635std::pair<unsigned, unsigned>
1636HeaderFileInfoTrait::ReadKeyDataLength(const unsigned char*& d) {
Justin Bogner57ba0b22014-03-28 22:03:24 +00001637 using namespace llvm::support;
1638 unsigned KeyLen = (unsigned) endian::readNext<uint16_t, little, unaligned>(d);
Guy Benyei11169dd2012-12-18 14:30:41 +00001639 unsigned DataLen = (unsigned) *d++;
Argyrios Kyrtzidis5c2a3452013-03-06 18:12:47 +00001640 return std::make_pair(KeyLen, DataLen);
Guy Benyei11169dd2012-12-18 14:30:41 +00001641}
Argyrios Kyrtzidis5c2a3452013-03-06 18:12:47 +00001642
1643HeaderFileInfoTrait::internal_key_type
1644HeaderFileInfoTrait::ReadKey(const unsigned char *d, unsigned) {
Justin Bogner57ba0b22014-03-28 22:03:24 +00001645 using namespace llvm::support;
Argyrios Kyrtzidis5c2a3452013-03-06 18:12:47 +00001646 internal_key_type ikey;
Justin Bogner57ba0b22014-03-28 22:03:24 +00001647 ikey.Size = off_t(endian::readNext<uint64_t, little, unaligned>(d));
1648 ikey.ModTime = time_t(endian::readNext<uint64_t, little, unaligned>(d));
Argyrios Kyrtzidis5c2a3452013-03-06 18:12:47 +00001649 ikey.Filename = (const char *)d;
Richard Smith7ed1bc92014-12-05 22:42:13 +00001650 ikey.Imported = true;
Argyrios Kyrtzidis5c2a3452013-03-06 18:12:47 +00001651 return ikey;
1652}
1653
David L. Jonesc4808b9e2016-12-15 20:53:26 +00001654HeaderFileInfoTrait::data_type
Argyrios Kyrtzidisb146baa2013-03-13 21:13:51 +00001655HeaderFileInfoTrait::ReadData(internal_key_ref key, const unsigned char *d,
Guy Benyei11169dd2012-12-18 14:30:41 +00001656 unsigned DataLen) {
1657 const unsigned char *End = d + DataLen;
Justin Bogner57ba0b22014-03-28 22:03:24 +00001658 using namespace llvm::support;
Guy Benyei11169dd2012-12-18 14:30:41 +00001659 HeaderFileInfo HFI;
1660 unsigned Flags = *d++;
Richard Smith386bb072015-08-18 23:42:23 +00001661 // FIXME: Refactor with mergeHeaderFileInfo in HeaderSearch.cpp.
1662 HFI.isImport |= (Flags >> 4) & 0x01;
1663 HFI.isPragmaOnce |= (Flags >> 3) & 0x01;
1664 HFI.DirInfo = (Flags >> 1) & 0x03;
Guy Benyei11169dd2012-12-18 14:30:41 +00001665 HFI.IndexHeaderMapHeader = Flags & 0x01;
Richard Smith386bb072015-08-18 23:42:23 +00001666 // FIXME: Find a better way to handle this. Maybe just store a
1667 // "has been included" flag?
1668 HFI.NumIncludes = std::max(endian::readNext<uint16_t, little, unaligned>(d),
1669 HFI.NumIncludes);
Justin Bogner57ba0b22014-03-28 22:03:24 +00001670 HFI.ControllingMacroID = Reader.getGlobalIdentifierID(
1671 M, endian::readNext<uint32_t, little, unaligned>(d));
1672 if (unsigned FrameworkOffset =
1673 endian::readNext<uint32_t, little, unaligned>(d)) {
David L. Jonesc4808b9e2016-12-15 20:53:26 +00001674 // The framework offset is 1 greater than the actual offset,
Guy Benyei11169dd2012-12-18 14:30:41 +00001675 // since 0 is used as an indicator for "no framework name".
1676 StringRef FrameworkName(FrameworkStrings + FrameworkOffset - 1);
1677 HFI.Framework = HS->getUniqueFrameworkName(FrameworkName);
1678 }
Richard Smith386bb072015-08-18 23:42:23 +00001679
1680 assert((End - d) % 4 == 0 &&
1681 "Wrong data length in HeaderFileInfo deserialization");
1682 while (d != End) {
Justin Bogner57ba0b22014-03-28 22:03:24 +00001683 uint32_t LocalSMID = endian::readNext<uint32_t, little, unaligned>(d);
Richard Smith386bb072015-08-18 23:42:23 +00001684 auto HeaderRole = static_cast<ModuleMap::ModuleHeaderRole>(LocalSMID & 3);
1685 LocalSMID >>= 2;
1686
1687 // This header is part of a module. Associate it with the module to enable
1688 // implicit module import.
1689 SubmoduleID GlobalSMID = Reader.getGlobalSubmoduleID(M, LocalSMID);
1690 Module *Mod = Reader.getSubmodule(GlobalSMID);
1691 FileManager &FileMgr = Reader.getFileManager();
1692 ModuleMap &ModMap =
1693 Reader.getPreprocessor().getHeaderSearchInfo().getModuleMap();
1694
1695 std::string Filename = key.Filename;
1696 if (key.Imported)
1697 Reader.ResolveImportedPath(M, Filename);
1698 // FIXME: This is not always the right filename-as-written, but we're not
1699 // going to use this information to rebuild the module, so it doesn't make
1700 // a lot of difference.
1701 Module::Header H = { key.Filename, FileMgr.getFile(Filename) };
Richard Smithd8879c82015-08-24 21:59:32 +00001702 ModMap.addHeader(Mod, H, HeaderRole, /*Imported*/true);
1703 HFI.isModuleHeader |= !(HeaderRole & ModuleMap::TextualHeader);
Argyrios Kyrtzidisb146baa2013-03-13 21:13:51 +00001704 }
1705
Guy Benyei11169dd2012-12-18 14:30:41 +00001706 // This HeaderFileInfo was externally loaded.
1707 HFI.External = true;
Richard Smithd8879c82015-08-24 21:59:32 +00001708 HFI.IsValid = true;
Guy Benyei11169dd2012-12-18 14:30:41 +00001709 return HFI;
1710}
1711
Richard Smithd7329392015-04-21 21:46:32 +00001712void ASTReader::addPendingMacro(IdentifierInfo *II,
1713 ModuleFile *M,
1714 uint64_t MacroDirectivesOffset) {
Argyrios Kyrtzidiseb663da2013-03-22 21:12:57 +00001715 assert(NumCurrentElementsDeserializing > 0 &&"Missing deserialization guard");
1716 PendingMacroIDs[II].push_back(PendingMacroInfo(M, MacroDirectivesOffset));
Guy Benyei11169dd2012-12-18 14:30:41 +00001717}
1718
1719void ASTReader::ReadDefinedMacros() {
1720 // Note that we are loading defined macros.
1721 Deserializing Macros(this);
1722
Duncan P. N. Exon Smith96a06e02017-01-28 22:15:22 +00001723 for (ModuleFile &I : llvm::reverse(ModuleMgr)) {
1724 BitstreamCursor &MacroCursor = I.MacroCursor;
Guy Benyei11169dd2012-12-18 14:30:41 +00001725
1726 // If there was no preprocessor block, skip this file.
Peter Collingbourne77c89b62016-11-08 04:17:11 +00001727 if (MacroCursor.getBitcodeBytes().empty())
Guy Benyei11169dd2012-12-18 14:30:41 +00001728 continue;
1729
Chris Lattner7fb3bef2013-01-20 00:56:42 +00001730 BitstreamCursor Cursor = MacroCursor;
Duncan P. N. Exon Smith96a06e02017-01-28 22:15:22 +00001731 Cursor.JumpToBit(I.MacroStartOffset);
Guy Benyei11169dd2012-12-18 14:30:41 +00001732
1733 RecordData Record;
1734 while (true) {
Chris Lattnere7b154b2013-01-19 21:39:22 +00001735 llvm::BitstreamEntry E = Cursor.advanceSkippingSubblocks();
David L. Jonesc4808b9e2016-12-15 20:53:26 +00001736
Chris Lattnere7b154b2013-01-19 21:39:22 +00001737 switch (E.Kind) {
1738 case llvm::BitstreamEntry::SubBlock: // Handled for us already.
1739 case llvm::BitstreamEntry::Error:
1740 Error("malformed block record in AST file");
1741 return;
1742 case llvm::BitstreamEntry::EndBlock:
1743 goto NextCursor;
David L. Jonesc4808b9e2016-12-15 20:53:26 +00001744
Chris Lattnere7b154b2013-01-19 21:39:22 +00001745 case llvm::BitstreamEntry::Record:
Chris Lattnere7b154b2013-01-19 21:39:22 +00001746 Record.clear();
Chris Lattner0e6c9402013-01-20 02:38:54 +00001747 switch (Cursor.readRecord(E.ID, Record)) {
Chris Lattnere7b154b2013-01-19 21:39:22 +00001748 default: // Default behavior: ignore.
1749 break;
David L. Jonesc4808b9e2016-12-15 20:53:26 +00001750
Chris Lattnere7b154b2013-01-19 21:39:22 +00001751 case PP_MACRO_OBJECT_LIKE:
Sean Callananf3682a72016-05-14 06:24:14 +00001752 case PP_MACRO_FUNCTION_LIKE: {
Duncan P. N. Exon Smith96a06e02017-01-28 22:15:22 +00001753 IdentifierInfo *II = getLocalIdentifier(I, Record[0]);
Sean Callananf3682a72016-05-14 06:24:14 +00001754 if (II->isOutOfDate())
1755 updateOutOfDateIdentifier(*II);
Chris Lattnere7b154b2013-01-19 21:39:22 +00001756 break;
Sean Callananf3682a72016-05-14 06:24:14 +00001757 }
David L. Jonesc4808b9e2016-12-15 20:53:26 +00001758
Chris Lattnere7b154b2013-01-19 21:39:22 +00001759 case PP_TOKEN:
1760 // Ignore tokens.
1761 break;
Guy Benyei11169dd2012-12-18 14:30:41 +00001762 }
Guy Benyei11169dd2012-12-18 14:30:41 +00001763 break;
1764 }
1765 }
Chris Lattnere7b154b2013-01-19 21:39:22 +00001766 NextCursor: ;
Guy Benyei11169dd2012-12-18 14:30:41 +00001767 }
1768}
1769
1770namespace {
Eugene Zelenkoe95e7d52016-09-07 21:53:17 +00001771
Guy Benyei11169dd2012-12-18 14:30:41 +00001772 /// \brief Visitor class used to look up identifirs in an AST file.
1773 class IdentifierLookupVisitor {
1774 StringRef Name;
Richard Smith3b637412015-07-14 18:42:41 +00001775 unsigned NameHash;
Guy Benyei11169dd2012-12-18 14:30:41 +00001776 unsigned PriorGeneration;
Douglas Gregor00a50f72013-01-25 00:38:33 +00001777 unsigned &NumIdentifierLookups;
1778 unsigned &NumIdentifierLookupHits;
Guy Benyei11169dd2012-12-18 14:30:41 +00001779 IdentifierInfo *Found;
Douglas Gregor00a50f72013-01-25 00:38:33 +00001780
Guy Benyei11169dd2012-12-18 14:30:41 +00001781 public:
Douglas Gregor00a50f72013-01-25 00:38:33 +00001782 IdentifierLookupVisitor(StringRef Name, unsigned PriorGeneration,
1783 unsigned &NumIdentifierLookups,
1784 unsigned &NumIdentifierLookupHits)
Richard Smith3b637412015-07-14 18:42:41 +00001785 : Name(Name), NameHash(ASTIdentifierLookupTrait::ComputeHash(Name)),
1786 PriorGeneration(PriorGeneration),
Douglas Gregor00a50f72013-01-25 00:38:33 +00001787 NumIdentifierLookups(NumIdentifierLookups),
1788 NumIdentifierLookupHits(NumIdentifierLookupHits),
1789 Found()
1790 {
1791 }
Benjamin Kramer9a9efba2015-07-25 12:14:04 +00001792
1793 bool operator()(ModuleFile &M) {
Guy Benyei11169dd2012-12-18 14:30:41 +00001794 // If we've already searched this module file, skip it now.
Richard Smithbdf2d932015-07-30 03:37:16 +00001795 if (M.Generation <= PriorGeneration)
Guy Benyei11169dd2012-12-18 14:30:41 +00001796 return true;
Douglas Gregore060e572013-01-25 01:03:03 +00001797
Guy Benyei11169dd2012-12-18 14:30:41 +00001798 ASTIdentifierLookupTable *IdTable
1799 = (ASTIdentifierLookupTable *)M.IdentifierLookupTable;
1800 if (!IdTable)
1801 return false;
Benjamin Kramer9a9efba2015-07-25 12:14:04 +00001802
1803 ASTIdentifierLookupTrait Trait(IdTable->getInfoObj().getReader(), M,
Richard Smithbdf2d932015-07-30 03:37:16 +00001804 Found);
1805 ++NumIdentifierLookups;
Richard Smith3b637412015-07-14 18:42:41 +00001806 ASTIdentifierLookupTable::iterator Pos =
Richard Smithbdf2d932015-07-30 03:37:16 +00001807 IdTable->find_hashed(Name, NameHash, &Trait);
Guy Benyei11169dd2012-12-18 14:30:41 +00001808 if (Pos == IdTable->end())
1809 return false;
David L. Jonesc4808b9e2016-12-15 20:53:26 +00001810
Guy Benyei11169dd2012-12-18 14:30:41 +00001811 // Dereferencing the iterator has the effect of building the
1812 // IdentifierInfo node and populating it with the various
1813 // declarations it needs.
Richard Smithbdf2d932015-07-30 03:37:16 +00001814 ++NumIdentifierLookupHits;
1815 Found = *Pos;
Guy Benyei11169dd2012-12-18 14:30:41 +00001816 return true;
1817 }
David L. Jonesc4808b9e2016-12-15 20:53:26 +00001818
Guy Benyei11169dd2012-12-18 14:30:41 +00001819 // \brief Retrieve the identifier info found within the module
1820 // files.
1821 IdentifierInfo *getIdentifierInfo() const { return Found; }
1822 };
Eugene Zelenkoe95e7d52016-09-07 21:53:17 +00001823
1824} // end anonymous namespace
Guy Benyei11169dd2012-12-18 14:30:41 +00001825
1826void ASTReader::updateOutOfDateIdentifier(IdentifierInfo &II) {
1827 // Note that we are loading an identifier.
1828 Deserializing AnIdentifier(this);
1829
1830 unsigned PriorGeneration = 0;
1831 if (getContext().getLangOpts().Modules)
1832 PriorGeneration = IdentifierGeneration[&II];
Douglas Gregore060e572013-01-25 01:03:03 +00001833
1834 // If there is a global index, look there first to determine which modules
1835 // provably do not have any results for this identifier.
Douglas Gregor7211ac12013-01-25 23:32:03 +00001836 GlobalModuleIndex::HitSet Hits;
Craig Toppera13603a2014-05-22 05:54:18 +00001837 GlobalModuleIndex::HitSet *HitsPtr = nullptr;
Douglas Gregore060e572013-01-25 01:03:03 +00001838 if (!loadGlobalIndex()) {
Douglas Gregor7211ac12013-01-25 23:32:03 +00001839 if (GlobalIndex->lookupIdentifier(II.getName(), Hits)) {
1840 HitsPtr = &Hits;
Douglas Gregore060e572013-01-25 01:03:03 +00001841 }
1842 }
1843
Douglas Gregor7211ac12013-01-25 23:32:03 +00001844 IdentifierLookupVisitor Visitor(II.getName(), PriorGeneration,
Douglas Gregor00a50f72013-01-25 00:38:33 +00001845 NumIdentifierLookups,
1846 NumIdentifierLookupHits);
Benjamin Kramer9a9efba2015-07-25 12:14:04 +00001847 ModuleMgr.visit(Visitor, HitsPtr);
Guy Benyei11169dd2012-12-18 14:30:41 +00001848 markIdentifierUpToDate(&II);
1849}
1850
1851void ASTReader::markIdentifierUpToDate(IdentifierInfo *II) {
1852 if (!II)
1853 return;
David L. Jonesc4808b9e2016-12-15 20:53:26 +00001854
Guy Benyei11169dd2012-12-18 14:30:41 +00001855 II->setOutOfDate(false);
1856
1857 // Update the generation for this identifier.
1858 if (getContext().getLangOpts().Modules)
Richard Smith053f6c62014-05-16 23:01:30 +00001859 IdentifierGeneration[II] = getGeneration();
Guy Benyei11169dd2012-12-18 14:30:41 +00001860}
1861
Argyrios Kyrtzidiseb663da2013-03-22 21:12:57 +00001862void ASTReader::resolvePendingMacro(IdentifierInfo *II,
1863 const PendingMacroInfo &PMInfo) {
Richard Smithd7329392015-04-21 21:46:32 +00001864 ModuleFile &M = *PMInfo.M;
Argyrios Kyrtzidiseb663da2013-03-22 21:12:57 +00001865
1866 BitstreamCursor &Cursor = M.MacroCursor;
1867 SavedStreamPosition SavedPosition(Cursor);
Richard Smithd7329392015-04-21 21:46:32 +00001868 Cursor.JumpToBit(PMInfo.MacroDirectivesOffset);
Argyrios Kyrtzidiseb663da2013-03-22 21:12:57 +00001869
Richard Smith713369b2015-04-23 20:40:50 +00001870 struct ModuleMacroRecord {
1871 SubmoduleID SubModID;
1872 MacroInfo *MI;
1873 SmallVector<SubmoduleID, 8> Overrides;
1874 };
1875 llvm::SmallVector<ModuleMacroRecord, 8> ModuleMacros;
Argyrios Kyrtzidiseb663da2013-03-22 21:12:57 +00001876
Richard Smithd7329392015-04-21 21:46:32 +00001877 // We expect to see a sequence of PP_MODULE_MACRO records listing exported
1878 // macros, followed by a PP_MACRO_DIRECTIVE_HISTORY record with the complete
1879 // macro histroy.
Argyrios Kyrtzidiseb663da2013-03-22 21:12:57 +00001880 RecordData Record;
Richard Smithd7329392015-04-21 21:46:32 +00001881 while (true) {
1882 llvm::BitstreamEntry Entry =
1883 Cursor.advance(BitstreamCursor::AF_DontPopBlockAtEnd);
1884 if (Entry.Kind != llvm::BitstreamEntry::Record) {
1885 Error("malformed block record in AST file");
1886 return;
1887 }
1888
1889 Record.clear();
Aaron Ballmanc75a1922015-04-22 15:25:05 +00001890 switch ((PreprocessorRecordTypes)Cursor.readRecord(Entry.ID, Record)) {
Richard Smithd7329392015-04-21 21:46:32 +00001891 case PP_MACRO_DIRECTIVE_HISTORY:
1892 break;
1893
1894 case PP_MODULE_MACRO: {
Richard Smith713369b2015-04-23 20:40:50 +00001895 ModuleMacros.push_back(ModuleMacroRecord());
1896 auto &Info = ModuleMacros.back();
Richard Smithe56c8bc2015-04-22 00:26:11 +00001897 Info.SubModID = getGlobalSubmoduleID(M, Record[0]);
1898 Info.MI = getMacro(getGlobalMacroID(M, Record[1]));
Richard Smith713369b2015-04-23 20:40:50 +00001899 for (int I = 2, N = Record.size(); I != N; ++I)
1900 Info.Overrides.push_back(getGlobalSubmoduleID(M, Record[I]));
Richard Smithd7329392015-04-21 21:46:32 +00001901 continue;
1902 }
1903
1904 default:
1905 Error("malformed block record in AST file");
1906 return;
1907 }
1908
1909 // We found the macro directive history; that's the last record
1910 // for this macro.
1911 break;
Argyrios Kyrtzidiseb663da2013-03-22 21:12:57 +00001912 }
1913
Richard Smithd7329392015-04-21 21:46:32 +00001914 // Module macros are listed in reverse dependency order.
Richard Smithe56c8bc2015-04-22 00:26:11 +00001915 {
1916 std::reverse(ModuleMacros.begin(), ModuleMacros.end());
Richard Smithe56c8bc2015-04-22 00:26:11 +00001917 llvm::SmallVector<ModuleMacro*, 8> Overrides;
Richard Smith713369b2015-04-23 20:40:50 +00001918 for (auto &MMR : ModuleMacros) {
Richard Smithe56c8bc2015-04-22 00:26:11 +00001919 Overrides.clear();
Richard Smith713369b2015-04-23 20:40:50 +00001920 for (unsigned ModID : MMR.Overrides) {
Richard Smithb8b2ed62015-04-23 18:18:26 +00001921 Module *Mod = getSubmodule(ModID);
1922 auto *Macro = PP.getModuleMacro(Mod, II);
Richard Smithe56c8bc2015-04-22 00:26:11 +00001923 assert(Macro && "missing definition for overridden macro");
Richard Smith5dbef922015-04-22 02:09:43 +00001924 Overrides.push_back(Macro);
Richard Smithe56c8bc2015-04-22 00:26:11 +00001925 }
1926
1927 bool Inserted = false;
Richard Smith713369b2015-04-23 20:40:50 +00001928 Module *Owner = getSubmodule(MMR.SubModID);
Richard Smith20e883e2015-04-29 23:20:19 +00001929 PP.addModuleMacro(Owner, II, MMR.MI, Overrides, Inserted);
Richard Smithd7329392015-04-21 21:46:32 +00001930 }
1931 }
1932
1933 // Don't read the directive history for a module; we don't have anywhere
1934 // to put it.
Manman Ren11f2a472016-08-18 17:42:15 +00001935 if (M.isModule())
Richard Smithd7329392015-04-21 21:46:32 +00001936 return;
1937
Argyrios Kyrtzidiseb663da2013-03-22 21:12:57 +00001938 // Deserialize the macro directives history in reverse source-order.
Craig Toppera13603a2014-05-22 05:54:18 +00001939 MacroDirective *Latest = nullptr, *Earliest = nullptr;
Argyrios Kyrtzidiseb663da2013-03-22 21:12:57 +00001940 unsigned Idx = 0, N = Record.size();
1941 while (Idx < N) {
Craig Toppera13603a2014-05-22 05:54:18 +00001942 MacroDirective *MD = nullptr;
Argyrios Kyrtzidiseb663da2013-03-22 21:12:57 +00001943 SourceLocation Loc = ReadSourceLocation(M, Record, Idx);
Argyrios Kyrtzidisb6210df2013-03-26 17:17:01 +00001944 MacroDirective::Kind K = (MacroDirective::Kind)Record[Idx++];
1945 switch (K) {
1946 case MacroDirective::MD_Define: {
Richard Smith713369b2015-04-23 20:40:50 +00001947 MacroInfo *MI = getMacro(getGlobalMacroID(M, Record[Idx++]));
Richard Smith3981b172015-04-30 02:16:23 +00001948 MD = PP.AllocateDefMacroDirective(MI, Loc);
Argyrios Kyrtzidisb6210df2013-03-26 17:17:01 +00001949 break;
1950 }
Richard Smithdaa69e02014-07-25 04:40:03 +00001951 case MacroDirective::MD_Undefine: {
Richard Smith3981b172015-04-30 02:16:23 +00001952 MD = PP.AllocateUndefMacroDirective(Loc);
Argyrios Kyrtzidisb6210df2013-03-26 17:17:01 +00001953 break;
Richard Smithdaa69e02014-07-25 04:40:03 +00001954 }
1955 case MacroDirective::MD_Visibility:
Argyrios Kyrtzidisb6210df2013-03-26 17:17:01 +00001956 bool isPublic = Record[Idx++];
1957 MD = PP.AllocateVisibilityMacroDirective(Loc, isPublic);
1958 break;
1959 }
Argyrios Kyrtzidiseb663da2013-03-22 21:12:57 +00001960
1961 if (!Latest)
1962 Latest = MD;
1963 if (Earliest)
1964 Earliest->setPrevious(MD);
1965 Earliest = MD;
1966 }
1967
Richard Smithd6e8c0d2015-05-04 19:58:00 +00001968 if (Latest)
Nico Weberfd870702016-12-09 17:32:52 +00001969 PP.setLoadedMacroDirective(II, Earliest, Latest);
Argyrios Kyrtzidiseb663da2013-03-22 21:12:57 +00001970}
1971
Argyrios Kyrtzidisce9b49e2014-03-14 02:26:27 +00001972ASTReader::InputFileInfo
1973ASTReader::readInputFileInfo(ModuleFile &F, unsigned ID) {
Ben Langmuir198c1682014-03-07 07:27:49 +00001974 // Go find this input file.
1975 BitstreamCursor &Cursor = F.InputFilesCursor;
1976 SavedStreamPosition SavedPosition(Cursor);
1977 Cursor.JumpToBit(F.InputFileOffsets[ID-1]);
1978
1979 unsigned Code = Cursor.ReadCode();
1980 RecordData Record;
1981 StringRef Blob;
1982
1983 unsigned Result = Cursor.readRecord(Code, Record, &Blob);
1984 assert(static_cast<InputFileRecordTypes>(Result) == INPUT_FILE &&
1985 "invalid record type for input file");
1986 (void)Result;
1987
1988 assert(Record[0] == ID && "Bogus stored ID or offset");
Richard Smitha8cfffa2015-11-26 02:04:16 +00001989 InputFileInfo R;
1990 R.StoredSize = static_cast<off_t>(Record[1]);
1991 R.StoredTime = static_cast<time_t>(Record[2]);
1992 R.Overridden = static_cast<bool>(Record[3]);
1993 R.Transient = static_cast<bool>(Record[4]);
1994 R.Filename = Blob;
1995 ResolveImportedPath(F, R.Filename);
Hans Wennborg73945142014-03-14 17:45:06 +00001996 return R;
Ben Langmuir198c1682014-03-07 07:27:49 +00001997}
1998
Manman Renc8c94152016-10-21 23:35:03 +00001999static unsigned moduleKindForDiagnostic(ModuleKind Kind);
Argyrios Kyrtzidis61c3d872013-03-01 03:26:04 +00002000InputFile ASTReader::getInputFile(ModuleFile &F, unsigned ID, bool Complain) {
Guy Benyei11169dd2012-12-18 14:30:41 +00002001 // If this ID is bogus, just return an empty input file.
2002 if (ID == 0 || ID > F.InputFilesLoaded.size())
2003 return InputFile();
2004
2005 // If we've already loaded this input file, return it.
Argyrios Kyrtzidis61c3d872013-03-01 03:26:04 +00002006 if (F.InputFilesLoaded[ID-1].getFile())
Guy Benyei11169dd2012-12-18 14:30:41 +00002007 return F.InputFilesLoaded[ID-1];
2008
Argyrios Kyrtzidis9308f0a2014-01-08 19:13:34 +00002009 if (F.InputFilesLoaded[ID-1].isNotFound())
2010 return InputFile();
2011
Guy Benyei11169dd2012-12-18 14:30:41 +00002012 // Go find this input file.
Chris Lattner7fb3bef2013-01-20 00:56:42 +00002013 BitstreamCursor &Cursor = F.InputFilesCursor;
Guy Benyei11169dd2012-12-18 14:30:41 +00002014 SavedStreamPosition SavedPosition(Cursor);
2015 Cursor.JumpToBit(F.InputFileOffsets[ID-1]);
David L. Jonesc4808b9e2016-12-15 20:53:26 +00002016
Argyrios Kyrtzidisce9b49e2014-03-14 02:26:27 +00002017 InputFileInfo FI = readInputFileInfo(F, ID);
2018 off_t StoredSize = FI.StoredSize;
2019 time_t StoredTime = FI.StoredTime;
2020 bool Overridden = FI.Overridden;
Richard Smitha8cfffa2015-11-26 02:04:16 +00002021 bool Transient = FI.Transient;
Argyrios Kyrtzidisce9b49e2014-03-14 02:26:27 +00002022 StringRef Filename = FI.Filename;
Argyrios Kyrtzidis61c3d872013-03-01 03:26:04 +00002023
Richard Smitha8cfffa2015-11-26 02:04:16 +00002024 const FileEntry *File = FileMgr.getFile(Filename, /*OpenFile=*/false);
Ben Langmuir198c1682014-03-07 07:27:49 +00002025
2026 // If we didn't find the file, resolve it relative to the
2027 // original directory from which this AST file was created.
Craig Toppera13603a2014-05-22 05:54:18 +00002028 if (File == nullptr && !F.OriginalDir.empty() && !CurrentDir.empty() &&
Ben Langmuir198c1682014-03-07 07:27:49 +00002029 F.OriginalDir != CurrentDir) {
2030 std::string Resolved = resolveFileRelativeToOriginalDir(Filename,
2031 F.OriginalDir,
2032 CurrentDir);
2033 if (!Resolved.empty())
2034 File = FileMgr.getFile(Resolved);
2035 }
2036
2037 // For an overridden file, create a virtual file with the stored
2038 // size/timestamp.
Richard Smitha8cfffa2015-11-26 02:04:16 +00002039 if ((Overridden || Transient) && File == nullptr)
Ben Langmuir198c1682014-03-07 07:27:49 +00002040 File = FileMgr.getVirtualFile(Filename, StoredSize, StoredTime);
Ben Langmuir198c1682014-03-07 07:27:49 +00002041
Craig Toppera13603a2014-05-22 05:54:18 +00002042 if (File == nullptr) {
Ben Langmuir198c1682014-03-07 07:27:49 +00002043 if (Complain) {
2044 std::string ErrorStr = "could not find file '";
2045 ErrorStr += Filename;
Richard Smith68142212015-10-13 01:26:26 +00002046 ErrorStr += "' referenced by AST file '";
2047 ErrorStr += F.FileName;
2048 ErrorStr += "'";
Eugene Zelenkoe95e7d52016-09-07 21:53:17 +00002049 Error(ErrorStr);
Guy Benyei11169dd2012-12-18 14:30:41 +00002050 }
Ben Langmuir198c1682014-03-07 07:27:49 +00002051 // Record that we didn't find the file.
2052 F.InputFilesLoaded[ID-1] = InputFile::getNotFound();
2053 return InputFile();
2054 }
Guy Benyei11169dd2012-12-18 14:30:41 +00002055
Ben Langmuir198c1682014-03-07 07:27:49 +00002056 // Check if there was a request to override the contents of the file
2057 // that was part of the precompiled header. Overridding such a file
2058 // can lead to problems when lexing using the source locations from the
2059 // PCH.
2060 SourceManager &SM = getSourceManager();
Richard Smith64daf7b2015-12-01 03:32:49 +00002061 // FIXME: Reject if the overrides are different.
2062 if ((!Overridden && !Transient) && SM.isFileOverridden(File)) {
Ben Langmuir198c1682014-03-07 07:27:49 +00002063 if (Complain)
2064 Error(diag::err_fe_pch_file_overridden, Filename);
2065 // After emitting the diagnostic, recover by disabling the override so
2066 // that the original file will be used.
Richard Smitha8cfffa2015-11-26 02:04:16 +00002067 //
2068 // FIXME: This recovery is just as broken as the original state; there may
2069 // be another precompiled module that's using the overridden contents, or
2070 // we might be half way through parsing it. Instead, we should treat the
2071 // overridden contents as belonging to a separate FileEntry.
Ben Langmuir198c1682014-03-07 07:27:49 +00002072 SM.disableFileContentsOverride(File);
2073 // The FileEntry is a virtual file entry with the size of the contents
2074 // that would override the original contents. Set it to the original's
2075 // size/time.
2076 FileMgr.modifyFileEntry(const_cast<FileEntry*>(File),
2077 StoredSize, StoredTime);
2078 }
Guy Benyei11169dd2012-12-18 14:30:41 +00002079
Ben Langmuir198c1682014-03-07 07:27:49 +00002080 bool IsOutOfDate = false;
2081
2082 // For an overridden file, there is nothing to validate.
Richard Smith96fdab62014-10-28 16:24:08 +00002083 if (!Overridden && //
2084 (StoredSize != File->getSize() ||
Richard Smithe75ee0f2015-08-17 07:13:32 +00002085 (StoredTime && StoredTime != File->getModificationTime() &&
2086 !DisableValidation)
Ben Langmuir198c1682014-03-07 07:27:49 +00002087 )) {
2088 if (Complain) {
2089 // Build a list of the PCH imports that got us here (in reverse).
2090 SmallVector<ModuleFile *, 4> ImportStack(1, &F);
2091 while (ImportStack.back()->ImportedBy.size() > 0)
2092 ImportStack.push_back(ImportStack.back()->ImportedBy[0]);
Ben Langmuire82630d2014-01-17 00:19:09 +00002093
Ben Langmuir198c1682014-03-07 07:27:49 +00002094 // The top-level PCH is stale.
2095 StringRef TopLevelPCHName(ImportStack.back()->FileName);
Manman Renc8c94152016-10-21 23:35:03 +00002096 unsigned DiagnosticKind = moduleKindForDiagnostic(ImportStack.back()->Kind);
2097 if (DiagnosticKind == 0)
2098 Error(diag::err_fe_pch_file_modified, Filename, TopLevelPCHName);
2099 else if (DiagnosticKind == 1)
2100 Error(diag::err_fe_module_file_modified, Filename, TopLevelPCHName);
2101 else
2102 Error(diag::err_fe_ast_file_modified, Filename, TopLevelPCHName);
Ben Langmuire82630d2014-01-17 00:19:09 +00002103
Ben Langmuir198c1682014-03-07 07:27:49 +00002104 // Print the import stack.
2105 if (ImportStack.size() > 1 && !Diags.isDiagnosticInFlight()) {
2106 Diag(diag::note_pch_required_by)
2107 << Filename << ImportStack[0]->FileName;
2108 for (unsigned I = 1; I < ImportStack.size(); ++I)
Ben Langmuire82630d2014-01-17 00:19:09 +00002109 Diag(diag::note_pch_required_by)
Ben Langmuir198c1682014-03-07 07:27:49 +00002110 << ImportStack[I-1]->FileName << ImportStack[I]->FileName;
Douglas Gregor7029ce12013-03-19 00:28:20 +00002111 }
2112
Ben Langmuir198c1682014-03-07 07:27:49 +00002113 if (!Diags.isDiagnosticInFlight())
2114 Diag(diag::note_pch_rebuild_required) << TopLevelPCHName;
Guy Benyei11169dd2012-12-18 14:30:41 +00002115 }
2116
Ben Langmuir198c1682014-03-07 07:27:49 +00002117 IsOutOfDate = true;
Guy Benyei11169dd2012-12-18 14:30:41 +00002118 }
Richard Smitha8cfffa2015-11-26 02:04:16 +00002119 // FIXME: If the file is overridden and we've already opened it,
2120 // issue an error (or split it into a separate FileEntry).
Guy Benyei11169dd2012-12-18 14:30:41 +00002121
Richard Smitha8cfffa2015-11-26 02:04:16 +00002122 InputFile IF = InputFile(File, Overridden || Transient, IsOutOfDate);
Ben Langmuir198c1682014-03-07 07:27:49 +00002123
2124 // Note that we've loaded this input file.
2125 F.InputFilesLoaded[ID-1] = IF;
2126 return IF;
Guy Benyei11169dd2012-12-18 14:30:41 +00002127}
2128
Richard Smith7ed1bc92014-12-05 22:42:13 +00002129/// \brief If we are loading a relocatable PCH or module file, and the filename
2130/// is not an absolute path, add the system or module root to the beginning of
2131/// the file name.
2132void ASTReader::ResolveImportedPath(ModuleFile &M, std::string &Filename) {
2133 // Resolve relative to the base directory, if we have one.
2134 if (!M.BaseDirectory.empty())
2135 return ResolveImportedPath(Filename, M.BaseDirectory);
Guy Benyei11169dd2012-12-18 14:30:41 +00002136}
2137
Richard Smith7ed1bc92014-12-05 22:42:13 +00002138void ASTReader::ResolveImportedPath(std::string &Filename, StringRef Prefix) {
Guy Benyei11169dd2012-12-18 14:30:41 +00002139 if (Filename.empty() || llvm::sys::path::is_absolute(Filename))
2140 return;
2141
Richard Smith7ed1bc92014-12-05 22:42:13 +00002142 SmallString<128> Buffer;
2143 llvm::sys::path::append(Buffer, Prefix, Filename);
2144 Filename.assign(Buffer.begin(), Buffer.end());
Guy Benyei11169dd2012-12-18 14:30:41 +00002145}
2146
Richard Smith0f99d6a2015-08-09 08:48:41 +00002147static bool isDiagnosedResult(ASTReader::ASTReadResult ARR, unsigned Caps) {
2148 switch (ARR) {
2149 case ASTReader::Failure: return true;
2150 case ASTReader::Missing: return !(Caps & ASTReader::ARR_Missing);
2151 case ASTReader::OutOfDate: return !(Caps & ASTReader::ARR_OutOfDate);
2152 case ASTReader::VersionMismatch: return !(Caps & ASTReader::ARR_VersionMismatch);
2153 case ASTReader::ConfigurationMismatch:
2154 return !(Caps & ASTReader::ARR_ConfigurationMismatch);
2155 case ASTReader::HadErrors: return true;
2156 case ASTReader::Success: return false;
2157 }
2158
2159 llvm_unreachable("unknown ASTReadResult");
2160}
2161
Richard Smith0516b182015-09-08 19:40:14 +00002162ASTReader::ASTReadResult ASTReader::ReadOptionsBlock(
2163 BitstreamCursor &Stream, unsigned ClientLoadCapabilities,
2164 bool AllowCompatibleConfigurationMismatch, ASTReaderListener &Listener,
Manman Ren47a44452016-07-26 17:12:17 +00002165 std::string &SuggestedPredefines, bool ValidateDiagnosticOptions) {
Richard Smith0516b182015-09-08 19:40:14 +00002166 if (Stream.EnterSubBlock(OPTIONS_BLOCK_ID))
2167 return Failure;
2168
2169 // Read all of the records in the options block.
2170 RecordData Record;
2171 ASTReadResult Result = Success;
Eugene Zelenkoe95e7d52016-09-07 21:53:17 +00002172 while (true) {
Richard Smith0516b182015-09-08 19:40:14 +00002173 llvm::BitstreamEntry Entry = Stream.advance();
David L. Jonesc4808b9e2016-12-15 20:53:26 +00002174
Richard Smith0516b182015-09-08 19:40:14 +00002175 switch (Entry.Kind) {
2176 case llvm::BitstreamEntry::Error:
2177 case llvm::BitstreamEntry::SubBlock:
2178 return Failure;
2179
2180 case llvm::BitstreamEntry::EndBlock:
2181 return Result;
2182
2183 case llvm::BitstreamEntry::Record:
2184 // The interesting case.
2185 break;
2186 }
2187
2188 // Read and process a record.
2189 Record.clear();
2190 switch ((OptionsRecordTypes)Stream.readRecord(Entry.ID, Record)) {
2191 case LANGUAGE_OPTIONS: {
2192 bool Complain = (ClientLoadCapabilities & ARR_ConfigurationMismatch) == 0;
2193 if (ParseLanguageOptions(Record, Complain, Listener,
2194 AllowCompatibleConfigurationMismatch))
2195 Result = ConfigurationMismatch;
2196 break;
2197 }
2198
2199 case TARGET_OPTIONS: {
2200 bool Complain = (ClientLoadCapabilities & ARR_ConfigurationMismatch) == 0;
2201 if (ParseTargetOptions(Record, Complain, Listener,
2202 AllowCompatibleConfigurationMismatch))
2203 Result = ConfigurationMismatch;
2204 break;
2205 }
2206
2207 case DIAGNOSTIC_OPTIONS: {
2208 bool Complain = (ClientLoadCapabilities & ARR_OutOfDate) == 0;
Manman Ren47a44452016-07-26 17:12:17 +00002209 if (ValidateDiagnosticOptions &&
2210 !AllowCompatibleConfigurationMismatch &&
Richard Smith0516b182015-09-08 19:40:14 +00002211 ParseDiagnosticOptions(Record, Complain, Listener))
2212 return OutOfDate;
2213 break;
2214 }
2215
2216 case FILE_SYSTEM_OPTIONS: {
2217 bool Complain = (ClientLoadCapabilities & ARR_ConfigurationMismatch) == 0;
2218 if (!AllowCompatibleConfigurationMismatch &&
2219 ParseFileSystemOptions(Record, Complain, Listener))
2220 Result = ConfigurationMismatch;
2221 break;
2222 }
2223
2224 case HEADER_SEARCH_OPTIONS: {
2225 bool Complain = (ClientLoadCapabilities & ARR_ConfigurationMismatch) == 0;
2226 if (!AllowCompatibleConfigurationMismatch &&
2227 ParseHeaderSearchOptions(Record, Complain, Listener))
2228 Result = ConfigurationMismatch;
2229 break;
2230 }
2231
2232 case PREPROCESSOR_OPTIONS:
2233 bool Complain = (ClientLoadCapabilities & ARR_ConfigurationMismatch) == 0;
2234 if (!AllowCompatibleConfigurationMismatch &&
2235 ParsePreprocessorOptions(Record, Complain, Listener,
2236 SuggestedPredefines))
2237 Result = ConfigurationMismatch;
2238 break;
2239 }
2240 }
2241}
2242
Guy Benyei11169dd2012-12-18 14:30:41 +00002243ASTReader::ASTReadResult
2244ASTReader::ReadControlBlock(ModuleFile &F,
Dmitri Gribenkof8579502013-01-12 19:30:44 +00002245 SmallVectorImpl<ImportedModule> &Loaded,
Ben Langmuirbeee15e2014-04-14 18:00:01 +00002246 const ModuleFile *ImportedBy,
Guy Benyei11169dd2012-12-18 14:30:41 +00002247 unsigned ClientLoadCapabilities) {
Chris Lattner7fb3bef2013-01-20 00:56:42 +00002248 BitstreamCursor &Stream = F.Stream;
Richard Smith8a308ec2015-11-05 00:54:55 +00002249 ASTReadResult Result = Success;
Guy Benyei11169dd2012-12-18 14:30:41 +00002250
2251 if (Stream.EnterSubBlock(CONTROL_BLOCK_ID)) {
2252 Error("malformed block record in AST file");
2253 return Failure;
2254 }
2255
2256 // Read all of the records and blocks in the control block.
2257 RecordData Record;
Richard Smitha1825302014-10-23 22:18:29 +00002258 unsigned NumInputs = 0;
2259 unsigned NumUserInputs = 0;
Eugene Zelenkoe95e7d52016-09-07 21:53:17 +00002260 while (true) {
Chris Lattnere7b154b2013-01-19 21:39:22 +00002261 llvm::BitstreamEntry Entry = Stream.advance();
David L. Jonesc4808b9e2016-12-15 20:53:26 +00002262
Chris Lattnere7b154b2013-01-19 21:39:22 +00002263 switch (Entry.Kind) {
2264 case llvm::BitstreamEntry::Error:
2265 Error("malformed block record in AST file");
2266 return Failure;
Dmitri Gribenkof430da42014-02-12 10:33:14 +00002267 case llvm::BitstreamEntry::EndBlock: {
2268 // Validate input files.
2269 const HeaderSearchOptions &HSOpts =
2270 PP.getHeaderSearchInfo().getHeaderSearchOpts();
Ben Langmuircb69b572014-03-07 06:40:32 +00002271
Richard Smitha1825302014-10-23 22:18:29 +00002272 // All user input files reside at the index range [0, NumUserInputs), and
Richard Smith0f99d6a2015-08-09 08:48:41 +00002273 // system input files reside at [NumUserInputs, NumInputs). For explicitly
2274 // loaded module files, ignore missing inputs.
Manman Ren11f2a472016-08-18 17:42:15 +00002275 if (!DisableValidation && F.Kind != MK_ExplicitModule &&
2276 F.Kind != MK_PrebuiltModule) {
Guy Benyei11169dd2012-12-18 14:30:41 +00002277 bool Complain = (ClientLoadCapabilities & ARR_OutOfDate) == 0;
Ben Langmuircb69b572014-03-07 06:40:32 +00002278
Dmitri Gribenkof430da42014-02-12 10:33:14 +00002279 // If we are reading a module, we will create a verification timestamp,
2280 // so we verify all input files. Otherwise, verify only user input
2281 // files.
Ben Langmuircb69b572014-03-07 06:40:32 +00002282
2283 unsigned N = NumUserInputs;
2284 if (ValidateSystemInputs ||
Richard Smithe842a472014-10-22 02:05:46 +00002285 (HSOpts.ModulesValidateOncePerBuildSession &&
Ben Langmuiracb803e2014-11-10 22:13:10 +00002286 F.InputFilesValidationTimestamp <= HSOpts.BuildSessionTimestamp &&
Richard Smithe842a472014-10-22 02:05:46 +00002287 F.Kind == MK_ImplicitModule))
Ben Langmuircb69b572014-03-07 06:40:32 +00002288 N = NumInputs;
2289
Ben Langmuir3d4417c2014-02-07 17:31:11 +00002290 for (unsigned I = 0; I < N; ++I) {
Argyrios Kyrtzidis61c3d872013-03-01 03:26:04 +00002291 InputFile IF = getInputFile(F, I+1, Complain);
2292 if (!IF.getFile() || IF.isOutOfDate())
Guy Benyei11169dd2012-12-18 14:30:41 +00002293 return OutOfDate;
Argyrios Kyrtzidis61c3d872013-03-01 03:26:04 +00002294 }
Guy Benyei11169dd2012-12-18 14:30:41 +00002295 }
Ben Langmuircb69b572014-03-07 06:40:32 +00002296
Argyrios Kyrtzidis6d0753d2014-03-14 03:07:38 +00002297 if (Listener)
Richard Smith216a3bd2015-08-13 17:57:10 +00002298 Listener->visitModuleFile(F.FileName, F.Kind);
Argyrios Kyrtzidis6d0753d2014-03-14 03:07:38 +00002299
Ben Langmuircb69b572014-03-07 06:40:32 +00002300 if (Listener && Listener->needsInputFileVisitation()) {
2301 unsigned N = Listener->needsSystemInputFileVisitation() ? NumInputs
2302 : NumUserInputs;
Argyrios Kyrtzidis68ccbe02014-03-14 02:26:31 +00002303 for (unsigned I = 0; I < N; ++I) {
2304 bool IsSystem = I >= NumUserInputs;
2305 InputFileInfo FI = readInputFileInfo(F, I+1);
Richard Smith216a3bd2015-08-13 17:57:10 +00002306 Listener->visitInputFile(FI.Filename, IsSystem, FI.Overridden,
Manman Ren11f2a472016-08-18 17:42:15 +00002307 F.Kind == MK_ExplicitModule ||
2308 F.Kind == MK_PrebuiltModule);
Argyrios Kyrtzidis68ccbe02014-03-14 02:26:31 +00002309 }
Ben Langmuircb69b572014-03-07 06:40:32 +00002310 }
2311
Richard Smith8a308ec2015-11-05 00:54:55 +00002312 return Result;
Dmitri Gribenkof430da42014-02-12 10:33:14 +00002313 }
2314
Chris Lattnere7b154b2013-01-19 21:39:22 +00002315 case llvm::BitstreamEntry::SubBlock:
2316 switch (Entry.ID) {
Guy Benyei11169dd2012-12-18 14:30:41 +00002317 case INPUT_FILES_BLOCK_ID:
2318 F.InputFilesCursor = Stream;
2319 if (Stream.SkipBlock() || // Skip with the main cursor
2320 // Read the abbreviations
2321 ReadBlockAbbrevs(F.InputFilesCursor, INPUT_FILES_BLOCK_ID)) {
2322 Error("malformed block record in AST file");
2323 return Failure;
2324 }
2325 continue;
Richard Smith0516b182015-09-08 19:40:14 +00002326
2327 case OPTIONS_BLOCK_ID:
2328 // If we're reading the first module for this group, check its options
2329 // are compatible with ours. For modules it imports, no further checking
2330 // is required, because we checked them when we built it.
2331 if (Listener && !ImportedBy) {
2332 // Should we allow the configuration of the module file to differ from
2333 // the configuration of the current translation unit in a compatible
2334 // way?
2335 //
2336 // FIXME: Allow this for files explicitly specified with -include-pch.
2337 bool AllowCompatibleConfigurationMismatch =
Manman Ren11f2a472016-08-18 17:42:15 +00002338 F.Kind == MK_ExplicitModule || F.Kind == MK_PrebuiltModule;
Manman Ren47a44452016-07-26 17:12:17 +00002339 const HeaderSearchOptions &HSOpts =
2340 PP.getHeaderSearchInfo().getHeaderSearchOpts();
Richard Smith0516b182015-09-08 19:40:14 +00002341
Richard Smith8a308ec2015-11-05 00:54:55 +00002342 Result = ReadOptionsBlock(Stream, ClientLoadCapabilities,
2343 AllowCompatibleConfigurationMismatch,
Manman Ren47a44452016-07-26 17:12:17 +00002344 *Listener, SuggestedPredefines,
2345 HSOpts.ModulesValidateDiagnosticOptions);
Richard Smith0516b182015-09-08 19:40:14 +00002346 if (Result == Failure) {
2347 Error("malformed block record in AST file");
2348 return Result;
2349 }
2350
Richard Smith8a308ec2015-11-05 00:54:55 +00002351 if (DisableValidation ||
2352 (AllowConfigurationMismatch && Result == ConfigurationMismatch))
2353 Result = Success;
2354
Ben Langmuir9b1e442e2016-02-11 18:54:02 +00002355 // If we can't load the module, exit early since we likely
2356 // will rebuild the module anyway. The stream may be in the
2357 // middle of a block.
2358 if (Result != Success)
Richard Smith0516b182015-09-08 19:40:14 +00002359 return Result;
2360 } else if (Stream.SkipBlock()) {
2361 Error("malformed block record in AST file");
2362 return Failure;
2363 }
2364 continue;
David L. Jonesc4808b9e2016-12-15 20:53:26 +00002365
Guy Benyei11169dd2012-12-18 14:30:41 +00002366 default:
Chris Lattnere7b154b2013-01-19 21:39:22 +00002367 if (Stream.SkipBlock()) {
2368 Error("malformed block record in AST file");
2369 return Failure;
2370 }
2371 continue;
Guy Benyei11169dd2012-12-18 14:30:41 +00002372 }
David L. Jonesc4808b9e2016-12-15 20:53:26 +00002373
Chris Lattnere7b154b2013-01-19 21:39:22 +00002374 case llvm::BitstreamEntry::Record:
2375 // The interesting case.
2376 break;
Guy Benyei11169dd2012-12-18 14:30:41 +00002377 }
2378
2379 // Read and process a record.
2380 Record.clear();
Chris Lattner0e6c9402013-01-20 02:38:54 +00002381 StringRef Blob;
2382 switch ((ControlRecordTypes)Stream.readRecord(Entry.ID, Record, &Blob)) {
Guy Benyei11169dd2012-12-18 14:30:41 +00002383 case METADATA: {
2384 if (Record[0] != VERSION_MAJOR && !DisableValidation) {
2385 if ((ClientLoadCapabilities & ARR_VersionMismatch) == 0)
Dmitri Gribenko2228cd32014-02-11 15:40:09 +00002386 Diag(Record[0] < VERSION_MAJOR? diag::err_pch_version_too_old
2387 : diag::err_pch_version_too_new);
Guy Benyei11169dd2012-12-18 14:30:41 +00002388 return VersionMismatch;
2389 }
2390
Richard Smithe75ee0f2015-08-17 07:13:32 +00002391 bool hasErrors = Record[6];
Guy Benyei11169dd2012-12-18 14:30:41 +00002392 if (hasErrors && !DisableValidation && !AllowASTWithCompilerErrors) {
2393 Diag(diag::err_pch_with_compiler_errors);
2394 return HadErrors;
2395 }
Argyrios Kyrtzidis70ec1c72016-07-13 20:35:26 +00002396 if (hasErrors) {
2397 Diags.ErrorOccurred = true;
2398 Diags.UncompilableErrorOccurred = true;
2399 Diags.UnrecoverableErrorOccurred = true;
2400 }
Guy Benyei11169dd2012-12-18 14:30:41 +00002401
2402 F.RelocatablePCH = Record[4];
Richard Smith7ed1bc92014-12-05 22:42:13 +00002403 // Relative paths in a relocatable PCH are relative to our sysroot.
2404 if (F.RelocatablePCH)
2405 F.BaseDirectory = isysroot.empty() ? "/" : isysroot;
Guy Benyei11169dd2012-12-18 14:30:41 +00002406
Richard Smithe75ee0f2015-08-17 07:13:32 +00002407 F.HasTimestamps = Record[5];
2408
Guy Benyei11169dd2012-12-18 14:30:41 +00002409 const std::string &CurBranch = getClangFullRepositoryVersion();
Chris Lattner0e6c9402013-01-20 02:38:54 +00002410 StringRef ASTBranch = Blob;
Guy Benyei11169dd2012-12-18 14:30:41 +00002411 if (StringRef(CurBranch) != ASTBranch && !DisableValidation) {
2412 if ((ClientLoadCapabilities & ARR_VersionMismatch) == 0)
Dmitri Gribenko2228cd32014-02-11 15:40:09 +00002413 Diag(diag::err_pch_different_branch) << ASTBranch << CurBranch;
Guy Benyei11169dd2012-12-18 14:30:41 +00002414 return VersionMismatch;
2415 }
2416 break;
2417 }
2418
Ben Langmuir487ea142014-10-23 18:05:36 +00002419 case SIGNATURE:
2420 assert((!F.Signature || F.Signature == Record[0]) && "signature changed");
2421 F.Signature = Record[0];
2422 break;
2423
Guy Benyei11169dd2012-12-18 14:30:41 +00002424 case IMPORTS: {
David L. Jonesc4808b9e2016-12-15 20:53:26 +00002425 // Load each of the imported PCH files.
Guy Benyei11169dd2012-12-18 14:30:41 +00002426 unsigned Idx = 0, N = Record.size();
2427 while (Idx < N) {
2428 // Read information about the AST file.
2429 ModuleKind ImportedKind = (ModuleKind)Record[Idx++];
2430 // The import location will be the local one for now; we will adjust
2431 // all import locations of module imports after the global source
Richard Smithb22a1d12016-03-27 20:13:24 +00002432 // location info are setup, in ReadAST.
Guy Benyei11169dd2012-12-18 14:30:41 +00002433 SourceLocation ImportLoc =
Richard Smithb22a1d12016-03-27 20:13:24 +00002434 ReadUntranslatedSourceLocation(Record[Idx++]);
Douglas Gregor7029ce12013-03-19 00:28:20 +00002435 off_t StoredSize = (off_t)Record[Idx++];
2436 time_t StoredModTime = (time_t)Record[Idx++];
Ben Langmuir487ea142014-10-23 18:05:36 +00002437 ASTFileSignature StoredSignature = Record[Idx++];
Richard Smith7ed1bc92014-12-05 22:42:13 +00002438 auto ImportedFile = ReadPath(F, Record, Idx);
Guy Benyei11169dd2012-12-18 14:30:41 +00002439
Richard Smith0f99d6a2015-08-09 08:48:41 +00002440 // If our client can't cope with us being out of date, we can't cope with
2441 // our dependency being missing.
2442 unsigned Capabilities = ClientLoadCapabilities;
2443 if ((ClientLoadCapabilities & ARR_OutOfDate) == 0)
2444 Capabilities &= ~ARR_Missing;
2445
Guy Benyei11169dd2012-12-18 14:30:41 +00002446 // Load the AST file.
Richard Smith0f99d6a2015-08-09 08:48:41 +00002447 auto Result = ReadASTCore(ImportedFile, ImportedKind, ImportLoc, &F,
2448 Loaded, StoredSize, StoredModTime,
2449 StoredSignature, Capabilities);
2450
2451 // If we diagnosed a problem, produce a backtrace.
2452 if (isDiagnosedResult(Result, Capabilities))
2453 Diag(diag::note_module_file_imported_by)
2454 << F.FileName << !F.ModuleName.empty() << F.ModuleName;
2455
2456 switch (Result) {
Guy Benyei11169dd2012-12-18 14:30:41 +00002457 case Failure: return Failure;
2458 // If we have to ignore the dependency, we'll have to ignore this too.
Douglas Gregor2f1806e2013-03-19 00:38:50 +00002459 case Missing:
Guy Benyei11169dd2012-12-18 14:30:41 +00002460 case OutOfDate: return OutOfDate;
2461 case VersionMismatch: return VersionMismatch;
2462 case ConfigurationMismatch: return ConfigurationMismatch;
2463 case HadErrors: return HadErrors;
2464 case Success: break;
2465 }
2466 }
2467 break;
2468 }
2469
Guy Benyei11169dd2012-12-18 14:30:41 +00002470 case ORIGINAL_FILE:
2471 F.OriginalSourceFileID = FileID::get(Record[0]);
Chris Lattner0e6c9402013-01-20 02:38:54 +00002472 F.ActualOriginalSourceFileName = Blob;
Guy Benyei11169dd2012-12-18 14:30:41 +00002473 F.OriginalSourceFileName = F.ActualOriginalSourceFileName;
Richard Smith7ed1bc92014-12-05 22:42:13 +00002474 ResolveImportedPath(F, F.OriginalSourceFileName);
Guy Benyei11169dd2012-12-18 14:30:41 +00002475 break;
2476
2477 case ORIGINAL_FILE_ID:
2478 F.OriginalSourceFileID = FileID::get(Record[0]);
2479 break;
2480
2481 case ORIGINAL_PCH_DIR:
Chris Lattner0e6c9402013-01-20 02:38:54 +00002482 F.OriginalDir = Blob;
Guy Benyei11169dd2012-12-18 14:30:41 +00002483 break;
2484
Ben Langmuirbeee15e2014-04-14 18:00:01 +00002485 case MODULE_NAME:
2486 F.ModuleName = Blob;
Ben Langmuir4f5212a2014-04-14 22:12:44 +00002487 if (Listener)
2488 Listener->ReadModuleName(F.ModuleName);
Ben Langmuirbeee15e2014-04-14 18:00:01 +00002489 break;
2490
Richard Smith223d3f22014-12-06 03:21:08 +00002491 case MODULE_DIRECTORY: {
2492 assert(!F.ModuleName.empty() &&
2493 "MODULE_DIRECTORY found before MODULE_NAME");
2494 // If we've already loaded a module map file covering this module, we may
2495 // have a better path for it (relative to the current build).
2496 Module *M = PP.getHeaderSearchInfo().lookupModule(F.ModuleName);
2497 if (M && M->Directory) {
2498 // If we're implicitly loading a module, the base directory can't
2499 // change between the build and use.
Manman Ren11f2a472016-08-18 17:42:15 +00002500 if (F.Kind != MK_ExplicitModule && F.Kind != MK_PrebuiltModule) {
Richard Smith223d3f22014-12-06 03:21:08 +00002501 const DirectoryEntry *BuildDir =
2502 PP.getFileManager().getDirectory(Blob);
2503 if (!BuildDir || BuildDir != M->Directory) {
2504 if ((ClientLoadCapabilities & ARR_OutOfDate) == 0)
2505 Diag(diag::err_imported_module_relocated)
2506 << F.ModuleName << Blob << M->Directory->getName();
2507 return OutOfDate;
2508 }
2509 }
2510 F.BaseDirectory = M->Directory->getName();
2511 } else {
2512 F.BaseDirectory = Blob;
2513 }
Richard Smith7ed1bc92014-12-05 22:42:13 +00002514 break;
Richard Smith223d3f22014-12-06 03:21:08 +00002515 }
Richard Smith7ed1bc92014-12-05 22:42:13 +00002516
Ben Langmuirbeee15e2014-04-14 18:00:01 +00002517 case MODULE_MAP_FILE:
Ben Langmuir4b8a9e92014-08-12 16:42:33 +00002518 if (ASTReadResult Result =
2519 ReadModuleMapFileBlock(Record, F, ImportedBy, ClientLoadCapabilities))
2520 return Result;
Ben Langmuir264ea152014-11-08 00:06:39 +00002521 break;
2522
Justin Bognerca9c0cc2015-06-21 20:32:36 +00002523 case INPUT_FILE_OFFSETS:
Richard Smitha1825302014-10-23 22:18:29 +00002524 NumInputs = Record[0];
2525 NumUserInputs = Record[1];
Justin Bogner4c183242015-06-21 20:32:40 +00002526 F.InputFileOffsets =
2527 (const llvm::support::unaligned_uint64_t *)Blob.data();
Richard Smitha1825302014-10-23 22:18:29 +00002528 F.InputFilesLoaded.resize(NumInputs);
Argyrios Kyrtzidisa38cb202017-01-30 06:05:58 +00002529 F.NumUserInputFiles = NumUserInputs;
Guy Benyei11169dd2012-12-18 14:30:41 +00002530 break;
2531 }
2532 }
Guy Benyei11169dd2012-12-18 14:30:41 +00002533}
2534
Ben Langmuir2c9af442014-04-10 17:57:43 +00002535ASTReader::ASTReadResult
2536ASTReader::ReadASTBlock(ModuleFile &F, unsigned ClientLoadCapabilities) {
Chris Lattner7fb3bef2013-01-20 00:56:42 +00002537 BitstreamCursor &Stream = F.Stream;
Guy Benyei11169dd2012-12-18 14:30:41 +00002538
2539 if (Stream.EnterSubBlock(AST_BLOCK_ID)) {
2540 Error("malformed block record in AST file");
Ben Langmuir2c9af442014-04-10 17:57:43 +00002541 return Failure;
Guy Benyei11169dd2012-12-18 14:30:41 +00002542 }
2543
2544 // Read all of the records and blocks for the AST file.
2545 RecordData Record;
Eugene Zelenkoe95e7d52016-09-07 21:53:17 +00002546 while (true) {
Chris Lattnere7b154b2013-01-19 21:39:22 +00002547 llvm::BitstreamEntry Entry = Stream.advance();
David L. Jonesc4808b9e2016-12-15 20:53:26 +00002548
Chris Lattnere7b154b2013-01-19 21:39:22 +00002549 switch (Entry.Kind) {
2550 case llvm::BitstreamEntry::Error:
2551 Error("error at end of module block in AST file");
Ben Langmuir2c9af442014-04-10 17:57:43 +00002552 return Failure;
Chris Lattnere7b154b2013-01-19 21:39:22 +00002553 case llvm::BitstreamEntry::EndBlock: {
Richard Smithc0fbba72013-04-03 22:49:41 +00002554 // Outside of C++, we do not store a lookup map for the translation unit.
2555 // Instead, mark it as needing a lookup map to be built if this module
2556 // contains any declarations lexically within it (which it always does!).
2557 // This usually has no cost, since we very rarely need the lookup map for
2558 // the translation unit outside C++.
Guy Benyei11169dd2012-12-18 14:30:41 +00002559 DeclContext *DC = Context.getTranslationUnitDecl();
Richard Smithc0fbba72013-04-03 22:49:41 +00002560 if (DC->hasExternalLexicalStorage() &&
2561 !getContext().getLangOpts().CPlusPlus)
Guy Benyei11169dd2012-12-18 14:30:41 +00002562 DC->setMustBuildLookupTable();
David L. Jonesc4808b9e2016-12-15 20:53:26 +00002563
Ben Langmuir2c9af442014-04-10 17:57:43 +00002564 return Success;
Guy Benyei11169dd2012-12-18 14:30:41 +00002565 }
Chris Lattnere7b154b2013-01-19 21:39:22 +00002566 case llvm::BitstreamEntry::SubBlock:
2567 switch (Entry.ID) {
Guy Benyei11169dd2012-12-18 14:30:41 +00002568 case DECLTYPES_BLOCK_ID:
2569 // We lazily load the decls block, but we want to set up the
2570 // DeclsCursor cursor to point into it. Clone our current bitcode
2571 // cursor to it, enter the block and read the abbrevs in that block.
2572 // With the main cursor, we just skip over it.
2573 F.DeclsCursor = Stream;
2574 if (Stream.SkipBlock() || // Skip with the main cursor.
2575 // Read the abbrevs.
2576 ReadBlockAbbrevs(F.DeclsCursor, DECLTYPES_BLOCK_ID)) {
2577 Error("malformed block record in AST file");
Ben Langmuir2c9af442014-04-10 17:57:43 +00002578 return Failure;
Guy Benyei11169dd2012-12-18 14:30:41 +00002579 }
2580 break;
Richard Smithb9eab6d2014-03-20 19:44:17 +00002581
Guy Benyei11169dd2012-12-18 14:30:41 +00002582 case PREPROCESSOR_BLOCK_ID:
2583 F.MacroCursor = Stream;
2584 if (!PP.getExternalSource())
2585 PP.setExternalSource(this);
David L. Jonesc4808b9e2016-12-15 20:53:26 +00002586
Guy Benyei11169dd2012-12-18 14:30:41 +00002587 if (Stream.SkipBlock() ||
2588 ReadBlockAbbrevs(F.MacroCursor, PREPROCESSOR_BLOCK_ID)) {
2589 Error("malformed block record in AST file");
Ben Langmuir2c9af442014-04-10 17:57:43 +00002590 return Failure;
Guy Benyei11169dd2012-12-18 14:30:41 +00002591 }
2592 F.MacroStartOffset = F.MacroCursor.GetCurrentBitNo();
2593 break;
David L. Jonesc4808b9e2016-12-15 20:53:26 +00002594
Guy Benyei11169dd2012-12-18 14:30:41 +00002595 case PREPROCESSOR_DETAIL_BLOCK_ID:
2596 F.PreprocessorDetailCursor = Stream;
2597 if (Stream.SkipBlock() ||
Chris Lattnere7b154b2013-01-19 21:39:22 +00002598 ReadBlockAbbrevs(F.PreprocessorDetailCursor,
Guy Benyei11169dd2012-12-18 14:30:41 +00002599 PREPROCESSOR_DETAIL_BLOCK_ID)) {
Chris Lattnere7b154b2013-01-19 21:39:22 +00002600 Error("malformed preprocessor detail record in AST file");
Ben Langmuir2c9af442014-04-10 17:57:43 +00002601 return Failure;
Chris Lattnere7b154b2013-01-19 21:39:22 +00002602 }
Guy Benyei11169dd2012-12-18 14:30:41 +00002603 F.PreprocessorDetailStartOffset
Chris Lattnere7b154b2013-01-19 21:39:22 +00002604 = F.PreprocessorDetailCursor.GetCurrentBitNo();
David L. Jonesc4808b9e2016-12-15 20:53:26 +00002605
Guy Benyei11169dd2012-12-18 14:30:41 +00002606 if (!PP.getPreprocessingRecord())
2607 PP.createPreprocessingRecord();
2608 if (!PP.getPreprocessingRecord()->getExternalSource())
2609 PP.getPreprocessingRecord()->SetExternalSource(*this);
2610 break;
David L. Jonesc4808b9e2016-12-15 20:53:26 +00002611
Guy Benyei11169dd2012-12-18 14:30:41 +00002612 case SOURCE_MANAGER_BLOCK_ID:
2613 if (ReadSourceManagerBlock(F))
Ben Langmuir2c9af442014-04-10 17:57:43 +00002614 return Failure;
Guy Benyei11169dd2012-12-18 14:30:41 +00002615 break;
David L. Jonesc4808b9e2016-12-15 20:53:26 +00002616
Guy Benyei11169dd2012-12-18 14:30:41 +00002617 case SUBMODULE_BLOCK_ID:
David Blaikie9ffe5a32017-01-30 05:00:26 +00002618 if (ASTReadResult Result =
2619 ReadSubmoduleBlock(F, ClientLoadCapabilities))
Ben Langmuir2c9af442014-04-10 17:57:43 +00002620 return Result;
Guy Benyei11169dd2012-12-18 14:30:41 +00002621 break;
David L. Jonesc4808b9e2016-12-15 20:53:26 +00002622
Guy Benyei11169dd2012-12-18 14:30:41 +00002623 case COMMENTS_BLOCK_ID: {
Chris Lattner7fb3bef2013-01-20 00:56:42 +00002624 BitstreamCursor C = Stream;
Guy Benyei11169dd2012-12-18 14:30:41 +00002625 if (Stream.SkipBlock() ||
2626 ReadBlockAbbrevs(C, COMMENTS_BLOCK_ID)) {
2627 Error("malformed comments block in AST file");
Ben Langmuir2c9af442014-04-10 17:57:43 +00002628 return Failure;
Guy Benyei11169dd2012-12-18 14:30:41 +00002629 }
2630 CommentsCursors.push_back(std::make_pair(C, &F));
2631 break;
2632 }
David L. Jonesc4808b9e2016-12-15 20:53:26 +00002633
Guy Benyei11169dd2012-12-18 14:30:41 +00002634 default:
Chris Lattnere7b154b2013-01-19 21:39:22 +00002635 if (Stream.SkipBlock()) {
2636 Error("malformed block record in AST file");
Ben Langmuir2c9af442014-04-10 17:57:43 +00002637 return Failure;
Chris Lattnere7b154b2013-01-19 21:39:22 +00002638 }
2639 break;
Guy Benyei11169dd2012-12-18 14:30:41 +00002640 }
2641 continue;
David L. Jonesc4808b9e2016-12-15 20:53:26 +00002642
Chris Lattnere7b154b2013-01-19 21:39:22 +00002643 case llvm::BitstreamEntry::Record:
2644 // The interesting case.
2645 break;
Guy Benyei11169dd2012-12-18 14:30:41 +00002646 }
2647
2648 // Read and process a record.
2649 Record.clear();
Chris Lattner0e6c9402013-01-20 02:38:54 +00002650 StringRef Blob;
2651 switch ((ASTRecordTypes)Stream.readRecord(Entry.ID, Record, &Blob)) {
Guy Benyei11169dd2012-12-18 14:30:41 +00002652 default: // Default behavior: ignore.
2653 break;
2654
2655 case TYPE_OFFSET: {
2656 if (F.LocalNumTypes != 0) {
2657 Error("duplicate TYPE_OFFSET record in AST file");
Ben Langmuir2c9af442014-04-10 17:57:43 +00002658 return Failure;
Guy Benyei11169dd2012-12-18 14:30:41 +00002659 }
Chris Lattner0e6c9402013-01-20 02:38:54 +00002660 F.TypeOffsets = (const uint32_t *)Blob.data();
Guy Benyei11169dd2012-12-18 14:30:41 +00002661 F.LocalNumTypes = Record[0];
2662 unsigned LocalBaseTypeIndex = Record[1];
2663 F.BaseTypeIndex = getTotalNumTypes();
David L. Jonesc4808b9e2016-12-15 20:53:26 +00002664
Guy Benyei11169dd2012-12-18 14:30:41 +00002665 if (F.LocalNumTypes > 0) {
2666 // Introduce the global -> local mapping for types within this module.
2667 GlobalTypeMap.insert(std::make_pair(getTotalNumTypes(), &F));
David L. Jonesc4808b9e2016-12-15 20:53:26 +00002668
Guy Benyei11169dd2012-12-18 14:30:41 +00002669 // Introduce the local -> global mapping for types within this module.
2670 F.TypeRemap.insertOrReplace(
David L. Jonesc4808b9e2016-12-15 20:53:26 +00002671 std::make_pair(LocalBaseTypeIndex,
Guy Benyei11169dd2012-12-18 14:30:41 +00002672 F.BaseTypeIndex - LocalBaseTypeIndex));
Ben Langmuir52ca6782014-10-20 16:27:32 +00002673
2674 TypesLoaded.resize(TypesLoaded.size() + F.LocalNumTypes);
Guy Benyei11169dd2012-12-18 14:30:41 +00002675 }
2676 break;
2677 }
David L. Jonesc4808b9e2016-12-15 20:53:26 +00002678
Guy Benyei11169dd2012-12-18 14:30:41 +00002679 case DECL_OFFSET: {
2680 if (F.LocalNumDecls != 0) {
2681 Error("duplicate DECL_OFFSET record in AST file");
Ben Langmuir2c9af442014-04-10 17:57:43 +00002682 return Failure;
Guy Benyei11169dd2012-12-18 14:30:41 +00002683 }
Chris Lattner0e6c9402013-01-20 02:38:54 +00002684 F.DeclOffsets = (const DeclOffset *)Blob.data();
Guy Benyei11169dd2012-12-18 14:30:41 +00002685 F.LocalNumDecls = Record[0];
2686 unsigned LocalBaseDeclID = Record[1];
2687 F.BaseDeclID = getTotalNumDecls();
David L. Jonesc4808b9e2016-12-15 20:53:26 +00002688
Guy Benyei11169dd2012-12-18 14:30:41 +00002689 if (F.LocalNumDecls > 0) {
David L. Jonesc4808b9e2016-12-15 20:53:26 +00002690 // Introduce the global -> local mapping for declarations within this
Guy Benyei11169dd2012-12-18 14:30:41 +00002691 // module.
2692 GlobalDeclMap.insert(
2693 std::make_pair(getTotalNumDecls() + NUM_PREDEF_DECL_IDS, &F));
David L. Jonesc4808b9e2016-12-15 20:53:26 +00002694
Guy Benyei11169dd2012-12-18 14:30:41 +00002695 // Introduce the local -> global mapping for declarations within this
2696 // module.
2697 F.DeclRemap.insertOrReplace(
2698 std::make_pair(LocalBaseDeclID, F.BaseDeclID - LocalBaseDeclID));
David L. Jonesc4808b9e2016-12-15 20:53:26 +00002699
Guy Benyei11169dd2012-12-18 14:30:41 +00002700 // Introduce the global -> local mapping for declarations within this
2701 // module.
2702 F.GlobalToLocalDeclIDs[&F] = LocalBaseDeclID;
Ben Langmuirfe971d92014-08-16 04:54:18 +00002703
Ben Langmuir52ca6782014-10-20 16:27:32 +00002704 DeclsLoaded.resize(DeclsLoaded.size() + F.LocalNumDecls);
2705 }
Guy Benyei11169dd2012-12-18 14:30:41 +00002706 break;
2707 }
David L. Jonesc4808b9e2016-12-15 20:53:26 +00002708
Guy Benyei11169dd2012-12-18 14:30:41 +00002709 case TU_UPDATE_LEXICAL: {
2710 DeclContext *TU = Context.getTranslationUnitDecl();
Richard Smith82f8fcd2015-08-06 22:07:25 +00002711 LexicalContents Contents(
2712 reinterpret_cast<const llvm::support::unaligned_uint32_t *>(
2713 Blob.data()),
2714 static_cast<unsigned int>(Blob.size() / 4));
2715 TULexicalDecls.push_back(std::make_pair(&F, Contents));
Guy Benyei11169dd2012-12-18 14:30:41 +00002716 TU->setHasExternalLexicalStorage(true);
2717 break;
2718 }
2719
2720 case UPDATE_VISIBLE: {
2721 unsigned Idx = 0;
2722 serialization::DeclID ID = ReadDeclID(F, Record, Idx);
Richard Smith0f4e2c42015-08-06 04:23:48 +00002723 auto *Data = (const unsigned char*)Blob.data();
Richard Smithd88a7f12015-09-01 20:35:42 +00002724 PendingVisibleUpdates[ID].push_back(PendingVisibleUpdate{&F, Data});
Richard Smith0f4e2c42015-08-06 04:23:48 +00002725 // If we've already loaded the decl, perform the updates when we finish
2726 // loading this block.
2727 if (Decl *D = GetExistingDecl(ID))
2728 PendingUpdateRecords.push_back(std::make_pair(ID, D));
Guy Benyei11169dd2012-12-18 14:30:41 +00002729 break;
2730 }
2731
2732 case IDENTIFIER_TABLE:
Chris Lattner0e6c9402013-01-20 02:38:54 +00002733 F.IdentifierTableData = Blob.data();
Guy Benyei11169dd2012-12-18 14:30:41 +00002734 if (Record[0]) {
Justin Bognerda4e6502014-04-14 16:34:29 +00002735 F.IdentifierLookupTable = ASTIdentifierLookupTable::Create(
2736 (const unsigned char *)F.IdentifierTableData + Record[0],
2737 (const unsigned char *)F.IdentifierTableData + sizeof(uint32_t),
2738 (const unsigned char *)F.IdentifierTableData,
2739 ASTIdentifierLookupTrait(*this, F));
David L. Jonesc4808b9e2016-12-15 20:53:26 +00002740
Guy Benyei11169dd2012-12-18 14:30:41 +00002741 PP.getIdentifierTable().setExternalIdentifierLookup(this);
2742 }
2743 break;
2744
2745 case IDENTIFIER_OFFSET: {
2746 if (F.LocalNumIdentifiers != 0) {
2747 Error("duplicate IDENTIFIER_OFFSET record in AST file");
Ben Langmuir2c9af442014-04-10 17:57:43 +00002748 return Failure;
Guy Benyei11169dd2012-12-18 14:30:41 +00002749 }
Chris Lattner0e6c9402013-01-20 02:38:54 +00002750 F.IdentifierOffsets = (const uint32_t *)Blob.data();
Guy Benyei11169dd2012-12-18 14:30:41 +00002751 F.LocalNumIdentifiers = Record[0];
2752 unsigned LocalBaseIdentifierID = Record[1];
2753 F.BaseIdentifierID = getTotalNumIdentifiers();
David L. Jonesc4808b9e2016-12-15 20:53:26 +00002754
Guy Benyei11169dd2012-12-18 14:30:41 +00002755 if (F.LocalNumIdentifiers > 0) {
2756 // Introduce the global -> local mapping for identifiers within this
2757 // module.
David L. Jonesc4808b9e2016-12-15 20:53:26 +00002758 GlobalIdentifierMap.insert(std::make_pair(getTotalNumIdentifiers() + 1,
Guy Benyei11169dd2012-12-18 14:30:41 +00002759 &F));
David L. Jonesc4808b9e2016-12-15 20:53:26 +00002760
Guy Benyei11169dd2012-12-18 14:30:41 +00002761 // Introduce the local -> global mapping for identifiers within this
2762 // module.
2763 F.IdentifierRemap.insertOrReplace(
2764 std::make_pair(LocalBaseIdentifierID,
2765 F.BaseIdentifierID - LocalBaseIdentifierID));
Ben Langmuirfe971d92014-08-16 04:54:18 +00002766
Ben Langmuir52ca6782014-10-20 16:27:32 +00002767 IdentifiersLoaded.resize(IdentifiersLoaded.size()
2768 + F.LocalNumIdentifiers);
2769 }
Guy Benyei11169dd2012-12-18 14:30:41 +00002770 break;
2771 }
2772
Richard Smith33e0f7e2015-07-22 02:08:40 +00002773 case INTERESTING_IDENTIFIERS:
2774 F.PreloadIdentifierOffsets.assign(Record.begin(), Record.end());
2775 break;
2776
Ben Langmuir332aafe2014-01-31 01:06:56 +00002777 case EAGERLY_DESERIALIZED_DECLS:
Richard Smith9e2341d2015-03-23 03:25:59 +00002778 // FIXME: Skip reading this record if our ASTConsumer doesn't care
2779 // about "interesting" decls (for instance, if we're building a module).
Guy Benyei11169dd2012-12-18 14:30:41 +00002780 for (unsigned I = 0, N = Record.size(); I != N; ++I)
Ben Langmuir332aafe2014-01-31 01:06:56 +00002781 EagerlyDeserializedDecls.push_back(getGlobalDeclID(F, Record[I]));
Guy Benyei11169dd2012-12-18 14:30:41 +00002782 break;
2783
David Blaikie9ffe5a32017-01-30 05:00:26 +00002784 case MODULAR_CODEGEN_DECLS:
2785 // FIXME: Skip reading this record if our ASTConsumer doesn't care about
2786 // them (ie: if we're not codegenerating this module).
2787 if (F.Kind == MK_MainFile)
2788 for (unsigned I = 0, N = Record.size(); I != N; ++I)
2789 EagerlyDeserializedDecls.push_back(getGlobalDeclID(F, Record[I]));
2790 break;
2791
Guy Benyei11169dd2012-12-18 14:30:41 +00002792 case SPECIAL_TYPES:
Douglas Gregor44180f82013-02-01 23:45:03 +00002793 if (SpecialTypes.empty()) {
2794 for (unsigned I = 0, N = Record.size(); I != N; ++I)
2795 SpecialTypes.push_back(getGlobalTypeID(F, Record[I]));
2796 break;
2797 }
2798
2799 if (SpecialTypes.size() != Record.size()) {
2800 Error("invalid special-types record");
Ben Langmuir2c9af442014-04-10 17:57:43 +00002801 return Failure;
Douglas Gregor44180f82013-02-01 23:45:03 +00002802 }
2803
2804 for (unsigned I = 0, N = Record.size(); I != N; ++I) {
2805 serialization::TypeID ID = getGlobalTypeID(F, Record[I]);
2806 if (!SpecialTypes[I])
2807 SpecialTypes[I] = ID;
2808 // FIXME: If ID && SpecialTypes[I] != ID, do we need a separate
2809 // merge step?
2810 }
Guy Benyei11169dd2012-12-18 14:30:41 +00002811 break;
2812
2813 case STATISTICS:
2814 TotalNumStatements += Record[0];
2815 TotalNumMacros += Record[1];
2816 TotalLexicalDeclContexts += Record[2];
2817 TotalVisibleDeclContexts += Record[3];
2818 break;
2819
2820 case UNUSED_FILESCOPED_DECLS:
2821 for (unsigned I = 0, N = Record.size(); I != N; ++I)
2822 UnusedFileScopedDecls.push_back(getGlobalDeclID(F, Record[I]));
2823 break;
2824
2825 case DELEGATING_CTORS:
2826 for (unsigned I = 0, N = Record.size(); I != N; ++I)
2827 DelegatingCtorDecls.push_back(getGlobalDeclID(F, Record[I]));
2828 break;
2829
2830 case WEAK_UNDECLARED_IDENTIFIERS:
2831 if (Record.size() % 4 != 0) {
2832 Error("invalid weak identifiers record");
Ben Langmuir2c9af442014-04-10 17:57:43 +00002833 return Failure;
Guy Benyei11169dd2012-12-18 14:30:41 +00002834 }
David L. Jonesc4808b9e2016-12-15 20:53:26 +00002835
2836 // FIXME: Ignore weak undeclared identifiers from non-original PCH
Guy Benyei11169dd2012-12-18 14:30:41 +00002837 // files. This isn't the way to do it :)
2838 WeakUndeclaredIdentifiers.clear();
David L. Jonesc4808b9e2016-12-15 20:53:26 +00002839
Guy Benyei11169dd2012-12-18 14:30:41 +00002840 // Translate the weak, undeclared identifiers into global IDs.
2841 for (unsigned I = 0, N = Record.size(); I < N; /* in loop */) {
2842 WeakUndeclaredIdentifiers.push_back(
2843 getGlobalIdentifierID(F, Record[I++]));
2844 WeakUndeclaredIdentifiers.push_back(
2845 getGlobalIdentifierID(F, Record[I++]));
2846 WeakUndeclaredIdentifiers.push_back(
2847 ReadSourceLocation(F, Record, I).getRawEncoding());
2848 WeakUndeclaredIdentifiers.push_back(Record[I++]);
2849 }
2850 break;
2851
Guy Benyei11169dd2012-12-18 14:30:41 +00002852 case SELECTOR_OFFSETS: {
Chris Lattner0e6c9402013-01-20 02:38:54 +00002853 F.SelectorOffsets = (const uint32_t *)Blob.data();
Guy Benyei11169dd2012-12-18 14:30:41 +00002854 F.LocalNumSelectors = Record[0];
2855 unsigned LocalBaseSelectorID = Record[1];
2856 F.BaseSelectorID = getTotalNumSelectors();
David L. Jonesc4808b9e2016-12-15 20:53:26 +00002857
Guy Benyei11169dd2012-12-18 14:30:41 +00002858 if (F.LocalNumSelectors > 0) {
David L. Jonesc4808b9e2016-12-15 20:53:26 +00002859 // Introduce the global -> local mapping for selectors within this
Guy Benyei11169dd2012-12-18 14:30:41 +00002860 // module.
2861 GlobalSelectorMap.insert(std::make_pair(getTotalNumSelectors()+1, &F));
David L. Jonesc4808b9e2016-12-15 20:53:26 +00002862
2863 // Introduce the local -> global mapping for selectors within this
Guy Benyei11169dd2012-12-18 14:30:41 +00002864 // module.
2865 F.SelectorRemap.insertOrReplace(
2866 std::make_pair(LocalBaseSelectorID,
2867 F.BaseSelectorID - LocalBaseSelectorID));
Ben Langmuir52ca6782014-10-20 16:27:32 +00002868
2869 SelectorsLoaded.resize(SelectorsLoaded.size() + F.LocalNumSelectors);
Guy Benyei11169dd2012-12-18 14:30:41 +00002870 }
2871 break;
2872 }
David L. Jonesc4808b9e2016-12-15 20:53:26 +00002873
Guy Benyei11169dd2012-12-18 14:30:41 +00002874 case METHOD_POOL:
Chris Lattner0e6c9402013-01-20 02:38:54 +00002875 F.SelectorLookupTableData = (const unsigned char *)Blob.data();
Guy Benyei11169dd2012-12-18 14:30:41 +00002876 if (Record[0])
2877 F.SelectorLookupTable
2878 = ASTSelectorLookupTable::Create(
2879 F.SelectorLookupTableData + Record[0],
2880 F.SelectorLookupTableData,
2881 ASTSelectorLookupTrait(*this, F));
2882 TotalNumMethodPoolEntries += Record[1];
2883 break;
2884
2885 case REFERENCED_SELECTOR_POOL:
2886 if (!Record.empty()) {
2887 for (unsigned Idx = 0, N = Record.size() - 1; Idx < N; /* in loop */) {
David L. Jonesc4808b9e2016-12-15 20:53:26 +00002888 ReferencedSelectorsData.push_back(getGlobalSelectorID(F,
Guy Benyei11169dd2012-12-18 14:30:41 +00002889 Record[Idx++]));
2890 ReferencedSelectorsData.push_back(ReadSourceLocation(F, Record, Idx).
2891 getRawEncoding());
2892 }
2893 }
2894 break;
2895
2896 case PP_COUNTER_VALUE:
2897 if (!Record.empty() && Listener)
2898 Listener->ReadCounter(F, Record[0]);
2899 break;
David L. Jonesc4808b9e2016-12-15 20:53:26 +00002900
Guy Benyei11169dd2012-12-18 14:30:41 +00002901 case FILE_SORTED_DECLS:
Chris Lattner0e6c9402013-01-20 02:38:54 +00002902 F.FileSortedDecls = (const DeclID *)Blob.data();
Guy Benyei11169dd2012-12-18 14:30:41 +00002903 F.NumFileSortedDecls = Record[0];
2904 break;
2905
2906 case SOURCE_LOCATION_OFFSETS: {
Chris Lattner0e6c9402013-01-20 02:38:54 +00002907 F.SLocEntryOffsets = (const uint32_t *)Blob.data();
Guy Benyei11169dd2012-12-18 14:30:41 +00002908 F.LocalNumSLocEntries = Record[0];
2909 unsigned SLocSpaceSize = Record[1];
Benjamin Kramer867ea1d2014-03-02 13:01:17 +00002910 std::tie(F.SLocEntryBaseID, F.SLocEntryBaseOffset) =
Ben Langmuir52ca6782014-10-20 16:27:32 +00002911 SourceMgr.AllocateLoadedSLocEntries(F.LocalNumSLocEntries,
Guy Benyei11169dd2012-12-18 14:30:41 +00002912 SLocSpaceSize);
Richard Smith78d81ec2015-08-12 22:25:24 +00002913 if (!F.SLocEntryBaseID) {
2914 Error("ran out of source locations");
2915 break;
2916 }
Guy Benyei11169dd2012-12-18 14:30:41 +00002917 // Make our entry in the range map. BaseID is negative and growing, so
2918 // we invert it. Because we invert it, though, we need the other end of
2919 // the range.
2920 unsigned RangeStart =
2921 unsigned(-F.SLocEntryBaseID) - F.LocalNumSLocEntries + 1;
2922 GlobalSLocEntryMap.insert(std::make_pair(RangeStart, &F));
2923 F.FirstLoc = SourceLocation::getFromRawEncoding(F.SLocEntryBaseOffset);
2924
2925 // SLocEntryBaseOffset is lower than MaxLoadedOffset and decreasing.
2926 assert((F.SLocEntryBaseOffset & (1U << 31U)) == 0);
2927 GlobalSLocOffsetMap.insert(
2928 std::make_pair(SourceManager::MaxLoadedOffset - F.SLocEntryBaseOffset
2929 - SLocSpaceSize,&F));
2930
2931 // Initialize the remapping table.
2932 // Invalid stays invalid.
Richard Smithb9eab6d2014-03-20 19:44:17 +00002933 F.SLocRemap.insertOrReplace(std::make_pair(0U, 0));
Guy Benyei11169dd2012-12-18 14:30:41 +00002934 // This module. Base was 2 when being compiled.
Richard Smithb9eab6d2014-03-20 19:44:17 +00002935 F.SLocRemap.insertOrReplace(std::make_pair(2U,
Guy Benyei11169dd2012-12-18 14:30:41 +00002936 static_cast<int>(F.SLocEntryBaseOffset - 2)));
David L. Jonesc4808b9e2016-12-15 20:53:26 +00002937
Guy Benyei11169dd2012-12-18 14:30:41 +00002938 TotalNumSLocEntries += F.LocalNumSLocEntries;
2939 break;
2940 }
2941
Richard Smith37a93df2017-02-18 00:32:02 +00002942 case MODULE_OFFSET_MAP:
2943 F.ModuleOffsetMap = Blob;
Guy Benyei11169dd2012-12-18 14:30:41 +00002944 break;
Guy Benyei11169dd2012-12-18 14:30:41 +00002945
2946 case SOURCE_MANAGER_LINE_TABLE:
2947 if (ParseLineTable(F, Record))
Ben Langmuir2c9af442014-04-10 17:57:43 +00002948 return Failure;
Guy Benyei11169dd2012-12-18 14:30:41 +00002949 break;
2950
2951 case SOURCE_LOCATION_PRELOADS: {
2952 // Need to transform from the local view (1-based IDs) to the global view,
2953 // which is based off F.SLocEntryBaseID.
2954 if (!F.PreloadSLocEntries.empty()) {
2955 Error("Multiple SOURCE_LOCATION_PRELOADS records in AST file");
Ben Langmuir2c9af442014-04-10 17:57:43 +00002956 return Failure;
Guy Benyei11169dd2012-12-18 14:30:41 +00002957 }
David L. Jonesc4808b9e2016-12-15 20:53:26 +00002958
Guy Benyei11169dd2012-12-18 14:30:41 +00002959 F.PreloadSLocEntries.swap(Record);
2960 break;
2961 }
2962
2963 case EXT_VECTOR_DECLS:
2964 for (unsigned I = 0, N = Record.size(); I != N; ++I)
2965 ExtVectorDecls.push_back(getGlobalDeclID(F, Record[I]));
2966 break;
2967
2968 case VTABLE_USES:
2969 if (Record.size() % 3 != 0) {
2970 Error("Invalid VTABLE_USES record");
Ben Langmuir2c9af442014-04-10 17:57:43 +00002971 return Failure;
Guy Benyei11169dd2012-12-18 14:30:41 +00002972 }
David L. Jonesc4808b9e2016-12-15 20:53:26 +00002973
Guy Benyei11169dd2012-12-18 14:30:41 +00002974 // Later tables overwrite earlier ones.
2975 // FIXME: Modules will have some trouble with this. This is clearly not
2976 // the right way to do this.
2977 VTableUses.clear();
David L. Jonesc4808b9e2016-12-15 20:53:26 +00002978
Guy Benyei11169dd2012-12-18 14:30:41 +00002979 for (unsigned Idx = 0, N = Record.size(); Idx != N; /* In loop */) {
2980 VTableUses.push_back(getGlobalDeclID(F, Record[Idx++]));
2981 VTableUses.push_back(
2982 ReadSourceLocation(F, Record, Idx).getRawEncoding());
2983 VTableUses.push_back(Record[Idx++]);
2984 }
2985 break;
2986
Guy Benyei11169dd2012-12-18 14:30:41 +00002987 case PENDING_IMPLICIT_INSTANTIATIONS:
2988 if (PendingInstantiations.size() % 2 != 0) {
2989 Error("Invalid existing PendingInstantiations");
Ben Langmuir2c9af442014-04-10 17:57:43 +00002990 return Failure;
Guy Benyei11169dd2012-12-18 14:30:41 +00002991 }
2992
2993 if (Record.size() % 2 != 0) {
2994 Error("Invalid PENDING_IMPLICIT_INSTANTIATIONS block");
Ben Langmuir2c9af442014-04-10 17:57:43 +00002995 return Failure;
Guy Benyei11169dd2012-12-18 14:30:41 +00002996 }
2997
2998 for (unsigned I = 0, N = Record.size(); I != N; /* in loop */) {
2999 PendingInstantiations.push_back(getGlobalDeclID(F, Record[I++]));
3000 PendingInstantiations.push_back(
3001 ReadSourceLocation(F, Record, I).getRawEncoding());
3002 }
3003 break;
3004
3005 case SEMA_DECL_REFS:
Richard Smith96269c52016-09-29 22:49:46 +00003006 if (Record.size() != 3) {
Richard Smith3d8e97e2013-10-18 06:54:39 +00003007 Error("Invalid SEMA_DECL_REFS block");
Ben Langmuir2c9af442014-04-10 17:57:43 +00003008 return Failure;
Richard Smith3d8e97e2013-10-18 06:54:39 +00003009 }
Guy Benyei11169dd2012-12-18 14:30:41 +00003010 for (unsigned I = 0, N = Record.size(); I != N; ++I)
3011 SemaDeclRefs.push_back(getGlobalDeclID(F, Record[I]));
3012 break;
3013
3014 case PPD_ENTITIES_OFFSETS: {
Chris Lattner0e6c9402013-01-20 02:38:54 +00003015 F.PreprocessedEntityOffsets = (const PPEntityOffset *)Blob.data();
3016 assert(Blob.size() % sizeof(PPEntityOffset) == 0);
3017 F.NumPreprocessedEntities = Blob.size() / sizeof(PPEntityOffset);
Guy Benyei11169dd2012-12-18 14:30:41 +00003018
3019 unsigned LocalBasePreprocessedEntityID = Record[0];
David L. Jonesc4808b9e2016-12-15 20:53:26 +00003020
Guy Benyei11169dd2012-12-18 14:30:41 +00003021 unsigned StartingID;
3022 if (!PP.getPreprocessingRecord())
3023 PP.createPreprocessingRecord();
3024 if (!PP.getPreprocessingRecord()->getExternalSource())
3025 PP.getPreprocessingRecord()->SetExternalSource(*this);
David L. Jonesc4808b9e2016-12-15 20:53:26 +00003026 StartingID
Guy Benyei11169dd2012-12-18 14:30:41 +00003027 = PP.getPreprocessingRecord()
Ben Langmuir52ca6782014-10-20 16:27:32 +00003028 ->allocateLoadedEntities(F.NumPreprocessedEntities);
Guy Benyei11169dd2012-12-18 14:30:41 +00003029 F.BasePreprocessedEntityID = StartingID;
3030
3031 if (F.NumPreprocessedEntities > 0) {
3032 // Introduce the global -> local mapping for preprocessed entities in
3033 // this module.
3034 GlobalPreprocessedEntityMap.insert(std::make_pair(StartingID, &F));
David L. Jonesc4808b9e2016-12-15 20:53:26 +00003035
Guy Benyei11169dd2012-12-18 14:30:41 +00003036 // Introduce the local -> global mapping for preprocessed entities in
3037 // this module.
3038 F.PreprocessedEntityRemap.insertOrReplace(
3039 std::make_pair(LocalBasePreprocessedEntityID,
3040 F.BasePreprocessedEntityID - LocalBasePreprocessedEntityID));
3041 }
3042
3043 break;
3044 }
David L. Jonesc4808b9e2016-12-15 20:53:26 +00003045
Guy Benyei11169dd2012-12-18 14:30:41 +00003046 case DECL_UPDATE_OFFSETS: {
3047 if (Record.size() % 2 != 0) {
3048 Error("invalid DECL_UPDATE_OFFSETS block in AST file");
Ben Langmuir2c9af442014-04-10 17:57:43 +00003049 return Failure;
Guy Benyei11169dd2012-12-18 14:30:41 +00003050 }
Richard Smithcd45dbc2014-04-19 03:48:30 +00003051 for (unsigned I = 0, N = Record.size(); I != N; I += 2) {
3052 GlobalDeclID ID = getGlobalDeclID(F, Record[I]);
3053 DeclUpdateOffsets[ID].push_back(std::make_pair(&F, Record[I + 1]));
3054
3055 // If we've already loaded the decl, perform the updates when we finish
3056 // loading this block.
3057 if (Decl *D = GetExistingDecl(ID))
3058 PendingUpdateRecords.push_back(std::make_pair(ID, D));
3059 }
Guy Benyei11169dd2012-12-18 14:30:41 +00003060 break;
3061 }
3062
Guy Benyei11169dd2012-12-18 14:30:41 +00003063 case OBJC_CATEGORIES_MAP: {
3064 if (F.LocalNumObjCCategoriesInMap != 0) {
3065 Error("duplicate OBJC_CATEGORIES_MAP record in AST file");
Ben Langmuir2c9af442014-04-10 17:57:43 +00003066 return Failure;
Guy Benyei11169dd2012-12-18 14:30:41 +00003067 }
David L. Jonesc4808b9e2016-12-15 20:53:26 +00003068
Guy Benyei11169dd2012-12-18 14:30:41 +00003069 F.LocalNumObjCCategoriesInMap = Record[0];
Chris Lattner0e6c9402013-01-20 02:38:54 +00003070 F.ObjCCategoriesMap = (const ObjCCategoriesInfo *)Blob.data();
Guy Benyei11169dd2012-12-18 14:30:41 +00003071 break;
3072 }
David L. Jonesc4808b9e2016-12-15 20:53:26 +00003073
Guy Benyei11169dd2012-12-18 14:30:41 +00003074 case OBJC_CATEGORIES:
3075 F.ObjCCategories.swap(Record);
3076 break;
Richard Smithc2bb8182015-03-24 06:36:48 +00003077
Guy Benyei11169dd2012-12-18 14:30:41 +00003078 case DIAG_PRAGMA_MAPPINGS:
3079 if (F.PragmaDiagMappings.empty())
3080 F.PragmaDiagMappings.swap(Record);
3081 else
3082 F.PragmaDiagMappings.insert(F.PragmaDiagMappings.end(),
3083 Record.begin(), Record.end());
3084 break;
David L. Jonesc4808b9e2016-12-15 20:53:26 +00003085
Guy Benyei11169dd2012-12-18 14:30:41 +00003086 case CUDA_SPECIAL_DECL_REFS:
3087 // Later tables overwrite earlier ones.
3088 // FIXME: Modules will have trouble with this.
3089 CUDASpecialDeclRefs.clear();
3090 for (unsigned I = 0, N = Record.size(); I != N; ++I)
3091 CUDASpecialDeclRefs.push_back(getGlobalDeclID(F, Record[I]));
3092 break;
3093
3094 case HEADER_SEARCH_TABLE: {
Chris Lattner0e6c9402013-01-20 02:38:54 +00003095 F.HeaderFileInfoTableData = Blob.data();
Guy Benyei11169dd2012-12-18 14:30:41 +00003096 F.LocalNumHeaderFileInfos = Record[1];
Guy Benyei11169dd2012-12-18 14:30:41 +00003097 if (Record[0]) {
3098 F.HeaderFileInfoTable
3099 = HeaderFileInfoLookupTable::Create(
3100 (const unsigned char *)F.HeaderFileInfoTableData + Record[0],
3101 (const unsigned char *)F.HeaderFileInfoTableData,
David L. Jonesc4808b9e2016-12-15 20:53:26 +00003102 HeaderFileInfoTrait(*this, F,
Guy Benyei11169dd2012-12-18 14:30:41 +00003103 &PP.getHeaderSearchInfo(),
Chris Lattner0e6c9402013-01-20 02:38:54 +00003104 Blob.data() + Record[2]));
David L. Jonesc4808b9e2016-12-15 20:53:26 +00003105
Guy Benyei11169dd2012-12-18 14:30:41 +00003106 PP.getHeaderSearchInfo().SetExternalSource(this);
3107 if (!PP.getHeaderSearchInfo().getExternalLookup())
3108 PP.getHeaderSearchInfo().SetExternalLookup(this);
3109 }
3110 break;
3111 }
David L. Jonesc4808b9e2016-12-15 20:53:26 +00003112
Guy Benyei11169dd2012-12-18 14:30:41 +00003113 case FP_PRAGMA_OPTIONS:
3114 // Later tables overwrite earlier ones.
3115 FPPragmaOptions.swap(Record);
3116 break;
3117
3118 case OPENCL_EXTENSIONS:
Yaxun Liu5b746652016-12-18 05:18:55 +00003119 for (unsigned I = 0, E = Record.size(); I != E; ) {
3120 auto Name = ReadString(Record, I);
3121 auto &Opt = OpenCLExtensions.OptMap[Name];
Yaxun Liucc2741c2016-12-18 06:35:06 +00003122 Opt.Supported = Record[I++] != 0;
3123 Opt.Enabled = Record[I++] != 0;
Yaxun Liu5b746652016-12-18 05:18:55 +00003124 Opt.Avail = Record[I++];
3125 Opt.Core = Record[I++];
3126 }
3127 break;
3128
3129 case OPENCL_EXTENSION_TYPES:
3130 for (unsigned I = 0, E = Record.size(); I != E;) {
3131 auto TypeID = static_cast<::TypeID>(Record[I++]);
3132 auto *Type = GetType(TypeID).getTypePtr();
3133 auto NumExt = static_cast<unsigned>(Record[I++]);
3134 for (unsigned II = 0; II != NumExt; ++II) {
3135 auto Ext = ReadString(Record, I);
3136 OpenCLTypeExtMap[Type].insert(Ext);
3137 }
3138 }
3139 break;
3140
3141 case OPENCL_EXTENSION_DECLS:
3142 for (unsigned I = 0, E = Record.size(); I != E;) {
3143 auto DeclID = static_cast<::DeclID>(Record[I++]);
3144 auto *Decl = GetDecl(DeclID);
3145 auto NumExt = static_cast<unsigned>(Record[I++]);
3146 for (unsigned II = 0; II != NumExt; ++II) {
3147 auto Ext = ReadString(Record, I);
3148 OpenCLDeclExtMap[Decl].insert(Ext);
3149 }
3150 }
Guy Benyei11169dd2012-12-18 14:30:41 +00003151 break;
3152
3153 case TENTATIVE_DEFINITIONS:
3154 for (unsigned I = 0, N = Record.size(); I != N; ++I)
3155 TentativeDefinitions.push_back(getGlobalDeclID(F, Record[I]));
3156 break;
David L. Jonesc4808b9e2016-12-15 20:53:26 +00003157
Guy Benyei11169dd2012-12-18 14:30:41 +00003158 case KNOWN_NAMESPACES:
3159 for (unsigned I = 0, N = Record.size(); I != N; ++I)
3160 KnownNamespaces.push_back(getGlobalDeclID(F, Record[I]));
3161 break;
Nick Lewycky8334af82013-01-26 00:35:08 +00003162
Nick Lewycky9c7eb1d2013-02-01 08:13:20 +00003163 case UNDEFINED_BUT_USED:
3164 if (UndefinedButUsed.size() % 2 != 0) {
3165 Error("Invalid existing UndefinedButUsed");
Ben Langmuir2c9af442014-04-10 17:57:43 +00003166 return Failure;
Nick Lewycky8334af82013-01-26 00:35:08 +00003167 }
3168
3169 if (Record.size() % 2 != 0) {
Nick Lewycky9c7eb1d2013-02-01 08:13:20 +00003170 Error("invalid undefined-but-used record");
Ben Langmuir2c9af442014-04-10 17:57:43 +00003171 return Failure;
Nick Lewycky8334af82013-01-26 00:35:08 +00003172 }
3173 for (unsigned I = 0, N = Record.size(); I != N; /* in loop */) {
Nick Lewycky9c7eb1d2013-02-01 08:13:20 +00003174 UndefinedButUsed.push_back(getGlobalDeclID(F, Record[I++]));
3175 UndefinedButUsed.push_back(
Nick Lewycky8334af82013-01-26 00:35:08 +00003176 ReadSourceLocation(F, Record, I).getRawEncoding());
3177 }
3178 break;
Ismail Pazarbasie5768d12015-05-18 19:59:11 +00003179 case DELETE_EXPRS_TO_ANALYZE:
3180 for (unsigned I = 0, N = Record.size(); I != N;) {
3181 DelayedDeleteExprs.push_back(getGlobalDeclID(F, Record[I++]));
3182 const uint64_t Count = Record[I++];
3183 DelayedDeleteExprs.push_back(Count);
3184 for (uint64_t C = 0; C < Count; ++C) {
3185 DelayedDeleteExprs.push_back(ReadSourceLocation(F, Record, I).getRawEncoding());
3186 bool IsArrayForm = Record[I++] == 1;
3187 DelayedDeleteExprs.push_back(IsArrayForm);
3188 }
3189 }
3190 break;
Nick Lewycky8334af82013-01-26 00:35:08 +00003191
Guy Benyei11169dd2012-12-18 14:30:41 +00003192 case IMPORTED_MODULES: {
Manman Ren11f2a472016-08-18 17:42:15 +00003193 if (!F.isModule()) {
Guy Benyei11169dd2012-12-18 14:30:41 +00003194 // If we aren't loading a module (which has its own exports), make
3195 // all of the imported modules visible.
3196 // FIXME: Deal with macros-only imports.
Richard Smith56be7542014-03-21 00:33:59 +00003197 for (unsigned I = 0, N = Record.size(); I != N; /**/) {
3198 unsigned GlobalID = getGlobalSubmoduleID(F, Record[I++]);
3199 SourceLocation Loc = ReadSourceLocation(F, Record, I);
Graydon Hoare9c982442017-01-18 20:36:59 +00003200 if (GlobalID) {
Aaron Ballman4f45b712014-03-21 15:22:56 +00003201 ImportedModules.push_back(ImportedSubmodule(GlobalID, Loc));
Graydon Hoare9c982442017-01-18 20:36:59 +00003202 if (DeserializationListener)
3203 DeserializationListener->ModuleImportRead(GlobalID, Loc);
3204 }
Guy Benyei11169dd2012-12-18 14:30:41 +00003205 }
3206 }
3207 break;
3208 }
3209
Guy Benyei11169dd2012-12-18 14:30:41 +00003210 case MACRO_OFFSET: {
3211 if (F.LocalNumMacros != 0) {
3212 Error("duplicate MACRO_OFFSET record in AST file");
Ben Langmuir2c9af442014-04-10 17:57:43 +00003213 return Failure;
Guy Benyei11169dd2012-12-18 14:30:41 +00003214 }
Chris Lattner0e6c9402013-01-20 02:38:54 +00003215 F.MacroOffsets = (const uint32_t *)Blob.data();
Guy Benyei11169dd2012-12-18 14:30:41 +00003216 F.LocalNumMacros = Record[0];
3217 unsigned LocalBaseMacroID = Record[1];
3218 F.BaseMacroID = getTotalNumMacros();
3219
3220 if (F.LocalNumMacros > 0) {
3221 // Introduce the global -> local mapping for macros within this module.
3222 GlobalMacroMap.insert(std::make_pair(getTotalNumMacros() + 1, &F));
3223
3224 // Introduce the local -> global mapping for macros within this module.
3225 F.MacroRemap.insertOrReplace(
3226 std::make_pair(LocalBaseMacroID,
3227 F.BaseMacroID - LocalBaseMacroID));
Ben Langmuir52ca6782014-10-20 16:27:32 +00003228
3229 MacrosLoaded.resize(MacrosLoaded.size() + F.LocalNumMacros);
Guy Benyei11169dd2012-12-18 14:30:41 +00003230 }
3231 break;
3232 }
3233
Richard Smithe40f2ba2013-08-07 21:41:30 +00003234 case LATE_PARSED_TEMPLATE: {
3235 LateParsedTemplates.append(Record.begin(), Record.end());
3236 break;
3237 }
Dario Domizioli13a0a382014-05-23 12:13:25 +00003238
3239 case OPTIMIZE_PRAGMA_OPTIONS:
3240 if (Record.size() != 1) {
3241 Error("invalid pragma optimize record");
3242 return Failure;
3243 }
3244 OptimizeOffPragmaLocation = ReadSourceLocation(F, Record[0]);
3245 break;
Nico Weber72889432014-09-06 01:25:55 +00003246
Nico Weber779355f2016-03-02 23:22:00 +00003247 case MSSTRUCT_PRAGMA_OPTIONS:
3248 if (Record.size() != 1) {
3249 Error("invalid pragma ms_struct record");
3250 return Failure;
3251 }
3252 PragmaMSStructState = Record[0];
3253 break;
3254
Nico Weber42932312016-03-03 00:17:35 +00003255 case POINTERS_TO_MEMBERS_PRAGMA_OPTIONS:
3256 if (Record.size() != 2) {
3257 Error("invalid pragma ms_struct record");
3258 return Failure;
3259 }
3260 PragmaMSPointersToMembersState = Record[0];
3261 PointersToMembersPragmaLocation = ReadSourceLocation(F, Record[1]);
3262 break;
3263
Nico Weber72889432014-09-06 01:25:55 +00003264 case UNUSED_LOCAL_TYPEDEF_NAME_CANDIDATES:
3265 for (unsigned I = 0, N = Record.size(); I != N; ++I)
3266 UnusedLocalTypedefNameCandidates.push_back(
3267 getGlobalDeclID(F, Record[I]));
3268 break;
Justin Lebar67a78a62016-10-08 22:15:58 +00003269
3270 case CUDA_PRAGMA_FORCE_HOST_DEVICE_DEPTH:
3271 if (Record.size() != 1) {
3272 Error("invalid cuda pragma options record");
3273 return Failure;
3274 }
3275 ForceCUDAHostDeviceDepth = Record[0];
3276 break;
Guy Benyei11169dd2012-12-18 14:30:41 +00003277 }
3278 }
Guy Benyei11169dd2012-12-18 14:30:41 +00003279}
3280
Richard Smith37a93df2017-02-18 00:32:02 +00003281void ASTReader::ReadModuleOffsetMap(ModuleFile &F) const {
3282 assert(!F.ModuleOffsetMap.empty() && "no module offset map to read");
3283
3284 // Additional remapping information.
3285 const unsigned char *Data = (const unsigned char*)F.ModuleOffsetMap.data();
3286 const unsigned char *DataEnd = Data + F.ModuleOffsetMap.size();
3287 F.ModuleOffsetMap = StringRef();
3288
3289 // If we see this entry before SOURCE_LOCATION_OFFSETS, add placeholders.
3290 if (F.SLocRemap.find(0) == F.SLocRemap.end()) {
3291 F.SLocRemap.insert(std::make_pair(0U, 0));
3292 F.SLocRemap.insert(std::make_pair(2U, 1));
3293 }
3294
3295 // Continuous range maps we may be updating in our module.
3296 typedef ContinuousRangeMap<uint32_t, int, 2>::Builder
3297 RemapBuilder;
3298 RemapBuilder SLocRemap(F.SLocRemap);
3299 RemapBuilder IdentifierRemap(F.IdentifierRemap);
3300 RemapBuilder MacroRemap(F.MacroRemap);
3301 RemapBuilder PreprocessedEntityRemap(F.PreprocessedEntityRemap);
3302 RemapBuilder SubmoduleRemap(F.SubmoduleRemap);
3303 RemapBuilder SelectorRemap(F.SelectorRemap);
3304 RemapBuilder DeclRemap(F.DeclRemap);
3305 RemapBuilder TypeRemap(F.TypeRemap);
3306
3307 while (Data < DataEnd) {
3308 // FIXME: Looking up dependency modules by filename is horrible.
3309 using namespace llvm::support;
3310 uint16_t Len = endian::readNext<uint16_t, little, unaligned>(Data);
3311 StringRef Name = StringRef((const char*)Data, Len);
3312 Data += Len;
3313 ModuleFile *OM = ModuleMgr.lookup(Name);
3314 if (!OM) {
3315 std::string Msg =
3316 "SourceLocation remap refers to unknown module, cannot find ";
3317 Msg.append(Name);
3318 Error(Msg);
3319 return;
3320 }
3321
3322 uint32_t SLocOffset =
3323 endian::readNext<uint32_t, little, unaligned>(Data);
3324 uint32_t IdentifierIDOffset =
3325 endian::readNext<uint32_t, little, unaligned>(Data);
3326 uint32_t MacroIDOffset =
3327 endian::readNext<uint32_t, little, unaligned>(Data);
3328 uint32_t PreprocessedEntityIDOffset =
3329 endian::readNext<uint32_t, little, unaligned>(Data);
3330 uint32_t SubmoduleIDOffset =
3331 endian::readNext<uint32_t, little, unaligned>(Data);
3332 uint32_t SelectorIDOffset =
3333 endian::readNext<uint32_t, little, unaligned>(Data);
3334 uint32_t DeclIDOffset =
3335 endian::readNext<uint32_t, little, unaligned>(Data);
3336 uint32_t TypeIndexOffset =
3337 endian::readNext<uint32_t, little, unaligned>(Data);
3338
3339 uint32_t None = std::numeric_limits<uint32_t>::max();
3340
3341 auto mapOffset = [&](uint32_t Offset, uint32_t BaseOffset,
3342 RemapBuilder &Remap) {
3343 if (Offset != None)
3344 Remap.insert(std::make_pair(Offset,
3345 static_cast<int>(BaseOffset - Offset)));
3346 };
3347 mapOffset(SLocOffset, OM->SLocEntryBaseOffset, SLocRemap);
3348 mapOffset(IdentifierIDOffset, OM->BaseIdentifierID, IdentifierRemap);
3349 mapOffset(MacroIDOffset, OM->BaseMacroID, MacroRemap);
3350 mapOffset(PreprocessedEntityIDOffset, OM->BasePreprocessedEntityID,
3351 PreprocessedEntityRemap);
3352 mapOffset(SubmoduleIDOffset, OM->BaseSubmoduleID, SubmoduleRemap);
3353 mapOffset(SelectorIDOffset, OM->BaseSelectorID, SelectorRemap);
3354 mapOffset(DeclIDOffset, OM->BaseDeclID, DeclRemap);
3355 mapOffset(TypeIndexOffset, OM->BaseTypeIndex, TypeRemap);
3356
3357 // Global -> local mappings.
3358 F.GlobalToLocalDeclIDs[OM] = DeclIDOffset;
3359 }
3360}
3361
Ben Langmuir4b8a9e92014-08-12 16:42:33 +00003362ASTReader::ASTReadResult
3363ASTReader::ReadModuleMapFileBlock(RecordData &Record, ModuleFile &F,
3364 const ModuleFile *ImportedBy,
3365 unsigned ClientLoadCapabilities) {
3366 unsigned Idx = 0;
Richard Smith7ed1bc92014-12-05 22:42:13 +00003367 F.ModuleMapPath = ReadPath(F, Record, Idx);
Ben Langmuir4b8a9e92014-08-12 16:42:33 +00003368
Manman Ren11f2a472016-08-18 17:42:15 +00003369 if (F.Kind == MK_ExplicitModule || F.Kind == MK_PrebuiltModule) {
Richard Smithe842a472014-10-22 02:05:46 +00003370 // For an explicitly-loaded module, we don't care whether the original
3371 // module map file exists or matches.
3372 return Success;
3373 }
3374
Ben Langmuir4b8a9e92014-08-12 16:42:33 +00003375 // Try to resolve ModuleName in the current header search context and
3376 // verify that it is found in the same module map file as we saved. If the
3377 // top-level AST file is a main file, skip this check because there is no
3378 // usable header search context.
3379 assert(!F.ModuleName.empty() &&
Richard Smithe842a472014-10-22 02:05:46 +00003380 "MODULE_NAME should come before MODULE_MAP_FILE");
Duncan P. N. Exon Smith96a06e02017-01-28 22:15:22 +00003381 if (F.Kind == MK_ImplicitModule && ModuleMgr.begin()->Kind != MK_MainFile) {
Richard Smithe842a472014-10-22 02:05:46 +00003382 // An implicitly-loaded module file should have its module listed in some
3383 // module map file that we've already loaded.
Ben Langmuir4b8a9e92014-08-12 16:42:33 +00003384 Module *M = PP.getHeaderSearchInfo().lookupModule(F.ModuleName);
Richard Smithe842a472014-10-22 02:05:46 +00003385 auto &Map = PP.getHeaderSearchInfo().getModuleMap();
3386 const FileEntry *ModMap = M ? Map.getModuleMapFileForUniquing(M) : nullptr;
3387 if (!ModMap) {
Ben Langmuir4b8a9e92014-08-12 16:42:33 +00003388 assert(ImportedBy && "top-level import should be verified");
Richard Smith0f99d6a2015-08-09 08:48:41 +00003389 if ((ClientLoadCapabilities & ARR_OutOfDate) == 0) {
3390 if (auto *ASTFE = M ? M->getASTFile() : nullptr)
3391 // This module was defined by an imported (explicit) module.
3392 Diag(diag::err_module_file_conflict) << F.ModuleName << F.FileName
3393 << ASTFE->getName();
3394 else
3395 // This module was built with a different module map.
3396 Diag(diag::err_imported_module_not_found)
3397 << F.ModuleName << F.FileName << ImportedBy->FileName
3398 << F.ModuleMapPath;
3399 }
3400 return OutOfDate;
Ben Langmuir4b8a9e92014-08-12 16:42:33 +00003401 }
3402
Richard Smithe842a472014-10-22 02:05:46 +00003403 assert(M->Name == F.ModuleName && "found module with different name");
3404
Ben Langmuir4b8a9e92014-08-12 16:42:33 +00003405 // Check the primary module map file.
Ben Langmuir4b8a9e92014-08-12 16:42:33 +00003406 const FileEntry *StoredModMap = FileMgr.getFile(F.ModuleMapPath);
Ben Langmuir4b8a9e92014-08-12 16:42:33 +00003407 if (StoredModMap == nullptr || StoredModMap != ModMap) {
3408 assert(ModMap && "found module is missing module map file");
Ben Langmuir4b8a9e92014-08-12 16:42:33 +00003409 assert(ImportedBy && "top-level import should be verified");
3410 if ((ClientLoadCapabilities & ARR_OutOfDate) == 0)
3411 Diag(diag::err_imported_module_modmap_changed)
3412 << F.ModuleName << ImportedBy->FileName
3413 << ModMap->getName() << F.ModuleMapPath;
3414 return OutOfDate;
3415 }
3416
3417 llvm::SmallPtrSet<const FileEntry *, 1> AdditionalStoredMaps;
3418 for (unsigned I = 0, N = Record[Idx++]; I < N; ++I) {
3419 // FIXME: we should use input files rather than storing names.
Richard Smith7ed1bc92014-12-05 22:42:13 +00003420 std::string Filename = ReadPath(F, Record, Idx);
Ben Langmuir4b8a9e92014-08-12 16:42:33 +00003421 const FileEntry *F =
3422 FileMgr.getFile(Filename, false, false);
3423 if (F == nullptr) {
3424 if ((ClientLoadCapabilities & ARR_OutOfDate) == 0)
3425 Error("could not find file '" + Filename +"' referenced by AST file");
3426 return OutOfDate;
3427 }
3428 AdditionalStoredMaps.insert(F);
3429 }
3430
3431 // Check any additional module map files (e.g. module.private.modulemap)
3432 // that are not in the pcm.
3433 if (auto *AdditionalModuleMaps = Map.getAdditionalModuleMapFiles(M)) {
3434 for (const FileEntry *ModMap : *AdditionalModuleMaps) {
3435 // Remove files that match
3436 // Note: SmallPtrSet::erase is really remove
3437 if (!AdditionalStoredMaps.erase(ModMap)) {
3438 if ((ClientLoadCapabilities & ARR_OutOfDate) == 0)
3439 Diag(diag::err_module_different_modmap)
3440 << F.ModuleName << /*new*/0 << ModMap->getName();
3441 return OutOfDate;
3442 }
3443 }
3444 }
3445
3446 // Check any additional module map files that are in the pcm, but not
3447 // found in header search. Cases that match are already removed.
3448 for (const FileEntry *ModMap : AdditionalStoredMaps) {
3449 if ((ClientLoadCapabilities & ARR_OutOfDate) == 0)
3450 Diag(diag::err_module_different_modmap)
3451 << F.ModuleName << /*not new*/1 << ModMap->getName();
3452 return OutOfDate;
3453 }
3454 }
3455
3456 if (Listener)
3457 Listener->ReadModuleMapFile(F.ModuleMapPath);
3458 return Success;
3459}
3460
3461
Douglas Gregorc1489562013-02-12 23:36:21 +00003462/// \brief Move the given method to the back of the global list of methods.
3463static void moveMethodToBackOfGlobalList(Sema &S, ObjCMethodDecl *Method) {
3464 // Find the entry for this selector in the method pool.
3465 Sema::GlobalMethodPool::iterator Known
3466 = S.MethodPool.find(Method->getSelector());
3467 if (Known == S.MethodPool.end())
3468 return;
3469
3470 // Retrieve the appropriate method list.
3471 ObjCMethodList &Start = Method->isInstanceMethod()? Known->second.first
3472 : Known->second.second;
3473 bool Found = false;
Argyrios Kyrtzidisd3da6e02013-04-17 00:08:58 +00003474 for (ObjCMethodList *List = &Start; List; List = List->getNext()) {
Douglas Gregorc1489562013-02-12 23:36:21 +00003475 if (!Found) {
Nico Weber2e0c8f72014-12-27 03:58:08 +00003476 if (List->getMethod() == Method) {
Douglas Gregorc1489562013-02-12 23:36:21 +00003477 Found = true;
3478 } else {
3479 // Keep searching.
3480 continue;
3481 }
3482 }
3483
Argyrios Kyrtzidisd3da6e02013-04-17 00:08:58 +00003484 if (List->getNext())
Nico Weber2e0c8f72014-12-27 03:58:08 +00003485 List->setMethod(List->getNext()->getMethod());
Douglas Gregorc1489562013-02-12 23:36:21 +00003486 else
Nico Weber2e0c8f72014-12-27 03:58:08 +00003487 List->setMethod(Method);
Douglas Gregorc1489562013-02-12 23:36:21 +00003488 }
3489}
3490
Richard Smithde711422015-04-23 21:20:19 +00003491void ASTReader::makeNamesVisible(const HiddenNames &Names, Module *Owner) {
Richard Smith10434f32015-05-02 02:08:26 +00003492 assert(Owner->NameVisibility != Module::Hidden && "nothing to make visible?");
Richard Smith20e883e2015-04-29 23:20:19 +00003493 for (Decl *D : Names) {
Richard Smith49f906a2014-03-01 00:08:04 +00003494 bool wasHidden = D->Hidden;
3495 D->Hidden = false;
Guy Benyei11169dd2012-12-18 14:30:41 +00003496
Richard Smith49f906a2014-03-01 00:08:04 +00003497 if (wasHidden && SemaObj) {
3498 if (ObjCMethodDecl *Method = dyn_cast<ObjCMethodDecl>(D)) {
3499 moveMethodToBackOfGlobalList(*SemaObj, Method);
Douglas Gregorc1489562013-02-12 23:36:21 +00003500 }
Guy Benyei11169dd2012-12-18 14:30:41 +00003501 }
3502 }
3503}
3504
Richard Smith49f906a2014-03-01 00:08:04 +00003505void ASTReader::makeModuleVisible(Module *Mod,
Argyrios Kyrtzidis125df052013-02-01 16:36:12 +00003506 Module::NameVisibilityKind NameVisibility,
Richard Smitha7e2cc62015-05-01 01:53:09 +00003507 SourceLocation ImportLoc) {
Guy Benyei11169dd2012-12-18 14:30:41 +00003508 llvm::SmallPtrSet<Module *, 4> Visited;
Dmitri Gribenkof8579502013-01-12 19:30:44 +00003509 SmallVector<Module *, 4> Stack;
Robert Wilhelm25284cc2013-08-23 16:11:15 +00003510 Stack.push_back(Mod);
Guy Benyei11169dd2012-12-18 14:30:41 +00003511 while (!Stack.empty()) {
Robert Wilhelm25284cc2013-08-23 16:11:15 +00003512 Mod = Stack.pop_back_val();
Guy Benyei11169dd2012-12-18 14:30:41 +00003513
3514 if (NameVisibility <= Mod->NameVisibility) {
Robert Wilhelm25284cc2013-08-23 16:11:15 +00003515 // This module already has this level of visibility (or greater), so
Guy Benyei11169dd2012-12-18 14:30:41 +00003516 // there is nothing more to do.
3517 continue;
3518 }
Richard Smith49f906a2014-03-01 00:08:04 +00003519
Guy Benyei11169dd2012-12-18 14:30:41 +00003520 if (!Mod->isAvailable()) {
3521 // Modules that aren't available cannot be made visible.
3522 continue;
3523 }
3524
3525 // Update the module's name visibility.
3526 Mod->NameVisibility = NameVisibility;
Richard Smith49f906a2014-03-01 00:08:04 +00003527
Guy Benyei11169dd2012-12-18 14:30:41 +00003528 // If we've already deserialized any names from this module,
3529 // mark them as visible.
3530 HiddenNamesMapType::iterator Hidden = HiddenNamesMap.find(Mod);
3531 if (Hidden != HiddenNamesMap.end()) {
Richard Smith57721ac2014-07-21 04:10:40 +00003532 auto HiddenNames = std::move(*Hidden);
Guy Benyei11169dd2012-12-18 14:30:41 +00003533 HiddenNamesMap.erase(Hidden);
Richard Smithde711422015-04-23 21:20:19 +00003534 makeNamesVisible(HiddenNames.second, HiddenNames.first);
Richard Smith57721ac2014-07-21 04:10:40 +00003535 assert(HiddenNamesMap.find(Mod) == HiddenNamesMap.end() &&
3536 "making names visible added hidden names");
Guy Benyei11169dd2012-12-18 14:30:41 +00003537 }
Dmitri Gribenkoe9bcf5b2013-11-04 21:51:33 +00003538
Guy Benyei11169dd2012-12-18 14:30:41 +00003539 // Push any exported modules onto the stack to be marked as visible.
Argyrios Kyrtzidis8739f7b2013-02-19 19:34:40 +00003540 SmallVector<Module *, 16> Exports;
3541 Mod->getExportedModules(Exports);
3542 for (SmallVectorImpl<Module *>::iterator
3543 I = Exports.begin(), E = Exports.end(); I != E; ++I) {
3544 Module *Exported = *I;
David Blaikie82e95a32014-11-19 07:49:47 +00003545 if (Visited.insert(Exported).second)
Argyrios Kyrtzidis8739f7b2013-02-19 19:34:40 +00003546 Stack.push_back(Exported);
Guy Benyei11169dd2012-12-18 14:30:41 +00003547 }
3548 }
3549}
3550
Richard Smith6561f922016-09-12 21:06:40 +00003551/// We've merged the definition \p MergedDef into the existing definition
3552/// \p Def. Ensure that \p Def is made visible whenever \p MergedDef is made
3553/// visible.
3554void ASTReader::mergeDefinitionVisibility(NamedDecl *Def,
3555 NamedDecl *MergedDef) {
Benjamin Kramera72a70a2016-10-17 13:00:44 +00003556 // FIXME: This doesn't correctly handle the case where MergedDef is visible
3557 // in modules other than its owning module. We should instead give the
3558 // ASTContext a list of merged definitions for Def.
Richard Smith6561f922016-09-12 21:06:40 +00003559 if (Def->isHidden()) {
3560 // If MergedDef is visible or becomes visible, make the definition visible.
Benjamin Kramera72a70a2016-10-17 13:00:44 +00003561 if (!MergedDef->isHidden())
3562 Def->Hidden = false;
3563 else if (getContext().getLangOpts().ModulesLocalVisibility) {
3564 getContext().mergeDefinitionIntoModule(
3565 Def, MergedDef->getImportedOwningModule(),
3566 /*NotifyListeners*/ false);
3567 PendingMergedDefinitionsToDeduplicate.insert(Def);
3568 } else {
3569 auto SubmoduleID = MergedDef->getOwningModuleID();
3570 assert(SubmoduleID && "hidden definition in no module");
3571 HiddenNamesMap[getSubmodule(SubmoduleID)].push_back(Def);
3572 }
Richard Smith6561f922016-09-12 21:06:40 +00003573 }
3574}
3575
Douglas Gregore060e572013-01-25 01:03:03 +00003576bool ASTReader::loadGlobalIndex() {
3577 if (GlobalIndex)
3578 return false;
3579
3580 if (TriedLoadingGlobalIndex || !UseGlobalIndex ||
3581 !Context.getLangOpts().Modules)
3582 return true;
David L. Jonesc4808b9e2016-12-15 20:53:26 +00003583
Douglas Gregore060e572013-01-25 01:03:03 +00003584 // Try to load the global index.
3585 TriedLoadingGlobalIndex = true;
3586 StringRef ModuleCachePath
3587 = getPreprocessor().getHeaderSearchInfo().getModuleCachePath();
3588 std::pair<GlobalModuleIndex *, GlobalModuleIndex::ErrorCode> Result
Douglas Gregor7029ce12013-03-19 00:28:20 +00003589 = GlobalModuleIndex::readIndex(ModuleCachePath);
Douglas Gregore060e572013-01-25 01:03:03 +00003590 if (!Result.first)
3591 return true;
3592
3593 GlobalIndex.reset(Result.first);
Douglas Gregor7211ac12013-01-25 23:32:03 +00003594 ModuleMgr.setGlobalIndex(GlobalIndex.get());
Douglas Gregore060e572013-01-25 01:03:03 +00003595 return false;
3596}
3597
3598bool ASTReader::isGlobalIndexUnavailable() const {
3599 return Context.getLangOpts().Modules && UseGlobalIndex &&
3600 !hasGlobalIndex() && TriedLoadingGlobalIndex;
3601}
3602
Dmitri Gribenkof430da42014-02-12 10:33:14 +00003603static void updateModuleTimestamp(ModuleFile &MF) {
3604 // Overwrite the timestamp file contents so that file's mtime changes.
3605 std::string TimestampFilename = MF.getTimestampFilename();
Rafael Espindoladae941a2014-08-25 18:17:04 +00003606 std::error_code EC;
3607 llvm::raw_fd_ostream OS(TimestampFilename, EC, llvm::sys::fs::F_Text);
3608 if (EC)
Dmitri Gribenkof430da42014-02-12 10:33:14 +00003609 return;
3610 OS << "Timestamp file\n";
3611}
3612
Douglas Gregor6623e1f2015-11-03 18:33:07 +00003613/// \brief Given a cursor at the start of an AST file, scan ahead and drop the
3614/// cursor into the start of the given block ID, returning false on success and
3615/// true on failure.
3616static bool SkipCursorToBlock(BitstreamCursor &Cursor, unsigned BlockID) {
Eugene Zelenkoe95e7d52016-09-07 21:53:17 +00003617 while (true) {
Douglas Gregor6623e1f2015-11-03 18:33:07 +00003618 llvm::BitstreamEntry Entry = Cursor.advance();
3619 switch (Entry.Kind) {
3620 case llvm::BitstreamEntry::Error:
3621 case llvm::BitstreamEntry::EndBlock:
3622 return true;
3623
3624 case llvm::BitstreamEntry::Record:
3625 // Ignore top-level records.
3626 Cursor.skipRecord(Entry.ID);
3627 break;
3628
3629 case llvm::BitstreamEntry::SubBlock:
3630 if (Entry.ID == BlockID) {
3631 if (Cursor.EnterSubBlock(BlockID))
3632 return true;
3633 // Found it!
3634 return false;
3635 }
3636
3637 if (Cursor.SkipBlock())
3638 return true;
3639 }
3640 }
3641}
3642
Benjamin Kramer0772c422016-02-13 13:42:54 +00003643ASTReader::ASTReadResult ASTReader::ReadAST(StringRef FileName,
Guy Benyei11169dd2012-12-18 14:30:41 +00003644 ModuleKind Type,
3645 SourceLocation ImportLoc,
Graydon Hoaree7196af2016-12-09 21:45:49 +00003646 unsigned ClientLoadCapabilities,
3647 SmallVectorImpl<ImportedSubmodule> *Imported) {
Argyrios Kyrtzidisdc9fdaf2013-05-24 05:44:08 +00003648 llvm::SaveAndRestore<SourceLocation>
3649 SetCurImportLocRAII(CurrentImportLoc, ImportLoc);
3650
Richard Smithd1c46742014-04-30 02:24:17 +00003651 // Defer any pending actions until we get to the end of reading the AST file.
3652 Deserializing AnASTFile(this);
3653
Guy Benyei11169dd2012-12-18 14:30:41 +00003654 // Bump the generation number.
Richard Smith053f6c62014-05-16 23:01:30 +00003655 unsigned PreviousGeneration = incrementGeneration(Context);
Guy Benyei11169dd2012-12-18 14:30:41 +00003656
3657 unsigned NumModules = ModuleMgr.size();
Dmitri Gribenkof8579502013-01-12 19:30:44 +00003658 SmallVector<ImportedModule, 4> Loaded;
Guy Benyei11169dd2012-12-18 14:30:41 +00003659 switch(ASTReadResult ReadResult = ReadASTCore(FileName, Type, ImportLoc,
Craig Toppera13603a2014-05-22 05:54:18 +00003660 /*ImportedBy=*/nullptr, Loaded,
Ben Langmuir487ea142014-10-23 18:05:36 +00003661 0, 0, 0,
Guy Benyei11169dd2012-12-18 14:30:41 +00003662 ClientLoadCapabilities)) {
3663 case Failure:
Douglas Gregor7029ce12013-03-19 00:28:20 +00003664 case Missing:
Guy Benyei11169dd2012-12-18 14:30:41 +00003665 case OutOfDate:
3666 case VersionMismatch:
3667 case ConfigurationMismatch:
Ben Langmuir9801b252014-06-20 00:24:56 +00003668 case HadErrors: {
3669 llvm::SmallPtrSet<ModuleFile *, 4> LoadedSet;
3670 for (const ImportedModule &IM : Loaded)
3671 LoadedSet.insert(IM.Mod);
3672
Duncan P. N. Exon Smith8e6bc1972017-01-28 23:02:12 +00003673 ModuleMgr.removeModules(ModuleMgr.begin() + NumModules, LoadedSet,
Douglas Gregor7029ce12013-03-19 00:28:20 +00003674 Context.getLangOpts().Modules
Duncan P. N. Exon Smith8e6bc1972017-01-28 23:02:12 +00003675 ? &PP.getHeaderSearchInfo().getModuleMap()
3676 : nullptr);
Douglas Gregore060e572013-01-25 01:03:03 +00003677
3678 // If we find that any modules are unusable, the global index is going
3679 // to be out-of-date. Just remove it.
3680 GlobalIndex.reset();
Craig Toppera13603a2014-05-22 05:54:18 +00003681 ModuleMgr.setGlobalIndex(nullptr);
Guy Benyei11169dd2012-12-18 14:30:41 +00003682 return ReadResult;
Ben Langmuir9801b252014-06-20 00:24:56 +00003683 }
Guy Benyei11169dd2012-12-18 14:30:41 +00003684 case Success:
3685 break;
3686 }
3687
3688 // Here comes stuff that we only do once the entire chain is loaded.
3689
3690 // Load the AST blocks of all of the modules that we loaded.
Dmitri Gribenkof8579502013-01-12 19:30:44 +00003691 for (SmallVectorImpl<ImportedModule>::iterator M = Loaded.begin(),
3692 MEnd = Loaded.end();
Guy Benyei11169dd2012-12-18 14:30:41 +00003693 M != MEnd; ++M) {
3694 ModuleFile &F = *M->Mod;
3695
3696 // Read the AST block.
Ben Langmuir2c9af442014-04-10 17:57:43 +00003697 if (ASTReadResult Result = ReadASTBlock(F, ClientLoadCapabilities))
3698 return Result;
Guy Benyei11169dd2012-12-18 14:30:41 +00003699
Douglas Gregor6623e1f2015-11-03 18:33:07 +00003700 // Read the extension blocks.
3701 while (!SkipCursorToBlock(F.Stream, EXTENSION_BLOCK_ID)) {
3702 if (ASTReadResult Result = ReadExtensionBlock(F))
3703 return Result;
3704 }
3705
David L. Jonesc4808b9e2016-12-15 20:53:26 +00003706 // Once read, set the ModuleFile bit base offset and update the size in
Guy Benyei11169dd2012-12-18 14:30:41 +00003707 // bits of all files we've seen.
3708 F.GlobalBitOffset = TotalModulesSizeInBits;
3709 TotalModulesSizeInBits += F.SizeInBits;
3710 GlobalBitOffsetsMap.insert(std::make_pair(F.GlobalBitOffset, &F));
David L. Jonesc4808b9e2016-12-15 20:53:26 +00003711
Guy Benyei11169dd2012-12-18 14:30:41 +00003712 // Preload SLocEntries.
3713 for (unsigned I = 0, N = F.PreloadSLocEntries.size(); I != N; ++I) {
3714 int Index = int(F.PreloadSLocEntries[I] - 1) + F.SLocEntryBaseID;
3715 // Load it through the SourceManager and don't call ReadSLocEntry()
3716 // directly because the entry may have already been loaded in which case
3717 // calling ReadSLocEntry() directly would trigger an assertion in
3718 // SourceManager.
3719 SourceMgr.getLoadedSLocEntryByID(Index);
3720 }
Richard Smith33e0f7e2015-07-22 02:08:40 +00003721
3722 // Preload all the pending interesting identifiers by marking them out of
3723 // date.
3724 for (auto Offset : F.PreloadIdentifierOffsets) {
3725 const unsigned char *Data = reinterpret_cast<const unsigned char *>(
3726 F.IdentifierTableData + Offset);
3727
3728 ASTIdentifierLookupTrait Trait(*this, F);
3729 auto KeyDataLen = Trait.ReadKeyDataLength(Data);
3730 auto Key = Trait.ReadKey(Data, KeyDataLen.first);
Richard Smith79bf9202015-08-24 03:33:22 +00003731 auto &II = PP.getIdentifierTable().getOwn(Key);
3732 II.setOutOfDate(true);
3733
3734 // Mark this identifier as being from an AST file so that we can track
3735 // whether we need to serialize it.
Richard Smitheb4b58f62016-02-05 01:40:54 +00003736 markIdentifierFromAST(*this, II);
Richard Smith79bf9202015-08-24 03:33:22 +00003737
3738 // Associate the ID with the identifier so that the writer can reuse it.
3739 auto ID = Trait.ReadIdentifierID(Data + KeyDataLen.first);
3740 SetIdentifierInfo(ID, &II);
Richard Smith33e0f7e2015-07-22 02:08:40 +00003741 }
Guy Benyei11169dd2012-12-18 14:30:41 +00003742 }
3743
Douglas Gregor603cd862013-03-22 18:50:14 +00003744 // Setup the import locations and notify the module manager that we've
3745 // committed to these module files.
Dmitri Gribenkof8579502013-01-12 19:30:44 +00003746 for (SmallVectorImpl<ImportedModule>::iterator M = Loaded.begin(),
3747 MEnd = Loaded.end();
Guy Benyei11169dd2012-12-18 14:30:41 +00003748 M != MEnd; ++M) {
3749 ModuleFile &F = *M->Mod;
Douglas Gregor603cd862013-03-22 18:50:14 +00003750
3751 ModuleMgr.moduleFileAccepted(&F);
3752
3753 // Set the import location.
Argyrios Kyrtzidis71c1af82013-02-01 16:36:14 +00003754 F.DirectImportLoc = ImportLoc;
Richard Smithb22a1d12016-03-27 20:13:24 +00003755 // FIXME: We assume that locations from PCH / preamble do not need
3756 // any translation.
Guy Benyei11169dd2012-12-18 14:30:41 +00003757 if (!M->ImportedBy)
3758 F.ImportLoc = M->ImportLoc;
3759 else
Richard Smithb22a1d12016-03-27 20:13:24 +00003760 F.ImportLoc = TranslateSourceLocation(*M->ImportedBy, M->ImportLoc);
Guy Benyei11169dd2012-12-18 14:30:41 +00003761 }
3762
Richard Smith33e0f7e2015-07-22 02:08:40 +00003763 if (!Context.getLangOpts().CPlusPlus ||
Manman Ren11f2a472016-08-18 17:42:15 +00003764 (Type != MK_ImplicitModule && Type != MK_ExplicitModule &&
3765 Type != MK_PrebuiltModule)) {
Richard Smith33e0f7e2015-07-22 02:08:40 +00003766 // Mark all of the identifiers in the identifier table as being out of date,
3767 // so that various accessors know to check the loaded modules when the
3768 // identifier is used.
3769 //
3770 // For C++ modules, we don't need information on many identifiers (just
3771 // those that provide macros or are poisoned), so we mark all of
3772 // the interesting ones via PreloadIdentifierOffsets.
3773 for (IdentifierTable::iterator Id = PP.getIdentifierTable().begin(),
3774 IdEnd = PP.getIdentifierTable().end();
3775 Id != IdEnd; ++Id)
3776 Id->second->setOutOfDate(true);
3777 }
Manman Rena0f31a02016-04-29 19:04:05 +00003778 // Mark selectors as out of date.
3779 for (auto Sel : SelectorGeneration)
3780 SelectorOutOfDate[Sel.first] = true;
David L. Jonesc4808b9e2016-12-15 20:53:26 +00003781
Guy Benyei11169dd2012-12-18 14:30:41 +00003782 // Resolve any unresolved module exports.
Douglas Gregorfb912652013-03-20 21:10:35 +00003783 for (unsigned I = 0, N = UnresolvedModuleRefs.size(); I != N; ++I) {
3784 UnresolvedModuleRef &Unresolved = UnresolvedModuleRefs[I];
Guy Benyei11169dd2012-12-18 14:30:41 +00003785 SubmoduleID GlobalID = getGlobalSubmoduleID(*Unresolved.File,Unresolved.ID);
3786 Module *ResolvedMod = getSubmodule(GlobalID);
Douglas Gregorfb912652013-03-20 21:10:35 +00003787
3788 switch (Unresolved.Kind) {
3789 case UnresolvedModuleRef::Conflict:
3790 if (ResolvedMod) {
3791 Module::Conflict Conflict;
3792 Conflict.Other = ResolvedMod;
3793 Conflict.Message = Unresolved.String.str();
3794 Unresolved.Mod->Conflicts.push_back(Conflict);
3795 }
3796 continue;
3797
3798 case UnresolvedModuleRef::Import:
Guy Benyei11169dd2012-12-18 14:30:41 +00003799 if (ResolvedMod)
Richard Smith38477db2015-05-02 00:45:56 +00003800 Unresolved.Mod->Imports.insert(ResolvedMod);
Guy Benyei11169dd2012-12-18 14:30:41 +00003801 continue;
Guy Benyei11169dd2012-12-18 14:30:41 +00003802
Douglas Gregorfb912652013-03-20 21:10:35 +00003803 case UnresolvedModuleRef::Export:
3804 if (ResolvedMod || Unresolved.IsWildcard)
3805 Unresolved.Mod->Exports.push_back(
3806 Module::ExportDecl(ResolvedMod, Unresolved.IsWildcard));
3807 continue;
3808 }
Guy Benyei11169dd2012-12-18 14:30:41 +00003809 }
Douglas Gregorfb912652013-03-20 21:10:35 +00003810 UnresolvedModuleRefs.clear();
Daniel Jasperba7f2f72013-09-24 09:14:14 +00003811
Graydon Hoaree7196af2016-12-09 21:45:49 +00003812 if (Imported)
3813 Imported->append(ImportedModules.begin(),
3814 ImportedModules.end());
3815
Daniel Jasperba7f2f72013-09-24 09:14:14 +00003816 // FIXME: How do we load the 'use'd modules? They may not be submodules.
3817 // Might be unnecessary as use declarations are only used to build the
3818 // module itself.
David L. Jonesc4808b9e2016-12-15 20:53:26 +00003819
Guy Benyei11169dd2012-12-18 14:30:41 +00003820 InitializeContext();
3821
Richard Smith3d8e97e2013-10-18 06:54:39 +00003822 if (SemaObj)
3823 UpdateSema();
3824
Guy Benyei11169dd2012-12-18 14:30:41 +00003825 if (DeserializationListener)
3826 DeserializationListener->ReaderInitialized(this);
3827
3828 ModuleFile &PrimaryModule = ModuleMgr.getPrimaryModule();
Yaron Keren8b563662015-10-03 10:46:20 +00003829 if (PrimaryModule.OriginalSourceFileID.isValid()) {
David L. Jonesc4808b9e2016-12-15 20:53:26 +00003830 PrimaryModule.OriginalSourceFileID
Guy Benyei11169dd2012-12-18 14:30:41 +00003831 = FileID::get(PrimaryModule.SLocEntryBaseID
3832 + PrimaryModule.OriginalSourceFileID.getOpaqueValue() - 1);
3833
3834 // If this AST file is a precompiled preamble, then set the
3835 // preamble file ID of the source manager to the file source file
3836 // from which the preamble was built.
3837 if (Type == MK_Preamble) {
3838 SourceMgr.setPreambleFileID(PrimaryModule.OriginalSourceFileID);
3839 } else if (Type == MK_MainFile) {
3840 SourceMgr.setMainFileID(PrimaryModule.OriginalSourceFileID);
3841 }
3842 }
David L. Jonesc4808b9e2016-12-15 20:53:26 +00003843
Guy Benyei11169dd2012-12-18 14:30:41 +00003844 // For any Objective-C class definitions we have already loaded, make sure
3845 // that we load any additional categories.
3846 for (unsigned I = 0, N = ObjCClassesLoaded.size(); I != N; ++I) {
David L. Jonesc4808b9e2016-12-15 20:53:26 +00003847 loadObjCCategories(ObjCClassesLoaded[I]->getGlobalID(),
Guy Benyei11169dd2012-12-18 14:30:41 +00003848 ObjCClassesLoaded[I],
3849 PreviousGeneration);
3850 }
Douglas Gregore060e572013-01-25 01:03:03 +00003851
Dmitri Gribenkof430da42014-02-12 10:33:14 +00003852 if (PP.getHeaderSearchInfo()
3853 .getHeaderSearchOpts()
3854 .ModulesValidateOncePerBuildSession) {
3855 // Now we are certain that the module and all modules it depends on are
3856 // up to date. Create or update timestamp files for modules that are
3857 // located in the module cache (not for PCH files that could be anywhere
3858 // in the filesystem).
3859 for (unsigned I = 0, N = Loaded.size(); I != N; ++I) {
3860 ImportedModule &M = Loaded[I];
Richard Smithe842a472014-10-22 02:05:46 +00003861 if (M.Mod->Kind == MK_ImplicitModule) {
Dmitri Gribenkof430da42014-02-12 10:33:14 +00003862 updateModuleTimestamp(*M.Mod);
3863 }
3864 }
3865 }
3866
Guy Benyei11169dd2012-12-18 14:30:41 +00003867 return Success;
3868}
3869
Peter Collingbourne77c89b62016-11-08 04:17:11 +00003870static ASTFileSignature readASTFileSignature(StringRef PCH);
Ben Langmuir487ea142014-10-23 18:05:36 +00003871
Ben Langmuir70a1b812015-03-24 04:43:52 +00003872/// \brief Whether \p Stream starts with the AST/PCH file magic number 'CPCH'.
3873static bool startsWithASTFileMagic(BitstreamCursor &Stream) {
Peter Collingbourne028eb5a2016-11-02 00:08:19 +00003874 return Stream.canSkipToPos(4) &&
3875 Stream.Read(8) == 'C' &&
Ben Langmuir70a1b812015-03-24 04:43:52 +00003876 Stream.Read(8) == 'P' &&
3877 Stream.Read(8) == 'C' &&
3878 Stream.Read(8) == 'H';
3879}
3880
Richard Smith0f99d6a2015-08-09 08:48:41 +00003881static unsigned moduleKindForDiagnostic(ModuleKind Kind) {
3882 switch (Kind) {
3883 case MK_PCH:
3884 return 0; // PCH
3885 case MK_ImplicitModule:
3886 case MK_ExplicitModule:
Manman Ren11f2a472016-08-18 17:42:15 +00003887 case MK_PrebuiltModule:
Richard Smith0f99d6a2015-08-09 08:48:41 +00003888 return 1; // module
3889 case MK_MainFile:
3890 case MK_Preamble:
3891 return 2; // main source file
3892 }
3893 llvm_unreachable("unknown module kind");
3894}
3895
Guy Benyei11169dd2012-12-18 14:30:41 +00003896ASTReader::ASTReadResult
3897ASTReader::ReadASTCore(StringRef FileName,
3898 ModuleKind Type,
3899 SourceLocation ImportLoc,
3900 ModuleFile *ImportedBy,
Dmitri Gribenkof8579502013-01-12 19:30:44 +00003901 SmallVectorImpl<ImportedModule> &Loaded,
Douglas Gregor7029ce12013-03-19 00:28:20 +00003902 off_t ExpectedSize, time_t ExpectedModTime,
Ben Langmuir487ea142014-10-23 18:05:36 +00003903 ASTFileSignature ExpectedSignature,
Guy Benyei11169dd2012-12-18 14:30:41 +00003904 unsigned ClientLoadCapabilities) {
3905 ModuleFile *M;
Guy Benyei11169dd2012-12-18 14:30:41 +00003906 std::string ErrorStr;
Douglas Gregor7029ce12013-03-19 00:28:20 +00003907 ModuleManager::AddModuleResult AddResult
3908 = ModuleMgr.addModule(FileName, Type, ImportLoc, ImportedBy,
Richard Smith053f6c62014-05-16 23:01:30 +00003909 getGeneration(), ExpectedSize, ExpectedModTime,
Ben Langmuir487ea142014-10-23 18:05:36 +00003910 ExpectedSignature, readASTFileSignature,
Douglas Gregor7029ce12013-03-19 00:28:20 +00003911 M, ErrorStr);
Guy Benyei11169dd2012-12-18 14:30:41 +00003912
Douglas Gregor7029ce12013-03-19 00:28:20 +00003913 switch (AddResult) {
3914 case ModuleManager::AlreadyLoaded:
3915 return Success;
3916
3917 case ModuleManager::NewlyLoaded:
3918 // Load module file below.
3919 break;
3920
3921 case ModuleManager::Missing:
Richard Smithe842a472014-10-22 02:05:46 +00003922 // The module file was missing; if the client can handle that, return
Douglas Gregor7029ce12013-03-19 00:28:20 +00003923 // it.
3924 if (ClientLoadCapabilities & ARR_Missing)
3925 return Missing;
3926
3927 // Otherwise, return an error.
Richard Smith0f99d6a2015-08-09 08:48:41 +00003928 Diag(diag::err_module_file_not_found) << moduleKindForDiagnostic(Type)
Adrian Prantlb3b5a732016-08-29 20:46:59 +00003929 << FileName << !ErrorStr.empty()
Richard Smith0f99d6a2015-08-09 08:48:41 +00003930 << ErrorStr;
Douglas Gregor7029ce12013-03-19 00:28:20 +00003931 return Failure;
3932
3933 case ModuleManager::OutOfDate:
3934 // We couldn't load the module file because it is out-of-date. If the
3935 // client can handle out-of-date, return it.
3936 if (ClientLoadCapabilities & ARR_OutOfDate)
3937 return OutOfDate;
3938
3939 // Otherwise, return an error.
Richard Smith0f99d6a2015-08-09 08:48:41 +00003940 Diag(diag::err_module_file_out_of_date) << moduleKindForDiagnostic(Type)
Adrian Prantl9a06a882016-08-29 20:46:56 +00003941 << FileName << !ErrorStr.empty()
Richard Smith0f99d6a2015-08-09 08:48:41 +00003942 << ErrorStr;
Guy Benyei11169dd2012-12-18 14:30:41 +00003943 return Failure;
3944 }
3945
Douglas Gregor7029ce12013-03-19 00:28:20 +00003946 assert(M && "Missing module file");
Guy Benyei11169dd2012-12-18 14:30:41 +00003947
3948 // FIXME: This seems rather a hack. Should CurrentDir be part of the
3949 // module?
3950 if (FileName != "-") {
3951 CurrentDir = llvm::sys::path::parent_path(FileName);
3952 if (CurrentDir.empty()) CurrentDir = ".";
3953 }
3954
3955 ModuleFile &F = *M;
Chris Lattner7fb3bef2013-01-20 00:56:42 +00003956 BitstreamCursor &Stream = F.Stream;
Peter Collingbourne77c89b62016-11-08 04:17:11 +00003957 Stream = BitstreamCursor(PCHContainerRdr.ExtractPCH(*F.Buffer));
Adrian Prantlcbc368c2015-02-25 02:44:04 +00003958 F.SizeInBits = F.Buffer->getBufferSize() * 8;
David L. Jonesc4808b9e2016-12-15 20:53:26 +00003959
Guy Benyei11169dd2012-12-18 14:30:41 +00003960 // Sniff for the signature.
Ben Langmuir70a1b812015-03-24 04:43:52 +00003961 if (!startsWithASTFileMagic(Stream)) {
Richard Smith0f99d6a2015-08-09 08:48:41 +00003962 Diag(diag::err_module_file_invalid) << moduleKindForDiagnostic(Type)
3963 << FileName;
Guy Benyei11169dd2012-12-18 14:30:41 +00003964 return Failure;
3965 }
3966
3967 // This is used for compatibility with older PCH formats.
3968 bool HaveReadControlBlock = false;
Eugene Zelenkoe95e7d52016-09-07 21:53:17 +00003969 while (true) {
Chris Lattnerefa77172013-01-20 00:00:22 +00003970 llvm::BitstreamEntry Entry = Stream.advance();
David L. Jonesc4808b9e2016-12-15 20:53:26 +00003971
Chris Lattnerefa77172013-01-20 00:00:22 +00003972 switch (Entry.Kind) {
3973 case llvm::BitstreamEntry::Error:
Chris Lattnerefa77172013-01-20 00:00:22 +00003974 case llvm::BitstreamEntry::Record:
Douglas Gregor6623e1f2015-11-03 18:33:07 +00003975 case llvm::BitstreamEntry::EndBlock:
Guy Benyei11169dd2012-12-18 14:30:41 +00003976 Error("invalid record at top-level of AST file");
3977 return Failure;
David L. Jonesc4808b9e2016-12-15 20:53:26 +00003978
Chris Lattnerefa77172013-01-20 00:00:22 +00003979 case llvm::BitstreamEntry::SubBlock:
3980 break;
Guy Benyei11169dd2012-12-18 14:30:41 +00003981 }
3982
Chris Lattnerefa77172013-01-20 00:00:22 +00003983 switch (Entry.ID) {
Guy Benyei11169dd2012-12-18 14:30:41 +00003984 case CONTROL_BLOCK_ID:
3985 HaveReadControlBlock = true;
Ben Langmuirbeee15e2014-04-14 18:00:01 +00003986 switch (ReadControlBlock(F, Loaded, ImportedBy, ClientLoadCapabilities)) {
Guy Benyei11169dd2012-12-18 14:30:41 +00003987 case Success:
Richard Smith0f99d6a2015-08-09 08:48:41 +00003988 // Check that we didn't try to load a non-module AST file as a module.
3989 //
3990 // FIXME: Should we also perform the converse check? Loading a module as
3991 // a PCH file sort of works, but it's a bit wonky.
Manman Ren11f2a472016-08-18 17:42:15 +00003992 if ((Type == MK_ImplicitModule || Type == MK_ExplicitModule ||
3993 Type == MK_PrebuiltModule) &&
Richard Smith0f99d6a2015-08-09 08:48:41 +00003994 F.ModuleName.empty()) {
3995 auto Result = (Type == MK_ImplicitModule) ? OutOfDate : Failure;
3996 if (Result != OutOfDate ||
3997 (ClientLoadCapabilities & ARR_OutOfDate) == 0)
3998 Diag(diag::err_module_file_not_module) << FileName;
3999 return Result;
4000 }
Guy Benyei11169dd2012-12-18 14:30:41 +00004001 break;
4002
4003 case Failure: return Failure;
Douglas Gregor7029ce12013-03-19 00:28:20 +00004004 case Missing: return Missing;
Guy Benyei11169dd2012-12-18 14:30:41 +00004005 case OutOfDate: return OutOfDate;
4006 case VersionMismatch: return VersionMismatch;
4007 case ConfigurationMismatch: return ConfigurationMismatch;
4008 case HadErrors: return HadErrors;
4009 }
4010 break;
Richard Smithf8c32552015-09-02 17:45:54 +00004011
Guy Benyei11169dd2012-12-18 14:30:41 +00004012 case AST_BLOCK_ID:
4013 if (!HaveReadControlBlock) {
4014 if ((ClientLoadCapabilities & ARR_VersionMismatch) == 0)
Dmitri Gribenko2228cd32014-02-11 15:40:09 +00004015 Diag(diag::err_pch_version_too_old);
Guy Benyei11169dd2012-12-18 14:30:41 +00004016 return VersionMismatch;
4017 }
4018
4019 // Record that we've loaded this module.
4020 Loaded.push_back(ImportedModule(M, ImportedBy, ImportLoc));
4021 return Success;
4022
4023 default:
4024 if (Stream.SkipBlock()) {
4025 Error("malformed block record in AST file");
4026 return Failure;
4027 }
4028 break;
4029 }
4030 }
Douglas Gregor6623e1f2015-11-03 18:33:07 +00004031
4032 return Success;
4033}
4034
4035/// Parse a record and blob containing module file extension metadata.
4036static bool parseModuleFileExtensionMetadata(
4037 const SmallVectorImpl<uint64_t> &Record,
4038 StringRef Blob,
4039 ModuleFileExtensionMetadata &Metadata) {
4040 if (Record.size() < 4) return true;
4041
4042 Metadata.MajorVersion = Record[0];
4043 Metadata.MinorVersion = Record[1];
4044
4045 unsigned BlockNameLen = Record[2];
4046 unsigned UserInfoLen = Record[3];
4047
4048 if (BlockNameLen + UserInfoLen > Blob.size()) return true;
4049
4050 Metadata.BlockName = std::string(Blob.data(), Blob.data() + BlockNameLen);
4051 Metadata.UserInfo = std::string(Blob.data() + BlockNameLen,
4052 Blob.data() + BlockNameLen + UserInfoLen);
4053 return false;
4054}
4055
4056ASTReader::ASTReadResult ASTReader::ReadExtensionBlock(ModuleFile &F) {
4057 BitstreamCursor &Stream = F.Stream;
4058
4059 RecordData Record;
4060 while (true) {
4061 llvm::BitstreamEntry Entry = Stream.advance();
4062 switch (Entry.Kind) {
4063 case llvm::BitstreamEntry::SubBlock:
4064 if (Stream.SkipBlock())
4065 return Failure;
4066
4067 continue;
4068
4069 case llvm::BitstreamEntry::EndBlock:
4070 return Success;
4071
4072 case llvm::BitstreamEntry::Error:
4073 return HadErrors;
4074
4075 case llvm::BitstreamEntry::Record:
4076 break;
4077 }
4078
4079 Record.clear();
4080 StringRef Blob;
4081 unsigned RecCode = Stream.readRecord(Entry.ID, Record, &Blob);
4082 switch (RecCode) {
4083 case EXTENSION_METADATA: {
4084 ModuleFileExtensionMetadata Metadata;
4085 if (parseModuleFileExtensionMetadata(Record, Blob, Metadata))
4086 return Failure;
4087
4088 // Find a module file extension with this block name.
4089 auto Known = ModuleFileExtensions.find(Metadata.BlockName);
4090 if (Known == ModuleFileExtensions.end()) break;
4091
4092 // Form a reader.
4093 if (auto Reader = Known->second->createExtensionReader(Metadata, *this,
4094 F, Stream)) {
4095 F.ExtensionReaders.push_back(std::move(Reader));
4096 }
4097
4098 break;
4099 }
4100 }
4101 }
4102
4103 return Success;
Guy Benyei11169dd2012-12-18 14:30:41 +00004104}
4105
Richard Smitha7e2cc62015-05-01 01:53:09 +00004106void ASTReader::InitializeContext() {
Guy Benyei11169dd2012-12-18 14:30:41 +00004107 // If there's a listener, notify them that we "read" the translation unit.
4108 if (DeserializationListener)
David L. Jonesc4808b9e2016-12-15 20:53:26 +00004109 DeserializationListener->DeclRead(PREDEF_DECL_TRANSLATION_UNIT_ID,
Guy Benyei11169dd2012-12-18 14:30:41 +00004110 Context.getTranslationUnitDecl());
4111
Guy Benyei11169dd2012-12-18 14:30:41 +00004112 // FIXME: Find a better way to deal with collisions between these
4113 // built-in types. Right now, we just ignore the problem.
David L. Jonesc4808b9e2016-12-15 20:53:26 +00004114
Guy Benyei11169dd2012-12-18 14:30:41 +00004115 // Load the special types.
4116 if (SpecialTypes.size() >= NumSpecialTypeIDs) {
4117 if (unsigned String = SpecialTypes[SPECIAL_TYPE_CF_CONSTANT_STRING]) {
4118 if (!Context.CFConstantStringTypeDecl)
4119 Context.setCFConstantStringType(GetType(String));
4120 }
David L. Jonesc4808b9e2016-12-15 20:53:26 +00004121
Guy Benyei11169dd2012-12-18 14:30:41 +00004122 if (unsigned File = SpecialTypes[SPECIAL_TYPE_FILE]) {
4123 QualType FileType = GetType(File);
4124 if (FileType.isNull()) {
4125 Error("FILE type is NULL");
4126 return;
4127 }
David L. Jonesc4808b9e2016-12-15 20:53:26 +00004128
Guy Benyei11169dd2012-12-18 14:30:41 +00004129 if (!Context.FILEDecl) {
4130 if (const TypedefType *Typedef = FileType->getAs<TypedefType>())
4131 Context.setFILEDecl(Typedef->getDecl());
4132 else {
4133 const TagType *Tag = FileType->getAs<TagType>();
4134 if (!Tag) {
4135 Error("Invalid FILE type in AST file");
4136 return;
4137 }
4138 Context.setFILEDecl(Tag->getDecl());
4139 }
4140 }
4141 }
David L. Jonesc4808b9e2016-12-15 20:53:26 +00004142
Guy Benyei11169dd2012-12-18 14:30:41 +00004143 if (unsigned Jmp_buf = SpecialTypes[SPECIAL_TYPE_JMP_BUF]) {
4144 QualType Jmp_bufType = GetType(Jmp_buf);
4145 if (Jmp_bufType.isNull()) {
4146 Error("jmp_buf type is NULL");
4147 return;
4148 }
David L. Jonesc4808b9e2016-12-15 20:53:26 +00004149
Guy Benyei11169dd2012-12-18 14:30:41 +00004150 if (!Context.jmp_bufDecl) {
4151 if (const TypedefType *Typedef = Jmp_bufType->getAs<TypedefType>())
4152 Context.setjmp_bufDecl(Typedef->getDecl());
4153 else {
4154 const TagType *Tag = Jmp_bufType->getAs<TagType>();
4155 if (!Tag) {
4156 Error("Invalid jmp_buf type in AST file");
4157 return;
4158 }
4159 Context.setjmp_bufDecl(Tag->getDecl());
4160 }
4161 }
4162 }
David L. Jonesc4808b9e2016-12-15 20:53:26 +00004163
Guy Benyei11169dd2012-12-18 14:30:41 +00004164 if (unsigned Sigjmp_buf = SpecialTypes[SPECIAL_TYPE_SIGJMP_BUF]) {
4165 QualType Sigjmp_bufType = GetType(Sigjmp_buf);
4166 if (Sigjmp_bufType.isNull()) {
4167 Error("sigjmp_buf type is NULL");
4168 return;
4169 }
David L. Jonesc4808b9e2016-12-15 20:53:26 +00004170
Guy Benyei11169dd2012-12-18 14:30:41 +00004171 if (!Context.sigjmp_bufDecl) {
4172 if (const TypedefType *Typedef = Sigjmp_bufType->getAs<TypedefType>())
4173 Context.setsigjmp_bufDecl(Typedef->getDecl());
4174 else {
4175 const TagType *Tag = Sigjmp_bufType->getAs<TagType>();
4176 assert(Tag && "Invalid sigjmp_buf type in AST file");
4177 Context.setsigjmp_bufDecl(Tag->getDecl());
4178 }
4179 }
4180 }
4181
4182 if (unsigned ObjCIdRedef
4183 = SpecialTypes[SPECIAL_TYPE_OBJC_ID_REDEFINITION]) {
4184 if (Context.ObjCIdRedefinitionType.isNull())
4185 Context.ObjCIdRedefinitionType = GetType(ObjCIdRedef);
4186 }
4187
4188 if (unsigned ObjCClassRedef
4189 = SpecialTypes[SPECIAL_TYPE_OBJC_CLASS_REDEFINITION]) {
4190 if (Context.ObjCClassRedefinitionType.isNull())
4191 Context.ObjCClassRedefinitionType = GetType(ObjCClassRedef);
4192 }
4193
4194 if (unsigned ObjCSelRedef
4195 = SpecialTypes[SPECIAL_TYPE_OBJC_SEL_REDEFINITION]) {
4196 if (Context.ObjCSelRedefinitionType.isNull())
4197 Context.ObjCSelRedefinitionType = GetType(ObjCSelRedef);
4198 }
4199
4200 if (unsigned Ucontext_t = SpecialTypes[SPECIAL_TYPE_UCONTEXT_T]) {
4201 QualType Ucontext_tType = GetType(Ucontext_t);
4202 if (Ucontext_tType.isNull()) {
4203 Error("ucontext_t type is NULL");
4204 return;
4205 }
4206
4207 if (!Context.ucontext_tDecl) {
4208 if (const TypedefType *Typedef = Ucontext_tType->getAs<TypedefType>())
4209 Context.setucontext_tDecl(Typedef->getDecl());
4210 else {
4211 const TagType *Tag = Ucontext_tType->getAs<TagType>();
4212 assert(Tag && "Invalid ucontext_t type in AST file");
4213 Context.setucontext_tDecl(Tag->getDecl());
4214 }
4215 }
4216 }
4217 }
David L. Jonesc4808b9e2016-12-15 20:53:26 +00004218
Guy Benyei11169dd2012-12-18 14:30:41 +00004219 ReadPragmaDiagnosticMappings(Context.getDiagnostics());
4220
4221 // If there were any CUDA special declarations, deserialize them.
4222 if (!CUDASpecialDeclRefs.empty()) {
4223 assert(CUDASpecialDeclRefs.size() == 1 && "More decl refs than expected!");
4224 Context.setcudaConfigureCallDecl(
4225 cast<FunctionDecl>(GetDecl(CUDASpecialDeclRefs[0])));
4226 }
Richard Smith56be7542014-03-21 00:33:59 +00004227
Guy Benyei11169dd2012-12-18 14:30:41 +00004228 // Re-export any modules that were imported by a non-module AST file.
Richard Smitha7e2cc62015-05-01 01:53:09 +00004229 // FIXME: This does not make macro-only imports visible again.
Richard Smith56be7542014-03-21 00:33:59 +00004230 for (auto &Import : ImportedModules) {
Richard Smitha7e2cc62015-05-01 01:53:09 +00004231 if (Module *Imported = getSubmodule(Import.ID)) {
Argyrios Kyrtzidis125df052013-02-01 16:36:12 +00004232 makeModuleVisible(Imported, Module::AllVisible,
Richard Smitha7e2cc62015-05-01 01:53:09 +00004233 /*ImportLoc=*/Import.ImportLoc);
Ben Langmuir6d25fdc2016-02-11 17:04:42 +00004234 if (Import.ImportLoc.isValid())
4235 PP.makeModuleVisible(Imported, Import.ImportLoc);
4236 // FIXME: should we tell Sema to make the module visible too?
Richard Smitha7e2cc62015-05-01 01:53:09 +00004237 }
Guy Benyei11169dd2012-12-18 14:30:41 +00004238 }
4239 ImportedModules.clear();
4240}
4241
4242void ASTReader::finalizeForWriting() {
Richard Smithde711422015-04-23 21:20:19 +00004243 // Nothing to do for now.
Guy Benyei11169dd2012-12-18 14:30:41 +00004244}
4245
Peter Collingbourne77c89b62016-11-08 04:17:11 +00004246/// \brief Reads and return the signature record from \p PCH's control block, or
4247/// else returns 0.
4248static ASTFileSignature readASTFileSignature(StringRef PCH) {
4249 BitstreamCursor Stream(PCH);
Ben Langmuir70a1b812015-03-24 04:43:52 +00004250 if (!startsWithASTFileMagic(Stream))
Ben Langmuir487ea142014-10-23 18:05:36 +00004251 return 0;
Ben Langmuir487ea142014-10-23 18:05:36 +00004252
4253 // Scan for the CONTROL_BLOCK_ID block.
4254 if (SkipCursorToBlock(Stream, CONTROL_BLOCK_ID))
4255 return 0;
4256
4257 // Scan for SIGNATURE inside the control block.
4258 ASTReader::RecordData Record;
Eugene Zelenkoe95e7d52016-09-07 21:53:17 +00004259 while (true) {
Ben Langmuir487ea142014-10-23 18:05:36 +00004260 llvm::BitstreamEntry Entry = Stream.advanceSkippingSubblocks();
Simon Pilgrim0b33f112016-11-16 16:11:08 +00004261 if (Entry.Kind != llvm::BitstreamEntry::Record)
Ben Langmuir487ea142014-10-23 18:05:36 +00004262 return 0;
4263
4264 Record.clear();
4265 StringRef Blob;
4266 if (SIGNATURE == Stream.readRecord(Entry.ID, Record, &Blob))
4267 return Record[0];
4268 }
4269}
4270
Guy Benyei11169dd2012-12-18 14:30:41 +00004271/// \brief Retrieve the name of the original source file name
4272/// directly from the AST file, without actually loading the AST
4273/// file.
Adrian Prantlbb165fb2015-06-20 18:53:08 +00004274std::string ASTReader::getOriginalSourceFile(
4275 const std::string &ASTFileName, FileManager &FileMgr,
Adrian Prantlfb2398d2015-07-17 01:19:54 +00004276 const PCHContainerReader &PCHContainerRdr, DiagnosticsEngine &Diags) {
Guy Benyei11169dd2012-12-18 14:30:41 +00004277 // Open the AST file.
Benjamin Kramera8857962014-10-26 22:44:13 +00004278 auto Buffer = FileMgr.getBufferForFile(ASTFileName);
Guy Benyei11169dd2012-12-18 14:30:41 +00004279 if (!Buffer) {
Benjamin Kramera8857962014-10-26 22:44:13 +00004280 Diags.Report(diag::err_fe_unable_to_read_pch_file)
4281 << ASTFileName << Buffer.getError().message();
Guy Benyei11169dd2012-12-18 14:30:41 +00004282 return std::string();
4283 }
4284
4285 // Initialize the stream
Peter Collingbourne77c89b62016-11-08 04:17:11 +00004286 BitstreamCursor Stream(PCHContainerRdr.ExtractPCH(**Buffer));
Guy Benyei11169dd2012-12-18 14:30:41 +00004287
4288 // Sniff for the signature.
Ben Langmuir70a1b812015-03-24 04:43:52 +00004289 if (!startsWithASTFileMagic(Stream)) {
Guy Benyei11169dd2012-12-18 14:30:41 +00004290 Diags.Report(diag::err_fe_not_a_pch_file) << ASTFileName;
4291 return std::string();
4292 }
David L. Jonesc4808b9e2016-12-15 20:53:26 +00004293
Chris Lattnere7b154b2013-01-19 21:39:22 +00004294 // Scan for the CONTROL_BLOCK_ID block.
Argyrios Kyrtzidisc4cd2c42013-05-06 19:23:40 +00004295 if (SkipCursorToBlock(Stream, CONTROL_BLOCK_ID)) {
Chris Lattner7fb3bef2013-01-20 00:56:42 +00004296 Diags.Report(diag::err_fe_pch_malformed_block) << ASTFileName;
4297 return std::string();
Chris Lattnere7b154b2013-01-19 21:39:22 +00004298 }
Guy Benyei11169dd2012-12-18 14:30:41 +00004299
Chris Lattner7fb3bef2013-01-20 00:56:42 +00004300 // Scan for ORIGINAL_FILE inside the control block.
4301 RecordData Record;
Eugene Zelenkoe95e7d52016-09-07 21:53:17 +00004302 while (true) {
Chris Lattner7fb3bef2013-01-20 00:56:42 +00004303 llvm::BitstreamEntry Entry = Stream.advanceSkippingSubblocks();
Chris Lattnere7b154b2013-01-19 21:39:22 +00004304 if (Entry.Kind == llvm::BitstreamEntry::EndBlock)
4305 return std::string();
David L. Jonesc4808b9e2016-12-15 20:53:26 +00004306
Chris Lattnere7b154b2013-01-19 21:39:22 +00004307 if (Entry.Kind != llvm::BitstreamEntry::Record) {
4308 Diags.Report(diag::err_fe_pch_malformed_block) << ASTFileName;
4309 return std::string();
Guy Benyei11169dd2012-12-18 14:30:41 +00004310 }
David L. Jonesc4808b9e2016-12-15 20:53:26 +00004311
Guy Benyei11169dd2012-12-18 14:30:41 +00004312 Record.clear();
Chris Lattner0e6c9402013-01-20 02:38:54 +00004313 StringRef Blob;
4314 if (Stream.readRecord(Entry.ID, Record, &Blob) == ORIGINAL_FILE)
4315 return Blob.str();
Guy Benyei11169dd2012-12-18 14:30:41 +00004316 }
Guy Benyei11169dd2012-12-18 14:30:41 +00004317}
4318
4319namespace {
Eugene Zelenkoe95e7d52016-09-07 21:53:17 +00004320
Guy Benyei11169dd2012-12-18 14:30:41 +00004321 class SimplePCHValidator : public ASTReaderListener {
4322 const LangOptions &ExistingLangOpts;
4323 const TargetOptions &ExistingTargetOpts;
4324 const PreprocessorOptions &ExistingPPOpts;
Argyrios Kyrtzidisbd0b6512015-02-19 20:12:20 +00004325 std::string ExistingModuleCachePath;
Guy Benyei11169dd2012-12-18 14:30:41 +00004326 FileManager &FileMgr;
Argyrios Kyrtzidisbd0b6512015-02-19 20:12:20 +00004327
Guy Benyei11169dd2012-12-18 14:30:41 +00004328 public:
4329 SimplePCHValidator(const LangOptions &ExistingLangOpts,
4330 const TargetOptions &ExistingTargetOpts,
4331 const PreprocessorOptions &ExistingPPOpts,
Argyrios Kyrtzidisbd0b6512015-02-19 20:12:20 +00004332 StringRef ExistingModuleCachePath,
Guy Benyei11169dd2012-12-18 14:30:41 +00004333 FileManager &FileMgr)
4334 : ExistingLangOpts(ExistingLangOpts),
4335 ExistingTargetOpts(ExistingTargetOpts),
4336 ExistingPPOpts(ExistingPPOpts),
Argyrios Kyrtzidisbd0b6512015-02-19 20:12:20 +00004337 ExistingModuleCachePath(ExistingModuleCachePath),
Guy Benyei11169dd2012-12-18 14:30:41 +00004338 FileMgr(FileMgr)
4339 {
4340 }
4341
Richard Smith1e2cf0d2014-10-31 02:28:58 +00004342 bool ReadLanguageOptions(const LangOptions &LangOpts, bool Complain,
4343 bool AllowCompatibleDifferences) override {
4344 return checkLanguageOptions(ExistingLangOpts, LangOpts, nullptr,
4345 AllowCompatibleDifferences);
Guy Benyei11169dd2012-12-18 14:30:41 +00004346 }
Eugene Zelenkoe95e7d52016-09-07 21:53:17 +00004347
Chandler Carruth0d745bc2015-03-14 04:47:43 +00004348 bool ReadTargetOptions(const TargetOptions &TargetOpts, bool Complain,
4349 bool AllowCompatibleDifferences) override {
4350 return checkTargetOptions(ExistingTargetOpts, TargetOpts, nullptr,
4351 AllowCompatibleDifferences);
Guy Benyei11169dd2012-12-18 14:30:41 +00004352 }
Eugene Zelenkoe95e7d52016-09-07 21:53:17 +00004353
Argyrios Kyrtzidisbd0b6512015-02-19 20:12:20 +00004354 bool ReadHeaderSearchOptions(const HeaderSearchOptions &HSOpts,
4355 StringRef SpecificModuleCachePath,
4356 bool Complain) override {
4357 return checkHeaderSearchOptions(HSOpts, SpecificModuleCachePath,
4358 ExistingModuleCachePath,
4359 nullptr, ExistingLangOpts);
4360 }
Eugene Zelenkoe95e7d52016-09-07 21:53:17 +00004361
Craig Topper3e89dfe2014-03-13 02:13:41 +00004362 bool ReadPreprocessorOptions(const PreprocessorOptions &PPOpts,
4363 bool Complain,
4364 std::string &SuggestedPredefines) override {
Craig Toppera13603a2014-05-22 05:54:18 +00004365 return checkPreprocessorOptions(ExistingPPOpts, PPOpts, nullptr, FileMgr,
Argyrios Kyrtzidisd3afa0c2013-04-26 21:33:40 +00004366 SuggestedPredefines, ExistingLangOpts);
Guy Benyei11169dd2012-12-18 14:30:41 +00004367 }
4368 };
Eugene Zelenkoe95e7d52016-09-07 21:53:17 +00004369
4370} // end anonymous namespace
Guy Benyei11169dd2012-12-18 14:30:41 +00004371
Adrian Prantlbb165fb2015-06-20 18:53:08 +00004372bool ASTReader::readASTFileControlBlock(
4373 StringRef Filename, FileManager &FileMgr,
Adrian Prantlfb2398d2015-07-17 01:19:54 +00004374 const PCHContainerReader &PCHContainerRdr,
Douglas Gregor6623e1f2015-11-03 18:33:07 +00004375 bool FindModuleFileExtensions,
Manman Ren47a44452016-07-26 17:12:17 +00004376 ASTReaderListener &Listener, bool ValidateDiagnosticOptions) {
Guy Benyei11169dd2012-12-18 14:30:41 +00004377 // Open the AST file.
Richard Smith7f330cd2015-03-18 01:42:29 +00004378 // FIXME: This allows use of the VFS; we do not allow use of the
4379 // VFS when actually loading a module.
Benjamin Kramera8857962014-10-26 22:44:13 +00004380 auto Buffer = FileMgr.getBufferForFile(Filename);
Guy Benyei11169dd2012-12-18 14:30:41 +00004381 if (!Buffer) {
4382 return true;
4383 }
4384
4385 // Initialize the stream
Peter Collingbourne77c89b62016-11-08 04:17:11 +00004386 BitstreamCursor Stream(PCHContainerRdr.ExtractPCH(**Buffer));
Guy Benyei11169dd2012-12-18 14:30:41 +00004387
4388 // Sniff for the signature.
Ben Langmuir70a1b812015-03-24 04:43:52 +00004389 if (!startsWithASTFileMagic(Stream))
Guy Benyei11169dd2012-12-18 14:30:41 +00004390 return true;
Guy Benyei11169dd2012-12-18 14:30:41 +00004391
Chris Lattner7fb3bef2013-01-20 00:56:42 +00004392 // Scan for the CONTROL_BLOCK_ID block.
Argyrios Kyrtzidisc4cd2c42013-05-06 19:23:40 +00004393 if (SkipCursorToBlock(Stream, CONTROL_BLOCK_ID))
Chris Lattner7fb3bef2013-01-20 00:56:42 +00004394 return true;
Argyrios Kyrtzidisc4cd2c42013-05-06 19:23:40 +00004395
4396 bool NeedsInputFiles = Listener.needsInputFileVisitation();
Ben Langmuircb69b572014-03-07 06:40:32 +00004397 bool NeedsSystemInputFiles = Listener.needsSystemInputFileVisitation();
Richard Smithd4b230b2014-10-27 23:01:16 +00004398 bool NeedsImports = Listener.needsImportVisitation();
Argyrios Kyrtzidisc4cd2c42013-05-06 19:23:40 +00004399 BitstreamCursor InputFilesCursor;
Argyrios Kyrtzidisc4cd2c42013-05-06 19:23:40 +00004400
Guy Benyei11169dd2012-12-18 14:30:41 +00004401 RecordData Record;
Richard Smith7ed1bc92014-12-05 22:42:13 +00004402 std::string ModuleDir;
Douglas Gregor6623e1f2015-11-03 18:33:07 +00004403 bool DoneWithControlBlock = false;
4404 while (!DoneWithControlBlock) {
Richard Smith0516b182015-09-08 19:40:14 +00004405 llvm::BitstreamEntry Entry = Stream.advance();
4406
4407 switch (Entry.Kind) {
4408 case llvm::BitstreamEntry::SubBlock: {
4409 switch (Entry.ID) {
4410 case OPTIONS_BLOCK_ID: {
4411 std::string IgnoredSuggestedPredefines;
4412 if (ReadOptionsBlock(Stream, ARR_ConfigurationMismatch | ARR_OutOfDate,
4413 /*AllowCompatibleConfigurationMismatch*/ false,
Manman Ren47a44452016-07-26 17:12:17 +00004414 Listener, IgnoredSuggestedPredefines,
4415 ValidateDiagnosticOptions) != Success)
Richard Smith0516b182015-09-08 19:40:14 +00004416 return true;
4417 break;
4418 }
4419
4420 case INPUT_FILES_BLOCK_ID:
4421 InputFilesCursor = Stream;
4422 if (Stream.SkipBlock() ||
4423 (NeedsInputFiles &&
4424 ReadBlockAbbrevs(InputFilesCursor, INPUT_FILES_BLOCK_ID)))
4425 return true;
4426 break;
4427
4428 default:
4429 if (Stream.SkipBlock())
4430 return true;
4431 break;
4432 }
4433
4434 continue;
4435 }
4436
4437 case llvm::BitstreamEntry::EndBlock:
Douglas Gregor6623e1f2015-11-03 18:33:07 +00004438 DoneWithControlBlock = true;
4439 break;
Richard Smith0516b182015-09-08 19:40:14 +00004440
4441 case llvm::BitstreamEntry::Error:
Chris Lattner7fb3bef2013-01-20 00:56:42 +00004442 return true;
Richard Smith0516b182015-09-08 19:40:14 +00004443
4444 case llvm::BitstreamEntry::Record:
4445 break;
4446 }
4447
Douglas Gregor6623e1f2015-11-03 18:33:07 +00004448 if (DoneWithControlBlock) break;
4449
Guy Benyei11169dd2012-12-18 14:30:41 +00004450 Record.clear();
Chris Lattner0e6c9402013-01-20 02:38:54 +00004451 StringRef Blob;
4452 unsigned RecCode = Stream.readRecord(Entry.ID, Record, &Blob);
Chris Lattner7fb3bef2013-01-20 00:56:42 +00004453 switch ((ControlRecordTypes)RecCode) {
4454 case METADATA: {
4455 if (Record[0] != VERSION_MAJOR)
4456 return true;
Guy Benyei11169dd2012-12-18 14:30:41 +00004457
Douglas Gregorbf7fc9c2013-03-27 16:47:18 +00004458 if (Listener.ReadFullVersionInformation(Blob))
Chris Lattner7fb3bef2013-01-20 00:56:42 +00004459 return true;
David L. Jonesc4808b9e2016-12-15 20:53:26 +00004460
Chris Lattner7fb3bef2013-01-20 00:56:42 +00004461 break;
4462 }
Ben Langmuir4f5212a2014-04-14 22:12:44 +00004463 case MODULE_NAME:
4464 Listener.ReadModuleName(Blob);
4465 break;
Richard Smith7ed1bc92014-12-05 22:42:13 +00004466 case MODULE_DIRECTORY:
4467 ModuleDir = Blob;
4468 break;
Ben Langmuir4b8a9e92014-08-12 16:42:33 +00004469 case MODULE_MAP_FILE: {
4470 unsigned Idx = 0;
Richard Smith7ed1bc92014-12-05 22:42:13 +00004471 auto Path = ReadString(Record, Idx);
4472 ResolveImportedPath(Path, ModuleDir);
4473 Listener.ReadModuleMapFile(Path);
Ben Langmuir4f5212a2014-04-14 22:12:44 +00004474 break;
Ben Langmuir4b8a9e92014-08-12 16:42:33 +00004475 }
Argyrios Kyrtzidisc4cd2c42013-05-06 19:23:40 +00004476 case INPUT_FILE_OFFSETS: {
4477 if (!NeedsInputFiles)
4478 break;
4479
4480 unsigned NumInputFiles = Record[0];
4481 unsigned NumUserFiles = Record[1];
Richard Smithec216502015-02-13 19:48:37 +00004482 const uint64_t *InputFileOffs = (const uint64_t *)Blob.data();
Argyrios Kyrtzidisc4cd2c42013-05-06 19:23:40 +00004483 for (unsigned I = 0; I != NumInputFiles; ++I) {
4484 // Go find this input file.
4485 bool isSystemFile = I >= NumUserFiles;
Ben Langmuircb69b572014-03-07 06:40:32 +00004486
4487 if (isSystemFile && !NeedsSystemInputFiles)
4488 break; // the rest are system input files
4489
Argyrios Kyrtzidisc4cd2c42013-05-06 19:23:40 +00004490 BitstreamCursor &Cursor = InputFilesCursor;
4491 SavedStreamPosition SavedPosition(Cursor);
4492 Cursor.JumpToBit(InputFileOffs[I]);
4493
4494 unsigned Code = Cursor.ReadCode();
4495 RecordData Record;
4496 StringRef Blob;
4497 bool shouldContinue = false;
4498 switch ((InputFileRecordTypes)Cursor.readRecord(Code, Record, &Blob)) {
4499 case INPUT_FILE:
Argyrios Kyrtzidis68ccbe02014-03-14 02:26:31 +00004500 bool Overridden = static_cast<bool>(Record[3]);
Richard Smith7ed1bc92014-12-05 22:42:13 +00004501 std::string Filename = Blob;
4502 ResolveImportedPath(Filename, ModuleDir);
Richard Smith216a3bd2015-08-13 17:57:10 +00004503 shouldContinue = Listener.visitInputFile(
4504 Filename, isSystemFile, Overridden, /*IsExplicitModule*/false);
Argyrios Kyrtzidisc4cd2c42013-05-06 19:23:40 +00004505 break;
4506 }
4507 if (!shouldContinue)
4508 break;
4509 }
4510 break;
4511 }
4512
Richard Smithd4b230b2014-10-27 23:01:16 +00004513 case IMPORTS: {
4514 if (!NeedsImports)
4515 break;
4516
4517 unsigned Idx = 0, N = Record.size();
4518 while (Idx < N) {
4519 // Read information about the AST file.
Richard Smith79c98cc2014-10-27 23:25:15 +00004520 Idx += 5; // ImportLoc, Size, ModTime, Signature
Richard Smith7ed1bc92014-12-05 22:42:13 +00004521 std::string Filename = ReadString(Record, Idx);
4522 ResolveImportedPath(Filename, ModuleDir);
4523 Listener.visitImport(Filename);
Richard Smithd4b230b2014-10-27 23:01:16 +00004524 }
4525 break;
4526 }
4527
Chris Lattner7fb3bef2013-01-20 00:56:42 +00004528 default:
4529 // No other validation to perform.
4530 break;
Guy Benyei11169dd2012-12-18 14:30:41 +00004531 }
4532 }
Douglas Gregor6623e1f2015-11-03 18:33:07 +00004533
4534 // Look for module file extension blocks, if requested.
4535 if (FindModuleFileExtensions) {
4536 while (!SkipCursorToBlock(Stream, EXTENSION_BLOCK_ID)) {
4537 bool DoneWithExtensionBlock = false;
4538 while (!DoneWithExtensionBlock) {
4539 llvm::BitstreamEntry Entry = Stream.advance();
4540
4541 switch (Entry.Kind) {
4542 case llvm::BitstreamEntry::SubBlock:
4543 if (Stream.SkipBlock())
4544 return true;
4545
4546 continue;
4547
4548 case llvm::BitstreamEntry::EndBlock:
4549 DoneWithExtensionBlock = true;
4550 continue;
4551
4552 case llvm::BitstreamEntry::Error:
4553 return true;
4554
4555 case llvm::BitstreamEntry::Record:
4556 break;
4557 }
4558
4559 Record.clear();
4560 StringRef Blob;
4561 unsigned RecCode = Stream.readRecord(Entry.ID, Record, &Blob);
4562 switch (RecCode) {
4563 case EXTENSION_METADATA: {
4564 ModuleFileExtensionMetadata Metadata;
4565 if (parseModuleFileExtensionMetadata(Record, Blob, Metadata))
4566 return true;
4567
4568 Listener.readModuleFileExtension(Metadata);
4569 break;
4570 }
4571 }
4572 }
4573 }
4574 }
4575
4576 return false;
Guy Benyei11169dd2012-12-18 14:30:41 +00004577}
4578
Adrian Prantlbb165fb2015-06-20 18:53:08 +00004579bool ASTReader::isAcceptableASTFile(
4580 StringRef Filename, FileManager &FileMgr,
Adrian Prantlfb2398d2015-07-17 01:19:54 +00004581 const PCHContainerReader &PCHContainerRdr, const LangOptions &LangOpts,
Adrian Prantlbb165fb2015-06-20 18:53:08 +00004582 const TargetOptions &TargetOpts, const PreprocessorOptions &PPOpts,
4583 std::string ExistingModuleCachePath) {
Argyrios Kyrtzidisbd0b6512015-02-19 20:12:20 +00004584 SimplePCHValidator validator(LangOpts, TargetOpts, PPOpts,
4585 ExistingModuleCachePath, FileMgr);
Adrian Prantlfb2398d2015-07-17 01:19:54 +00004586 return !readASTFileControlBlock(Filename, FileMgr, PCHContainerRdr,
Douglas Gregor6623e1f2015-11-03 18:33:07 +00004587 /*FindModuleFileExtensions=*/false,
Manman Ren47a44452016-07-26 17:12:17 +00004588 validator,
4589 /*ValidateDiagnosticOptions=*/true);
Guy Benyei11169dd2012-12-18 14:30:41 +00004590}
4591
Ben Langmuir2c9af442014-04-10 17:57:43 +00004592ASTReader::ASTReadResult
4593ASTReader::ReadSubmoduleBlock(ModuleFile &F, unsigned ClientLoadCapabilities) {
Guy Benyei11169dd2012-12-18 14:30:41 +00004594 // Enter the submodule block.
4595 if (F.Stream.EnterSubBlock(SUBMODULE_BLOCK_ID)) {
4596 Error("malformed submodule block record in AST file");
Ben Langmuir2c9af442014-04-10 17:57:43 +00004597 return Failure;
Guy Benyei11169dd2012-12-18 14:30:41 +00004598 }
4599
4600 ModuleMap &ModMap = PP.getHeaderSearchInfo().getModuleMap();
4601 bool First = true;
Craig Toppera13603a2014-05-22 05:54:18 +00004602 Module *CurrentModule = nullptr;
Guy Benyei11169dd2012-12-18 14:30:41 +00004603 RecordData Record;
4604 while (true) {
Chris Lattner7fb3bef2013-01-20 00:56:42 +00004605 llvm::BitstreamEntry Entry = F.Stream.advanceSkippingSubblocks();
David L. Jonesc4808b9e2016-12-15 20:53:26 +00004606
Chris Lattner7fb3bef2013-01-20 00:56:42 +00004607 switch (Entry.Kind) {
4608 case llvm::BitstreamEntry::SubBlock: // Handled for us already.
4609 case llvm::BitstreamEntry::Error:
4610 Error("malformed block record in AST file");
Ben Langmuir2c9af442014-04-10 17:57:43 +00004611 return Failure;
Chris Lattner7fb3bef2013-01-20 00:56:42 +00004612 case llvm::BitstreamEntry::EndBlock:
Ben Langmuir2c9af442014-04-10 17:57:43 +00004613 return Success;
Chris Lattner7fb3bef2013-01-20 00:56:42 +00004614 case llvm::BitstreamEntry::Record:
4615 // The interesting case.
4616 break;
Guy Benyei11169dd2012-12-18 14:30:41 +00004617 }
Chris Lattner7fb3bef2013-01-20 00:56:42 +00004618
Guy Benyei11169dd2012-12-18 14:30:41 +00004619 // Read a record.
Chris Lattner0e6c9402013-01-20 02:38:54 +00004620 StringRef Blob;
Guy Benyei11169dd2012-12-18 14:30:41 +00004621 Record.clear();
Richard Smith03478d92014-10-23 22:12:14 +00004622 auto Kind = F.Stream.readRecord(Entry.ID, Record, &Blob);
4623
4624 if ((Kind == SUBMODULE_METADATA) != First) {
4625 Error("submodule metadata record should be at beginning of block");
4626 return Failure;
4627 }
4628 First = false;
4629
4630 // Submodule information is only valid if we have a current module.
4631 // FIXME: Should we error on these cases?
4632 if (!CurrentModule && Kind != SUBMODULE_METADATA &&
4633 Kind != SUBMODULE_DEFINITION)
4634 continue;
4635
4636 switch (Kind) {
Guy Benyei11169dd2012-12-18 14:30:41 +00004637 default: // Default behavior: ignore.
4638 break;
Guy Benyei11169dd2012-12-18 14:30:41 +00004639
Richard Smith03478d92014-10-23 22:12:14 +00004640 case SUBMODULE_DEFINITION: {
Douglas Gregor8d932422013-03-20 03:59:18 +00004641 if (Record.size() < 8) {
Guy Benyei11169dd2012-12-18 14:30:41 +00004642 Error("malformed module definition");
Ben Langmuir2c9af442014-04-10 17:57:43 +00004643 return Failure;
Guy Benyei11169dd2012-12-18 14:30:41 +00004644 }
Richard Smith03478d92014-10-23 22:12:14 +00004645
Chris Lattner0e6c9402013-01-20 02:38:54 +00004646 StringRef Name = Blob;
Richard Smith9bca2982014-03-08 00:03:56 +00004647 unsigned Idx = 0;
4648 SubmoduleID GlobalID = getGlobalSubmoduleID(F, Record[Idx++]);
4649 SubmoduleID Parent = getGlobalSubmoduleID(F, Record[Idx++]);
4650 bool IsFramework = Record[Idx++];
4651 bool IsExplicit = Record[Idx++];
4652 bool IsSystem = Record[Idx++];
4653 bool IsExternC = Record[Idx++];
4654 bool InferSubmodules = Record[Idx++];
4655 bool InferExplicitSubmodules = Record[Idx++];
4656 bool InferExportWildcard = Record[Idx++];
4657 bool ConfigMacrosExhaustive = Record[Idx++];
David Blaikie9ffe5a32017-01-30 05:00:26 +00004658 bool WithCodegen = Record[Idx++];
Douglas Gregor8d932422013-03-20 03:59:18 +00004659
Ben Langmuirbeee15e2014-04-14 18:00:01 +00004660 Module *ParentModule = nullptr;
Ben Langmuir9d6448b2014-08-09 00:57:23 +00004661 if (Parent)
Guy Benyei11169dd2012-12-18 14:30:41 +00004662 ParentModule = getSubmodule(Parent);
Ben Langmuirbeee15e2014-04-14 18:00:01 +00004663
Guy Benyei11169dd2012-12-18 14:30:41 +00004664 // Retrieve this (sub)module from the module map, creating it if
4665 // necessary.
David Blaikie9ffe5a32017-01-30 05:00:26 +00004666 CurrentModule =
4667 ModMap.findOrCreateModule(Name, ParentModule, IsFramework, IsExplicit)
4668 .first;
Ben Langmuir9d6448b2014-08-09 00:57:23 +00004669
4670 // FIXME: set the definition loc for CurrentModule, or call
4671 // ModMap.setInferredModuleAllowedBy()
4672
Guy Benyei11169dd2012-12-18 14:30:41 +00004673 SubmoduleID GlobalIndex = GlobalID - NUM_PREDEF_SUBMODULE_IDS;
4674 if (GlobalIndex >= SubmodulesLoaded.size() ||
4675 SubmodulesLoaded[GlobalIndex]) {
4676 Error("too many submodules");
Ben Langmuir2c9af442014-04-10 17:57:43 +00004677 return Failure;
Guy Benyei11169dd2012-12-18 14:30:41 +00004678 }
Douglas Gregor8a114ab2013-02-06 22:40:31 +00004679
Douglas Gregor7029ce12013-03-19 00:28:20 +00004680 if (!ParentModule) {
4681 if (const FileEntry *CurFile = CurrentModule->getASTFile()) {
4682 if (CurFile != F.File) {
4683 if (!Diags.isDiagnosticInFlight()) {
4684 Diag(diag::err_module_file_conflict)
4685 << CurrentModule->getTopLevelModuleName()
4686 << CurFile->getName()
4687 << F.File->getName();
4688 }
Ben Langmuir2c9af442014-04-10 17:57:43 +00004689 return Failure;
Douglas Gregor8a114ab2013-02-06 22:40:31 +00004690 }
Douglas Gregor8a114ab2013-02-06 22:40:31 +00004691 }
Douglas Gregor7029ce12013-03-19 00:28:20 +00004692
4693 CurrentModule->setASTFile(F.File);
Douglas Gregor8a114ab2013-02-06 22:40:31 +00004694 }
Ben Langmuirbeee15e2014-04-14 18:00:01 +00004695
Adrian Prantl15bcf702015-06-30 17:39:43 +00004696 CurrentModule->Signature = F.Signature;
Guy Benyei11169dd2012-12-18 14:30:41 +00004697 CurrentModule->IsFromModuleFile = true;
4698 CurrentModule->IsSystem = IsSystem || CurrentModule->IsSystem;
Richard Smith9bca2982014-03-08 00:03:56 +00004699 CurrentModule->IsExternC = IsExternC;
Guy Benyei11169dd2012-12-18 14:30:41 +00004700 CurrentModule->InferSubmodules = InferSubmodules;
4701 CurrentModule->InferExplicitSubmodules = InferExplicitSubmodules;
4702 CurrentModule->InferExportWildcard = InferExportWildcard;
Douglas Gregor8d932422013-03-20 03:59:18 +00004703 CurrentModule->ConfigMacrosExhaustive = ConfigMacrosExhaustive;
David Blaikie9ffe5a32017-01-30 05:00:26 +00004704 CurrentModule->WithCodegen = WithCodegen;
Guy Benyei11169dd2012-12-18 14:30:41 +00004705 if (DeserializationListener)
4706 DeserializationListener->ModuleRead(GlobalID, CurrentModule);
David L. Jonesc4808b9e2016-12-15 20:53:26 +00004707
Guy Benyei11169dd2012-12-18 14:30:41 +00004708 SubmodulesLoaded[GlobalIndex] = CurrentModule;
Douglas Gregor6ddfca92013-01-14 17:21:00 +00004709
Richard Smith8a3e39a2016-03-28 21:31:09 +00004710 // Clear out data that will be replaced by what is in the module file.
Douglas Gregor6ddfca92013-01-14 17:21:00 +00004711 CurrentModule->LinkLibraries.clear();
Douglas Gregor8d932422013-03-20 03:59:18 +00004712 CurrentModule->ConfigMacros.clear();
Douglas Gregorfb912652013-03-20 21:10:35 +00004713 CurrentModule->UnresolvedConflicts.clear();
4714 CurrentModule->Conflicts.clear();
Richard Smith8a3e39a2016-03-28 21:31:09 +00004715
4716 // The module is available unless it's missing a requirement; relevant
4717 // requirements will be (re-)added by SUBMODULE_REQUIRES records.
4718 // Missing headers that were present when the module was built do not
4719 // make it unavailable -- if we got this far, this must be an explicitly
4720 // imported module file.
4721 CurrentModule->Requirements.clear();
4722 CurrentModule->MissingHeaders.clear();
4723 CurrentModule->IsMissingRequirement =
4724 ParentModule && ParentModule->IsMissingRequirement;
4725 CurrentModule->IsAvailable = !CurrentModule->IsMissingRequirement;
Guy Benyei11169dd2012-12-18 14:30:41 +00004726 break;
4727 }
Richard Smith8a3e39a2016-03-28 21:31:09 +00004728
Guy Benyei11169dd2012-12-18 14:30:41 +00004729 case SUBMODULE_UMBRELLA_HEADER: {
Richard Smith2b63d152015-05-16 02:28:53 +00004730 std::string Filename = Blob;
4731 ResolveImportedPath(F, Filename);
4732 if (auto *Umbrella = PP.getFileManager().getFile(Filename)) {
Guy Benyei11169dd2012-12-18 14:30:41 +00004733 if (!CurrentModule->getUmbrellaHeader())
Richard Smith2b63d152015-05-16 02:28:53 +00004734 ModMap.setUmbrellaHeader(CurrentModule, Umbrella, Blob);
4735 else if (CurrentModule->getUmbrellaHeader().Entry != Umbrella) {
Ben Langmuirbc35fbe2015-02-20 21:46:39 +00004736 // This can be a spurious difference caused by changing the VFS to
4737 // point to a different copy of the file, and it is too late to
4738 // to rebuild safely.
4739 // FIXME: If we wrote the virtual paths instead of the 'real' paths,
4740 // after input file validation only real problems would remain and we
4741 // could just error. For now, assume it's okay.
4742 break;
Guy Benyei11169dd2012-12-18 14:30:41 +00004743 }
4744 }
4745 break;
4746 }
David L. Jonesc4808b9e2016-12-15 20:53:26 +00004747
Richard Smith202210b2014-10-24 20:23:01 +00004748 case SUBMODULE_HEADER:
4749 case SUBMODULE_EXCLUDED_HEADER:
4750 case SUBMODULE_PRIVATE_HEADER:
4751 // We lazily associate headers with their modules via the HeaderInfo table.
Argyrios Kyrtzidisb146baa2013-03-13 21:13:51 +00004752 // FIXME: Re-evaluate this section; maybe only store InputFile IDs instead
4753 // of complete filenames or remove it entirely.
Richard Smith202210b2014-10-24 20:23:01 +00004754 break;
Guy Benyei11169dd2012-12-18 14:30:41 +00004755
Richard Smith202210b2014-10-24 20:23:01 +00004756 case SUBMODULE_TEXTUAL_HEADER:
4757 case SUBMODULE_PRIVATE_TEXTUAL_HEADER:
4758 // FIXME: Textual headers are not marked in the HeaderInfo table. Load
4759 // them here.
4760 break;
Lawrence Crowlb53e5482013-06-20 21:14:14 +00004761
Guy Benyei11169dd2012-12-18 14:30:41 +00004762 case SUBMODULE_TOPHEADER: {
Argyrios Kyrtzidis3c5305c2013-03-13 21:13:43 +00004763 CurrentModule->addTopHeaderFilename(Blob);
Guy Benyei11169dd2012-12-18 14:30:41 +00004764 break;
4765 }
4766
4767 case SUBMODULE_UMBRELLA_DIR: {
Richard Smith2b63d152015-05-16 02:28:53 +00004768 std::string Dirname = Blob;
4769 ResolveImportedPath(F, Dirname);
4770 if (auto *Umbrella = PP.getFileManager().getDirectory(Dirname)) {
Guy Benyei11169dd2012-12-18 14:30:41 +00004771 if (!CurrentModule->getUmbrellaDir())
Richard Smith2b63d152015-05-16 02:28:53 +00004772 ModMap.setUmbrellaDir(CurrentModule, Umbrella, Blob);
4773 else if (CurrentModule->getUmbrellaDir().Entry != Umbrella) {
Ben Langmuir2c9af442014-04-10 17:57:43 +00004774 if ((ClientLoadCapabilities & ARR_OutOfDate) == 0)
4775 Error("mismatched umbrella directories in submodule");
4776 return OutOfDate;
Guy Benyei11169dd2012-12-18 14:30:41 +00004777 }
4778 }
4779 break;
4780 }
David L. Jonesc4808b9e2016-12-15 20:53:26 +00004781
Guy Benyei11169dd2012-12-18 14:30:41 +00004782 case SUBMODULE_METADATA: {
Guy Benyei11169dd2012-12-18 14:30:41 +00004783 F.BaseSubmoduleID = getTotalNumSubmodules();
4784 F.LocalNumSubmodules = Record[0];
4785 unsigned LocalBaseSubmoduleID = Record[1];
4786 if (F.LocalNumSubmodules > 0) {
David L. Jonesc4808b9e2016-12-15 20:53:26 +00004787 // Introduce the global -> local mapping for submodules within this
Guy Benyei11169dd2012-12-18 14:30:41 +00004788 // module.
4789 GlobalSubmoduleMap.insert(std::make_pair(getTotalNumSubmodules()+1,&F));
David L. Jonesc4808b9e2016-12-15 20:53:26 +00004790
4791 // Introduce the local -> global mapping for submodules within this
Guy Benyei11169dd2012-12-18 14:30:41 +00004792 // module.
4793 F.SubmoduleRemap.insertOrReplace(
4794 std::make_pair(LocalBaseSubmoduleID,
4795 F.BaseSubmoduleID - LocalBaseSubmoduleID));
Ben Langmuirfe971d92014-08-16 04:54:18 +00004796
Ben Langmuir52ca6782014-10-20 16:27:32 +00004797 SubmodulesLoaded.resize(SubmodulesLoaded.size() + F.LocalNumSubmodules);
4798 }
Guy Benyei11169dd2012-12-18 14:30:41 +00004799 break;
4800 }
David L. Jonesc4808b9e2016-12-15 20:53:26 +00004801
Guy Benyei11169dd2012-12-18 14:30:41 +00004802 case SUBMODULE_IMPORTS: {
Guy Benyei11169dd2012-12-18 14:30:41 +00004803 for (unsigned Idx = 0; Idx != Record.size(); ++Idx) {
Douglas Gregorfb912652013-03-20 21:10:35 +00004804 UnresolvedModuleRef Unresolved;
Guy Benyei11169dd2012-12-18 14:30:41 +00004805 Unresolved.File = &F;
4806 Unresolved.Mod = CurrentModule;
4807 Unresolved.ID = Record[Idx];
Douglas Gregorfb912652013-03-20 21:10:35 +00004808 Unresolved.Kind = UnresolvedModuleRef::Import;
Guy Benyei11169dd2012-12-18 14:30:41 +00004809 Unresolved.IsWildcard = false;
Douglas Gregorfb912652013-03-20 21:10:35 +00004810 UnresolvedModuleRefs.push_back(Unresolved);
Guy Benyei11169dd2012-12-18 14:30:41 +00004811 }
4812 break;
4813 }
4814
4815 case SUBMODULE_EXPORTS: {
Guy Benyei11169dd2012-12-18 14:30:41 +00004816 for (unsigned Idx = 0; Idx + 1 < Record.size(); Idx += 2) {
Douglas Gregorfb912652013-03-20 21:10:35 +00004817 UnresolvedModuleRef Unresolved;
Guy Benyei11169dd2012-12-18 14:30:41 +00004818 Unresolved.File = &F;
4819 Unresolved.Mod = CurrentModule;
4820 Unresolved.ID = Record[Idx];
Douglas Gregorfb912652013-03-20 21:10:35 +00004821 Unresolved.Kind = UnresolvedModuleRef::Export;
Guy Benyei11169dd2012-12-18 14:30:41 +00004822 Unresolved.IsWildcard = Record[Idx + 1];
Douglas Gregorfb912652013-03-20 21:10:35 +00004823 UnresolvedModuleRefs.push_back(Unresolved);
Guy Benyei11169dd2012-12-18 14:30:41 +00004824 }
David L. Jonesc4808b9e2016-12-15 20:53:26 +00004825
4826 // Once we've loaded the set of exports, there's no reason to keep
Guy Benyei11169dd2012-12-18 14:30:41 +00004827 // the parsed, unresolved exports around.
4828 CurrentModule->UnresolvedExports.clear();
4829 break;
4830 }
4831 case SUBMODULE_REQUIRES: {
Richard Smitha3feee22013-10-28 22:18:19 +00004832 CurrentModule->addRequirement(Blob, Record[0], Context.getLangOpts(),
Guy Benyei11169dd2012-12-18 14:30:41 +00004833 Context.getTargetInfo());
4834 break;
4835 }
Douglas Gregor6ddfca92013-01-14 17:21:00 +00004836
4837 case SUBMODULE_LINK_LIBRARY:
Douglas Gregor6ddfca92013-01-14 17:21:00 +00004838 CurrentModule->LinkLibraries.push_back(
Chris Lattner0e6c9402013-01-20 02:38:54 +00004839 Module::LinkLibrary(Blob, Record[0]));
Douglas Gregor6ddfca92013-01-14 17:21:00 +00004840 break;
Douglas Gregor35b13ec2013-03-20 00:22:05 +00004841
4842 case SUBMODULE_CONFIG_MACRO:
Douglas Gregor35b13ec2013-03-20 00:22:05 +00004843 CurrentModule->ConfigMacros.push_back(Blob.str());
4844 break;
Douglas Gregorfb912652013-03-20 21:10:35 +00004845
4846 case SUBMODULE_CONFLICT: {
Douglas Gregorfb912652013-03-20 21:10:35 +00004847 UnresolvedModuleRef Unresolved;
4848 Unresolved.File = &F;
4849 Unresolved.Mod = CurrentModule;
4850 Unresolved.ID = Record[0];
4851 Unresolved.Kind = UnresolvedModuleRef::Conflict;
4852 Unresolved.IsWildcard = false;
4853 Unresolved.String = Blob;
4854 UnresolvedModuleRefs.push_back(Unresolved);
4855 break;
4856 }
Richard Smithdc1f0422016-07-20 19:10:16 +00004857
4858 case SUBMODULE_INITIALIZERS:
4859 SmallVector<uint32_t, 16> Inits;
4860 for (auto &ID : Record)
4861 Inits.push_back(getGlobalDeclID(F, ID));
4862 Context.addLazyModuleInitializers(CurrentModule, Inits);
4863 break;
Guy Benyei11169dd2012-12-18 14:30:41 +00004864 }
4865 }
4866}
4867
4868/// \brief Parse the record that corresponds to a LangOptions data
4869/// structure.
4870///
4871/// This routine parses the language options from the AST file and then gives
4872/// them to the AST listener if one is set.
4873///
4874/// \returns true if the listener deems the file unacceptable, false otherwise.
4875bool ASTReader::ParseLanguageOptions(const RecordData &Record,
4876 bool Complain,
Richard Smith1e2cf0d2014-10-31 02:28:58 +00004877 ASTReaderListener &Listener,
4878 bool AllowCompatibleDifferences) {
Guy Benyei11169dd2012-12-18 14:30:41 +00004879 LangOptions LangOpts;
4880 unsigned Idx = 0;
4881#define LANGOPT(Name, Bits, Default, Description) \
4882 LangOpts.Name = Record[Idx++];
4883#define ENUM_LANGOPT(Name, Type, Bits, Default, Description) \
4884 LangOpts.set##Name(static_cast<LangOptions::Type>(Record[Idx++]));
4885#include "clang/Basic/LangOptions.def"
Alexey Samsonovedf99a92014-11-07 22:29:38 +00004886#define SANITIZER(NAME, ID) \
4887 LangOpts.Sanitize.set(SanitizerKind::ID, Record[Idx++]);
Will Dietzf54319c2013-01-18 11:30:38 +00004888#include "clang/Basic/Sanitizers.def"
Guy Benyei11169dd2012-12-18 14:30:41 +00004889
Ben Langmuircd98cb72015-06-23 18:20:18 +00004890 for (unsigned N = Record[Idx++]; N; --N)
4891 LangOpts.ModuleFeatures.push_back(ReadString(Record, Idx));
4892
Guy Benyei11169dd2012-12-18 14:30:41 +00004893 ObjCRuntime::Kind runtimeKind = (ObjCRuntime::Kind) Record[Idx++];
4894 VersionTuple runtimeVersion = ReadVersionTuple(Record, Idx);
4895 LangOpts.ObjCRuntime = ObjCRuntime(runtimeKind, runtimeVersion);
Dmitri Gribenkoacf2e782013-02-22 14:21:27 +00004896
Ben Langmuird4a667a2015-06-23 18:20:23 +00004897 LangOpts.CurrentModule = ReadString(Record, Idx);
Dmitri Gribenkoacf2e782013-02-22 14:21:27 +00004898
4899 // Comment options.
4900 for (unsigned N = Record[Idx++]; N; --N) {
4901 LangOpts.CommentOpts.BlockCommandNames.push_back(
4902 ReadString(Record, Idx));
4903 }
Dmitri Gribenkoa7d16ce2013-04-10 15:35:17 +00004904 LangOpts.CommentOpts.ParseAllComments = Record[Idx++];
Dmitri Gribenkoacf2e782013-02-22 14:21:27 +00004905
Samuel Antaoee8fb302016-01-06 13:42:12 +00004906 // OpenMP offloading options.
4907 for (unsigned N = Record[Idx++]; N; --N) {
4908 LangOpts.OMPTargetTriples.push_back(llvm::Triple(ReadString(Record, Idx)));
4909 }
4910
4911 LangOpts.OMPHostIRFile = ReadString(Record, Idx);
4912
Richard Smith1e2cf0d2014-10-31 02:28:58 +00004913 return Listener.ReadLanguageOptions(LangOpts, Complain,
4914 AllowCompatibleDifferences);
Guy Benyei11169dd2012-12-18 14:30:41 +00004915}
4916
Chandler Carruth0d745bc2015-03-14 04:47:43 +00004917bool ASTReader::ParseTargetOptions(const RecordData &Record, bool Complain,
4918 ASTReaderListener &Listener,
4919 bool AllowCompatibleDifferences) {
Guy Benyei11169dd2012-12-18 14:30:41 +00004920 unsigned Idx = 0;
4921 TargetOptions TargetOpts;
4922 TargetOpts.Triple = ReadString(Record, Idx);
4923 TargetOpts.CPU = ReadString(Record, Idx);
4924 TargetOpts.ABI = ReadString(Record, Idx);
Guy Benyei11169dd2012-12-18 14:30:41 +00004925 for (unsigned N = Record[Idx++]; N; --N) {
4926 TargetOpts.FeaturesAsWritten.push_back(ReadString(Record, Idx));
4927 }
4928 for (unsigned N = Record[Idx++]; N; --N) {
4929 TargetOpts.Features.push_back(ReadString(Record, Idx));
4930 }
4931
Chandler Carruth0d745bc2015-03-14 04:47:43 +00004932 return Listener.ReadTargetOptions(TargetOpts, Complain,
4933 AllowCompatibleDifferences);
Guy Benyei11169dd2012-12-18 14:30:41 +00004934}
4935
4936bool ASTReader::ParseDiagnosticOptions(const RecordData &Record, bool Complain,
4937 ASTReaderListener &Listener) {
Ben Langmuirb92de022014-04-29 16:25:26 +00004938 IntrusiveRefCntPtr<DiagnosticOptions> DiagOpts(new DiagnosticOptions);
Guy Benyei11169dd2012-12-18 14:30:41 +00004939 unsigned Idx = 0;
Ben Langmuirb92de022014-04-29 16:25:26 +00004940#define DIAGOPT(Name, Bits, Default) DiagOpts->Name = Record[Idx++];
Guy Benyei11169dd2012-12-18 14:30:41 +00004941#define ENUM_DIAGOPT(Name, Type, Bits, Default) \
Ben Langmuirb92de022014-04-29 16:25:26 +00004942 DiagOpts->set##Name(static_cast<Type>(Record[Idx++]));
Guy Benyei11169dd2012-12-18 14:30:41 +00004943#include "clang/Basic/DiagnosticOptions.def"
4944
Richard Smith3be1cb22014-08-07 00:24:21 +00004945 for (unsigned N = Record[Idx++]; N; --N)
Ben Langmuirb92de022014-04-29 16:25:26 +00004946 DiagOpts->Warnings.push_back(ReadString(Record, Idx));
Richard Smith3be1cb22014-08-07 00:24:21 +00004947 for (unsigned N = Record[Idx++]; N; --N)
4948 DiagOpts->Remarks.push_back(ReadString(Record, Idx));
Guy Benyei11169dd2012-12-18 14:30:41 +00004949
4950 return Listener.ReadDiagnosticOptions(DiagOpts, Complain);
4951}
4952
4953bool ASTReader::ParseFileSystemOptions(const RecordData &Record, bool Complain,
4954 ASTReaderListener &Listener) {
4955 FileSystemOptions FSOpts;
4956 unsigned Idx = 0;
4957 FSOpts.WorkingDir = ReadString(Record, Idx);
4958 return Listener.ReadFileSystemOptions(FSOpts, Complain);
4959}
4960
4961bool ASTReader::ParseHeaderSearchOptions(const RecordData &Record,
4962 bool Complain,
4963 ASTReaderListener &Listener) {
4964 HeaderSearchOptions HSOpts;
4965 unsigned Idx = 0;
4966 HSOpts.Sysroot = ReadString(Record, Idx);
4967
4968 // Include entries.
4969 for (unsigned N = Record[Idx++]; N; --N) {
4970 std::string Path = ReadString(Record, Idx);
4971 frontend::IncludeDirGroup Group
4972 = static_cast<frontend::IncludeDirGroup>(Record[Idx++]);
Guy Benyei11169dd2012-12-18 14:30:41 +00004973 bool IsFramework = Record[Idx++];
4974 bool IgnoreSysRoot = Record[Idx++];
Benjamin Kramer3204b152015-05-29 19:42:19 +00004975 HSOpts.UserEntries.emplace_back(std::move(Path), Group, IsFramework,
4976 IgnoreSysRoot);
Guy Benyei11169dd2012-12-18 14:30:41 +00004977 }
4978
4979 // System header prefixes.
4980 for (unsigned N = Record[Idx++]; N; --N) {
4981 std::string Prefix = ReadString(Record, Idx);
4982 bool IsSystemHeader = Record[Idx++];
Benjamin Kramer3204b152015-05-29 19:42:19 +00004983 HSOpts.SystemHeaderPrefixes.emplace_back(std::move(Prefix), IsSystemHeader);
Guy Benyei11169dd2012-12-18 14:30:41 +00004984 }
4985
4986 HSOpts.ResourceDir = ReadString(Record, Idx);
4987 HSOpts.ModuleCachePath = ReadString(Record, Idx);
Argyrios Kyrtzidis1594c152014-03-03 08:12:05 +00004988 HSOpts.ModuleUserBuildPath = ReadString(Record, Idx);
Guy Benyei11169dd2012-12-18 14:30:41 +00004989 HSOpts.DisableModuleHash = Record[Idx++];
4990 HSOpts.UseBuiltinIncludes = Record[Idx++];
4991 HSOpts.UseStandardSystemIncludes = Record[Idx++];
4992 HSOpts.UseStandardCXXIncludes = Record[Idx++];
4993 HSOpts.UseLibcxx = Record[Idx++];
Argyrios Kyrtzidisbd0b6512015-02-19 20:12:20 +00004994 std::string SpecificModuleCachePath = ReadString(Record, Idx);
Guy Benyei11169dd2012-12-18 14:30:41 +00004995
Argyrios Kyrtzidisbd0b6512015-02-19 20:12:20 +00004996 return Listener.ReadHeaderSearchOptions(HSOpts, SpecificModuleCachePath,
4997 Complain);
Guy Benyei11169dd2012-12-18 14:30:41 +00004998}
4999
5000bool ASTReader::ParsePreprocessorOptions(const RecordData &Record,
5001 bool Complain,
5002 ASTReaderListener &Listener,
5003 std::string &SuggestedPredefines) {
5004 PreprocessorOptions PPOpts;
5005 unsigned Idx = 0;
5006
5007 // Macro definitions/undefs
5008 for (unsigned N = Record[Idx++]; N; --N) {
5009 std::string Macro = ReadString(Record, Idx);
5010 bool IsUndef = Record[Idx++];
5011 PPOpts.Macros.push_back(std::make_pair(Macro, IsUndef));
5012 }
5013
5014 // Includes
5015 for (unsigned N = Record[Idx++]; N; --N) {
5016 PPOpts.Includes.push_back(ReadString(Record, Idx));
5017 }
5018
5019 // Macro Includes
5020 for (unsigned N = Record[Idx++]; N; --N) {
5021 PPOpts.MacroIncludes.push_back(ReadString(Record, Idx));
5022 }
5023
5024 PPOpts.UsePredefines = Record[Idx++];
Argyrios Kyrtzidisd3afa0c2013-04-26 21:33:40 +00005025 PPOpts.DetailedRecord = Record[Idx++];
Guy Benyei11169dd2012-12-18 14:30:41 +00005026 PPOpts.ImplicitPCHInclude = ReadString(Record, Idx);
5027 PPOpts.ImplicitPTHInclude = ReadString(Record, Idx);
5028 PPOpts.ObjCXXARCStandardLibrary =
5029 static_cast<ObjCXXARCStandardLibraryKind>(Record[Idx++]);
5030 SuggestedPredefines.clear();
5031 return Listener.ReadPreprocessorOptions(PPOpts, Complain,
5032 SuggestedPredefines);
5033}
5034
5035std::pair<ModuleFile *, unsigned>
5036ASTReader::getModulePreprocessedEntity(unsigned GlobalIndex) {
5037 GlobalPreprocessedEntityMapType::iterator
5038 I = GlobalPreprocessedEntityMap.find(GlobalIndex);
David L. Jonesc4808b9e2016-12-15 20:53:26 +00005039 assert(I != GlobalPreprocessedEntityMap.end() &&
Guy Benyei11169dd2012-12-18 14:30:41 +00005040 "Corrupted global preprocessed entity map");
5041 ModuleFile *M = I->second;
5042 unsigned LocalIndex = GlobalIndex - M->BasePreprocessedEntityID;
5043 return std::make_pair(M, LocalIndex);
5044}
5045
Benjamin Kramerb4ef6682015-02-06 17:25:10 +00005046llvm::iterator_range<PreprocessingRecord::iterator>
Guy Benyei11169dd2012-12-18 14:30:41 +00005047ASTReader::getModulePreprocessedEntities(ModuleFile &Mod) const {
5048 if (PreprocessingRecord *PPRec = PP.getPreprocessingRecord())
5049 return PPRec->getIteratorsForLoadedRange(Mod.BasePreprocessedEntityID,
5050 Mod.NumPreprocessedEntities);
5051
Benjamin Kramerb4ef6682015-02-06 17:25:10 +00005052 return llvm::make_range(PreprocessingRecord::iterator(),
5053 PreprocessingRecord::iterator());
Guy Benyei11169dd2012-12-18 14:30:41 +00005054}
5055
Benjamin Kramerb4ef6682015-02-06 17:25:10 +00005056llvm::iterator_range<ASTReader::ModuleDeclIterator>
Guy Benyei11169dd2012-12-18 14:30:41 +00005057ASTReader::getModuleFileLevelDecls(ModuleFile &Mod) {
Benjamin Kramerb4ef6682015-02-06 17:25:10 +00005058 return llvm::make_range(
5059 ModuleDeclIterator(this, &Mod, Mod.FileSortedDecls),
5060 ModuleDeclIterator(this, &Mod,
5061 Mod.FileSortedDecls + Mod.NumFileSortedDecls));
Guy Benyei11169dd2012-12-18 14:30:41 +00005062}
5063
5064PreprocessedEntity *ASTReader::ReadPreprocessedEntity(unsigned Index) {
5065 PreprocessedEntityID PPID = Index+1;
5066 std::pair<ModuleFile *, unsigned> PPInfo = getModulePreprocessedEntity(Index);
5067 ModuleFile &M = *PPInfo.first;
5068 unsigned LocalIndex = PPInfo.second;
5069 const PPEntityOffset &PPOffs = M.PreprocessedEntityOffsets[LocalIndex];
5070
Guy Benyei11169dd2012-12-18 14:30:41 +00005071 if (!PP.getPreprocessingRecord()) {
5072 Error("no preprocessing record");
Craig Toppera13603a2014-05-22 05:54:18 +00005073 return nullptr;
Guy Benyei11169dd2012-12-18 14:30:41 +00005074 }
David L. Jonesc4808b9e2016-12-15 20:53:26 +00005075
5076 SavedStreamPosition SavedPosition(M.PreprocessorDetailCursor);
Chris Lattner7fb3bef2013-01-20 00:56:42 +00005077 M.PreprocessorDetailCursor.JumpToBit(PPOffs.BitOffset);
5078
5079 llvm::BitstreamEntry Entry =
5080 M.PreprocessorDetailCursor.advance(BitstreamCursor::AF_DontPopBlockAtEnd);
5081 if (Entry.Kind != llvm::BitstreamEntry::Record)
Craig Toppera13603a2014-05-22 05:54:18 +00005082 return nullptr;
Chris Lattner7fb3bef2013-01-20 00:56:42 +00005083
Guy Benyei11169dd2012-12-18 14:30:41 +00005084 // Read the record.
Richard Smithcb34bd32016-03-27 07:28:06 +00005085 SourceRange Range(TranslateSourceLocation(M, PPOffs.getBegin()),
5086 TranslateSourceLocation(M, PPOffs.getEnd()));
Guy Benyei11169dd2012-12-18 14:30:41 +00005087 PreprocessingRecord &PPRec = *PP.getPreprocessingRecord();
Chris Lattner0e6c9402013-01-20 02:38:54 +00005088 StringRef Blob;
Guy Benyei11169dd2012-12-18 14:30:41 +00005089 RecordData Record;
5090 PreprocessorDetailRecordTypes RecType =
Chris Lattner0e6c9402013-01-20 02:38:54 +00005091 (PreprocessorDetailRecordTypes)M.PreprocessorDetailCursor.readRecord(
5092 Entry.ID, Record, &Blob);
Guy Benyei11169dd2012-12-18 14:30:41 +00005093 switch (RecType) {
5094 case PPD_MACRO_EXPANSION: {
5095 bool isBuiltin = Record[0];
Craig Toppera13603a2014-05-22 05:54:18 +00005096 IdentifierInfo *Name = nullptr;
Richard Smith66a81862015-05-04 02:25:31 +00005097 MacroDefinitionRecord *Def = nullptr;
Guy Benyei11169dd2012-12-18 14:30:41 +00005098 if (isBuiltin)
5099 Name = getLocalIdentifier(M, Record[1]);
5100 else {
Richard Smith66a81862015-05-04 02:25:31 +00005101 PreprocessedEntityID GlobalID =
5102 getGlobalPreprocessedEntityID(M, Record[1]);
5103 Def = cast<MacroDefinitionRecord>(
5104 PPRec.getLoadedPreprocessedEntity(GlobalID - 1));
Guy Benyei11169dd2012-12-18 14:30:41 +00005105 }
5106
5107 MacroExpansion *ME;
5108 if (isBuiltin)
5109 ME = new (PPRec) MacroExpansion(Name, Range);
5110 else
5111 ME = new (PPRec) MacroExpansion(Def, Range);
5112
5113 return ME;
5114 }
David L. Jonesc4808b9e2016-12-15 20:53:26 +00005115
Guy Benyei11169dd2012-12-18 14:30:41 +00005116 case PPD_MACRO_DEFINITION: {
5117 // Decode the identifier info and then check again; if the macro is
5118 // still defined and associated with the identifier,
5119 IdentifierInfo *II = getLocalIdentifier(M, Record[0]);
Richard Smith66a81862015-05-04 02:25:31 +00005120 MacroDefinitionRecord *MD = new (PPRec) MacroDefinitionRecord(II, Range);
Guy Benyei11169dd2012-12-18 14:30:41 +00005121
5122 if (DeserializationListener)
5123 DeserializationListener->MacroDefinitionRead(PPID, MD);
5124
5125 return MD;
5126 }
David L. Jonesc4808b9e2016-12-15 20:53:26 +00005127
Guy Benyei11169dd2012-12-18 14:30:41 +00005128 case PPD_INCLUSION_DIRECTIVE: {
Chris Lattner0e6c9402013-01-20 02:38:54 +00005129 const char *FullFileNameStart = Blob.data() + Record[0];
5130 StringRef FullFileName(FullFileNameStart, Blob.size() - Record[0]);
Craig Toppera13603a2014-05-22 05:54:18 +00005131 const FileEntry *File = nullptr;
Guy Benyei11169dd2012-12-18 14:30:41 +00005132 if (!FullFileName.empty())
5133 File = PP.getFileManager().getFile(FullFileName);
David L. Jonesc4808b9e2016-12-15 20:53:26 +00005134
Guy Benyei11169dd2012-12-18 14:30:41 +00005135 // FIXME: Stable encoding
5136 InclusionDirective::InclusionKind Kind
5137 = static_cast<InclusionDirective::InclusionKind>(Record[2]);
5138 InclusionDirective *ID
5139 = new (PPRec) InclusionDirective(PPRec, Kind,
Chris Lattner0e6c9402013-01-20 02:38:54 +00005140 StringRef(Blob.data(), Record[0]),
Guy Benyei11169dd2012-12-18 14:30:41 +00005141 Record[1], Record[3],
5142 File,
5143 Range);
5144 return ID;
5145 }
5146 }
5147
5148 llvm_unreachable("Invalid PreprocessorDetailRecordTypes");
5149}
5150
5151/// \brief \arg SLocMapI points at a chunk of a module that contains no
5152/// preprocessed entities or the entities it contains are not the ones we are
5153/// looking for. Find the next module that contains entities and return the ID
5154/// of the first entry.
5155PreprocessedEntityID ASTReader::findNextPreprocessedEntity(
5156 GlobalSLocOffsetMapType::const_iterator SLocMapI) const {
5157 ++SLocMapI;
5158 for (GlobalSLocOffsetMapType::const_iterator
5159 EndI = GlobalSLocOffsetMap.end(); SLocMapI != EndI; ++SLocMapI) {
5160 ModuleFile &M = *SLocMapI->second;
5161 if (M.NumPreprocessedEntities)
5162 return M.BasePreprocessedEntityID;
5163 }
5164
5165 return getTotalNumPreprocessedEntities();
5166}
5167
5168namespace {
5169
Guy Benyei11169dd2012-12-18 14:30:41 +00005170struct PPEntityComp {
5171 const ASTReader &Reader;
5172 ModuleFile &M;
5173
5174 PPEntityComp(const ASTReader &Reader, ModuleFile &M) : Reader(Reader), M(M) { }
5175
5176 bool operator()(const PPEntityOffset &L, const PPEntityOffset &R) const {
5177 SourceLocation LHS = getLoc(L);
5178 SourceLocation RHS = getLoc(R);
5179 return Reader.getSourceManager().isBeforeInTranslationUnit(LHS, RHS);
5180 }
5181
5182 bool operator()(const PPEntityOffset &L, SourceLocation RHS) const {
5183 SourceLocation LHS = getLoc(L);
5184 return Reader.getSourceManager().isBeforeInTranslationUnit(LHS, RHS);
5185 }
5186
5187 bool operator()(SourceLocation LHS, const PPEntityOffset &R) const {
5188 SourceLocation RHS = getLoc(R);
5189 return Reader.getSourceManager().isBeforeInTranslationUnit(LHS, RHS);
5190 }
5191
5192 SourceLocation getLoc(const PPEntityOffset &PPE) const {
Richard Smithb22a1d12016-03-27 20:13:24 +00005193 return Reader.TranslateSourceLocation(M, PPE.getBegin());
Guy Benyei11169dd2012-12-18 14:30:41 +00005194 }
5195};
5196
Eugene Zelenkoe95e7d52016-09-07 21:53:17 +00005197} // end anonymous namespace
Guy Benyei11169dd2012-12-18 14:30:41 +00005198
Alp Toker2e9ce4c2014-05-16 18:59:21 +00005199PreprocessedEntityID ASTReader::findPreprocessedEntity(SourceLocation Loc,
5200 bool EndsAfter) const {
5201 if (SourceMgr.isLocalSourceLocation(Loc))
Guy Benyei11169dd2012-12-18 14:30:41 +00005202 return getTotalNumPreprocessedEntities();
5203
Alp Toker2e9ce4c2014-05-16 18:59:21 +00005204 GlobalSLocOffsetMapType::const_iterator SLocMapI = GlobalSLocOffsetMap.find(
5205 SourceManager::MaxLoadedOffset - Loc.getOffset() - 1);
Guy Benyei11169dd2012-12-18 14:30:41 +00005206 assert(SLocMapI != GlobalSLocOffsetMap.end() &&
5207 "Corrupted global sloc offset map");
5208
5209 if (SLocMapI->second->NumPreprocessedEntities == 0)
5210 return findNextPreprocessedEntity(SLocMapI);
5211
5212 ModuleFile &M = *SLocMapI->second;
5213 typedef const PPEntityOffset *pp_iterator;
5214 pp_iterator pp_begin = M.PreprocessedEntityOffsets;
5215 pp_iterator pp_end = pp_begin + M.NumPreprocessedEntities;
5216
5217 size_t Count = M.NumPreprocessedEntities;
5218 size_t Half;
5219 pp_iterator First = pp_begin;
5220 pp_iterator PPI;
5221
Alp Toker2e9ce4c2014-05-16 18:59:21 +00005222 if (EndsAfter) {
5223 PPI = std::upper_bound(pp_begin, pp_end, Loc,
Richard Smithb22a1d12016-03-27 20:13:24 +00005224 PPEntityComp(*this, M));
Alp Toker2e9ce4c2014-05-16 18:59:21 +00005225 } else {
5226 // Do a binary search manually instead of using std::lower_bound because
5227 // The end locations of entities may be unordered (when a macro expansion
5228 // is inside another macro argument), but for this case it is not important
5229 // whether we get the first macro expansion or its containing macro.
5230 while (Count > 0) {
5231 Half = Count / 2;
5232 PPI = First;
5233 std::advance(PPI, Half);
Richard Smithb22a1d12016-03-27 20:13:24 +00005234 if (SourceMgr.isBeforeInTranslationUnit(
5235 TranslateSourceLocation(M, PPI->getEnd()), Loc)) {
Alp Toker2e9ce4c2014-05-16 18:59:21 +00005236 First = PPI;
5237 ++First;
5238 Count = Count - Half - 1;
5239 } else
5240 Count = Half;
5241 }
Guy Benyei11169dd2012-12-18 14:30:41 +00005242 }
5243
5244 if (PPI == pp_end)
5245 return findNextPreprocessedEntity(SLocMapI);
5246
5247 return M.BasePreprocessedEntityID + (PPI - pp_begin);
5248}
5249
Guy Benyei11169dd2012-12-18 14:30:41 +00005250/// \brief Returns a pair of [Begin, End) indices of preallocated
5251/// preprocessed entities that \arg Range encompasses.
5252std::pair<unsigned, unsigned>
5253 ASTReader::findPreprocessedEntitiesInRange(SourceRange Range) {
5254 if (Range.isInvalid())
5255 return std::make_pair(0,0);
5256 assert(!SourceMgr.isBeforeInTranslationUnit(Range.getEnd(),Range.getBegin()));
5257
Alp Toker2e9ce4c2014-05-16 18:59:21 +00005258 PreprocessedEntityID BeginID =
5259 findPreprocessedEntity(Range.getBegin(), false);
5260 PreprocessedEntityID EndID = findPreprocessedEntity(Range.getEnd(), true);
Guy Benyei11169dd2012-12-18 14:30:41 +00005261 return std::make_pair(BeginID, EndID);
5262}
5263
5264/// \brief Optionally returns true or false if the preallocated preprocessed
5265/// entity with index \arg Index came from file \arg FID.
David Blaikie05785d12013-02-20 22:23:23 +00005266Optional<bool> ASTReader::isPreprocessedEntityInFileID(unsigned Index,
Guy Benyei11169dd2012-12-18 14:30:41 +00005267 FileID FID) {
5268 if (FID.isInvalid())
5269 return false;
5270
5271 std::pair<ModuleFile *, unsigned> PPInfo = getModulePreprocessedEntity(Index);
5272 ModuleFile &M = *PPInfo.first;
5273 unsigned LocalIndex = PPInfo.second;
5274 const PPEntityOffset &PPOffs = M.PreprocessedEntityOffsets[LocalIndex];
David L. Jonesc4808b9e2016-12-15 20:53:26 +00005275
Richard Smithcb34bd32016-03-27 07:28:06 +00005276 SourceLocation Loc = TranslateSourceLocation(M, PPOffs.getBegin());
Guy Benyei11169dd2012-12-18 14:30:41 +00005277 if (Loc.isInvalid())
5278 return false;
David L. Jonesc4808b9e2016-12-15 20:53:26 +00005279
Guy Benyei11169dd2012-12-18 14:30:41 +00005280 if (SourceMgr.isInFileID(SourceMgr.getFileLoc(Loc), FID))
5281 return true;
5282 else
5283 return false;
5284}
5285
5286namespace {
Eugene Zelenkoe95e7d52016-09-07 21:53:17 +00005287
Guy Benyei11169dd2012-12-18 14:30:41 +00005288 /// \brief Visitor used to search for information about a header file.
5289 class HeaderFileInfoVisitor {
Guy Benyei11169dd2012-12-18 14:30:41 +00005290 const FileEntry *FE;
David L. Jonesc4808b9e2016-12-15 20:53:26 +00005291
David Blaikie05785d12013-02-20 22:23:23 +00005292 Optional<HeaderFileInfo> HFI;
David L. Jonesc4808b9e2016-12-15 20:53:26 +00005293
Guy Benyei11169dd2012-12-18 14:30:41 +00005294 public:
Argyrios Kyrtzidis61a38962013-03-06 18:12:44 +00005295 explicit HeaderFileInfoVisitor(const FileEntry *FE)
5296 : FE(FE) { }
Benjamin Kramer9a9efba2015-07-25 12:14:04 +00005297
5298 bool operator()(ModuleFile &M) {
Guy Benyei11169dd2012-12-18 14:30:41 +00005299 HeaderFileInfoLookupTable *Table
5300 = static_cast<HeaderFileInfoLookupTable *>(M.HeaderFileInfoTable);
5301 if (!Table)
5302 return false;
5303
5304 // Look in the on-disk hash table for an entry for this file name.
Richard Smithbdf2d932015-07-30 03:37:16 +00005305 HeaderFileInfoLookupTable::iterator Pos = Table->find(FE);
Guy Benyei11169dd2012-12-18 14:30:41 +00005306 if (Pos == Table->end())
5307 return false;
5308
Richard Smithbdf2d932015-07-30 03:37:16 +00005309 HFI = *Pos;
Guy Benyei11169dd2012-12-18 14:30:41 +00005310 return true;
5311 }
David L. Jonesc4808b9e2016-12-15 20:53:26 +00005312
David Blaikie05785d12013-02-20 22:23:23 +00005313 Optional<HeaderFileInfo> getHeaderFileInfo() const { return HFI; }
Guy Benyei11169dd2012-12-18 14:30:41 +00005314 };
Eugene Zelenkoe95e7d52016-09-07 21:53:17 +00005315
5316} // end anonymous namespace
Guy Benyei11169dd2012-12-18 14:30:41 +00005317
5318HeaderFileInfo ASTReader::GetHeaderFileInfo(const FileEntry *FE) {
Argyrios Kyrtzidis61a38962013-03-06 18:12:44 +00005319 HeaderFileInfoVisitor Visitor(FE);
Benjamin Kramer9a9efba2015-07-25 12:14:04 +00005320 ModuleMgr.visit(Visitor);
Argyrios Kyrtzidis1054bbf2013-05-08 23:46:55 +00005321 if (Optional<HeaderFileInfo> HFI = Visitor.getHeaderFileInfo())
Guy Benyei11169dd2012-12-18 14:30:41 +00005322 return *HFI;
David L. Jonesc4808b9e2016-12-15 20:53:26 +00005323
Guy Benyei11169dd2012-12-18 14:30:41 +00005324 return HeaderFileInfo();
5325}
5326
5327void ASTReader::ReadPragmaDiagnosticMappings(DiagnosticsEngine &Diag) {
Richard Smithd230de22017-01-26 01:01:01 +00005328 using DiagState = DiagnosticsEngine::DiagState;
5329 SmallVector<DiagState *, 32> DiagStates;
5330
Duncan P. N. Exon Smith96a06e02017-01-28 22:15:22 +00005331 for (ModuleFile &F : ModuleMgr) {
Guy Benyei11169dd2012-12-18 14:30:41 +00005332 unsigned Idx = 0;
Richard Smithd230de22017-01-26 01:01:01 +00005333 auto &Record = F.PragmaDiagMappings;
5334 if (Record.empty())
5335 continue;
David L. Jonesc4808b9e2016-12-15 20:53:26 +00005336
Richard Smithd230de22017-01-26 01:01:01 +00005337 DiagStates.clear();
5338
5339 auto ReadDiagState =
5340 [&](const DiagState &BasedOn, SourceLocation Loc,
5341 bool IncludeNonPragmaStates) -> DiagnosticsEngine::DiagState * {
5342 unsigned BackrefID = Record[Idx++];
5343 if (BackrefID != 0)
5344 return DiagStates[BackrefID - 1];
5345
Guy Benyei11169dd2012-12-18 14:30:41 +00005346 // A new DiagState was created here.
Richard Smithd230de22017-01-26 01:01:01 +00005347 Diag.DiagStates.push_back(BasedOn);
5348 DiagState *NewState = &Diag.DiagStates.back();
Guy Benyei11169dd2012-12-18 14:30:41 +00005349 DiagStates.push_back(NewState);
Richard Smithd230de22017-01-26 01:01:01 +00005350 while (Idx + 1 < Record.size() && Record[Idx] != unsigned(-1)) {
5351 unsigned DiagID = Record[Idx++];
5352 diag::Severity Map = (diag::Severity)Record[Idx++];
Alp Tokerc726c362014-06-10 09:31:37 +00005353 DiagnosticMapping Mapping = Diag.makeUserMapping(Map, Loc);
Richard Smithd230de22017-01-26 01:01:01 +00005354 if (Mapping.isPragma() || IncludeNonPragmaStates)
5355 NewState->setMapping(DiagID, Mapping);
5356 }
5357 assert(Idx != Record.size() && Record[Idx] == unsigned(-1) &&
5358 "Invalid data, didn't find '-1' marking end of diag/map pairs");
5359 ++Idx;
5360 return NewState;
5361 };
5362
5363 auto *FirstState = ReadDiagState(
5364 F.isModule() ? DiagState() : *Diag.DiagStatesByLoc.CurDiagState,
5365 SourceLocation(), F.isModule());
5366 SourceLocation CurStateLoc =
5367 ReadSourceLocation(F, F.PragmaDiagMappings[Idx++]);
5368 auto *CurState = ReadDiagState(*FirstState, CurStateLoc, false);
5369
5370 if (!F.isModule()) {
5371 Diag.DiagStatesByLoc.CurDiagState = CurState;
5372 Diag.DiagStatesByLoc.CurDiagStateLoc = CurStateLoc;
5373
5374 // Preserve the property that the imaginary root file describes the
5375 // current state.
5376 auto &T = Diag.DiagStatesByLoc.Files[FileID()].StateTransitions;
5377 if (T.empty())
5378 T.push_back({CurState, 0});
5379 else
5380 T[0].State = CurState;
5381 }
5382
5383 while (Idx < Record.size()) {
5384 SourceLocation Loc = ReadSourceLocation(F, Record[Idx++]);
5385 auto IDAndOffset = SourceMgr.getDecomposedLoc(Loc);
5386 assert(IDAndOffset.second == 0 && "not a start location for a FileID");
5387 unsigned Transitions = Record[Idx++];
5388
5389 // Note that we don't need to set up Parent/ParentOffset here, because
5390 // we won't be changing the diagnostic state within imported FileIDs
5391 // (other than perhaps appending to the main source file, which has no
5392 // parent).
5393 auto &F = Diag.DiagStatesByLoc.Files[IDAndOffset.first];
5394 F.StateTransitions.reserve(F.StateTransitions.size() + Transitions);
5395 for (unsigned I = 0; I != Transitions; ++I) {
5396 unsigned Offset = Record[Idx++];
5397 auto *State =
5398 ReadDiagState(*FirstState, Loc.getLocWithOffset(Offset), false);
5399 F.StateTransitions.push_back({State, Offset});
Guy Benyei11169dd2012-12-18 14:30:41 +00005400 }
5401 }
Richard Smithd230de22017-01-26 01:01:01 +00005402
5403 // Don't try to read these mappings again.
5404 Record.clear();
Guy Benyei11169dd2012-12-18 14:30:41 +00005405 }
5406}
5407
5408/// \brief Get the correct cursor and offset for loading a type.
5409ASTReader::RecordLocation ASTReader::TypeCursorForIndex(unsigned Index) {
5410 GlobalTypeMapType::iterator I = GlobalTypeMap.find(Index);
5411 assert(I != GlobalTypeMap.end() && "Corrupted global type map");
5412 ModuleFile *M = I->second;
5413 return RecordLocation(M, M->TypeOffsets[Index - M->BaseTypeIndex]);
5414}
5415
5416/// \brief Read and return the type with the given index..
5417///
5418/// The index is the type ID, shifted and minus the number of predefs. This
5419/// routine actually reads the record corresponding to the type at the given
5420/// location. It is a helper routine for GetType, which deals with reading type
5421/// IDs.
5422QualType ASTReader::readTypeRecord(unsigned Index) {
5423 RecordLocation Loc = TypeCursorForIndex(Index);
Chris Lattner7fb3bef2013-01-20 00:56:42 +00005424 BitstreamCursor &DeclsCursor = Loc.F->DeclsCursor;
Guy Benyei11169dd2012-12-18 14:30:41 +00005425
5426 // Keep track of where we are in the stream, then jump back there
5427 // after reading this type.
5428 SavedStreamPosition SavedPosition(DeclsCursor);
5429
5430 ReadingKindTracker ReadingKind(Read_Type, *this);
5431
5432 // Note that we are loading a type record.
5433 Deserializing AType(this);
5434
5435 unsigned Idx = 0;
5436 DeclsCursor.JumpToBit(Loc.Offset);
5437 RecordData Record;
5438 unsigned Code = DeclsCursor.ReadCode();
Chris Lattner0e6c9402013-01-20 02:38:54 +00005439 switch ((TypeCode)DeclsCursor.readRecord(Code, Record)) {
Guy Benyei11169dd2012-12-18 14:30:41 +00005440 case TYPE_EXT_QUAL: {
5441 if (Record.size() != 2) {
5442 Error("Incorrect encoding of extended qualifier type");
5443 return QualType();
5444 }
5445 QualType Base = readType(*Loc.F, Record, Idx);
5446 Qualifiers Quals = Qualifiers::fromOpaqueValue(Record[Idx++]);
5447 return Context.getQualifiedType(Base, Quals);
5448 }
5449
5450 case TYPE_COMPLEX: {
5451 if (Record.size() != 1) {
5452 Error("Incorrect encoding of complex type");
5453 return QualType();
5454 }
5455 QualType ElemType = readType(*Loc.F, Record, Idx);
5456 return Context.getComplexType(ElemType);
5457 }
5458
5459 case TYPE_POINTER: {
5460 if (Record.size() != 1) {
5461 Error("Incorrect encoding of pointer type");
5462 return QualType();
5463 }
5464 QualType PointeeType = readType(*Loc.F, Record, Idx);
5465 return Context.getPointerType(PointeeType);
5466 }
5467
Reid Kleckner8a365022013-06-24 17:51:48 +00005468 case TYPE_DECAYED: {
5469 if (Record.size() != 1) {
5470 Error("Incorrect encoding of decayed type");
5471 return QualType();
5472 }
5473 QualType OriginalType = readType(*Loc.F, Record, Idx);
5474 QualType DT = Context.getAdjustedParameterType(OriginalType);
5475 if (!isa<DecayedType>(DT))
5476 Error("Decayed type does not decay");
5477 return DT;
5478 }
5479
Reid Kleckner0503a872013-12-05 01:23:43 +00005480 case TYPE_ADJUSTED: {
5481 if (Record.size() != 2) {
5482 Error("Incorrect encoding of adjusted type");
5483 return QualType();
5484 }
5485 QualType OriginalTy = readType(*Loc.F, Record, Idx);
5486 QualType AdjustedTy = readType(*Loc.F, Record, Idx);
5487 return Context.getAdjustedType(OriginalTy, AdjustedTy);
5488 }
5489
Guy Benyei11169dd2012-12-18 14:30:41 +00005490 case TYPE_BLOCK_POINTER: {
5491 if (Record.size() != 1) {
5492 Error("Incorrect encoding of block pointer type");
5493 return QualType();
5494 }
5495 QualType PointeeType = readType(*Loc.F, Record, Idx);
5496 return Context.getBlockPointerType(PointeeType);
5497 }
5498
5499 case TYPE_LVALUE_REFERENCE: {
5500 if (Record.size() != 2) {
5501 Error("Incorrect encoding of lvalue reference type");
5502 return QualType();
5503 }
5504 QualType PointeeType = readType(*Loc.F, Record, Idx);
5505 return Context.getLValueReferenceType(PointeeType, Record[1]);
5506 }
5507
5508 case TYPE_RVALUE_REFERENCE: {
5509 if (Record.size() != 1) {
5510 Error("Incorrect encoding of rvalue reference type");
5511 return QualType();
5512 }
5513 QualType PointeeType = readType(*Loc.F, Record, Idx);
5514 return Context.getRValueReferenceType(PointeeType);
5515 }
5516
5517 case TYPE_MEMBER_POINTER: {
5518 if (Record.size() != 2) {
5519 Error("Incorrect encoding of member pointer type");
5520 return QualType();
5521 }
5522 QualType PointeeType = readType(*Loc.F, Record, Idx);
5523 QualType ClassType = readType(*Loc.F, Record, Idx);
5524 if (PointeeType.isNull() || ClassType.isNull())
5525 return QualType();
David L. Jonesc4808b9e2016-12-15 20:53:26 +00005526
Guy Benyei11169dd2012-12-18 14:30:41 +00005527 return Context.getMemberPointerType(PointeeType, ClassType.getTypePtr());
5528 }
5529
5530 case TYPE_CONSTANT_ARRAY: {
5531 QualType ElementType = readType(*Loc.F, Record, Idx);
5532 ArrayType::ArraySizeModifier ASM = (ArrayType::ArraySizeModifier)Record[1];
5533 unsigned IndexTypeQuals = Record[2];
5534 unsigned Idx = 3;
5535 llvm::APInt Size = ReadAPInt(Record, Idx);
5536 return Context.getConstantArrayType(ElementType, Size,
5537 ASM, IndexTypeQuals);
5538 }
5539
5540 case TYPE_INCOMPLETE_ARRAY: {
5541 QualType ElementType = readType(*Loc.F, Record, Idx);
5542 ArrayType::ArraySizeModifier ASM = (ArrayType::ArraySizeModifier)Record[1];
5543 unsigned IndexTypeQuals = Record[2];
5544 return Context.getIncompleteArrayType(ElementType, ASM, IndexTypeQuals);
5545 }
5546
5547 case TYPE_VARIABLE_ARRAY: {
5548 QualType ElementType = readType(*Loc.F, Record, Idx);
5549 ArrayType::ArraySizeModifier ASM = (ArrayType::ArraySizeModifier)Record[1];
5550 unsigned IndexTypeQuals = Record[2];
5551 SourceLocation LBLoc = ReadSourceLocation(*Loc.F, Record[3]);
5552 SourceLocation RBLoc = ReadSourceLocation(*Loc.F, Record[4]);
5553 return Context.getVariableArrayType(ElementType, ReadExpr(*Loc.F),
5554 ASM, IndexTypeQuals,
5555 SourceRange(LBLoc, RBLoc));
5556 }
5557
5558 case TYPE_VECTOR: {
5559 if (Record.size() != 3) {
5560 Error("incorrect encoding of vector type in AST file");
5561 return QualType();
5562 }
5563
5564 QualType ElementType = readType(*Loc.F, Record, Idx);
5565 unsigned NumElements = Record[1];
5566 unsigned VecKind = Record[2];
5567 return Context.getVectorType(ElementType, NumElements,
5568 (VectorType::VectorKind)VecKind);
5569 }
5570
5571 case TYPE_EXT_VECTOR: {
5572 if (Record.size() != 3) {
5573 Error("incorrect encoding of extended vector type in AST file");
5574 return QualType();
5575 }
5576
5577 QualType ElementType = readType(*Loc.F, Record, Idx);
5578 unsigned NumElements = Record[1];
5579 return Context.getExtVectorType(ElementType, NumElements);
5580 }
5581
5582 case TYPE_FUNCTION_NO_PROTO: {
5583 if (Record.size() != 6) {
5584 Error("incorrect encoding of no-proto function type");
5585 return QualType();
5586 }
5587 QualType ResultType = readType(*Loc.F, Record, Idx);
5588 FunctionType::ExtInfo Info(Record[1], Record[2], Record[3],
5589 (CallingConv)Record[4], Record[5]);
5590 return Context.getFunctionNoProtoType(ResultType, Info);
5591 }
5592
5593 case TYPE_FUNCTION_PROTO: {
5594 QualType ResultType = readType(*Loc.F, Record, Idx);
5595
5596 FunctionProtoType::ExtProtoInfo EPI;
5597 EPI.ExtInfo = FunctionType::ExtInfo(/*noreturn*/ Record[1],
5598 /*hasregparm*/ Record[2],
5599 /*regparm*/ Record[3],
5600 static_cast<CallingConv>(Record[4]),
5601 /*produces*/ Record[5]);
5602
5603 unsigned Idx = 6;
Guy Benyei11169dd2012-12-18 14:30:41 +00005604
5605 EPI.Variadic = Record[Idx++];
5606 EPI.HasTrailingReturn = Record[Idx++];
5607 EPI.TypeQuals = Record[Idx++];
5608 EPI.RefQualifier = static_cast<RefQualifierKind>(Record[Idx++]);
Richard Smith564417a2014-03-20 21:47:22 +00005609 SmallVector<QualType, 8> ExceptionStorage;
Richard Smith8acb4282014-07-31 21:57:55 +00005610 readExceptionSpec(*Loc.F, ExceptionStorage, EPI.ExceptionSpec, Record, Idx);
Richard Smith01b2cb42014-07-26 06:37:51 +00005611
5612 unsigned NumParams = Record[Idx++];
5613 SmallVector<QualType, 16> ParamTypes;
5614 for (unsigned I = 0; I != NumParams; ++I)
5615 ParamTypes.push_back(readType(*Loc.F, Record, Idx));
5616
John McCall18afab72016-03-01 00:49:02 +00005617 SmallVector<FunctionProtoType::ExtParameterInfo, 4> ExtParameterInfos;
5618 if (Idx != Record.size()) {
5619 for (unsigned I = 0; I != NumParams; ++I)
5620 ExtParameterInfos.push_back(
5621 FunctionProtoType::ExtParameterInfo
5622 ::getFromOpaqueValue(Record[Idx++]));
5623 EPI.ExtParameterInfos = ExtParameterInfos.data();
5624 }
5625
5626 assert(Idx == Record.size());
5627
Jordan Rose5c382722013-03-08 21:51:21 +00005628 return Context.getFunctionType(ResultType, ParamTypes, EPI);
Guy Benyei11169dd2012-12-18 14:30:41 +00005629 }
5630
5631 case TYPE_UNRESOLVED_USING: {
5632 unsigned Idx = 0;
5633 return Context.getTypeDeclType(
5634 ReadDeclAs<UnresolvedUsingTypenameDecl>(*Loc.F, Record, Idx));
5635 }
David L. Jonesc4808b9e2016-12-15 20:53:26 +00005636
Guy Benyei11169dd2012-12-18 14:30:41 +00005637 case TYPE_TYPEDEF: {
5638 if (Record.size() != 2) {
5639 Error("incorrect encoding of typedef type");
5640 return QualType();
5641 }
5642 unsigned Idx = 0;
5643 TypedefNameDecl *Decl = ReadDeclAs<TypedefNameDecl>(*Loc.F, Record, Idx);
5644 QualType Canonical = readType(*Loc.F, Record, Idx);
5645 if (!Canonical.isNull())
5646 Canonical = Context.getCanonicalType(Canonical);
5647 return Context.getTypedefType(Decl, Canonical);
5648 }
5649
5650 case TYPE_TYPEOF_EXPR:
5651 return Context.getTypeOfExprType(ReadExpr(*Loc.F));
5652
5653 case TYPE_TYPEOF: {
5654 if (Record.size() != 1) {
5655 Error("incorrect encoding of typeof(type) in AST file");
5656 return QualType();
5657 }
5658 QualType UnderlyingType = readType(*Loc.F, Record, Idx);
5659 return Context.getTypeOfType(UnderlyingType);
5660 }
5661
5662 case TYPE_DECLTYPE: {
5663 QualType UnderlyingType = readType(*Loc.F, Record, Idx);
5664 return Context.getDecltypeType(ReadExpr(*Loc.F), UnderlyingType);
5665 }
5666
5667 case TYPE_UNARY_TRANSFORM: {
5668 QualType BaseType = readType(*Loc.F, Record, Idx);
5669 QualType UnderlyingType = readType(*Loc.F, Record, Idx);
5670 UnaryTransformType::UTTKind UKind = (UnaryTransformType::UTTKind)Record[2];
5671 return Context.getUnaryTransformType(BaseType, UnderlyingType, UKind);
5672 }
5673
Richard Smith74aeef52013-04-26 16:15:35 +00005674 case TYPE_AUTO: {
5675 QualType Deduced = readType(*Loc.F, Record, Idx);
Richard Smithe301ba22015-11-11 02:02:15 +00005676 AutoTypeKeyword Keyword = (AutoTypeKeyword)Record[Idx++];
Richard Smith27d807c2013-04-30 13:56:41 +00005677 bool IsDependent = Deduced.isNull() ? Record[Idx++] : false;
Richard Smithe301ba22015-11-11 02:02:15 +00005678 return Context.getAutoType(Deduced, Keyword, IsDependent);
Richard Smith74aeef52013-04-26 16:15:35 +00005679 }
Guy Benyei11169dd2012-12-18 14:30:41 +00005680
Richard Smith600b5262017-01-26 20:40:47 +00005681 case TYPE_DEDUCED_TEMPLATE_SPECIALIZATION: {
5682 TemplateName Name = ReadTemplateName(*Loc.F, Record, Idx);
5683 QualType Deduced = readType(*Loc.F, Record, Idx);
5684 bool IsDependent = Deduced.isNull() ? Record[Idx++] : false;
5685 return Context.getDeducedTemplateSpecializationType(Name, Deduced,
5686 IsDependent);
5687 }
5688
Guy Benyei11169dd2012-12-18 14:30:41 +00005689 case TYPE_RECORD: {
5690 if (Record.size() != 2) {
5691 Error("incorrect encoding of record type");
5692 return QualType();
5693 }
5694 unsigned Idx = 0;
5695 bool IsDependent = Record[Idx++];
5696 RecordDecl *RD = ReadDeclAs<RecordDecl>(*Loc.F, Record, Idx);
5697 RD = cast_or_null<RecordDecl>(RD->getCanonicalDecl());
5698 QualType T = Context.getRecordType(RD);
5699 const_cast<Type*>(T.getTypePtr())->setDependent(IsDependent);
5700 return T;
5701 }
5702
5703 case TYPE_ENUM: {
5704 if (Record.size() != 2) {
5705 Error("incorrect encoding of enum type");
5706 return QualType();
5707 }
5708 unsigned Idx = 0;
5709 bool IsDependent = Record[Idx++];
5710 QualType T
5711 = Context.getEnumType(ReadDeclAs<EnumDecl>(*Loc.F, Record, Idx));
5712 const_cast<Type*>(T.getTypePtr())->setDependent(IsDependent);
5713 return T;
5714 }
5715
5716 case TYPE_ATTRIBUTED: {
5717 if (Record.size() != 3) {
5718 Error("incorrect encoding of attributed type");
5719 return QualType();
5720 }
5721 QualType modifiedType = readType(*Loc.F, Record, Idx);
5722 QualType equivalentType = readType(*Loc.F, Record, Idx);
5723 AttributedType::Kind kind = static_cast<AttributedType::Kind>(Record[2]);
5724 return Context.getAttributedType(kind, modifiedType, equivalentType);
5725 }
5726
5727 case TYPE_PAREN: {
5728 if (Record.size() != 1) {
5729 Error("incorrect encoding of paren type");
5730 return QualType();
5731 }
5732 QualType InnerType = readType(*Loc.F, Record, Idx);
5733 return Context.getParenType(InnerType);
5734 }
5735
5736 case TYPE_PACK_EXPANSION: {
5737 if (Record.size() != 2) {
5738 Error("incorrect encoding of pack expansion type");
5739 return QualType();
5740 }
5741 QualType Pattern = readType(*Loc.F, Record, Idx);
5742 if (Pattern.isNull())
5743 return QualType();
David Blaikie05785d12013-02-20 22:23:23 +00005744 Optional<unsigned> NumExpansions;
Guy Benyei11169dd2012-12-18 14:30:41 +00005745 if (Record[1])
5746 NumExpansions = Record[1] - 1;
5747 return Context.getPackExpansionType(Pattern, NumExpansions);
5748 }
5749
5750 case TYPE_ELABORATED: {
5751 unsigned Idx = 0;
5752 ElaboratedTypeKeyword Keyword = (ElaboratedTypeKeyword)Record[Idx++];
5753 NestedNameSpecifier *NNS = ReadNestedNameSpecifier(*Loc.F, Record, Idx);
5754 QualType NamedType = readType(*Loc.F, Record, Idx);
5755 return Context.getElaboratedType(Keyword, NNS, NamedType);
5756 }
5757
5758 case TYPE_OBJC_INTERFACE: {
5759 unsigned Idx = 0;
5760 ObjCInterfaceDecl *ItfD
5761 = ReadDeclAs<ObjCInterfaceDecl>(*Loc.F, Record, Idx);
5762 return Context.getObjCInterfaceType(ItfD->getCanonicalDecl());
5763 }
5764
Manman Rene6be26c2016-09-13 17:25:08 +00005765 case TYPE_OBJC_TYPE_PARAM: {
5766 unsigned Idx = 0;
5767 ObjCTypeParamDecl *Decl
5768 = ReadDeclAs<ObjCTypeParamDecl>(*Loc.F, Record, Idx);
5769 unsigned NumProtos = Record[Idx++];
5770 SmallVector<ObjCProtocolDecl*, 4> Protos;
5771 for (unsigned I = 0; I != NumProtos; ++I)
5772 Protos.push_back(ReadDeclAs<ObjCProtocolDecl>(*Loc.F, Record, Idx));
5773 return Context.getObjCTypeParamType(Decl, Protos);
5774 }
Guy Benyei11169dd2012-12-18 14:30:41 +00005775 case TYPE_OBJC_OBJECT: {
5776 unsigned Idx = 0;
5777 QualType Base = readType(*Loc.F, Record, Idx);
Douglas Gregore9d95f12015-07-07 03:57:35 +00005778 unsigned NumTypeArgs = Record[Idx++];
5779 SmallVector<QualType, 4> TypeArgs;
5780 for (unsigned I = 0; I != NumTypeArgs; ++I)
5781 TypeArgs.push_back(readType(*Loc.F, Record, Idx));
Guy Benyei11169dd2012-12-18 14:30:41 +00005782 unsigned NumProtos = Record[Idx++];
5783 SmallVector<ObjCProtocolDecl*, 4> Protos;
5784 for (unsigned I = 0; I != NumProtos; ++I)
5785 Protos.push_back(ReadDeclAs<ObjCProtocolDecl>(*Loc.F, Record, Idx));
Douglas Gregorab209d82015-07-07 03:58:42 +00005786 bool IsKindOf = Record[Idx++];
5787 return Context.getObjCObjectType(Base, TypeArgs, Protos, IsKindOf);
Guy Benyei11169dd2012-12-18 14:30:41 +00005788 }
5789
5790 case TYPE_OBJC_OBJECT_POINTER: {
5791 unsigned Idx = 0;
5792 QualType Pointee = readType(*Loc.F, Record, Idx);
5793 return Context.getObjCObjectPointerType(Pointee);
5794 }
5795
5796 case TYPE_SUBST_TEMPLATE_TYPE_PARM: {
5797 unsigned Idx = 0;
5798 QualType Parm = readType(*Loc.F, Record, Idx);
5799 QualType Replacement = readType(*Loc.F, Record, Idx);
Stephan Tolksdorfe96f8b32014-03-15 10:23:27 +00005800 return Context.getSubstTemplateTypeParmType(
5801 cast<TemplateTypeParmType>(Parm),
5802 Context.getCanonicalType(Replacement));
Guy Benyei11169dd2012-12-18 14:30:41 +00005803 }
5804
5805 case TYPE_SUBST_TEMPLATE_TYPE_PARM_PACK: {
5806 unsigned Idx = 0;
5807 QualType Parm = readType(*Loc.F, Record, Idx);
5808 TemplateArgument ArgPack = ReadTemplateArgument(*Loc.F, Record, Idx);
5809 return Context.getSubstTemplateTypeParmPackType(
5810 cast<TemplateTypeParmType>(Parm),
5811 ArgPack);
5812 }
5813
5814 case TYPE_INJECTED_CLASS_NAME: {
5815 CXXRecordDecl *D = ReadDeclAs<CXXRecordDecl>(*Loc.F, Record, Idx);
5816 QualType TST = readType(*Loc.F, Record, Idx); // probably derivable
5817 // FIXME: ASTContext::getInjectedClassNameType is not currently suitable
5818 // for AST reading, too much interdependencies.
Richard Smith6377f8f2014-10-21 21:15:18 +00005819 const Type *T = nullptr;
5820 for (auto *DI = D; DI; DI = DI->getPreviousDecl()) {
5821 if (const Type *Existing = DI->getTypeForDecl()) {
5822 T = Existing;
5823 break;
5824 }
5825 }
5826 if (!T) {
Richard Smithf17fdbd2014-04-24 02:25:27 +00005827 T = new (Context, TypeAlignment) InjectedClassNameType(D, TST);
Richard Smith6377f8f2014-10-21 21:15:18 +00005828 for (auto *DI = D; DI; DI = DI->getPreviousDecl())
5829 DI->setTypeForDecl(T);
5830 }
Richard Smithf17fdbd2014-04-24 02:25:27 +00005831 return QualType(T, 0);
Guy Benyei11169dd2012-12-18 14:30:41 +00005832 }
5833
5834 case TYPE_TEMPLATE_TYPE_PARM: {
5835 unsigned Idx = 0;
5836 unsigned Depth = Record[Idx++];
5837 unsigned Index = Record[Idx++];
5838 bool Pack = Record[Idx++];
5839 TemplateTypeParmDecl *D
5840 = ReadDeclAs<TemplateTypeParmDecl>(*Loc.F, Record, Idx);
5841 return Context.getTemplateTypeParmType(Depth, Index, Pack, D);
5842 }
5843
5844 case TYPE_DEPENDENT_NAME: {
5845 unsigned Idx = 0;
5846 ElaboratedTypeKeyword Keyword = (ElaboratedTypeKeyword)Record[Idx++];
5847 NestedNameSpecifier *NNS = ReadNestedNameSpecifier(*Loc.F, Record, Idx);
Richard Smithbdf2d932015-07-30 03:37:16 +00005848 const IdentifierInfo *Name = GetIdentifierInfo(*Loc.F, Record, Idx);
Guy Benyei11169dd2012-12-18 14:30:41 +00005849 QualType Canon = readType(*Loc.F, Record, Idx);
5850 if (!Canon.isNull())
5851 Canon = Context.getCanonicalType(Canon);
5852 return Context.getDependentNameType(Keyword, NNS, Name, Canon);
5853 }
5854
5855 case TYPE_DEPENDENT_TEMPLATE_SPECIALIZATION: {
5856 unsigned Idx = 0;
5857 ElaboratedTypeKeyword Keyword = (ElaboratedTypeKeyword)Record[Idx++];
5858 NestedNameSpecifier *NNS = ReadNestedNameSpecifier(*Loc.F, Record, Idx);
Richard Smithbdf2d932015-07-30 03:37:16 +00005859 const IdentifierInfo *Name = GetIdentifierInfo(*Loc.F, Record, Idx);
Guy Benyei11169dd2012-12-18 14:30:41 +00005860 unsigned NumArgs = Record[Idx++];
5861 SmallVector<TemplateArgument, 8> Args;
5862 Args.reserve(NumArgs);
5863 while (NumArgs--)
5864 Args.push_back(ReadTemplateArgument(*Loc.F, Record, Idx));
5865 return Context.getDependentTemplateSpecializationType(Keyword, NNS, Name,
David Majnemer6fbeee32016-07-07 04:43:07 +00005866 Args);
Guy Benyei11169dd2012-12-18 14:30:41 +00005867 }
5868
5869 case TYPE_DEPENDENT_SIZED_ARRAY: {
5870 unsigned Idx = 0;
5871
5872 // ArrayType
5873 QualType ElementType = readType(*Loc.F, Record, Idx);
5874 ArrayType::ArraySizeModifier ASM
5875 = (ArrayType::ArraySizeModifier)Record[Idx++];
5876 unsigned IndexTypeQuals = Record[Idx++];
5877
5878 // DependentSizedArrayType
5879 Expr *NumElts = ReadExpr(*Loc.F);
5880 SourceRange Brackets = ReadSourceRange(*Loc.F, Record, Idx);
5881
5882 return Context.getDependentSizedArrayType(ElementType, NumElts, ASM,
5883 IndexTypeQuals, Brackets);
5884 }
5885
5886 case TYPE_TEMPLATE_SPECIALIZATION: {
5887 unsigned Idx = 0;
5888 bool IsDependent = Record[Idx++];
5889 TemplateName Name = ReadTemplateName(*Loc.F, Record, Idx);
5890 SmallVector<TemplateArgument, 8> Args;
5891 ReadTemplateArgumentList(Args, *Loc.F, Record, Idx);
5892 QualType Underlying = readType(*Loc.F, Record, Idx);
5893 QualType T;
5894 if (Underlying.isNull())
David Majnemer6fbeee32016-07-07 04:43:07 +00005895 T = Context.getCanonicalTemplateSpecializationType(Name, Args);
Guy Benyei11169dd2012-12-18 14:30:41 +00005896 else
David Majnemer6fbeee32016-07-07 04:43:07 +00005897 T = Context.getTemplateSpecializationType(Name, Args, Underlying);
Guy Benyei11169dd2012-12-18 14:30:41 +00005898 const_cast<Type*>(T.getTypePtr())->setDependent(IsDependent);
5899 return T;
5900 }
5901
5902 case TYPE_ATOMIC: {
5903 if (Record.size() != 1) {
5904 Error("Incorrect encoding of atomic type");
5905 return QualType();
5906 }
5907 QualType ValueType = readType(*Loc.F, Record, Idx);
5908 return Context.getAtomicType(ValueType);
5909 }
Xiuli Pan9c14e282016-01-09 12:53:17 +00005910
Joey Goulye3c85de2016-12-01 11:30:49 +00005911 case TYPE_PIPE: {
5912 if (Record.size() != 2) {
Xiuli Pan9c14e282016-01-09 12:53:17 +00005913 Error("Incorrect encoding of pipe type");
5914 return QualType();
5915 }
5916
5917 // Reading the pipe element type.
5918 QualType ElementType = readType(*Loc.F, Record, Idx);
Joey Goulye3c85de2016-12-01 11:30:49 +00005919 unsigned ReadOnly = Record[1];
5920 return Context.getPipeType(ElementType, ReadOnly);
Joey Gouly5788b782016-11-18 14:10:54 +00005921 }
5922
Guy Benyei11169dd2012-12-18 14:30:41 +00005923 }
5924 llvm_unreachable("Invalid TypeCode!");
5925}
5926
Richard Smith564417a2014-03-20 21:47:22 +00005927void ASTReader::readExceptionSpec(ModuleFile &ModuleFile,
5928 SmallVectorImpl<QualType> &Exceptions,
Richard Smith8acb4282014-07-31 21:57:55 +00005929 FunctionProtoType::ExceptionSpecInfo &ESI,
Richard Smith564417a2014-03-20 21:47:22 +00005930 const RecordData &Record, unsigned &Idx) {
5931 ExceptionSpecificationType EST =
5932 static_cast<ExceptionSpecificationType>(Record[Idx++]);
Richard Smith8acb4282014-07-31 21:57:55 +00005933 ESI.Type = EST;
Richard Smith564417a2014-03-20 21:47:22 +00005934 if (EST == EST_Dynamic) {
Richard Smith8acb4282014-07-31 21:57:55 +00005935 for (unsigned I = 0, N = Record[Idx++]; I != N; ++I)
Richard Smith564417a2014-03-20 21:47:22 +00005936 Exceptions.push_back(readType(ModuleFile, Record, Idx));
Richard Smith8acb4282014-07-31 21:57:55 +00005937 ESI.Exceptions = Exceptions;
Richard Smith564417a2014-03-20 21:47:22 +00005938 } else if (EST == EST_ComputedNoexcept) {
Richard Smith8acb4282014-07-31 21:57:55 +00005939 ESI.NoexceptExpr = ReadExpr(ModuleFile);
Richard Smith564417a2014-03-20 21:47:22 +00005940 } else if (EST == EST_Uninstantiated) {
Richard Smith8acb4282014-07-31 21:57:55 +00005941 ESI.SourceDecl = ReadDeclAs<FunctionDecl>(ModuleFile, Record, Idx);
5942 ESI.SourceTemplate = ReadDeclAs<FunctionDecl>(ModuleFile, Record, Idx);
Richard Smith564417a2014-03-20 21:47:22 +00005943 } else if (EST == EST_Unevaluated) {
Richard Smith8acb4282014-07-31 21:57:55 +00005944 ESI.SourceDecl = ReadDeclAs<FunctionDecl>(ModuleFile, Record, Idx);
Richard Smith564417a2014-03-20 21:47:22 +00005945 }
5946}
5947
Guy Benyei11169dd2012-12-18 14:30:41 +00005948class clang::TypeLocReader : public TypeLocVisitor<TypeLocReader> {
David L. Jonesbe1557a2016-12-21 00:17:49 +00005949 ModuleFile *F;
5950 ASTReader *Reader;
5951 const ASTReader::RecordData &Record;
Guy Benyei11169dd2012-12-18 14:30:41 +00005952 unsigned &Idx;
5953
David L. Jonesc4808b9e2016-12-15 20:53:26 +00005954 SourceLocation ReadSourceLocation() {
David L. Jonesbe1557a2016-12-21 00:17:49 +00005955 return Reader->ReadSourceLocation(*F, Record, Idx);
5956 }
5957
5958 TypeSourceInfo *GetTypeSourceInfo() {
5959 return Reader->GetTypeSourceInfo(*F, Record, Idx);
5960 }
5961
5962 NestedNameSpecifierLoc ReadNestedNameSpecifierLoc() {
5963 return Reader->ReadNestedNameSpecifierLoc(*F, Record, Idx);
Guy Benyei11169dd2012-12-18 14:30:41 +00005964 }
5965
Guy Benyei11169dd2012-12-18 14:30:41 +00005966public:
David L. Jonesbe1557a2016-12-21 00:17:49 +00005967 TypeLocReader(ModuleFile &F, ASTReader &Reader,
Guy Benyei11169dd2012-12-18 14:30:41 +00005968 const ASTReader::RecordData &Record, unsigned &Idx)
David L. Jonesbe1557a2016-12-21 00:17:49 +00005969 : F(&F), Reader(&Reader), Record(Record), Idx(Idx) {}
Guy Benyei11169dd2012-12-18 14:30:41 +00005970
5971 // We want compile-time assurance that we've enumerated all of
5972 // these, so unfortunately we have to declare them first, then
5973 // define them out-of-line.
5974#define ABSTRACT_TYPELOC(CLASS, PARENT)
5975#define TYPELOC(CLASS, PARENT) \
5976 void Visit##CLASS##TypeLoc(CLASS##TypeLoc TyLoc);
5977#include "clang/AST/TypeLocNodes.def"
5978
5979 void VisitFunctionTypeLoc(FunctionTypeLoc);
5980 void VisitArrayTypeLoc(ArrayTypeLoc);
5981};
5982
5983void TypeLocReader::VisitQualifiedTypeLoc(QualifiedTypeLoc TL) {
5984 // nothing to do
5985}
Eugene Zelenkoe95e7d52016-09-07 21:53:17 +00005986
Guy Benyei11169dd2012-12-18 14:30:41 +00005987void TypeLocReader::VisitBuiltinTypeLoc(BuiltinTypeLoc TL) {
David L. Jonesc4808b9e2016-12-15 20:53:26 +00005988 TL.setBuiltinLoc(ReadSourceLocation());
Guy Benyei11169dd2012-12-18 14:30:41 +00005989 if (TL.needsExtraLocalData()) {
David L. Jonesbe1557a2016-12-21 00:17:49 +00005990 TL.setWrittenTypeSpec(static_cast<DeclSpec::TST>(Record[Idx++]));
5991 TL.setWrittenSignSpec(static_cast<DeclSpec::TSS>(Record[Idx++]));
5992 TL.setWrittenWidthSpec(static_cast<DeclSpec::TSW>(Record[Idx++]));
5993 TL.setModeAttr(Record[Idx++]);
Guy Benyei11169dd2012-12-18 14:30:41 +00005994 }
5995}
Eugene Zelenkoe95e7d52016-09-07 21:53:17 +00005996
Guy Benyei11169dd2012-12-18 14:30:41 +00005997void TypeLocReader::VisitComplexTypeLoc(ComplexTypeLoc TL) {
David L. Jonesc4808b9e2016-12-15 20:53:26 +00005998 TL.setNameLoc(ReadSourceLocation());
Guy Benyei11169dd2012-12-18 14:30:41 +00005999}
Eugene Zelenkoe95e7d52016-09-07 21:53:17 +00006000
Guy Benyei11169dd2012-12-18 14:30:41 +00006001void TypeLocReader::VisitPointerTypeLoc(PointerTypeLoc TL) {
David L. Jonesc4808b9e2016-12-15 20:53:26 +00006002 TL.setStarLoc(ReadSourceLocation());
Guy Benyei11169dd2012-12-18 14:30:41 +00006003}
Eugene Zelenkoe95e7d52016-09-07 21:53:17 +00006004
Reid Kleckner8a365022013-06-24 17:51:48 +00006005void TypeLocReader::VisitDecayedTypeLoc(DecayedTypeLoc TL) {
6006 // nothing to do
6007}
Eugene Zelenkoe95e7d52016-09-07 21:53:17 +00006008
Reid Kleckner0503a872013-12-05 01:23:43 +00006009void TypeLocReader::VisitAdjustedTypeLoc(AdjustedTypeLoc TL) {
6010 // nothing to do
6011}
Eugene Zelenkoe95e7d52016-09-07 21:53:17 +00006012
Guy Benyei11169dd2012-12-18 14:30:41 +00006013void TypeLocReader::VisitBlockPointerTypeLoc(BlockPointerTypeLoc TL) {
David L. Jonesc4808b9e2016-12-15 20:53:26 +00006014 TL.setCaretLoc(ReadSourceLocation());
Guy Benyei11169dd2012-12-18 14:30:41 +00006015}
Eugene Zelenkoe95e7d52016-09-07 21:53:17 +00006016
Guy Benyei11169dd2012-12-18 14:30:41 +00006017void TypeLocReader::VisitLValueReferenceTypeLoc(LValueReferenceTypeLoc TL) {
David L. Jonesc4808b9e2016-12-15 20:53:26 +00006018 TL.setAmpLoc(ReadSourceLocation());
Guy Benyei11169dd2012-12-18 14:30:41 +00006019}
Eugene Zelenkoe95e7d52016-09-07 21:53:17 +00006020
Guy Benyei11169dd2012-12-18 14:30:41 +00006021void TypeLocReader::VisitRValueReferenceTypeLoc(RValueReferenceTypeLoc TL) {
David L. Jonesc4808b9e2016-12-15 20:53:26 +00006022 TL.setAmpAmpLoc(ReadSourceLocation());
Guy Benyei11169dd2012-12-18 14:30:41 +00006023}
Eugene Zelenkoe95e7d52016-09-07 21:53:17 +00006024
Guy Benyei11169dd2012-12-18 14:30:41 +00006025void TypeLocReader::VisitMemberPointerTypeLoc(MemberPointerTypeLoc TL) {
David L. Jonesc4808b9e2016-12-15 20:53:26 +00006026 TL.setStarLoc(ReadSourceLocation());
David L. Jonesbe1557a2016-12-21 00:17:49 +00006027 TL.setClassTInfo(GetTypeSourceInfo());
Guy Benyei11169dd2012-12-18 14:30:41 +00006028}
Eugene Zelenkoe95e7d52016-09-07 21:53:17 +00006029
Guy Benyei11169dd2012-12-18 14:30:41 +00006030void TypeLocReader::VisitArrayTypeLoc(ArrayTypeLoc TL) {
David L. Jonesc4808b9e2016-12-15 20:53:26 +00006031 TL.setLBracketLoc(ReadSourceLocation());
6032 TL.setRBracketLoc(ReadSourceLocation());
David L. Jonesbe1557a2016-12-21 00:17:49 +00006033 if (Record[Idx++])
6034 TL.setSizeExpr(Reader->ReadExpr(*F));
Guy Benyei11169dd2012-12-18 14:30:41 +00006035 else
Craig Toppera13603a2014-05-22 05:54:18 +00006036 TL.setSizeExpr(nullptr);
Guy Benyei11169dd2012-12-18 14:30:41 +00006037}
Eugene Zelenkoe95e7d52016-09-07 21:53:17 +00006038
Guy Benyei11169dd2012-12-18 14:30:41 +00006039void TypeLocReader::VisitConstantArrayTypeLoc(ConstantArrayTypeLoc TL) {
6040 VisitArrayTypeLoc(TL);
6041}
Eugene Zelenkoe95e7d52016-09-07 21:53:17 +00006042
Guy Benyei11169dd2012-12-18 14:30:41 +00006043void TypeLocReader::VisitIncompleteArrayTypeLoc(IncompleteArrayTypeLoc TL) {
6044 VisitArrayTypeLoc(TL);
6045}
Eugene Zelenkoe95e7d52016-09-07 21:53:17 +00006046
Guy Benyei11169dd2012-12-18 14:30:41 +00006047void TypeLocReader::VisitVariableArrayTypeLoc(VariableArrayTypeLoc TL) {
6048 VisitArrayTypeLoc(TL);
6049}
Eugene Zelenkoe95e7d52016-09-07 21:53:17 +00006050
Guy Benyei11169dd2012-12-18 14:30:41 +00006051void TypeLocReader::VisitDependentSizedArrayTypeLoc(
6052 DependentSizedArrayTypeLoc TL) {
6053 VisitArrayTypeLoc(TL);
6054}
Eugene Zelenkoe95e7d52016-09-07 21:53:17 +00006055
Guy Benyei11169dd2012-12-18 14:30:41 +00006056void TypeLocReader::VisitDependentSizedExtVectorTypeLoc(
6057 DependentSizedExtVectorTypeLoc TL) {
David L. Jonesc4808b9e2016-12-15 20:53:26 +00006058 TL.setNameLoc(ReadSourceLocation());
Guy Benyei11169dd2012-12-18 14:30:41 +00006059}
Eugene Zelenkoe95e7d52016-09-07 21:53:17 +00006060
Guy Benyei11169dd2012-12-18 14:30:41 +00006061void TypeLocReader::VisitVectorTypeLoc(VectorTypeLoc TL) {
David L. Jonesc4808b9e2016-12-15 20:53:26 +00006062 TL.setNameLoc(ReadSourceLocation());
Guy Benyei11169dd2012-12-18 14:30:41 +00006063}
Eugene Zelenkoe95e7d52016-09-07 21:53:17 +00006064
Guy Benyei11169dd2012-12-18 14:30:41 +00006065void TypeLocReader::VisitExtVectorTypeLoc(ExtVectorTypeLoc TL) {
David L. Jonesc4808b9e2016-12-15 20:53:26 +00006066 TL.setNameLoc(ReadSourceLocation());
Guy Benyei11169dd2012-12-18 14:30:41 +00006067}
Eugene Zelenkoe95e7d52016-09-07 21:53:17 +00006068
Guy Benyei11169dd2012-12-18 14:30:41 +00006069void TypeLocReader::VisitFunctionTypeLoc(FunctionTypeLoc TL) {
David L. Jonesc4808b9e2016-12-15 20:53:26 +00006070 TL.setLocalRangeBegin(ReadSourceLocation());
6071 TL.setLParenLoc(ReadSourceLocation());
6072 TL.setRParenLoc(ReadSourceLocation());
Malcolm Parsonsa3220ce2017-01-12 16:11:28 +00006073 TL.setExceptionSpecRange(SourceRange(Reader->ReadSourceLocation(*F, Record, Idx),
6074 Reader->ReadSourceLocation(*F, Record, Idx)));
David L. Jonesc4808b9e2016-12-15 20:53:26 +00006075 TL.setLocalRangeEnd(ReadSourceLocation());
Alp Tokerb3fd5cf2014-01-21 00:32:38 +00006076 for (unsigned i = 0, e = TL.getNumParams(); i != e; ++i) {
David L. Jonesbe1557a2016-12-21 00:17:49 +00006077 TL.setParam(i, Reader->ReadDeclAs<ParmVarDecl>(*F, Record, Idx));
Guy Benyei11169dd2012-12-18 14:30:41 +00006078 }
6079}
Eugene Zelenkoe95e7d52016-09-07 21:53:17 +00006080
Guy Benyei11169dd2012-12-18 14:30:41 +00006081void TypeLocReader::VisitFunctionProtoTypeLoc(FunctionProtoTypeLoc TL) {
6082 VisitFunctionTypeLoc(TL);
6083}
Eugene Zelenkoe95e7d52016-09-07 21:53:17 +00006084
Guy Benyei11169dd2012-12-18 14:30:41 +00006085void TypeLocReader::VisitFunctionNoProtoTypeLoc(FunctionNoProtoTypeLoc TL) {
6086 VisitFunctionTypeLoc(TL);
6087}
6088void TypeLocReader::VisitUnresolvedUsingTypeLoc(UnresolvedUsingTypeLoc TL) {
David L. Jonesc4808b9e2016-12-15 20:53:26 +00006089 TL.setNameLoc(ReadSourceLocation());
Guy Benyei11169dd2012-12-18 14:30:41 +00006090}
6091void TypeLocReader::VisitTypedefTypeLoc(TypedefTypeLoc TL) {
David L. Jonesc4808b9e2016-12-15 20:53:26 +00006092 TL.setNameLoc(ReadSourceLocation());
Guy Benyei11169dd2012-12-18 14:30:41 +00006093}
6094void TypeLocReader::VisitTypeOfExprTypeLoc(TypeOfExprTypeLoc TL) {
David L. Jonesc4808b9e2016-12-15 20:53:26 +00006095 TL.setTypeofLoc(ReadSourceLocation());
6096 TL.setLParenLoc(ReadSourceLocation());
6097 TL.setRParenLoc(ReadSourceLocation());
Guy Benyei11169dd2012-12-18 14:30:41 +00006098}
6099void TypeLocReader::VisitTypeOfTypeLoc(TypeOfTypeLoc TL) {
David L. Jonesc4808b9e2016-12-15 20:53:26 +00006100 TL.setTypeofLoc(ReadSourceLocation());
6101 TL.setLParenLoc(ReadSourceLocation());
6102 TL.setRParenLoc(ReadSourceLocation());
David L. Jonesbe1557a2016-12-21 00:17:49 +00006103 TL.setUnderlyingTInfo(GetTypeSourceInfo());
Guy Benyei11169dd2012-12-18 14:30:41 +00006104}
6105void TypeLocReader::VisitDecltypeTypeLoc(DecltypeTypeLoc TL) {
David L. Jonesc4808b9e2016-12-15 20:53:26 +00006106 TL.setNameLoc(ReadSourceLocation());
Guy Benyei11169dd2012-12-18 14:30:41 +00006107}
Eugene Zelenkoe95e7d52016-09-07 21:53:17 +00006108
Guy Benyei11169dd2012-12-18 14:30:41 +00006109void TypeLocReader::VisitUnaryTransformTypeLoc(UnaryTransformTypeLoc TL) {
David L. Jonesc4808b9e2016-12-15 20:53:26 +00006110 TL.setKWLoc(ReadSourceLocation());
6111 TL.setLParenLoc(ReadSourceLocation());
6112 TL.setRParenLoc(ReadSourceLocation());
David L. Jonesbe1557a2016-12-21 00:17:49 +00006113 TL.setUnderlyingTInfo(GetTypeSourceInfo());
Guy Benyei11169dd2012-12-18 14:30:41 +00006114}
Eugene Zelenkoe95e7d52016-09-07 21:53:17 +00006115
Guy Benyei11169dd2012-12-18 14:30:41 +00006116void TypeLocReader::VisitAutoTypeLoc(AutoTypeLoc TL) {
David L. Jonesc4808b9e2016-12-15 20:53:26 +00006117 TL.setNameLoc(ReadSourceLocation());
Guy Benyei11169dd2012-12-18 14:30:41 +00006118}
Eugene Zelenkoe95e7d52016-09-07 21:53:17 +00006119
Richard Smith600b5262017-01-26 20:40:47 +00006120void TypeLocReader::VisitDeducedTemplateSpecializationTypeLoc(
6121 DeducedTemplateSpecializationTypeLoc TL) {
6122 TL.setTemplateNameLoc(ReadSourceLocation());
6123}
6124
Guy Benyei11169dd2012-12-18 14:30:41 +00006125void TypeLocReader::VisitRecordTypeLoc(RecordTypeLoc TL) {
David L. Jonesc4808b9e2016-12-15 20:53:26 +00006126 TL.setNameLoc(ReadSourceLocation());
Guy Benyei11169dd2012-12-18 14:30:41 +00006127}
Eugene Zelenkoe95e7d52016-09-07 21:53:17 +00006128
Guy Benyei11169dd2012-12-18 14:30:41 +00006129void TypeLocReader::VisitEnumTypeLoc(EnumTypeLoc TL) {
David L. Jonesc4808b9e2016-12-15 20:53:26 +00006130 TL.setNameLoc(ReadSourceLocation());
Guy Benyei11169dd2012-12-18 14:30:41 +00006131}
Eugene Zelenkoe95e7d52016-09-07 21:53:17 +00006132
Guy Benyei11169dd2012-12-18 14:30:41 +00006133void TypeLocReader::VisitAttributedTypeLoc(AttributedTypeLoc TL) {
David L. Jonesc4808b9e2016-12-15 20:53:26 +00006134 TL.setAttrNameLoc(ReadSourceLocation());
Guy Benyei11169dd2012-12-18 14:30:41 +00006135 if (TL.hasAttrOperand()) {
6136 SourceRange range;
David L. Jonesc4808b9e2016-12-15 20:53:26 +00006137 range.setBegin(ReadSourceLocation());
6138 range.setEnd(ReadSourceLocation());
Guy Benyei11169dd2012-12-18 14:30:41 +00006139 TL.setAttrOperandParensRange(range);
6140 }
6141 if (TL.hasAttrExprOperand()) {
David L. Jonesbe1557a2016-12-21 00:17:49 +00006142 if (Record[Idx++])
6143 TL.setAttrExprOperand(Reader->ReadExpr(*F));
Guy Benyei11169dd2012-12-18 14:30:41 +00006144 else
Craig Toppera13603a2014-05-22 05:54:18 +00006145 TL.setAttrExprOperand(nullptr);
Guy Benyei11169dd2012-12-18 14:30:41 +00006146 } else if (TL.hasAttrEnumOperand())
David L. Jonesc4808b9e2016-12-15 20:53:26 +00006147 TL.setAttrEnumOperandLoc(ReadSourceLocation());
Guy Benyei11169dd2012-12-18 14:30:41 +00006148}
Eugene Zelenkoe95e7d52016-09-07 21:53:17 +00006149
Guy Benyei11169dd2012-12-18 14:30:41 +00006150void TypeLocReader::VisitTemplateTypeParmTypeLoc(TemplateTypeParmTypeLoc TL) {
David L. Jonesc4808b9e2016-12-15 20:53:26 +00006151 TL.setNameLoc(ReadSourceLocation());
Guy Benyei11169dd2012-12-18 14:30:41 +00006152}
Eugene Zelenkoe95e7d52016-09-07 21:53:17 +00006153
Guy Benyei11169dd2012-12-18 14:30:41 +00006154void TypeLocReader::VisitSubstTemplateTypeParmTypeLoc(
6155 SubstTemplateTypeParmTypeLoc TL) {
David L. Jonesc4808b9e2016-12-15 20:53:26 +00006156 TL.setNameLoc(ReadSourceLocation());
Guy Benyei11169dd2012-12-18 14:30:41 +00006157}
6158void TypeLocReader::VisitSubstTemplateTypeParmPackTypeLoc(
6159 SubstTemplateTypeParmPackTypeLoc TL) {
David L. Jonesc4808b9e2016-12-15 20:53:26 +00006160 TL.setNameLoc(ReadSourceLocation());
Guy Benyei11169dd2012-12-18 14:30:41 +00006161}
6162void TypeLocReader::VisitTemplateSpecializationTypeLoc(
6163 TemplateSpecializationTypeLoc TL) {
David L. Jonesc4808b9e2016-12-15 20:53:26 +00006164 TL.setTemplateKeywordLoc(ReadSourceLocation());
6165 TL.setTemplateNameLoc(ReadSourceLocation());
6166 TL.setLAngleLoc(ReadSourceLocation());
6167 TL.setRAngleLoc(ReadSourceLocation());
Guy Benyei11169dd2012-12-18 14:30:41 +00006168 for (unsigned i = 0, e = TL.getNumArgs(); i != e; ++i)
David L. Jonesbe1557a2016-12-21 00:17:49 +00006169 TL.setArgLocInfo(
6170 i,
6171 Reader->GetTemplateArgumentLocInfo(
6172 *F, TL.getTypePtr()->getArg(i).getKind(), Record, Idx));
Guy Benyei11169dd2012-12-18 14:30:41 +00006173}
6174void TypeLocReader::VisitParenTypeLoc(ParenTypeLoc TL) {
David L. Jonesc4808b9e2016-12-15 20:53:26 +00006175 TL.setLParenLoc(ReadSourceLocation());
6176 TL.setRParenLoc(ReadSourceLocation());
Guy Benyei11169dd2012-12-18 14:30:41 +00006177}
Eugene Zelenkoe95e7d52016-09-07 21:53:17 +00006178
Guy Benyei11169dd2012-12-18 14:30:41 +00006179void TypeLocReader::VisitElaboratedTypeLoc(ElaboratedTypeLoc TL) {
David L. Jonesc4808b9e2016-12-15 20:53:26 +00006180 TL.setElaboratedKeywordLoc(ReadSourceLocation());
David L. Jonesbe1557a2016-12-21 00:17:49 +00006181 TL.setQualifierLoc(ReadNestedNameSpecifierLoc());
Guy Benyei11169dd2012-12-18 14:30:41 +00006182}
Eugene Zelenkoe95e7d52016-09-07 21:53:17 +00006183
Guy Benyei11169dd2012-12-18 14:30:41 +00006184void TypeLocReader::VisitInjectedClassNameTypeLoc(InjectedClassNameTypeLoc TL) {
David L. Jonesc4808b9e2016-12-15 20:53:26 +00006185 TL.setNameLoc(ReadSourceLocation());
Guy Benyei11169dd2012-12-18 14:30:41 +00006186}
Eugene Zelenkoe95e7d52016-09-07 21:53:17 +00006187
Guy Benyei11169dd2012-12-18 14:30:41 +00006188void TypeLocReader::VisitDependentNameTypeLoc(DependentNameTypeLoc TL) {
David L. Jonesc4808b9e2016-12-15 20:53:26 +00006189 TL.setElaboratedKeywordLoc(ReadSourceLocation());
David L. Jonesbe1557a2016-12-21 00:17:49 +00006190 TL.setQualifierLoc(ReadNestedNameSpecifierLoc());
David L. Jonesc4808b9e2016-12-15 20:53:26 +00006191 TL.setNameLoc(ReadSourceLocation());
Guy Benyei11169dd2012-12-18 14:30:41 +00006192}
Eugene Zelenkoe95e7d52016-09-07 21:53:17 +00006193
Guy Benyei11169dd2012-12-18 14:30:41 +00006194void TypeLocReader::VisitDependentTemplateSpecializationTypeLoc(
6195 DependentTemplateSpecializationTypeLoc TL) {
David L. Jonesc4808b9e2016-12-15 20:53:26 +00006196 TL.setElaboratedKeywordLoc(ReadSourceLocation());
David L. Jonesbe1557a2016-12-21 00:17:49 +00006197 TL.setQualifierLoc(ReadNestedNameSpecifierLoc());
David L. Jonesc4808b9e2016-12-15 20:53:26 +00006198 TL.setTemplateKeywordLoc(ReadSourceLocation());
6199 TL.setTemplateNameLoc(ReadSourceLocation());
6200 TL.setLAngleLoc(ReadSourceLocation());
6201 TL.setRAngleLoc(ReadSourceLocation());
Guy Benyei11169dd2012-12-18 14:30:41 +00006202 for (unsigned I = 0, E = TL.getNumArgs(); I != E; ++I)
David L. Jonesbe1557a2016-12-21 00:17:49 +00006203 TL.setArgLocInfo(
6204 I,
6205 Reader->GetTemplateArgumentLocInfo(
6206 *F, TL.getTypePtr()->getArg(I).getKind(), Record, Idx));
Guy Benyei11169dd2012-12-18 14:30:41 +00006207}
Eugene Zelenkoe95e7d52016-09-07 21:53:17 +00006208
Guy Benyei11169dd2012-12-18 14:30:41 +00006209void TypeLocReader::VisitPackExpansionTypeLoc(PackExpansionTypeLoc TL) {
David L. Jonesc4808b9e2016-12-15 20:53:26 +00006210 TL.setEllipsisLoc(ReadSourceLocation());
Guy Benyei11169dd2012-12-18 14:30:41 +00006211}
Eugene Zelenkoe95e7d52016-09-07 21:53:17 +00006212
Guy Benyei11169dd2012-12-18 14:30:41 +00006213void TypeLocReader::VisitObjCInterfaceTypeLoc(ObjCInterfaceTypeLoc TL) {
David L. Jonesc4808b9e2016-12-15 20:53:26 +00006214 TL.setNameLoc(ReadSourceLocation());
Guy Benyei11169dd2012-12-18 14:30:41 +00006215}
Eugene Zelenkoe95e7d52016-09-07 21:53:17 +00006216
Manman Rene6be26c2016-09-13 17:25:08 +00006217void TypeLocReader::VisitObjCTypeParamTypeLoc(ObjCTypeParamTypeLoc TL) {
6218 if (TL.getNumProtocols()) {
David L. Jonesc4808b9e2016-12-15 20:53:26 +00006219 TL.setProtocolLAngleLoc(ReadSourceLocation());
6220 TL.setProtocolRAngleLoc(ReadSourceLocation());
Manman Rene6be26c2016-09-13 17:25:08 +00006221 }
6222 for (unsigned i = 0, e = TL.getNumProtocols(); i != e; ++i)
David L. Jonesc4808b9e2016-12-15 20:53:26 +00006223 TL.setProtocolLoc(i, ReadSourceLocation());
Manman Rene6be26c2016-09-13 17:25:08 +00006224}
6225
Guy Benyei11169dd2012-12-18 14:30:41 +00006226void TypeLocReader::VisitObjCObjectTypeLoc(ObjCObjectTypeLoc TL) {
David L. Jonesbe1557a2016-12-21 00:17:49 +00006227 TL.setHasBaseTypeAsWritten(Record[Idx++]);
David L. Jonesc4808b9e2016-12-15 20:53:26 +00006228 TL.setTypeArgsLAngleLoc(ReadSourceLocation());
6229 TL.setTypeArgsRAngleLoc(ReadSourceLocation());
Douglas Gregore9d95f12015-07-07 03:57:35 +00006230 for (unsigned i = 0, e = TL.getNumTypeArgs(); i != e; ++i)
David L. Jonesbe1557a2016-12-21 00:17:49 +00006231 TL.setTypeArgTInfo(i, GetTypeSourceInfo());
David L. Jonesc4808b9e2016-12-15 20:53:26 +00006232 TL.setProtocolLAngleLoc(ReadSourceLocation());
6233 TL.setProtocolRAngleLoc(ReadSourceLocation());
Guy Benyei11169dd2012-12-18 14:30:41 +00006234 for (unsigned i = 0, e = TL.getNumProtocols(); i != e; ++i)
David L. Jonesc4808b9e2016-12-15 20:53:26 +00006235 TL.setProtocolLoc(i, ReadSourceLocation());
Guy Benyei11169dd2012-12-18 14:30:41 +00006236}
Eugene Zelenkoe95e7d52016-09-07 21:53:17 +00006237
Guy Benyei11169dd2012-12-18 14:30:41 +00006238void TypeLocReader::VisitObjCObjectPointerTypeLoc(ObjCObjectPointerTypeLoc TL) {
David L. Jonesc4808b9e2016-12-15 20:53:26 +00006239 TL.setStarLoc(ReadSourceLocation());
Guy Benyei11169dd2012-12-18 14:30:41 +00006240}
Eugene Zelenkoe95e7d52016-09-07 21:53:17 +00006241
Guy Benyei11169dd2012-12-18 14:30:41 +00006242void TypeLocReader::VisitAtomicTypeLoc(AtomicTypeLoc TL) {
David L. Jonesc4808b9e2016-12-15 20:53:26 +00006243 TL.setKWLoc(ReadSourceLocation());
6244 TL.setLParenLoc(ReadSourceLocation());
6245 TL.setRParenLoc(ReadSourceLocation());
Guy Benyei11169dd2012-12-18 14:30:41 +00006246}
Eugene Zelenkoe95e7d52016-09-07 21:53:17 +00006247
Xiuli Pan9c14e282016-01-09 12:53:17 +00006248void TypeLocReader::VisitPipeTypeLoc(PipeTypeLoc TL) {
David L. Jonesc4808b9e2016-12-15 20:53:26 +00006249 TL.setKWLoc(ReadSourceLocation());
Xiuli Pan9c14e282016-01-09 12:53:17 +00006250}
Guy Benyei11169dd2012-12-18 14:30:41 +00006251
David L. Jonesbe1557a2016-12-21 00:17:49 +00006252TypeSourceInfo *
6253ASTReader::GetTypeSourceInfo(ModuleFile &F, const ASTReader::RecordData &Record,
6254 unsigned &Idx) {
Guy Benyei11169dd2012-12-18 14:30:41 +00006255 QualType InfoTy = readType(F, Record, Idx);
6256 if (InfoTy.isNull())
Craig Toppera13603a2014-05-22 05:54:18 +00006257 return nullptr;
Guy Benyei11169dd2012-12-18 14:30:41 +00006258
6259 TypeSourceInfo *TInfo = getContext().CreateTypeSourceInfo(InfoTy);
David L. Jonesbe1557a2016-12-21 00:17:49 +00006260 TypeLocReader TLR(F, *this, Record, Idx);
Guy Benyei11169dd2012-12-18 14:30:41 +00006261 for (TypeLoc TL = TInfo->getTypeLoc(); !TL.isNull(); TL = TL.getNextTypeLoc())
6262 TLR.Visit(TL);
6263 return TInfo;
6264}
6265
6266QualType ASTReader::GetType(TypeID ID) {
6267 unsigned FastQuals = ID & Qualifiers::FastMask;
6268 unsigned Index = ID >> Qualifiers::FastWidth;
6269
6270 if (Index < NUM_PREDEF_TYPE_IDS) {
6271 QualType T;
6272 switch ((PredefinedTypeIDs)Index) {
Alexey Baderbdf7c842015-09-15 12:18:29 +00006273 case PREDEF_TYPE_NULL_ID:
6274 return QualType();
6275 case PREDEF_TYPE_VOID_ID:
6276 T = Context.VoidTy;
6277 break;
6278 case PREDEF_TYPE_BOOL_ID:
6279 T = Context.BoolTy;
6280 break;
Guy Benyei11169dd2012-12-18 14:30:41 +00006281
6282 case PREDEF_TYPE_CHAR_U_ID:
6283 case PREDEF_TYPE_CHAR_S_ID:
6284 // FIXME: Check that the signedness of CharTy is correct!
6285 T = Context.CharTy;
6286 break;
6287
Alexey Baderbdf7c842015-09-15 12:18:29 +00006288 case PREDEF_TYPE_UCHAR_ID:
6289 T = Context.UnsignedCharTy;
6290 break;
6291 case PREDEF_TYPE_USHORT_ID:
6292 T = Context.UnsignedShortTy;
6293 break;
6294 case PREDEF_TYPE_UINT_ID:
6295 T = Context.UnsignedIntTy;
6296 break;
6297 case PREDEF_TYPE_ULONG_ID:
6298 T = Context.UnsignedLongTy;
6299 break;
6300 case PREDEF_TYPE_ULONGLONG_ID:
6301 T = Context.UnsignedLongLongTy;
6302 break;
6303 case PREDEF_TYPE_UINT128_ID:
6304 T = Context.UnsignedInt128Ty;
6305 break;
6306 case PREDEF_TYPE_SCHAR_ID:
6307 T = Context.SignedCharTy;
6308 break;
6309 case PREDEF_TYPE_WCHAR_ID:
6310 T = Context.WCharTy;
6311 break;
6312 case PREDEF_TYPE_SHORT_ID:
6313 T = Context.ShortTy;
6314 break;
6315 case PREDEF_TYPE_INT_ID:
6316 T = Context.IntTy;
6317 break;
6318 case PREDEF_TYPE_LONG_ID:
6319 T = Context.LongTy;
6320 break;
6321 case PREDEF_TYPE_LONGLONG_ID:
6322 T = Context.LongLongTy;
6323 break;
6324 case PREDEF_TYPE_INT128_ID:
6325 T = Context.Int128Ty;
6326 break;
6327 case PREDEF_TYPE_HALF_ID:
6328 T = Context.HalfTy;
6329 break;
6330 case PREDEF_TYPE_FLOAT_ID:
6331 T = Context.FloatTy;
6332 break;
6333 case PREDEF_TYPE_DOUBLE_ID:
6334 T = Context.DoubleTy;
6335 break;
6336 case PREDEF_TYPE_LONGDOUBLE_ID:
6337 T = Context.LongDoubleTy;
6338 break;
Nemanja Ivanovicbb1ea2d2016-05-09 08:52:33 +00006339 case PREDEF_TYPE_FLOAT128_ID:
6340 T = Context.Float128Ty;
6341 break;
Alexey Baderbdf7c842015-09-15 12:18:29 +00006342 case PREDEF_TYPE_OVERLOAD_ID:
6343 T = Context.OverloadTy;
6344 break;
6345 case PREDEF_TYPE_BOUND_MEMBER:
6346 T = Context.BoundMemberTy;
6347 break;
6348 case PREDEF_TYPE_PSEUDO_OBJECT:
6349 T = Context.PseudoObjectTy;
6350 break;
6351 case PREDEF_TYPE_DEPENDENT_ID:
6352 T = Context.DependentTy;
6353 break;
6354 case PREDEF_TYPE_UNKNOWN_ANY:
6355 T = Context.UnknownAnyTy;
6356 break;
6357 case PREDEF_TYPE_NULLPTR_ID:
6358 T = Context.NullPtrTy;
6359 break;
6360 case PREDEF_TYPE_CHAR16_ID:
6361 T = Context.Char16Ty;
6362 break;
6363 case PREDEF_TYPE_CHAR32_ID:
6364 T = Context.Char32Ty;
6365 break;
6366 case PREDEF_TYPE_OBJC_ID:
6367 T = Context.ObjCBuiltinIdTy;
6368 break;
6369 case PREDEF_TYPE_OBJC_CLASS:
6370 T = Context.ObjCBuiltinClassTy;
6371 break;
6372 case PREDEF_TYPE_OBJC_SEL:
6373 T = Context.ObjCBuiltinSelTy;
6374 break;
Alexey Bader954ba212016-04-08 13:40:33 +00006375#define IMAGE_TYPE(ImgType, Id, SingletonId, Access, Suffix) \
6376 case PREDEF_TYPE_##Id##_ID: \
6377 T = Context.SingletonId; \
Alexey Baderbdf7c842015-09-15 12:18:29 +00006378 break;
Alexey Baderb62f1442016-04-13 08:33:41 +00006379#include "clang/Basic/OpenCLImageTypes.def"
Alexey Baderbdf7c842015-09-15 12:18:29 +00006380 case PREDEF_TYPE_SAMPLER_ID:
6381 T = Context.OCLSamplerTy;
6382 break;
6383 case PREDEF_TYPE_EVENT_ID:
6384 T = Context.OCLEventTy;
6385 break;
Alexey Bader9c8453f2015-09-15 11:18:52 +00006386 case PREDEF_TYPE_CLK_EVENT_ID:
6387 T = Context.OCLClkEventTy;
6388 break;
6389 case PREDEF_TYPE_QUEUE_ID:
6390 T = Context.OCLQueueTy;
6391 break;
Alexey Bader9c8453f2015-09-15 11:18:52 +00006392 case PREDEF_TYPE_RESERVE_ID_ID:
6393 T = Context.OCLReserveIDTy;
6394 break;
Alexey Baderbdf7c842015-09-15 12:18:29 +00006395 case PREDEF_TYPE_AUTO_DEDUCT:
6396 T = Context.getAutoDeductType();
6397 break;
6398
6399 case PREDEF_TYPE_AUTO_RREF_DEDUCT:
6400 T = Context.getAutoRRefDeductType();
Guy Benyei11169dd2012-12-18 14:30:41 +00006401 break;
6402
6403 case PREDEF_TYPE_ARC_UNBRIDGED_CAST:
6404 T = Context.ARCUnbridgedCastTy;
6405 break;
6406
Guy Benyei11169dd2012-12-18 14:30:41 +00006407 case PREDEF_TYPE_BUILTIN_FN:
6408 T = Context.BuiltinFnTy;
6409 break;
Alexey Bataev1a3320e2015-08-25 14:24:04 +00006410
6411 case PREDEF_TYPE_OMP_ARRAY_SECTION:
6412 T = Context.OMPArraySectionTy;
6413 break;
Guy Benyei11169dd2012-12-18 14:30:41 +00006414 }
6415
6416 assert(!T.isNull() && "Unknown predefined type");
6417 return T.withFastQualifiers(FastQuals);
6418 }
6419
6420 Index -= NUM_PREDEF_TYPE_IDS;
6421 assert(Index < TypesLoaded.size() && "Type index out-of-range");
6422 if (TypesLoaded[Index].isNull()) {
6423 TypesLoaded[Index] = readTypeRecord(Index);
6424 if (TypesLoaded[Index].isNull())
6425 return QualType();
6426
6427 TypesLoaded[Index]->setFromAST();
6428 if (DeserializationListener)
6429 DeserializationListener->TypeRead(TypeIdx::fromTypeID(ID),
6430 TypesLoaded[Index]);
6431 }
6432
6433 return TypesLoaded[Index].withFastQualifiers(FastQuals);
6434}
6435
6436QualType ASTReader::getLocalType(ModuleFile &F, unsigned LocalID) {
6437 return GetType(getGlobalTypeID(F, LocalID));
6438}
6439
David L. Jonesc4808b9e2016-12-15 20:53:26 +00006440serialization::TypeID
Guy Benyei11169dd2012-12-18 14:30:41 +00006441ASTReader::getGlobalTypeID(ModuleFile &F, unsigned LocalID) const {
6442 unsigned FastQuals = LocalID & Qualifiers::FastMask;
6443 unsigned LocalIndex = LocalID >> Qualifiers::FastWidth;
David L. Jonesc4808b9e2016-12-15 20:53:26 +00006444
Guy Benyei11169dd2012-12-18 14:30:41 +00006445 if (LocalIndex < NUM_PREDEF_TYPE_IDS)
6446 return LocalID;
6447
Richard Smith37a93df2017-02-18 00:32:02 +00006448 if (!F.ModuleOffsetMap.empty())
6449 ReadModuleOffsetMap(F);
6450
Guy Benyei11169dd2012-12-18 14:30:41 +00006451 ContinuousRangeMap<uint32_t, int, 2>::iterator I
6452 = F.TypeRemap.find(LocalIndex - NUM_PREDEF_TYPE_IDS);
6453 assert(I != F.TypeRemap.end() && "Invalid index into type index remap");
David L. Jonesc4808b9e2016-12-15 20:53:26 +00006454
Guy Benyei11169dd2012-12-18 14:30:41 +00006455 unsigned GlobalIndex = LocalIndex + I->second;
6456 return (GlobalIndex << Qualifiers::FastWidth) | FastQuals;
6457}
6458
6459TemplateArgumentLocInfo
6460ASTReader::GetTemplateArgumentLocInfo(ModuleFile &F,
6461 TemplateArgument::ArgKind Kind,
6462 const RecordData &Record,
6463 unsigned &Index) {
6464 switch (Kind) {
6465 case TemplateArgument::Expression:
6466 return ReadExpr(F);
6467 case TemplateArgument::Type:
6468 return GetTypeSourceInfo(F, Record, Index);
6469 case TemplateArgument::Template: {
David L. Jonesc4808b9e2016-12-15 20:53:26 +00006470 NestedNameSpecifierLoc QualifierLoc = ReadNestedNameSpecifierLoc(F, Record,
Guy Benyei11169dd2012-12-18 14:30:41 +00006471 Index);
6472 SourceLocation TemplateNameLoc = ReadSourceLocation(F, Record, Index);
6473 return TemplateArgumentLocInfo(QualifierLoc, TemplateNameLoc,
6474 SourceLocation());
6475 }
6476 case TemplateArgument::TemplateExpansion: {
David L. Jonesc4808b9e2016-12-15 20:53:26 +00006477 NestedNameSpecifierLoc QualifierLoc = ReadNestedNameSpecifierLoc(F, Record,
Guy Benyei11169dd2012-12-18 14:30:41 +00006478 Index);
6479 SourceLocation TemplateNameLoc = ReadSourceLocation(F, Record, Index);
6480 SourceLocation EllipsisLoc = ReadSourceLocation(F, Record, Index);
David L. Jonesc4808b9e2016-12-15 20:53:26 +00006481 return TemplateArgumentLocInfo(QualifierLoc, TemplateNameLoc,
Guy Benyei11169dd2012-12-18 14:30:41 +00006482 EllipsisLoc);
6483 }
6484 case TemplateArgument::Null:
6485 case TemplateArgument::Integral:
6486 case TemplateArgument::Declaration:
6487 case TemplateArgument::NullPtr:
6488 case TemplateArgument::Pack:
6489 // FIXME: Is this right?
6490 return TemplateArgumentLocInfo();
6491 }
6492 llvm_unreachable("unexpected template argument loc");
6493}
6494
6495TemplateArgumentLoc
6496ASTReader::ReadTemplateArgumentLoc(ModuleFile &F,
6497 const RecordData &Record, unsigned &Index) {
6498 TemplateArgument Arg = ReadTemplateArgument(F, Record, Index);
6499
6500 if (Arg.getKind() == TemplateArgument::Expression) {
6501 if (Record[Index++]) // bool InfoHasSameExpr.
6502 return TemplateArgumentLoc(Arg, TemplateArgumentLocInfo(Arg.getAsExpr()));
6503 }
6504 return TemplateArgumentLoc(Arg, GetTemplateArgumentLocInfo(F, Arg.getKind(),
6505 Record, Index));
6506}
6507
Enea Zaffanella6dbe1872013-08-10 07:24:53 +00006508const ASTTemplateArgumentListInfo*
6509ASTReader::ReadASTTemplateArgumentListInfo(ModuleFile &F,
6510 const RecordData &Record,
6511 unsigned &Index) {
6512 SourceLocation LAngleLoc = ReadSourceLocation(F, Record, Index);
6513 SourceLocation RAngleLoc = ReadSourceLocation(F, Record, Index);
6514 unsigned NumArgsAsWritten = Record[Index++];
6515 TemplateArgumentListInfo TemplArgsInfo(LAngleLoc, RAngleLoc);
6516 for (unsigned i = 0; i != NumArgsAsWritten; ++i)
6517 TemplArgsInfo.addArgument(ReadTemplateArgumentLoc(F, Record, Index));
6518 return ASTTemplateArgumentListInfo::Create(getContext(), TemplArgsInfo);
6519}
6520
Guy Benyei11169dd2012-12-18 14:30:41 +00006521Decl *ASTReader::GetExternalDecl(uint32_t ID) {
6522 return GetDecl(ID);
6523}
6524
Richard Smith50895422015-01-31 03:04:55 +00006525template<typename TemplateSpecializationDecl>
6526static void completeRedeclChainForTemplateSpecialization(Decl *D) {
6527 if (auto *TSD = dyn_cast<TemplateSpecializationDecl>(D))
6528 TSD->getSpecializedTemplate()->LoadLazySpecializations();
6529}
6530
Richard Smith053f6c62014-05-16 23:01:30 +00006531void ASTReader::CompleteRedeclChain(const Decl *D) {
Richard Smith851072e2014-05-19 20:59:20 +00006532 if (NumCurrentElementsDeserializing) {
6533 // We arrange to not care about the complete redeclaration chain while we're
6534 // deserializing. Just remember that the AST has marked this one as complete
6535 // but that it's not actually complete yet, so we know we still need to
6536 // complete it later.
6537 PendingIncompleteDeclChains.push_back(const_cast<Decl*>(D));
6538 return;
6539 }
6540
Richard Smith053f6c62014-05-16 23:01:30 +00006541 const DeclContext *DC = D->getDeclContext()->getRedeclContext();
6542
Richard Smith053f6c62014-05-16 23:01:30 +00006543 // If this is a named declaration, complete it by looking it up
6544 // within its context.
6545 //
Richard Smith01bdb7a2014-08-28 05:44:07 +00006546 // FIXME: Merging a function definition should merge
Richard Smith053f6c62014-05-16 23:01:30 +00006547 // all mergeable entities within it.
6548 if (isa<TranslationUnitDecl>(DC) || isa<NamespaceDecl>(DC) ||
6549 isa<CXXRecordDecl>(DC) || isa<EnumDecl>(DC)) {
6550 if (DeclarationName Name = cast<NamedDecl>(D)->getDeclName()) {
Richard Smitha534a312015-07-21 23:54:07 +00006551 if (!getContext().getLangOpts().CPlusPlus &&
6552 isa<TranslationUnitDecl>(DC)) {
Richard Smith053f6c62014-05-16 23:01:30 +00006553 // Outside of C++, we don't have a lookup table for the TU, so update
Richard Smitha534a312015-07-21 23:54:07 +00006554 // the identifier instead. (For C++ modules, we don't store decls
6555 // in the serialized identifier table, so we do the lookup in the TU.)
6556 auto *II = Name.getAsIdentifierInfo();
6557 assert(II && "non-identifier name in C?");
Richard Smith053f6c62014-05-16 23:01:30 +00006558 if (II->isOutOfDate())
6559 updateOutOfDateIdentifier(*II);
6560 } else
6561 DC->lookup(Name);
Richard Smith01bdb7a2014-08-28 05:44:07 +00006562 } else if (needsAnonymousDeclarationNumber(cast<NamedDecl>(D))) {
Richard Smith3cb15722015-08-05 22:41:45 +00006563 // Find all declarations of this kind from the relevant context.
6564 for (auto *DCDecl : cast<Decl>(D->getLexicalDeclContext())->redecls()) {
6565 auto *DC = cast<DeclContext>(DCDecl);
6566 SmallVector<Decl*, 8> Decls;
6567 FindExternalLexicalDecls(
6568 DC, [&](Decl::Kind K) { return K == D->getKind(); }, Decls);
6569 }
Richard Smith053f6c62014-05-16 23:01:30 +00006570 }
6571 }
Richard Smith50895422015-01-31 03:04:55 +00006572
6573 if (auto *CTSD = dyn_cast<ClassTemplateSpecializationDecl>(D))
6574 CTSD->getSpecializedTemplate()->LoadLazySpecializations();
6575 if (auto *VTSD = dyn_cast<VarTemplateSpecializationDecl>(D))
6576 VTSD->getSpecializedTemplate()->LoadLazySpecializations();
6577 if (auto *FD = dyn_cast<FunctionDecl>(D)) {
6578 if (auto *Template = FD->getPrimaryTemplate())
6579 Template->LoadLazySpecializations();
6580 }
Richard Smith053f6c62014-05-16 23:01:30 +00006581}
6582
Richard Smithc2bb8182015-03-24 06:36:48 +00006583CXXCtorInitializer **
6584ASTReader::GetExternalCXXCtorInitializers(uint64_t Offset) {
6585 RecordLocation Loc = getLocalBitOffset(Offset);
6586 BitstreamCursor &Cursor = Loc.F->DeclsCursor;
6587 SavedStreamPosition SavedPosition(Cursor);
6588 Cursor.JumpToBit(Loc.Offset);
6589 ReadingKindTracker ReadingKind(Read_Decl, *this);
6590
6591 RecordData Record;
6592 unsigned Code = Cursor.ReadCode();
6593 unsigned RecCode = Cursor.readRecord(Code, Record);
6594 if (RecCode != DECL_CXX_CTOR_INITIALIZERS) {
6595 Error("malformed AST file: missing C++ ctor initializers");
6596 return nullptr;
6597 }
6598
6599 unsigned Idx = 0;
6600 return ReadCXXCtorInitializers(*Loc.F, Record, Idx);
6601}
6602
Guy Benyei11169dd2012-12-18 14:30:41 +00006603CXXBaseSpecifier *ASTReader::GetExternalCXXBaseSpecifiers(uint64_t Offset) {
6604 RecordLocation Loc = getLocalBitOffset(Offset);
Chris Lattner7fb3bef2013-01-20 00:56:42 +00006605 BitstreamCursor &Cursor = Loc.F->DeclsCursor;
Guy Benyei11169dd2012-12-18 14:30:41 +00006606 SavedStreamPosition SavedPosition(Cursor);
6607 Cursor.JumpToBit(Loc.Offset);
6608 ReadingKindTracker ReadingKind(Read_Decl, *this);
6609 RecordData Record;
6610 unsigned Code = Cursor.ReadCode();
Chris Lattner0e6c9402013-01-20 02:38:54 +00006611 unsigned RecCode = Cursor.readRecord(Code, Record);
Guy Benyei11169dd2012-12-18 14:30:41 +00006612 if (RecCode != DECL_CXX_BASE_SPECIFIERS) {
Richard Smithcd45dbc2014-04-19 03:48:30 +00006613 Error("malformed AST file: missing C++ base specifiers");
Craig Toppera13603a2014-05-22 05:54:18 +00006614 return nullptr;
Guy Benyei11169dd2012-12-18 14:30:41 +00006615 }
6616
6617 unsigned Idx = 0;
6618 unsigned NumBases = Record[Idx++];
6619 void *Mem = Context.Allocate(sizeof(CXXBaseSpecifier) * NumBases);
6620 CXXBaseSpecifier *Bases = new (Mem) CXXBaseSpecifier [NumBases];
6621 for (unsigned I = 0; I != NumBases; ++I)
6622 Bases[I] = ReadCXXBaseSpecifier(*Loc.F, Record, Idx);
6623 return Bases;
6624}
6625
David L. Jonesc4808b9e2016-12-15 20:53:26 +00006626serialization::DeclID
Guy Benyei11169dd2012-12-18 14:30:41 +00006627ASTReader::getGlobalDeclID(ModuleFile &F, LocalDeclID LocalID) const {
6628 if (LocalID < NUM_PREDEF_DECL_IDS)
6629 return LocalID;
6630
Richard Smith37a93df2017-02-18 00:32:02 +00006631 if (!F.ModuleOffsetMap.empty())
6632 ReadModuleOffsetMap(F);
6633
Guy Benyei11169dd2012-12-18 14:30:41 +00006634 ContinuousRangeMap<uint32_t, int, 2>::iterator I
6635 = F.DeclRemap.find(LocalID - NUM_PREDEF_DECL_IDS);
6636 assert(I != F.DeclRemap.end() && "Invalid index into decl index remap");
David L. Jonesc4808b9e2016-12-15 20:53:26 +00006637
Guy Benyei11169dd2012-12-18 14:30:41 +00006638 return LocalID + I->second;
6639}
6640
6641bool ASTReader::isDeclIDFromModule(serialization::GlobalDeclID ID,
6642 ModuleFile &M) const {
Richard Smithfe620d22015-03-05 23:24:12 +00006643 // Predefined decls aren't from any module.
6644 if (ID < NUM_PREDEF_DECL_IDS)
6645 return false;
6646
David L. Jonesc4808b9e2016-12-15 20:53:26 +00006647 return ID - NUM_PREDEF_DECL_IDS >= M.BaseDeclID &&
Richard Smithbcda1a92015-07-12 23:51:20 +00006648 ID - NUM_PREDEF_DECL_IDS < M.BaseDeclID + M.LocalNumDecls;
Guy Benyei11169dd2012-12-18 14:30:41 +00006649}
6650
Douglas Gregor9f782892013-01-21 15:25:38 +00006651ModuleFile *ASTReader::getOwningModuleFile(const Decl *D) {
Guy Benyei11169dd2012-12-18 14:30:41 +00006652 if (!D->isFromASTFile())
Craig Toppera13603a2014-05-22 05:54:18 +00006653 return nullptr;
Guy Benyei11169dd2012-12-18 14:30:41 +00006654 GlobalDeclMapType::const_iterator I = GlobalDeclMap.find(D->getGlobalID());
6655 assert(I != GlobalDeclMap.end() && "Corrupted global declaration map");
6656 return I->second;
6657}
6658
6659SourceLocation ASTReader::getSourceLocationForDeclID(GlobalDeclID ID) {
6660 if (ID < NUM_PREDEF_DECL_IDS)
6661 return SourceLocation();
Richard Smithcd45dbc2014-04-19 03:48:30 +00006662
Guy Benyei11169dd2012-12-18 14:30:41 +00006663 unsigned Index = ID - NUM_PREDEF_DECL_IDS;
6664
6665 if (Index > DeclsLoaded.size()) {
6666 Error("declaration ID out-of-range for AST file");
6667 return SourceLocation();
6668 }
Richard Smithcd45dbc2014-04-19 03:48:30 +00006669
Guy Benyei11169dd2012-12-18 14:30:41 +00006670 if (Decl *D = DeclsLoaded[Index])
6671 return D->getLocation();
6672
Richard Smithcb34bd32016-03-27 07:28:06 +00006673 SourceLocation Loc;
6674 DeclCursorForID(ID, Loc);
6675 return Loc;
Guy Benyei11169dd2012-12-18 14:30:41 +00006676}
6677
Richard Smithfe620d22015-03-05 23:24:12 +00006678static Decl *getPredefinedDecl(ASTContext &Context, PredefinedDeclIDs ID) {
6679 switch (ID) {
6680 case PREDEF_DECL_NULL_ID:
6681 return nullptr;
6682
6683 case PREDEF_DECL_TRANSLATION_UNIT_ID:
6684 return Context.getTranslationUnitDecl();
6685
6686 case PREDEF_DECL_OBJC_ID_ID:
6687 return Context.getObjCIdDecl();
6688
6689 case PREDEF_DECL_OBJC_SEL_ID:
6690 return Context.getObjCSelDecl();
6691
6692 case PREDEF_DECL_OBJC_CLASS_ID:
6693 return Context.getObjCClassDecl();
6694
6695 case PREDEF_DECL_OBJC_PROTOCOL_ID:
6696 return Context.getObjCProtocolDecl();
6697
6698 case PREDEF_DECL_INT_128_ID:
6699 return Context.getInt128Decl();
6700
6701 case PREDEF_DECL_UNSIGNED_INT_128_ID:
6702 return Context.getUInt128Decl();
6703
6704 case PREDEF_DECL_OBJC_INSTANCETYPE_ID:
6705 return Context.getObjCInstanceTypeDecl();
6706
6707 case PREDEF_DECL_BUILTIN_VA_LIST_ID:
6708 return Context.getBuiltinVaListDecl();
Richard Smithf19e1272015-03-07 00:04:49 +00006709
Richard Smith9b88a4c2015-07-27 05:40:23 +00006710 case PREDEF_DECL_VA_LIST_TAG:
6711 return Context.getVaListTagDecl();
6712
Charles Davisc7d5c942015-09-17 20:55:33 +00006713 case PREDEF_DECL_BUILTIN_MS_VA_LIST_ID:
6714 return Context.getBuiltinMSVaListDecl();
6715
Richard Smithf19e1272015-03-07 00:04:49 +00006716 case PREDEF_DECL_EXTERN_C_CONTEXT_ID:
6717 return Context.getExternCContextDecl();
David Majnemerd9b1a4f2015-11-04 03:40:30 +00006718
6719 case PREDEF_DECL_MAKE_INTEGER_SEQ_ID:
6720 return Context.getMakeIntegerSeqDecl();
Quentin Colombet043406b2016-02-03 22:41:00 +00006721
6722 case PREDEF_DECL_CF_CONSTANT_STRING_ID:
6723 return Context.getCFConstantStringDecl();
Ben Langmuirf5416742016-02-04 00:55:24 +00006724
6725 case PREDEF_DECL_CF_CONSTANT_STRING_TAG_ID:
6726 return Context.getCFConstantStringTagDecl();
Eric Fiselier6ad68552016-07-01 01:24:09 +00006727
6728 case PREDEF_DECL_TYPE_PACK_ELEMENT_ID:
6729 return Context.getTypePackElementDecl();
Richard Smithfe620d22015-03-05 23:24:12 +00006730 }
Yaron Keren322bdad2015-03-06 07:49:14 +00006731 llvm_unreachable("PredefinedDeclIDs unknown enum value");
Richard Smithfe620d22015-03-05 23:24:12 +00006732}
6733
Richard Smithcd45dbc2014-04-19 03:48:30 +00006734Decl *ASTReader::GetExistingDecl(DeclID ID) {
6735 if (ID < NUM_PREDEF_DECL_IDS) {
Richard Smithfe620d22015-03-05 23:24:12 +00006736 Decl *D = getPredefinedDecl(Context, (PredefinedDeclIDs)ID);
6737 if (D) {
6738 // Track that we have merged the declaration with ID \p ID into the
6739 // pre-existing predefined declaration \p D.
Richard Smith5fc18a92015-07-12 23:43:21 +00006740 auto &Merged = KeyDecls[D->getCanonicalDecl()];
Richard Smithfe620d22015-03-05 23:24:12 +00006741 if (Merged.empty())
6742 Merged.push_back(ID);
Guy Benyei11169dd2012-12-18 14:30:41 +00006743 }
Richard Smithfe620d22015-03-05 23:24:12 +00006744 return D;
Guy Benyei11169dd2012-12-18 14:30:41 +00006745 }
Richard Smithcd45dbc2014-04-19 03:48:30 +00006746
Guy Benyei11169dd2012-12-18 14:30:41 +00006747 unsigned Index = ID - NUM_PREDEF_DECL_IDS;
6748
6749 if (Index >= DeclsLoaded.size()) {
6750 assert(0 && "declaration ID out-of-range for AST file");
6751 Error("declaration ID out-of-range for AST file");
Craig Toppera13603a2014-05-22 05:54:18 +00006752 return nullptr;
Guy Benyei11169dd2012-12-18 14:30:41 +00006753 }
Richard Smithcd45dbc2014-04-19 03:48:30 +00006754
6755 return DeclsLoaded[Index];
6756}
6757
6758Decl *ASTReader::GetDecl(DeclID ID) {
6759 if (ID < NUM_PREDEF_DECL_IDS)
6760 return GetExistingDecl(ID);
6761
6762 unsigned Index = ID - NUM_PREDEF_DECL_IDS;
6763
6764 if (Index >= DeclsLoaded.size()) {
6765 assert(0 && "declaration ID out-of-range for AST file");
6766 Error("declaration ID out-of-range for AST file");
Craig Toppera13603a2014-05-22 05:54:18 +00006767 return nullptr;
Richard Smithcd45dbc2014-04-19 03:48:30 +00006768 }
6769
Guy Benyei11169dd2012-12-18 14:30:41 +00006770 if (!DeclsLoaded[Index]) {
6771 ReadDeclRecord(ID);
6772 if (DeserializationListener)
6773 DeserializationListener->DeclRead(ID, DeclsLoaded[Index]);
6774 }
6775
6776 return DeclsLoaded[Index];
6777}
6778
David L. Jonesc4808b9e2016-12-15 20:53:26 +00006779DeclID ASTReader::mapGlobalIDToModuleFileGlobalID(ModuleFile &M,
Guy Benyei11169dd2012-12-18 14:30:41 +00006780 DeclID GlobalID) {
6781 if (GlobalID < NUM_PREDEF_DECL_IDS)
6782 return GlobalID;
David L. Jonesc4808b9e2016-12-15 20:53:26 +00006783
Guy Benyei11169dd2012-12-18 14:30:41 +00006784 GlobalDeclMapType::const_iterator I = GlobalDeclMap.find(GlobalID);
6785 assert(I != GlobalDeclMap.end() && "Corrupted global declaration map");
6786 ModuleFile *Owner = I->second;
6787
6788 llvm::DenseMap<ModuleFile *, serialization::DeclID>::iterator Pos
6789 = M.GlobalToLocalDeclIDs.find(Owner);
6790 if (Pos == M.GlobalToLocalDeclIDs.end())
6791 return 0;
David L. Jonesc4808b9e2016-12-15 20:53:26 +00006792
Guy Benyei11169dd2012-12-18 14:30:41 +00006793 return GlobalID - Owner->BaseDeclID + Pos->second;
6794}
6795
David L. Jonesc4808b9e2016-12-15 20:53:26 +00006796serialization::DeclID ASTReader::ReadDeclID(ModuleFile &F,
Guy Benyei11169dd2012-12-18 14:30:41 +00006797 const RecordData &Record,
6798 unsigned &Idx) {
6799 if (Idx >= Record.size()) {
6800 Error("Corrupted AST file");
6801 return 0;
6802 }
David L. Jonesc4808b9e2016-12-15 20:53:26 +00006803
Guy Benyei11169dd2012-12-18 14:30:41 +00006804 return getGlobalDeclID(F, Record[Idx++]);
6805}
6806
6807/// \brief Resolve the offset of a statement into a statement.
6808///
6809/// This operation will read a new statement from the external
6810/// source each time it is called, and is meant to be used via a
6811/// LazyOffsetPtr (which is used by Decls for the body of functions, etc).
6812Stmt *ASTReader::GetExternalDeclStmt(uint64_t Offset) {
6813 // Switch case IDs are per Decl.
6814 ClearSwitchCaseIDs();
6815
6816 // Offset here is a global offset across the entire chain.
6817 RecordLocation Loc = getLocalBitOffset(Offset);
6818 Loc.F->DeclsCursor.JumpToBit(Loc.Offset);
6819 return ReadStmtFromStream(*Loc.F);
6820}
6821
Richard Smith3cb15722015-08-05 22:41:45 +00006822void ASTReader::FindExternalLexicalDecls(
6823 const DeclContext *DC, llvm::function_ref<bool(Decl::Kind)> IsKindWeWant,
6824 SmallVectorImpl<Decl *> &Decls) {
Richard Smith82f8fcd2015-08-06 22:07:25 +00006825 bool PredefsVisited[NUM_PREDEF_DECL_IDS] = {};
6826
Richard Smith9ccdd932015-08-06 22:14:12 +00006827 auto Visit = [&] (ModuleFile *M, LexicalContents LexicalDecls) {
Richard Smith82f8fcd2015-08-06 22:07:25 +00006828 assert(LexicalDecls.size() % 2 == 0 && "expected an even number of entries");
6829 for (int I = 0, N = LexicalDecls.size(); I != N; I += 2) {
6830 auto K = (Decl::Kind)+LexicalDecls[I];
6831 if (!IsKindWeWant(K))
6832 continue;
6833
6834 auto ID = (serialization::DeclID)+LexicalDecls[I + 1];
6835
6836 // Don't add predefined declarations to the lexical context more
6837 // than once.
6838 if (ID < NUM_PREDEF_DECL_IDS) {
6839 if (PredefsVisited[ID])
6840 continue;
6841
6842 PredefsVisited[ID] = true;
6843 }
6844
6845 if (Decl *D = GetLocalDecl(*M, ID)) {
Richard Smith2317a3e2015-08-11 21:21:20 +00006846 assert(D->getKind() == K && "wrong kind for lexical decl");
Richard Smith82f8fcd2015-08-06 22:07:25 +00006847 if (!DC->isDeclInLexicalTraversal(D))
6848 Decls.push_back(D);
6849 }
6850 }
6851 };
6852
6853 if (isa<TranslationUnitDecl>(DC)) {
6854 for (auto Lexical : TULexicalDecls)
6855 Visit(Lexical.first, Lexical.second);
6856 } else {
6857 auto I = LexicalDecls.find(DC);
6858 if (I != LexicalDecls.end())
Richard Smith9c9173d2015-08-11 22:00:24 +00006859 Visit(I->second.first, I->second.second);
Richard Smith82f8fcd2015-08-06 22:07:25 +00006860 }
6861
Guy Benyei11169dd2012-12-18 14:30:41 +00006862 ++NumLexicalDeclContextsRead;
Guy Benyei11169dd2012-12-18 14:30:41 +00006863}
6864
6865namespace {
6866
6867class DeclIDComp {
6868 ASTReader &Reader;
6869 ModuleFile &Mod;
6870
6871public:
6872 DeclIDComp(ASTReader &Reader, ModuleFile &M) : Reader(Reader), Mod(M) {}
6873
6874 bool operator()(LocalDeclID L, LocalDeclID R) const {
6875 SourceLocation LHS = getLocation(L);
6876 SourceLocation RHS = getLocation(R);
6877 return Reader.getSourceManager().isBeforeInTranslationUnit(LHS, RHS);
6878 }
6879
6880 bool operator()(SourceLocation LHS, LocalDeclID R) const {
6881 SourceLocation RHS = getLocation(R);
6882 return Reader.getSourceManager().isBeforeInTranslationUnit(LHS, RHS);
6883 }
6884
6885 bool operator()(LocalDeclID L, SourceLocation RHS) const {
6886 SourceLocation LHS = getLocation(L);
6887 return Reader.getSourceManager().isBeforeInTranslationUnit(LHS, RHS);
6888 }
6889
6890 SourceLocation getLocation(LocalDeclID ID) const {
6891 return Reader.getSourceManager().getFileLoc(
6892 Reader.getSourceLocationForDeclID(Reader.getGlobalDeclID(Mod, ID)));
6893 }
6894};
6895
Eugene Zelenkoe95e7d52016-09-07 21:53:17 +00006896} // end anonymous namespace
Guy Benyei11169dd2012-12-18 14:30:41 +00006897
6898void ASTReader::FindFileRegionDecls(FileID File,
6899 unsigned Offset, unsigned Length,
6900 SmallVectorImpl<Decl *> &Decls) {
6901 SourceManager &SM = getSourceManager();
6902
6903 llvm::DenseMap<FileID, FileDeclsInfo>::iterator I = FileDeclIDs.find(File);
6904 if (I == FileDeclIDs.end())
6905 return;
6906
6907 FileDeclsInfo &DInfo = I->second;
6908 if (DInfo.Decls.empty())
6909 return;
6910
6911 SourceLocation
6912 BeginLoc = SM.getLocForStartOfFile(File).getLocWithOffset(Offset);
6913 SourceLocation EndLoc = BeginLoc.getLocWithOffset(Length);
6914
6915 DeclIDComp DIDComp(*this, *DInfo.Mod);
6916 ArrayRef<serialization::LocalDeclID>::iterator
6917 BeginIt = std::lower_bound(DInfo.Decls.begin(), DInfo.Decls.end(),
6918 BeginLoc, DIDComp);
6919 if (BeginIt != DInfo.Decls.begin())
6920 --BeginIt;
6921
6922 // If we are pointing at a top-level decl inside an objc container, we need
6923 // to backtrack until we find it otherwise we will fail to report that the
6924 // region overlaps with an objc container.
6925 while (BeginIt != DInfo.Decls.begin() &&
6926 GetDecl(getGlobalDeclID(*DInfo.Mod, *BeginIt))
6927 ->isTopLevelDeclInObjCContainer())
6928 --BeginIt;
6929
6930 ArrayRef<serialization::LocalDeclID>::iterator
6931 EndIt = std::upper_bound(DInfo.Decls.begin(), DInfo.Decls.end(),
6932 EndLoc, DIDComp);
6933 if (EndIt != DInfo.Decls.end())
6934 ++EndIt;
David L. Jonesc4808b9e2016-12-15 20:53:26 +00006935
Guy Benyei11169dd2012-12-18 14:30:41 +00006936 for (ArrayRef<serialization::LocalDeclID>::iterator
6937 DIt = BeginIt; DIt != EndIt; ++DIt)
6938 Decls.push_back(GetDecl(getGlobalDeclID(*DInfo.Mod, *DIt)));
6939}
6940
Richard Smith9ce12e32013-02-07 03:30:24 +00006941bool
Guy Benyei11169dd2012-12-18 14:30:41 +00006942ASTReader::FindExternalVisibleDeclsByName(const DeclContext *DC,
6943 DeclarationName Name) {
Richard Smithd88a7f12015-09-01 20:35:42 +00006944 assert(DC->hasExternalVisibleStorage() && DC == DC->getPrimaryContext() &&
Guy Benyei11169dd2012-12-18 14:30:41 +00006945 "DeclContext has no visible decls in storage");
6946 if (!Name)
Richard Smith9ce12e32013-02-07 03:30:24 +00006947 return false;
Guy Benyei11169dd2012-12-18 14:30:41 +00006948
Richard Smithd88a7f12015-09-01 20:35:42 +00006949 auto It = Lookups.find(DC);
6950 if (It == Lookups.end())
6951 return false;
6952
Richard Smith8c913ec2014-08-14 02:21:01 +00006953 Deserializing LookupResults(this);
6954
Richard Smithd88a7f12015-09-01 20:35:42 +00006955 // Load the list of declarations.
Guy Benyei11169dd2012-12-18 14:30:41 +00006956 SmallVector<NamedDecl *, 64> Decls;
Richard Smithd88a7f12015-09-01 20:35:42 +00006957 for (DeclID ID : It->second.Table.find(Name)) {
6958 NamedDecl *ND = cast<NamedDecl>(GetDecl(ID));
6959 if (ND->getDeclName() == Name)
6960 Decls.push_back(ND);
6961 }
Richard Smithcd45dbc2014-04-19 03:48:30 +00006962
Guy Benyei11169dd2012-12-18 14:30:41 +00006963 ++NumVisibleDeclContextsRead;
6964 SetExternalVisibleDeclsForName(DC, Name, Decls);
Richard Smith9ce12e32013-02-07 03:30:24 +00006965 return !Decls.empty();
Guy Benyei11169dd2012-12-18 14:30:41 +00006966}
6967
Guy Benyei11169dd2012-12-18 14:30:41 +00006968void ASTReader::completeVisibleDeclsMap(const DeclContext *DC) {
6969 if (!DC->hasExternalVisibleStorage())
6970 return;
Richard Smithd88a7f12015-09-01 20:35:42 +00006971
6972 auto It = Lookups.find(DC);
6973 assert(It != Lookups.end() &&
6974 "have external visible storage but no lookup tables");
6975
Craig Topper79be4cd2013-07-05 04:33:53 +00006976 DeclsMap Decls;
Guy Benyei11169dd2012-12-18 14:30:41 +00006977
Richard Smithd88a7f12015-09-01 20:35:42 +00006978 for (DeclID ID : It->second.Table.findAll()) {
6979 NamedDecl *ND = cast<NamedDecl>(GetDecl(ID));
6980 Decls[ND->getDeclName()].push_back(ND);
Guy Benyei11169dd2012-12-18 14:30:41 +00006981 }
6982
Guy Benyei11169dd2012-12-18 14:30:41 +00006983 ++NumVisibleDeclContextsRead;
6984
Craig Topper79be4cd2013-07-05 04:33:53 +00006985 for (DeclsMap::iterator I = Decls.begin(), E = Decls.end(); I != E; ++I) {
Guy Benyei11169dd2012-12-18 14:30:41 +00006986 SetExternalVisibleDeclsForName(DC, I->first, I->second);
6987 }
6988 const_cast<DeclContext *>(DC)->setHasExternalVisibleStorage(false);
6989}
6990
Richard Smithd88a7f12015-09-01 20:35:42 +00006991const serialization::reader::DeclContextLookupTable *
6992ASTReader::getLoadedLookupTables(DeclContext *Primary) const {
6993 auto I = Lookups.find(Primary);
6994 return I == Lookups.end() ? nullptr : &I->second;
6995}
6996
Guy Benyei11169dd2012-12-18 14:30:41 +00006997/// \brief Under non-PCH compilation the consumer receives the objc methods
6998/// before receiving the implementation, and codegen depends on this.
6999/// We simulate this by deserializing and passing to consumer the methods of the
7000/// implementation before passing the deserialized implementation decl.
7001static void PassObjCImplDeclToConsumer(ObjCImplDecl *ImplD,
7002 ASTConsumer *Consumer) {
7003 assert(ImplD && Consumer);
7004
Aaron Ballmanaff18c02014-03-13 19:03:34 +00007005 for (auto *I : ImplD->methods())
7006 Consumer->HandleInterestingDecl(DeclGroupRef(I));
Guy Benyei11169dd2012-12-18 14:30:41 +00007007
7008 Consumer->HandleInterestingDecl(DeclGroupRef(ImplD));
7009}
7010
7011void ASTReader::PassInterestingDeclsToConsumer() {
7012 assert(Consumer);
Richard Smith04d05b52014-03-23 00:27:18 +00007013
7014 if (PassingDeclsToConsumer)
7015 return;
7016
7017 // Guard variable to avoid recursively redoing the process of passing
7018 // decls to consumer.
7019 SaveAndRestore<bool> GuardPassingDeclsToConsumer(PassingDeclsToConsumer,
7020 true);
7021
Richard Smith9e2341d2015-03-23 03:25:59 +00007022 // Ensure that we've loaded all potentially-interesting declarations
7023 // that need to be eagerly loaded.
7024 for (auto ID : EagerlyDeserializedDecls)
7025 GetDecl(ID);
7026 EagerlyDeserializedDecls.clear();
7027
Guy Benyei11169dd2012-12-18 14:30:41 +00007028 while (!InterestingDecls.empty()) {
7029 Decl *D = InterestingDecls.front();
7030 InterestingDecls.pop_front();
7031
7032 PassInterestingDeclToConsumer(D);
7033 }
7034}
7035
7036void ASTReader::PassInterestingDeclToConsumer(Decl *D) {
7037 if (ObjCImplDecl *ImplD = dyn_cast<ObjCImplDecl>(D))
7038 PassObjCImplDeclToConsumer(ImplD, Consumer);
7039 else
7040 Consumer->HandleInterestingDecl(DeclGroupRef(D));
7041}
7042
7043void ASTReader::StartTranslationUnit(ASTConsumer *Consumer) {
7044 this->Consumer = Consumer;
7045
Richard Smith9e2341d2015-03-23 03:25:59 +00007046 if (Consumer)
7047 PassInterestingDeclsToConsumer();
Richard Smith7f330cd2015-03-18 01:42:29 +00007048
7049 if (DeserializationListener)
7050 DeserializationListener->ReaderInitialized(this);
Guy Benyei11169dd2012-12-18 14:30:41 +00007051}
7052
7053void ASTReader::PrintStats() {
7054 std::fprintf(stderr, "*** AST File Statistics:\n");
7055
7056 unsigned NumTypesLoaded
7057 = TypesLoaded.size() - std::count(TypesLoaded.begin(), TypesLoaded.end(),
7058 QualType());
7059 unsigned NumDeclsLoaded
7060 = DeclsLoaded.size() - std::count(DeclsLoaded.begin(), DeclsLoaded.end(),
Craig Toppera13603a2014-05-22 05:54:18 +00007061 (Decl *)nullptr);
Guy Benyei11169dd2012-12-18 14:30:41 +00007062 unsigned NumIdentifiersLoaded
7063 = IdentifiersLoaded.size() - std::count(IdentifiersLoaded.begin(),
7064 IdentifiersLoaded.end(),
Craig Toppera13603a2014-05-22 05:54:18 +00007065 (IdentifierInfo *)nullptr);
Guy Benyei11169dd2012-12-18 14:30:41 +00007066 unsigned NumMacrosLoaded
7067 = MacrosLoaded.size() - std::count(MacrosLoaded.begin(),
7068 MacrosLoaded.end(),
Craig Toppera13603a2014-05-22 05:54:18 +00007069 (MacroInfo *)nullptr);
Guy Benyei11169dd2012-12-18 14:30:41 +00007070 unsigned NumSelectorsLoaded
7071 = SelectorsLoaded.size() - std::count(SelectorsLoaded.begin(),
7072 SelectorsLoaded.end(),
7073 Selector());
7074
7075 if (unsigned TotalNumSLocEntries = getTotalNumSLocs())
7076 std::fprintf(stderr, " %u/%u source location entries read (%f%%)\n",
7077 NumSLocEntriesRead, TotalNumSLocEntries,
7078 ((float)NumSLocEntriesRead/TotalNumSLocEntries * 100));
7079 if (!TypesLoaded.empty())
7080 std::fprintf(stderr, " %u/%u types read (%f%%)\n",
7081 NumTypesLoaded, (unsigned)TypesLoaded.size(),
7082 ((float)NumTypesLoaded/TypesLoaded.size() * 100));
7083 if (!DeclsLoaded.empty())
7084 std::fprintf(stderr, " %u/%u declarations read (%f%%)\n",
7085 NumDeclsLoaded, (unsigned)DeclsLoaded.size(),
7086 ((float)NumDeclsLoaded/DeclsLoaded.size() * 100));
7087 if (!IdentifiersLoaded.empty())
7088 std::fprintf(stderr, " %u/%u identifiers read (%f%%)\n",
7089 NumIdentifiersLoaded, (unsigned)IdentifiersLoaded.size(),
7090 ((float)NumIdentifiersLoaded/IdentifiersLoaded.size() * 100));
7091 if (!MacrosLoaded.empty())
7092 std::fprintf(stderr, " %u/%u macros read (%f%%)\n",
7093 NumMacrosLoaded, (unsigned)MacrosLoaded.size(),
7094 ((float)NumMacrosLoaded/MacrosLoaded.size() * 100));
7095 if (!SelectorsLoaded.empty())
7096 std::fprintf(stderr, " %u/%u selectors read (%f%%)\n",
7097 NumSelectorsLoaded, (unsigned)SelectorsLoaded.size(),
7098 ((float)NumSelectorsLoaded/SelectorsLoaded.size() * 100));
7099 if (TotalNumStatements)
7100 std::fprintf(stderr, " %u/%u statements read (%f%%)\n",
7101 NumStatementsRead, TotalNumStatements,
7102 ((float)NumStatementsRead/TotalNumStatements * 100));
7103 if (TotalNumMacros)
7104 std::fprintf(stderr, " %u/%u macros read (%f%%)\n",
7105 NumMacrosRead, TotalNumMacros,
7106 ((float)NumMacrosRead/TotalNumMacros * 100));
7107 if (TotalLexicalDeclContexts)
7108 std::fprintf(stderr, " %u/%u lexical declcontexts read (%f%%)\n",
7109 NumLexicalDeclContextsRead, TotalLexicalDeclContexts,
7110 ((float)NumLexicalDeclContextsRead/TotalLexicalDeclContexts
7111 * 100));
7112 if (TotalVisibleDeclContexts)
7113 std::fprintf(stderr, " %u/%u visible declcontexts read (%f%%)\n",
7114 NumVisibleDeclContextsRead, TotalVisibleDeclContexts,
7115 ((float)NumVisibleDeclContextsRead/TotalVisibleDeclContexts
7116 * 100));
7117 if (TotalNumMethodPoolEntries) {
7118 std::fprintf(stderr, " %u/%u method pool entries read (%f%%)\n",
7119 NumMethodPoolEntriesRead, TotalNumMethodPoolEntries,
7120 ((float)NumMethodPoolEntriesRead/TotalNumMethodPoolEntries
7121 * 100));
Guy Benyei11169dd2012-12-18 14:30:41 +00007122 }
Douglas Gregorad2f7a52013-01-28 17:54:36 +00007123 if (NumMethodPoolLookups) {
7124 std::fprintf(stderr, " %u/%u method pool lookups succeeded (%f%%)\n",
7125 NumMethodPoolHits, NumMethodPoolLookups,
7126 ((float)NumMethodPoolHits/NumMethodPoolLookups * 100.0));
7127 }
7128 if (NumMethodPoolTableLookups) {
7129 std::fprintf(stderr, " %u/%u method pool table lookups succeeded (%f%%)\n",
7130 NumMethodPoolTableHits, NumMethodPoolTableLookups,
7131 ((float)NumMethodPoolTableHits/NumMethodPoolTableLookups
7132 * 100.0));
7133 }
7134
Douglas Gregor00a50f72013-01-25 00:38:33 +00007135 if (NumIdentifierLookupHits) {
7136 std::fprintf(stderr,
7137 " %u / %u identifier table lookups succeeded (%f%%)\n",
7138 NumIdentifierLookupHits, NumIdentifierLookups,
7139 (double)NumIdentifierLookupHits*100.0/NumIdentifierLookups);
7140 }
7141
Douglas Gregore060e572013-01-25 01:03:03 +00007142 if (GlobalIndex) {
7143 std::fprintf(stderr, "\n");
7144 GlobalIndex->printStats();
7145 }
David L. Jonesc4808b9e2016-12-15 20:53:26 +00007146
Guy Benyei11169dd2012-12-18 14:30:41 +00007147 std::fprintf(stderr, "\n");
7148 dump();
7149 std::fprintf(stderr, "\n");
7150}
7151
7152template<typename Key, typename ModuleFile, unsigned InitialCapacity>
David L. Jonesc4808b9e2016-12-15 20:53:26 +00007153static void
Guy Benyei11169dd2012-12-18 14:30:41 +00007154dumpModuleIDMap(StringRef Name,
David L. Jonesc4808b9e2016-12-15 20:53:26 +00007155 const ContinuousRangeMap<Key, ModuleFile *,
Guy Benyei11169dd2012-12-18 14:30:41 +00007156 InitialCapacity> &Map) {
7157 if (Map.begin() == Map.end())
7158 return;
David L. Jonesc4808b9e2016-12-15 20:53:26 +00007159
Guy Benyei11169dd2012-12-18 14:30:41 +00007160 typedef ContinuousRangeMap<Key, ModuleFile *, InitialCapacity> MapType;
7161 llvm::errs() << Name << ":\n";
David L. Jonesc4808b9e2016-12-15 20:53:26 +00007162 for (typename MapType::const_iterator I = Map.begin(), IEnd = Map.end();
Guy Benyei11169dd2012-12-18 14:30:41 +00007163 I != IEnd; ++I) {
7164 llvm::errs() << " " << I->first << " -> " << I->second->FileName
7165 << "\n";
7166 }
7167}
7168
Yaron Kerencdae9412016-01-29 19:38:18 +00007169LLVM_DUMP_METHOD void ASTReader::dump() {
Guy Benyei11169dd2012-12-18 14:30:41 +00007170 llvm::errs() << "*** PCH/ModuleFile Remappings:\n";
7171 dumpModuleIDMap("Global bit offset map", GlobalBitOffsetsMap);
7172 dumpModuleIDMap("Global source location entry map", GlobalSLocEntryMap);
7173 dumpModuleIDMap("Global type map", GlobalTypeMap);
7174 dumpModuleIDMap("Global declaration map", GlobalDeclMap);
7175 dumpModuleIDMap("Global identifier map", GlobalIdentifierMap);
7176 dumpModuleIDMap("Global macro map", GlobalMacroMap);
7177 dumpModuleIDMap("Global submodule map", GlobalSubmoduleMap);
7178 dumpModuleIDMap("Global selector map", GlobalSelectorMap);
David L. Jonesc4808b9e2016-12-15 20:53:26 +00007179 dumpModuleIDMap("Global preprocessed entity map",
Guy Benyei11169dd2012-12-18 14:30:41 +00007180 GlobalPreprocessedEntityMap);
David L. Jonesc4808b9e2016-12-15 20:53:26 +00007181
Guy Benyei11169dd2012-12-18 14:30:41 +00007182 llvm::errs() << "\n*** PCH/Modules Loaded:";
Duncan P. N. Exon Smith96a06e02017-01-28 22:15:22 +00007183 for (ModuleFile &M : ModuleMgr)
7184 M.dump();
Guy Benyei11169dd2012-12-18 14:30:41 +00007185}
7186
7187/// Return the amount of memory used by memory buffers, breaking down
7188/// by heap-backed versus mmap'ed memory.
7189void ASTReader::getMemoryBufferSizes(MemoryBufferSizes &sizes) const {
Duncan P. N. Exon Smith96a06e02017-01-28 22:15:22 +00007190 for (ModuleFile &I : ModuleMgr) {
7191 if (llvm::MemoryBuffer *buf = I.Buffer.get()) {
Guy Benyei11169dd2012-12-18 14:30:41 +00007192 size_t bytes = buf->getBufferSize();
7193 switch (buf->getBufferKind()) {
7194 case llvm::MemoryBuffer::MemoryBuffer_Malloc:
7195 sizes.malloc_bytes += bytes;
7196 break;
7197 case llvm::MemoryBuffer::MemoryBuffer_MMap:
7198 sizes.mmap_bytes += bytes;
7199 break;
7200 }
7201 }
7202 }
7203}
7204
7205void ASTReader::InitializeSema(Sema &S) {
7206 SemaObj = &S;
7207 S.addExternalSource(this);
7208
7209 // Makes sure any declarations that were deserialized "too early"
7210 // still get added to the identifier's declaration chains.
Ben Langmuir5418f402014-09-10 21:29:41 +00007211 for (uint64_t ID : PreloadedDeclIDs) {
7212 NamedDecl *D = cast<NamedDecl>(GetDecl(ID));
7213 pushExternalDeclIntoScope(D, D->getDeclName());
Guy Benyei11169dd2012-12-18 14:30:41 +00007214 }
Ben Langmuir5418f402014-09-10 21:29:41 +00007215 PreloadedDeclIDs.clear();
Guy Benyei11169dd2012-12-18 14:30:41 +00007216
Richard Smith3d8e97e2013-10-18 06:54:39 +00007217 // FIXME: What happens if these are changed by a module import?
Guy Benyei11169dd2012-12-18 14:30:41 +00007218 if (!FPPragmaOptions.empty()) {
7219 assert(FPPragmaOptions.size() == 1 && "Wrong number of FP_PRAGMA_OPTIONS");
7220 SemaObj->FPFeatures.fp_contract = FPPragmaOptions[0];
7221 }
7222
Yaxun Liu5b746652016-12-18 05:18:55 +00007223 SemaObj->OpenCLFeatures.copy(OpenCLExtensions);
7224 SemaObj->OpenCLTypeExtMap = OpenCLTypeExtMap;
7225 SemaObj->OpenCLDeclExtMap = OpenCLDeclExtMap;
Richard Smith3d8e97e2013-10-18 06:54:39 +00007226
7227 UpdateSema();
7228}
7229
7230void ASTReader::UpdateSema() {
7231 assert(SemaObj && "no Sema to update");
7232
7233 // Load the offsets of the declarations that Sema references.
7234 // They will be lazily deserialized when needed.
7235 if (!SemaDeclRefs.empty()) {
Richard Smith96269c52016-09-29 22:49:46 +00007236 assert(SemaDeclRefs.size() % 3 == 0);
7237 for (unsigned I = 0; I != SemaDeclRefs.size(); I += 3) {
Richard Smith3d8e97e2013-10-18 06:54:39 +00007238 if (!SemaObj->StdNamespace)
7239 SemaObj->StdNamespace = SemaDeclRefs[I];
7240 if (!SemaObj->StdBadAlloc)
7241 SemaObj->StdBadAlloc = SemaDeclRefs[I+1];
Richard Smith96269c52016-09-29 22:49:46 +00007242 if (!SemaObj->StdAlignValT)
7243 SemaObj->StdAlignValT = SemaDeclRefs[I+2];
Richard Smith3d8e97e2013-10-18 06:54:39 +00007244 }
7245 SemaDeclRefs.clear();
7246 }
Dario Domizioli13a0a382014-05-23 12:13:25 +00007247
Nico Weber779355f2016-03-02 23:22:00 +00007248 // Update the state of pragmas. Use the same API as if we had encountered the
7249 // pragma in the source.
Dario Domizioli13a0a382014-05-23 12:13:25 +00007250 if(OptimizeOffPragmaLocation.isValid())
7251 SemaObj->ActOnPragmaOptimize(/* IsOn = */ false, OptimizeOffPragmaLocation);
Nico Weber779355f2016-03-02 23:22:00 +00007252 if (PragmaMSStructState != -1)
7253 SemaObj->ActOnPragmaMSStruct((PragmaMSStructKind)PragmaMSStructState);
Nico Weber42932312016-03-03 00:17:35 +00007254 if (PointersToMembersPragmaLocation.isValid()) {
7255 SemaObj->ActOnPragmaMSPointersToMembers(
7256 (LangOptions::PragmaMSPointersToMembersKind)
7257 PragmaMSPointersToMembersState,
7258 PointersToMembersPragmaLocation);
7259 }
Justin Lebar67a78a62016-10-08 22:15:58 +00007260 SemaObj->ForceCUDAHostDeviceDepth = ForceCUDAHostDeviceDepth;
Guy Benyei11169dd2012-12-18 14:30:41 +00007261}
7262
Richard Smitha8d5b6a2015-07-17 19:51:03 +00007263IdentifierInfo *ASTReader::get(StringRef Name) {
Guy Benyei11169dd2012-12-18 14:30:41 +00007264 // Note that we are loading an identifier.
7265 Deserializing AnIdentifier(this);
Douglas Gregore060e572013-01-25 01:03:03 +00007266
Douglas Gregor7211ac12013-01-25 23:32:03 +00007267 IdentifierLookupVisitor Visitor(Name, /*PriorGeneration=*/0,
Douglas Gregor00a50f72013-01-25 00:38:33 +00007268 NumIdentifierLookups,
7269 NumIdentifierLookupHits);
Richard Smith33e0f7e2015-07-22 02:08:40 +00007270
7271 // We don't need to do identifier table lookups in C++ modules (we preload
7272 // all interesting declarations, and don't need to use the scope for name
7273 // lookups). Perform the lookup in PCH files, though, since we don't build
7274 // a complete initial identifier table if we're carrying on from a PCH.
7275 if (Context.getLangOpts().CPlusPlus) {
7276 for (auto F : ModuleMgr.pch_modules())
Benjamin Kramer9a9efba2015-07-25 12:14:04 +00007277 if (Visitor(*F))
Richard Smith33e0f7e2015-07-22 02:08:40 +00007278 break;
7279 } else {
7280 // If there is a global index, look there first to determine which modules
7281 // provably do not have any results for this identifier.
7282 GlobalModuleIndex::HitSet Hits;
7283 GlobalModuleIndex::HitSet *HitsPtr = nullptr;
7284 if (!loadGlobalIndex()) {
7285 if (GlobalIndex->lookupIdentifier(Name, Hits)) {
7286 HitsPtr = &Hits;
7287 }
7288 }
7289
Benjamin Kramer9a9efba2015-07-25 12:14:04 +00007290 ModuleMgr.visit(Visitor, HitsPtr);
Richard Smith33e0f7e2015-07-22 02:08:40 +00007291 }
7292
Guy Benyei11169dd2012-12-18 14:30:41 +00007293 IdentifierInfo *II = Visitor.getIdentifierInfo();
7294 markIdentifierUpToDate(II);
7295 return II;
7296}
7297
7298namespace clang {
Eugene Zelenkoe95e7d52016-09-07 21:53:17 +00007299
Guy Benyei11169dd2012-12-18 14:30:41 +00007300 /// \brief An identifier-lookup iterator that enumerates all of the
7301 /// identifiers stored within a set of AST files.
7302 class ASTIdentifierIterator : public IdentifierIterator {
7303 /// \brief The AST reader whose identifiers are being enumerated.
7304 const ASTReader &Reader;
7305
7306 /// \brief The current index into the chain of AST files stored in
7307 /// the AST reader.
7308 unsigned Index;
7309
7310 /// \brief The current position within the identifier lookup table
7311 /// of the current AST file.
7312 ASTIdentifierLookupTable::key_iterator Current;
7313
7314 /// \brief The end position within the identifier lookup table of
7315 /// the current AST file.
7316 ASTIdentifierLookupTable::key_iterator End;
7317
Ben Langmuir537c5b52016-05-04 00:53:13 +00007318 /// \brief Whether to skip any modules in the ASTReader.
7319 bool SkipModules;
7320
Guy Benyei11169dd2012-12-18 14:30:41 +00007321 public:
Ben Langmuir537c5b52016-05-04 00:53:13 +00007322 explicit ASTIdentifierIterator(const ASTReader &Reader,
7323 bool SkipModules = false);
Guy Benyei11169dd2012-12-18 14:30:41 +00007324
Craig Topper3e89dfe2014-03-13 02:13:41 +00007325 StringRef Next() override;
Guy Benyei11169dd2012-12-18 14:30:41 +00007326 };
Eugene Zelenkoe95e7d52016-09-07 21:53:17 +00007327
7328} // end namespace clang
Guy Benyei11169dd2012-12-18 14:30:41 +00007329
Ben Langmuir537c5b52016-05-04 00:53:13 +00007330ASTIdentifierIterator::ASTIdentifierIterator(const ASTReader &Reader,
7331 bool SkipModules)
7332 : Reader(Reader), Index(Reader.ModuleMgr.size()), SkipModules(SkipModules) {
Guy Benyei11169dd2012-12-18 14:30:41 +00007333}
7334
7335StringRef ASTIdentifierIterator::Next() {
7336 while (Current == End) {
7337 // If we have exhausted all of our AST files, we're done.
7338 if (Index == 0)
7339 return StringRef();
7340
7341 --Index;
Ben Langmuir537c5b52016-05-04 00:53:13 +00007342 ModuleFile &F = Reader.ModuleMgr[Index];
7343 if (SkipModules && F.isModule())
7344 continue;
7345
7346 ASTIdentifierLookupTable *IdTable =
7347 (ASTIdentifierLookupTable *)F.IdentifierLookupTable;
Guy Benyei11169dd2012-12-18 14:30:41 +00007348 Current = IdTable->key_begin();
7349 End = IdTable->key_end();
7350 }
7351
7352 // We have any identifiers remaining in the current AST file; return
7353 // the next one.
Douglas Gregorbfd73d72013-01-23 18:53:14 +00007354 StringRef Result = *Current;
Guy Benyei11169dd2012-12-18 14:30:41 +00007355 ++Current;
Douglas Gregorbfd73d72013-01-23 18:53:14 +00007356 return Result;
Guy Benyei11169dd2012-12-18 14:30:41 +00007357}
7358
Ben Langmuir537c5b52016-05-04 00:53:13 +00007359namespace {
Eugene Zelenkoe95e7d52016-09-07 21:53:17 +00007360
Ben Langmuir537c5b52016-05-04 00:53:13 +00007361/// A utility for appending two IdentifierIterators.
7362class ChainedIdentifierIterator : public IdentifierIterator {
7363 std::unique_ptr<IdentifierIterator> Current;
7364 std::unique_ptr<IdentifierIterator> Queued;
7365
7366public:
7367 ChainedIdentifierIterator(std::unique_ptr<IdentifierIterator> First,
7368 std::unique_ptr<IdentifierIterator> Second)
7369 : Current(std::move(First)), Queued(std::move(Second)) {}
7370
7371 StringRef Next() override {
7372 if (!Current)
7373 return StringRef();
7374
7375 StringRef result = Current->Next();
7376 if (!result.empty())
7377 return result;
7378
7379 // Try the queued iterator, which may itself be empty.
7380 Current.reset();
7381 std::swap(Current, Queued);
7382 return Next();
7383 }
7384};
Eugene Zelenkoe95e7d52016-09-07 21:53:17 +00007385
Ben Langmuir537c5b52016-05-04 00:53:13 +00007386} // end anonymous namespace.
7387
Argyrios Kyrtzidis9aca3c62013-04-17 22:10:55 +00007388IdentifierIterator *ASTReader::getIdentifiers() {
Ben Langmuir537c5b52016-05-04 00:53:13 +00007389 if (!loadGlobalIndex()) {
7390 std::unique_ptr<IdentifierIterator> ReaderIter(
7391 new ASTIdentifierIterator(*this, /*SkipModules=*/true));
7392 std::unique_ptr<IdentifierIterator> ModulesIter(
7393 GlobalIndex->createIdentifierIterator());
7394 return new ChainedIdentifierIterator(std::move(ReaderIter),
7395 std::move(ModulesIter));
7396 }
Argyrios Kyrtzidis9aca3c62013-04-17 22:10:55 +00007397
Guy Benyei11169dd2012-12-18 14:30:41 +00007398 return new ASTIdentifierIterator(*this);
7399}
7400
Eugene Zelenkoe95e7d52016-09-07 21:53:17 +00007401namespace clang {
7402namespace serialization {
7403
Guy Benyei11169dd2012-12-18 14:30:41 +00007404 class ReadMethodPoolVisitor {
7405 ASTReader &Reader;
7406 Selector Sel;
7407 unsigned PriorGeneration;
Argyrios Kyrtzidisd3da6e02013-04-17 00:08:58 +00007408 unsigned InstanceBits;
7409 unsigned FactoryBits;
Nico Weberff4b35e2014-12-27 22:14:15 +00007410 bool InstanceHasMoreThanOneDecl;
7411 bool FactoryHasMoreThanOneDecl;
Dmitri Gribenkof8579502013-01-12 19:30:44 +00007412 SmallVector<ObjCMethodDecl *, 4> InstanceMethods;
7413 SmallVector<ObjCMethodDecl *, 4> FactoryMethods;
Guy Benyei11169dd2012-12-18 14:30:41 +00007414
7415 public:
Nico Weber2e0c8f72014-12-27 03:58:08 +00007416 ReadMethodPoolVisitor(ASTReader &Reader, Selector Sel,
Guy Benyei11169dd2012-12-18 14:30:41 +00007417 unsigned PriorGeneration)
Nico Weber2e0c8f72014-12-27 03:58:08 +00007418 : Reader(Reader), Sel(Sel), PriorGeneration(PriorGeneration),
Nico Weberff4b35e2014-12-27 22:14:15 +00007419 InstanceBits(0), FactoryBits(0), InstanceHasMoreThanOneDecl(false),
7420 FactoryHasMoreThanOneDecl(false) {}
Nico Weber2e0c8f72014-12-27 03:58:08 +00007421
Benjamin Kramer9a9efba2015-07-25 12:14:04 +00007422 bool operator()(ModuleFile &M) {
Guy Benyei11169dd2012-12-18 14:30:41 +00007423 if (!M.SelectorLookupTable)
7424 return false;
David L. Jonesc4808b9e2016-12-15 20:53:26 +00007425
Guy Benyei11169dd2012-12-18 14:30:41 +00007426 // If we've already searched this module file, skip it now.
Richard Smithbdf2d932015-07-30 03:37:16 +00007427 if (M.Generation <= PriorGeneration)
Guy Benyei11169dd2012-12-18 14:30:41 +00007428 return true;
7429
Richard Smithbdf2d932015-07-30 03:37:16 +00007430 ++Reader.NumMethodPoolTableLookups;
Guy Benyei11169dd2012-12-18 14:30:41 +00007431 ASTSelectorLookupTable *PoolTable
7432 = (ASTSelectorLookupTable*)M.SelectorLookupTable;
Richard Smithbdf2d932015-07-30 03:37:16 +00007433 ASTSelectorLookupTable::iterator Pos = PoolTable->find(Sel);
Guy Benyei11169dd2012-12-18 14:30:41 +00007434 if (Pos == PoolTable->end())
7435 return false;
Douglas Gregorad2f7a52013-01-28 17:54:36 +00007436
Richard Smithbdf2d932015-07-30 03:37:16 +00007437 ++Reader.NumMethodPoolTableHits;
7438 ++Reader.NumSelectorsRead;
Guy Benyei11169dd2012-12-18 14:30:41 +00007439 // FIXME: Not quite happy with the statistics here. We probably should
7440 // disable this tracking when called via LoadSelector.
7441 // Also, should entries without methods count as misses?
Richard Smithbdf2d932015-07-30 03:37:16 +00007442 ++Reader.NumMethodPoolEntriesRead;
Guy Benyei11169dd2012-12-18 14:30:41 +00007443 ASTSelectorLookupTrait::data_type Data = *Pos;
Richard Smithbdf2d932015-07-30 03:37:16 +00007444 if (Reader.DeserializationListener)
7445 Reader.DeserializationListener->SelectorRead(Data.ID, Sel);
Benjamin Kramer9a9efba2015-07-25 12:14:04 +00007446
Richard Smithbdf2d932015-07-30 03:37:16 +00007447 InstanceMethods.append(Data.Instance.begin(), Data.Instance.end());
7448 FactoryMethods.append(Data.Factory.begin(), Data.Factory.end());
7449 InstanceBits = Data.InstanceBits;
7450 FactoryBits = Data.FactoryBits;
7451 InstanceHasMoreThanOneDecl = Data.InstanceHasMoreThanOneDecl;
7452 FactoryHasMoreThanOneDecl = Data.FactoryHasMoreThanOneDecl;
Guy Benyei11169dd2012-12-18 14:30:41 +00007453 return true;
7454 }
David L. Jonesc4808b9e2016-12-15 20:53:26 +00007455
Guy Benyei11169dd2012-12-18 14:30:41 +00007456 /// \brief Retrieve the instance methods found by this visitor.
David L. Jonesc4808b9e2016-12-15 20:53:26 +00007457 ArrayRef<ObjCMethodDecl *> getInstanceMethods() const {
7458 return InstanceMethods;
Guy Benyei11169dd2012-12-18 14:30:41 +00007459 }
7460
7461 /// \brief Retrieve the instance methods found by this visitor.
David L. Jonesc4808b9e2016-12-15 20:53:26 +00007462 ArrayRef<ObjCMethodDecl *> getFactoryMethods() const {
Guy Benyei11169dd2012-12-18 14:30:41 +00007463 return FactoryMethods;
7464 }
Argyrios Kyrtzidisd3da6e02013-04-17 00:08:58 +00007465
7466 unsigned getInstanceBits() const { return InstanceBits; }
7467 unsigned getFactoryBits() const { return FactoryBits; }
Nico Weberff4b35e2014-12-27 22:14:15 +00007468 bool instanceHasMoreThanOneDecl() const {
7469 return InstanceHasMoreThanOneDecl;
7470 }
7471 bool factoryHasMoreThanOneDecl() const { return FactoryHasMoreThanOneDecl; }
Guy Benyei11169dd2012-12-18 14:30:41 +00007472 };
Eugene Zelenkoe95e7d52016-09-07 21:53:17 +00007473
7474} // end namespace serialization
7475} // end namespace clang
Guy Benyei11169dd2012-12-18 14:30:41 +00007476
7477/// \brief Add the given set of methods to the method list.
7478static void addMethodsToPool(Sema &S, ArrayRef<ObjCMethodDecl *> Methods,
7479 ObjCMethodList &List) {
7480 for (unsigned I = 0, N = Methods.size(); I != N; ++I) {
7481 S.addMethodToGlobalList(&List, Methods[I]);
7482 }
7483}
David L. Jonesc4808b9e2016-12-15 20:53:26 +00007484
Guy Benyei11169dd2012-12-18 14:30:41 +00007485void ASTReader::ReadMethodPool(Selector Sel) {
7486 // Get the selector generation and update it to the current generation.
7487 unsigned &Generation = SelectorGeneration[Sel];
7488 unsigned PriorGeneration = Generation;
Richard Smith053f6c62014-05-16 23:01:30 +00007489 Generation = getGeneration();
Manman Rena0f31a02016-04-29 19:04:05 +00007490 SelectorOutOfDate[Sel] = false;
David L. Jonesc4808b9e2016-12-15 20:53:26 +00007491
Guy Benyei11169dd2012-12-18 14:30:41 +00007492 // Search for methods defined with this selector.
Douglas Gregorad2f7a52013-01-28 17:54:36 +00007493 ++NumMethodPoolLookups;
Guy Benyei11169dd2012-12-18 14:30:41 +00007494 ReadMethodPoolVisitor Visitor(*this, Sel, PriorGeneration);
Benjamin Kramer9a9efba2015-07-25 12:14:04 +00007495 ModuleMgr.visit(Visitor);
7496
Guy Benyei11169dd2012-12-18 14:30:41 +00007497 if (Visitor.getInstanceMethods().empty() &&
Douglas Gregorad2f7a52013-01-28 17:54:36 +00007498 Visitor.getFactoryMethods().empty())
Guy Benyei11169dd2012-12-18 14:30:41 +00007499 return;
Douglas Gregorad2f7a52013-01-28 17:54:36 +00007500
7501 ++NumMethodPoolHits;
7502
Guy Benyei11169dd2012-12-18 14:30:41 +00007503 if (!getSema())
7504 return;
David L. Jonesc4808b9e2016-12-15 20:53:26 +00007505
Guy Benyei11169dd2012-12-18 14:30:41 +00007506 Sema &S = *getSema();
7507 Sema::GlobalMethodPool::iterator Pos
7508 = S.MethodPool.insert(std::make_pair(Sel, Sema::GlobalMethods())).first;
Ben Langmuira0c32e92015-01-12 19:27:00 +00007509
Argyrios Kyrtzidisd3da6e02013-04-17 00:08:58 +00007510 Pos->second.first.setBits(Visitor.getInstanceBits());
Nico Weberff4b35e2014-12-27 22:14:15 +00007511 Pos->second.first.setHasMoreThanOneDecl(Visitor.instanceHasMoreThanOneDecl());
Argyrios Kyrtzidisd3da6e02013-04-17 00:08:58 +00007512 Pos->second.second.setBits(Visitor.getFactoryBits());
Nico Weberff4b35e2014-12-27 22:14:15 +00007513 Pos->second.second.setHasMoreThanOneDecl(Visitor.factoryHasMoreThanOneDecl());
Ben Langmuira0c32e92015-01-12 19:27:00 +00007514
7515 // Add methods to the global pool *after* setting hasMoreThanOneDecl, since
7516 // when building a module we keep every method individually and may need to
7517 // update hasMoreThanOneDecl as we add the methods.
7518 addMethodsToPool(S, Visitor.getInstanceMethods(), Pos->second.first);
7519 addMethodsToPool(S, Visitor.getFactoryMethods(), Pos->second.second);
Guy Benyei11169dd2012-12-18 14:30:41 +00007520}
7521
Manman Rena0f31a02016-04-29 19:04:05 +00007522void ASTReader::updateOutOfDateSelector(Selector Sel) {
7523 if (SelectorOutOfDate[Sel])
7524 ReadMethodPool(Sel);
7525}
7526
Guy Benyei11169dd2012-12-18 14:30:41 +00007527void ASTReader::ReadKnownNamespaces(
7528 SmallVectorImpl<NamespaceDecl *> &Namespaces) {
7529 Namespaces.clear();
David L. Jonesc4808b9e2016-12-15 20:53:26 +00007530
Guy Benyei11169dd2012-12-18 14:30:41 +00007531 for (unsigned I = 0, N = KnownNamespaces.size(); I != N; ++I) {
David L. Jonesc4808b9e2016-12-15 20:53:26 +00007532 if (NamespaceDecl *Namespace
Guy Benyei11169dd2012-12-18 14:30:41 +00007533 = dyn_cast_or_null<NamespaceDecl>(GetDecl(KnownNamespaces[I])))
7534 Namespaces.push_back(Namespace);
7535 }
7536}
7537
Nick Lewycky9c7eb1d2013-02-01 08:13:20 +00007538void ASTReader::ReadUndefinedButUsed(
Richard Smithd6a04d72016-03-25 21:49:43 +00007539 llvm::MapVector<NamedDecl *, SourceLocation> &Undefined) {
Nick Lewycky9c7eb1d2013-02-01 08:13:20 +00007540 for (unsigned Idx = 0, N = UndefinedButUsed.size(); Idx != N;) {
7541 NamedDecl *D = cast<NamedDecl>(GetDecl(UndefinedButUsed[Idx++]));
Nick Lewycky8334af82013-01-26 00:35:08 +00007542 SourceLocation Loc =
Nick Lewycky9c7eb1d2013-02-01 08:13:20 +00007543 SourceLocation::getFromRawEncoding(UndefinedButUsed[Idx++]);
Nick Lewycky8334af82013-01-26 00:35:08 +00007544 Undefined.insert(std::make_pair(D, Loc));
7545 }
7546}
Nick Lewycky8334af82013-01-26 00:35:08 +00007547
Ismail Pazarbasie5768d12015-05-18 19:59:11 +00007548void ASTReader::ReadMismatchingDeleteExpressions(llvm::MapVector<
7549 FieldDecl *, llvm::SmallVector<std::pair<SourceLocation, bool>, 4>> &
7550 Exprs) {
7551 for (unsigned Idx = 0, N = DelayedDeleteExprs.size(); Idx != N;) {
7552 FieldDecl *FD = cast<FieldDecl>(GetDecl(DelayedDeleteExprs[Idx++]));
7553 uint64_t Count = DelayedDeleteExprs[Idx++];
7554 for (uint64_t C = 0; C < Count; ++C) {
7555 SourceLocation DeleteLoc =
7556 SourceLocation::getFromRawEncoding(DelayedDeleteExprs[Idx++]);
7557 const bool IsArrayForm = DelayedDeleteExprs[Idx++];
7558 Exprs[FD].push_back(std::make_pair(DeleteLoc, IsArrayForm));
7559 }
7560 }
7561}
7562
Guy Benyei11169dd2012-12-18 14:30:41 +00007563void ASTReader::ReadTentativeDefinitions(
7564 SmallVectorImpl<VarDecl *> &TentativeDefs) {
7565 for (unsigned I = 0, N = TentativeDefinitions.size(); I != N; ++I) {
7566 VarDecl *Var = dyn_cast_or_null<VarDecl>(GetDecl(TentativeDefinitions[I]));
7567 if (Var)
7568 TentativeDefs.push_back(Var);
7569 }
7570 TentativeDefinitions.clear();
7571}
7572
7573void ASTReader::ReadUnusedFileScopedDecls(
7574 SmallVectorImpl<const DeclaratorDecl *> &Decls) {
7575 for (unsigned I = 0, N = UnusedFileScopedDecls.size(); I != N; ++I) {
7576 DeclaratorDecl *D
7577 = dyn_cast_or_null<DeclaratorDecl>(GetDecl(UnusedFileScopedDecls[I]));
7578 if (D)
7579 Decls.push_back(D);
7580 }
7581 UnusedFileScopedDecls.clear();
7582}
7583
7584void ASTReader::ReadDelegatingConstructors(
7585 SmallVectorImpl<CXXConstructorDecl *> &Decls) {
7586 for (unsigned I = 0, N = DelegatingCtorDecls.size(); I != N; ++I) {
7587 CXXConstructorDecl *D
7588 = dyn_cast_or_null<CXXConstructorDecl>(GetDecl(DelegatingCtorDecls[I]));
7589 if (D)
7590 Decls.push_back(D);
7591 }
7592 DelegatingCtorDecls.clear();
7593}
7594
7595void ASTReader::ReadExtVectorDecls(SmallVectorImpl<TypedefNameDecl *> &Decls) {
7596 for (unsigned I = 0, N = ExtVectorDecls.size(); I != N; ++I) {
7597 TypedefNameDecl *D
7598 = dyn_cast_or_null<TypedefNameDecl>(GetDecl(ExtVectorDecls[I]));
7599 if (D)
7600 Decls.push_back(D);
7601 }
7602 ExtVectorDecls.clear();
7603}
7604
Nico Weber72889432014-09-06 01:25:55 +00007605void ASTReader::ReadUnusedLocalTypedefNameCandidates(
7606 llvm::SmallSetVector<const TypedefNameDecl *, 4> &Decls) {
7607 for (unsigned I = 0, N = UnusedLocalTypedefNameCandidates.size(); I != N;
7608 ++I) {
7609 TypedefNameDecl *D = dyn_cast_or_null<TypedefNameDecl>(
7610 GetDecl(UnusedLocalTypedefNameCandidates[I]));
7611 if (D)
7612 Decls.insert(D);
7613 }
7614 UnusedLocalTypedefNameCandidates.clear();
7615}
7616
Guy Benyei11169dd2012-12-18 14:30:41 +00007617void ASTReader::ReadReferencedSelectors(
7618 SmallVectorImpl<std::pair<Selector, SourceLocation> > &Sels) {
7619 if (ReferencedSelectorsData.empty())
7620 return;
David L. Jonesc4808b9e2016-12-15 20:53:26 +00007621
Guy Benyei11169dd2012-12-18 14:30:41 +00007622 // If there are @selector references added them to its pool. This is for
7623 // implementation of -Wselector.
7624 unsigned int DataSize = ReferencedSelectorsData.size()-1;
7625 unsigned I = 0;
7626 while (I < DataSize) {
7627 Selector Sel = DecodeSelector(ReferencedSelectorsData[I++]);
7628 SourceLocation SelLoc
7629 = SourceLocation::getFromRawEncoding(ReferencedSelectorsData[I++]);
7630 Sels.push_back(std::make_pair(Sel, SelLoc));
7631 }
7632 ReferencedSelectorsData.clear();
7633}
7634
7635void ASTReader::ReadWeakUndeclaredIdentifiers(
7636 SmallVectorImpl<std::pair<IdentifierInfo *, WeakInfo> > &WeakIDs) {
7637 if (WeakUndeclaredIdentifiers.empty())
7638 return;
7639
7640 for (unsigned I = 0, N = WeakUndeclaredIdentifiers.size(); I < N; /*none*/) {
David L. Jonesc4808b9e2016-12-15 20:53:26 +00007641 IdentifierInfo *WeakId
Guy Benyei11169dd2012-12-18 14:30:41 +00007642 = DecodeIdentifierInfo(WeakUndeclaredIdentifiers[I++]);
David L. Jonesc4808b9e2016-12-15 20:53:26 +00007643 IdentifierInfo *AliasId
Guy Benyei11169dd2012-12-18 14:30:41 +00007644 = DecodeIdentifierInfo(WeakUndeclaredIdentifiers[I++]);
7645 SourceLocation Loc
7646 = SourceLocation::getFromRawEncoding(WeakUndeclaredIdentifiers[I++]);
7647 bool Used = WeakUndeclaredIdentifiers[I++];
7648 WeakInfo WI(AliasId, Loc);
7649 WI.setUsed(Used);
7650 WeakIDs.push_back(std::make_pair(WeakId, WI));
7651 }
7652 WeakUndeclaredIdentifiers.clear();
7653}
7654
7655void ASTReader::ReadUsedVTables(SmallVectorImpl<ExternalVTableUse> &VTables) {
7656 for (unsigned Idx = 0, N = VTableUses.size(); Idx < N; /* In loop */) {
7657 ExternalVTableUse VT;
7658 VT.Record = dyn_cast_or_null<CXXRecordDecl>(GetDecl(VTableUses[Idx++]));
7659 VT.Location = SourceLocation::getFromRawEncoding(VTableUses[Idx++]);
7660 VT.DefinitionRequired = VTableUses[Idx++];
7661 VTables.push_back(VT);
7662 }
David L. Jonesc4808b9e2016-12-15 20:53:26 +00007663
Guy Benyei11169dd2012-12-18 14:30:41 +00007664 VTableUses.clear();
7665}
7666
7667void ASTReader::ReadPendingInstantiations(
7668 SmallVectorImpl<std::pair<ValueDecl *, SourceLocation> > &Pending) {
7669 for (unsigned Idx = 0, N = PendingInstantiations.size(); Idx < N;) {
7670 ValueDecl *D = cast<ValueDecl>(GetDecl(PendingInstantiations[Idx++]));
7671 SourceLocation Loc
7672 = SourceLocation::getFromRawEncoding(PendingInstantiations[Idx++]);
7673
7674 Pending.push_back(std::make_pair(D, Loc));
David L. Jonesc4808b9e2016-12-15 20:53:26 +00007675 }
Guy Benyei11169dd2012-12-18 14:30:41 +00007676 PendingInstantiations.clear();
7677}
7678
Richard Smithe40f2ba2013-08-07 21:41:30 +00007679void ASTReader::ReadLateParsedTemplates(
Justin Lebar28f09c52016-10-10 16:26:08 +00007680 llvm::MapVector<const FunctionDecl *, std::unique_ptr<LateParsedTemplate>>
7681 &LPTMap) {
Richard Smithe40f2ba2013-08-07 21:41:30 +00007682 for (unsigned Idx = 0, N = LateParsedTemplates.size(); Idx < N;
7683 /* In loop */) {
7684 FunctionDecl *FD = cast<FunctionDecl>(GetDecl(LateParsedTemplates[Idx++]));
7685
Justin Lebar28f09c52016-10-10 16:26:08 +00007686 auto LT = llvm::make_unique<LateParsedTemplate>();
Richard Smithe40f2ba2013-08-07 21:41:30 +00007687 LT->D = GetDecl(LateParsedTemplates[Idx++]);
7688
7689 ModuleFile *F = getOwningModuleFile(LT->D);
7690 assert(F && "No module");
7691
7692 unsigned TokN = LateParsedTemplates[Idx++];
7693 LT->Toks.reserve(TokN);
7694 for (unsigned T = 0; T < TokN; ++T)
7695 LT->Toks.push_back(ReadToken(*F, LateParsedTemplates, Idx));
7696
Justin Lebar28f09c52016-10-10 16:26:08 +00007697 LPTMap.insert(std::make_pair(FD, std::move(LT)));
Richard Smithe40f2ba2013-08-07 21:41:30 +00007698 }
7699
7700 LateParsedTemplates.clear();
7701}
7702
Guy Benyei11169dd2012-12-18 14:30:41 +00007703void ASTReader::LoadSelector(Selector Sel) {
7704 // It would be complicated to avoid reading the methods anyway. So don't.
7705 ReadMethodPool(Sel);
7706}
7707
7708void ASTReader::SetIdentifierInfo(IdentifierID ID, IdentifierInfo *II) {
7709 assert(ID && "Non-zero identifier ID required");
7710 assert(ID <= IdentifiersLoaded.size() && "identifier ID out of range");
7711 IdentifiersLoaded[ID - 1] = II;
7712 if (DeserializationListener)
7713 DeserializationListener->IdentifierRead(ID, II);
7714}
7715
7716/// \brief Set the globally-visible declarations associated with the given
7717/// identifier.
7718///
7719/// If the AST reader is currently in a state where the given declaration IDs
7720/// cannot safely be resolved, they are queued until it is safe to resolve
7721/// them.
7722///
7723/// \param II an IdentifierInfo that refers to one or more globally-visible
7724/// declarations.
7725///
7726/// \param DeclIDs the set of declaration IDs with the name @p II that are
7727/// visible at global scope.
7728///
Douglas Gregor6168bd22013-02-18 15:53:43 +00007729/// \param Decls if non-null, this vector will be populated with the set of
7730/// deserialized declarations. These declarations will not be pushed into
7731/// scope.
Guy Benyei11169dd2012-12-18 14:30:41 +00007732void
7733ASTReader::SetGloballyVisibleDecls(IdentifierInfo *II,
7734 const SmallVectorImpl<uint32_t> &DeclIDs,
Douglas Gregor6168bd22013-02-18 15:53:43 +00007735 SmallVectorImpl<Decl *> *Decls) {
7736 if (NumCurrentElementsDeserializing && !Decls) {
7737 PendingIdentifierInfos[II].append(DeclIDs.begin(), DeclIDs.end());
Guy Benyei11169dd2012-12-18 14:30:41 +00007738 return;
7739 }
7740
7741 for (unsigned I = 0, N = DeclIDs.size(); I != N; ++I) {
Ben Langmuir5418f402014-09-10 21:29:41 +00007742 if (!SemaObj) {
Guy Benyei11169dd2012-12-18 14:30:41 +00007743 // Queue this declaration so that it will be added to the
7744 // translation unit scope and identifier's declaration chain
7745 // once a Sema object is known.
Ben Langmuir5418f402014-09-10 21:29:41 +00007746 PreloadedDeclIDs.push_back(DeclIDs[I]);
7747 continue;
Guy Benyei11169dd2012-12-18 14:30:41 +00007748 }
Ben Langmuir5418f402014-09-10 21:29:41 +00007749
7750 NamedDecl *D = cast<NamedDecl>(GetDecl(DeclIDs[I]));
7751
7752 // If we're simply supposed to record the declarations, do so now.
7753 if (Decls) {
7754 Decls->push_back(D);
7755 continue;
7756 }
7757
7758 // Introduce this declaration into the translation-unit scope
7759 // and add it to the declaration chain for this identifier, so
7760 // that (unqualified) name lookup will find it.
7761 pushExternalDeclIntoScope(D, II);
Guy Benyei11169dd2012-12-18 14:30:41 +00007762 }
7763}
7764
Douglas Gregorc8a992f2013-01-21 16:52:34 +00007765IdentifierInfo *ASTReader::DecodeIdentifierInfo(IdentifierID ID) {
Guy Benyei11169dd2012-12-18 14:30:41 +00007766 if (ID == 0)
Craig Toppera13603a2014-05-22 05:54:18 +00007767 return nullptr;
Guy Benyei11169dd2012-12-18 14:30:41 +00007768
7769 if (IdentifiersLoaded.empty()) {
7770 Error("no identifier table in AST file");
Craig Toppera13603a2014-05-22 05:54:18 +00007771 return nullptr;
Guy Benyei11169dd2012-12-18 14:30:41 +00007772 }
7773
7774 ID -= 1;
7775 if (!IdentifiersLoaded[ID]) {
7776 GlobalIdentifierMapType::iterator I = GlobalIdentifierMap.find(ID + 1);
7777 assert(I != GlobalIdentifierMap.end() && "Corrupted global identifier map");
7778 ModuleFile *M = I->second;
7779 unsigned Index = ID - M->BaseIdentifierID;
7780 const char *Str = M->IdentifierTableData + M->IdentifierOffsets[Index];
7781
7782 // All of the strings in the AST file are preceded by a 16-bit length.
7783 // Extract that 16-bit length to avoid having to execute strlen().
7784 // NOTE: 'StrLenPtr' is an 'unsigned char*' so that we load bytes as
7785 // unsigned integers. This is important to avoid integer overflow when
7786 // we cast them to 'unsigned'.
7787 const unsigned char *StrLenPtr = (const unsigned char*) Str - 2;
7788 unsigned StrLen = (((unsigned) StrLenPtr[0])
7789 | (((unsigned) StrLenPtr[1]) << 8)) - 1;
Richard Smitheb4b58f62016-02-05 01:40:54 +00007790 auto &II = PP.getIdentifierTable().get(StringRef(Str, StrLen));
7791 IdentifiersLoaded[ID] = &II;
7792 markIdentifierFromAST(*this, II);
Guy Benyei11169dd2012-12-18 14:30:41 +00007793 if (DeserializationListener)
Richard Smitheb4b58f62016-02-05 01:40:54 +00007794 DeserializationListener->IdentifierRead(ID + 1, &II);
Guy Benyei11169dd2012-12-18 14:30:41 +00007795 }
7796
7797 return IdentifiersLoaded[ID];
7798}
7799
Douglas Gregorc8a992f2013-01-21 16:52:34 +00007800IdentifierInfo *ASTReader::getLocalIdentifier(ModuleFile &M, unsigned LocalID) {
7801 return DecodeIdentifierInfo(getGlobalIdentifierID(M, LocalID));
Guy Benyei11169dd2012-12-18 14:30:41 +00007802}
7803
7804IdentifierID ASTReader::getGlobalIdentifierID(ModuleFile &M, unsigned LocalID) {
7805 if (LocalID < NUM_PREDEF_IDENT_IDS)
7806 return LocalID;
David L. Jonesc4808b9e2016-12-15 20:53:26 +00007807
Richard Smith37a93df2017-02-18 00:32:02 +00007808 if (!M.ModuleOffsetMap.empty())
7809 ReadModuleOffsetMap(M);
7810
Guy Benyei11169dd2012-12-18 14:30:41 +00007811 ContinuousRangeMap<uint32_t, int, 2>::iterator I
7812 = M.IdentifierRemap.find(LocalID - NUM_PREDEF_IDENT_IDS);
David L. Jonesc4808b9e2016-12-15 20:53:26 +00007813 assert(I != M.IdentifierRemap.end()
Guy Benyei11169dd2012-12-18 14:30:41 +00007814 && "Invalid index into identifier index remap");
David L. Jonesc4808b9e2016-12-15 20:53:26 +00007815
Guy Benyei11169dd2012-12-18 14:30:41 +00007816 return LocalID + I->second;
7817}
7818
Argyrios Kyrtzidiseb663da2013-03-22 21:12:57 +00007819MacroInfo *ASTReader::getMacro(MacroID ID) {
Guy Benyei11169dd2012-12-18 14:30:41 +00007820 if (ID == 0)
Craig Toppera13603a2014-05-22 05:54:18 +00007821 return nullptr;
Guy Benyei11169dd2012-12-18 14:30:41 +00007822
7823 if (MacrosLoaded.empty()) {
7824 Error("no macro table in AST file");
Craig Toppera13603a2014-05-22 05:54:18 +00007825 return nullptr;
Guy Benyei11169dd2012-12-18 14:30:41 +00007826 }
7827
7828 ID -= NUM_PREDEF_MACRO_IDS;
7829 if (!MacrosLoaded[ID]) {
7830 GlobalMacroMapType::iterator I
7831 = GlobalMacroMap.find(ID + NUM_PREDEF_MACRO_IDS);
7832 assert(I != GlobalMacroMap.end() && "Corrupted global macro map");
7833 ModuleFile *M = I->second;
7834 unsigned Index = ID - M->BaseMacroID;
Argyrios Kyrtzidiseb663da2013-03-22 21:12:57 +00007835 MacrosLoaded[ID] = ReadMacroRecord(*M, M->MacroOffsets[Index]);
David L. Jonesc4808b9e2016-12-15 20:53:26 +00007836
Argyrios Kyrtzidiseb663da2013-03-22 21:12:57 +00007837 if (DeserializationListener)
7838 DeserializationListener->MacroRead(ID + NUM_PREDEF_MACRO_IDS,
7839 MacrosLoaded[ID]);
Guy Benyei11169dd2012-12-18 14:30:41 +00007840 }
7841
7842 return MacrosLoaded[ID];
7843}
7844
7845MacroID ASTReader::getGlobalMacroID(ModuleFile &M, unsigned LocalID) {
7846 if (LocalID < NUM_PREDEF_MACRO_IDS)
7847 return LocalID;
7848
Richard Smith37a93df2017-02-18 00:32:02 +00007849 if (!M.ModuleOffsetMap.empty())
7850 ReadModuleOffsetMap(M);
7851
Guy Benyei11169dd2012-12-18 14:30:41 +00007852 ContinuousRangeMap<uint32_t, int, 2>::iterator I
7853 = M.MacroRemap.find(LocalID - NUM_PREDEF_MACRO_IDS);
7854 assert(I != M.MacroRemap.end() && "Invalid index into macro index remap");
7855
7856 return LocalID + I->second;
7857}
7858
7859serialization::SubmoduleID
7860ASTReader::getGlobalSubmoduleID(ModuleFile &M, unsigned LocalID) {
7861 if (LocalID < NUM_PREDEF_SUBMODULE_IDS)
7862 return LocalID;
David L. Jonesc4808b9e2016-12-15 20:53:26 +00007863
Richard Smith37a93df2017-02-18 00:32:02 +00007864 if (!M.ModuleOffsetMap.empty())
7865 ReadModuleOffsetMap(M);
7866
Guy Benyei11169dd2012-12-18 14:30:41 +00007867 ContinuousRangeMap<uint32_t, int, 2>::iterator I
7868 = M.SubmoduleRemap.find(LocalID - NUM_PREDEF_SUBMODULE_IDS);
David L. Jonesc4808b9e2016-12-15 20:53:26 +00007869 assert(I != M.SubmoduleRemap.end()
Guy Benyei11169dd2012-12-18 14:30:41 +00007870 && "Invalid index into submodule index remap");
David L. Jonesc4808b9e2016-12-15 20:53:26 +00007871
Guy Benyei11169dd2012-12-18 14:30:41 +00007872 return LocalID + I->second;
7873}
7874
7875Module *ASTReader::getSubmodule(SubmoduleID GlobalID) {
7876 if (GlobalID < NUM_PREDEF_SUBMODULE_IDS) {
7877 assert(GlobalID == 0 && "Unhandled global submodule ID");
Craig Toppera13603a2014-05-22 05:54:18 +00007878 return nullptr;
Guy Benyei11169dd2012-12-18 14:30:41 +00007879 }
David L. Jonesc4808b9e2016-12-15 20:53:26 +00007880
Guy Benyei11169dd2012-12-18 14:30:41 +00007881 if (GlobalID > SubmodulesLoaded.size()) {
7882 Error("submodule ID out of range in AST file");
Craig Toppera13603a2014-05-22 05:54:18 +00007883 return nullptr;
Guy Benyei11169dd2012-12-18 14:30:41 +00007884 }
David L. Jonesc4808b9e2016-12-15 20:53:26 +00007885
Guy Benyei11169dd2012-12-18 14:30:41 +00007886 return SubmodulesLoaded[GlobalID - NUM_PREDEF_SUBMODULE_IDS];
7887}
Douglas Gregorc147b0b2013-01-12 01:29:50 +00007888
7889Module *ASTReader::getModule(unsigned ID) {
7890 return getSubmodule(ID);
7891}
7892
Richard Smithd88a7f12015-09-01 20:35:42 +00007893ModuleFile *ASTReader::getLocalModuleFile(ModuleFile &F, unsigned ID) {
7894 if (ID & 1) {
7895 // It's a module, look it up by submodule ID.
7896 auto I = GlobalSubmoduleMap.find(getGlobalSubmoduleID(F, ID >> 1));
7897 return I == GlobalSubmoduleMap.end() ? nullptr : I->second;
7898 } else {
7899 // It's a prefix (preamble, PCH, ...). Look it up by index.
7900 unsigned IndexFromEnd = ID >> 1;
7901 assert(IndexFromEnd && "got reference to unknown module file");
7902 return getModuleManager().pch_modules().end()[-IndexFromEnd];
7903 }
7904}
7905
7906unsigned ASTReader::getModuleFileID(ModuleFile *F) {
7907 if (!F)
7908 return 1;
7909
7910 // For a file representing a module, use the submodule ID of the top-level
7911 // module as the file ID. For any other kind of file, the number of such
7912 // files loaded beforehand will be the same on reload.
7913 // FIXME: Is this true even if we have an explicit module file and a PCH?
7914 if (F->isModule())
7915 return ((F->BaseSubmoduleID + NUM_PREDEF_SUBMODULE_IDS) << 1) | 1;
7916
7917 auto PCHModules = getModuleManager().pch_modules();
7918 auto I = std::find(PCHModules.begin(), PCHModules.end(), F);
7919 assert(I != PCHModules.end() && "emitting reference to unknown file");
7920 return (I - PCHModules.end()) << 1;
7921}
7922
Adrian Prantl15bcf702015-06-30 17:39:43 +00007923llvm::Optional<ExternalASTSource::ASTSourceDescriptor>
7924ASTReader::getSourceDescriptor(unsigned ID) {
7925 if (const Module *M = getSubmodule(ID))
Adrian Prantlc6458d62015-09-19 00:10:32 +00007926 return ExternalASTSource::ASTSourceDescriptor(*M);
Adrian Prantl15bcf702015-06-30 17:39:43 +00007927
7928 // If there is only a single PCH, return it instead.
7929 // Chained PCH are not suported.
7930 if (ModuleMgr.size() == 1) {
7931 ModuleFile &MF = ModuleMgr.getPrimaryModule();
Adrian Prantl3a2d4942016-01-22 23:30:56 +00007932 StringRef ModuleName = llvm::sys::path::filename(MF.OriginalSourceFileName);
Adrian Prantl9bc3c4f2016-04-27 17:06:22 +00007933 StringRef FileName = llvm::sys::path::filename(MF.FileName);
7934 return ASTReader::ASTSourceDescriptor(ModuleName, MF.OriginalDir, FileName,
7935 MF.Signature);
Adrian Prantl15bcf702015-06-30 17:39:43 +00007936 }
7937 return None;
7938}
7939
David Blaikie9ffe5a32017-01-30 05:00:26 +00007940ExternalASTSource::ExtKind ASTReader::hasExternalDefinitions(unsigned ID) {
7941 const Module *M = getSubmodule(ID);
7942 if (!M || !M->WithCodegen)
7943 return EK_ReplyHazy;
7944
7945 ModuleFile *MF = ModuleMgr.lookup(M->getASTFile());
7946 assert(MF); // ?
7947 if (MF->Kind == ModuleKind::MK_MainFile)
7948 return EK_Never;
7949 return EK_Always;
7950}
7951
Guy Benyei11169dd2012-12-18 14:30:41 +00007952Selector ASTReader::getLocalSelector(ModuleFile &M, unsigned LocalID) {
7953 return DecodeSelector(getGlobalSelectorID(M, LocalID));
7954}
7955
7956Selector ASTReader::DecodeSelector(serialization::SelectorID ID) {
7957 if (ID == 0)
7958 return Selector();
7959
7960 if (ID > SelectorsLoaded.size()) {
7961 Error("selector ID out of range in AST file");
7962 return Selector();
7963 }
7964
Craig Toppera13603a2014-05-22 05:54:18 +00007965 if (SelectorsLoaded[ID - 1].getAsOpaquePtr() == nullptr) {
Guy Benyei11169dd2012-12-18 14:30:41 +00007966 // Load this selector from the selector table.
7967 GlobalSelectorMapType::iterator I = GlobalSelectorMap.find(ID);
7968 assert(I != GlobalSelectorMap.end() && "Corrupted global selector map");
7969 ModuleFile &M = *I->second;
7970 ASTSelectorLookupTrait Trait(*this, M);
7971 unsigned Idx = ID - M.BaseSelectorID - NUM_PREDEF_SELECTOR_IDS;
7972 SelectorsLoaded[ID - 1] =
7973 Trait.ReadKey(M.SelectorLookupTableData + M.SelectorOffsets[Idx], 0);
7974 if (DeserializationListener)
7975 DeserializationListener->SelectorRead(ID, SelectorsLoaded[ID - 1]);
7976 }
7977
7978 return SelectorsLoaded[ID - 1];
7979}
7980
7981Selector ASTReader::GetExternalSelector(serialization::SelectorID ID) {
7982 return DecodeSelector(ID);
7983}
7984
7985uint32_t ASTReader::GetNumExternalSelectors() {
7986 // ID 0 (the null selector) is considered an external selector.
7987 return getTotalNumSelectors() + 1;
7988}
7989
7990serialization::SelectorID
7991ASTReader::getGlobalSelectorID(ModuleFile &M, unsigned LocalID) const {
7992 if (LocalID < NUM_PREDEF_SELECTOR_IDS)
7993 return LocalID;
David L. Jonesc4808b9e2016-12-15 20:53:26 +00007994
Richard Smith37a93df2017-02-18 00:32:02 +00007995 if (!M.ModuleOffsetMap.empty())
7996 ReadModuleOffsetMap(M);
7997
Guy Benyei11169dd2012-12-18 14:30:41 +00007998 ContinuousRangeMap<uint32_t, int, 2>::iterator I
7999 = M.SelectorRemap.find(LocalID - NUM_PREDEF_SELECTOR_IDS);
David L. Jonesc4808b9e2016-12-15 20:53:26 +00008000 assert(I != M.SelectorRemap.end()
Guy Benyei11169dd2012-12-18 14:30:41 +00008001 && "Invalid index into selector index remap");
David L. Jonesc4808b9e2016-12-15 20:53:26 +00008002
Guy Benyei11169dd2012-12-18 14:30:41 +00008003 return LocalID + I->second;
8004}
8005
8006DeclarationName
David L. Jonesc4808b9e2016-12-15 20:53:26 +00008007ASTReader::ReadDeclarationName(ModuleFile &F,
Guy Benyei11169dd2012-12-18 14:30:41 +00008008 const RecordData &Record, unsigned &Idx) {
8009 DeclarationName::NameKind Kind = (DeclarationName::NameKind)Record[Idx++];
8010 switch (Kind) {
8011 case DeclarationName::Identifier:
Douglas Gregorc8a992f2013-01-21 16:52:34 +00008012 return DeclarationName(GetIdentifierInfo(F, Record, Idx));
Guy Benyei11169dd2012-12-18 14:30:41 +00008013
8014 case DeclarationName::ObjCZeroArgSelector:
8015 case DeclarationName::ObjCOneArgSelector:
8016 case DeclarationName::ObjCMultiArgSelector:
8017 return DeclarationName(ReadSelector(F, Record, Idx));
8018
8019 case DeclarationName::CXXConstructorName:
8020 return Context.DeclarationNames.getCXXConstructorName(
8021 Context.getCanonicalType(readType(F, Record, Idx)));
8022
8023 case DeclarationName::CXXDestructorName:
8024 return Context.DeclarationNames.getCXXDestructorName(
8025 Context.getCanonicalType(readType(F, Record, Idx)));
8026
Richard Smith35845152017-02-07 01:37:30 +00008027 case DeclarationName::CXXDeductionGuideName:
8028 return Context.DeclarationNames.getCXXDeductionGuideName(
8029 ReadDeclAs<TemplateDecl>(F, Record, Idx));
8030
Guy Benyei11169dd2012-12-18 14:30:41 +00008031 case DeclarationName::CXXConversionFunctionName:
8032 return Context.DeclarationNames.getCXXConversionFunctionName(
8033 Context.getCanonicalType(readType(F, Record, Idx)));
8034
8035 case DeclarationName::CXXOperatorName:
8036 return Context.DeclarationNames.getCXXOperatorName(
8037 (OverloadedOperatorKind)Record[Idx++]);
8038
8039 case DeclarationName::CXXLiteralOperatorName:
8040 return Context.DeclarationNames.getCXXLiteralOperatorName(
8041 GetIdentifierInfo(F, Record, Idx));
8042
8043 case DeclarationName::CXXUsingDirective:
8044 return DeclarationName::getUsingDirectiveName();
8045 }
8046
8047 llvm_unreachable("Invalid NameKind!");
8048}
8049
8050void ASTReader::ReadDeclarationNameLoc(ModuleFile &F,
8051 DeclarationNameLoc &DNLoc,
8052 DeclarationName Name,
8053 const RecordData &Record, unsigned &Idx) {
8054 switch (Name.getNameKind()) {
8055 case DeclarationName::CXXConstructorName:
8056 case DeclarationName::CXXDestructorName:
8057 case DeclarationName::CXXConversionFunctionName:
8058 DNLoc.NamedType.TInfo = GetTypeSourceInfo(F, Record, Idx);
8059 break;
8060
8061 case DeclarationName::CXXOperatorName:
8062 DNLoc.CXXOperatorName.BeginOpNameLoc
8063 = ReadSourceLocation(F, Record, Idx).getRawEncoding();
8064 DNLoc.CXXOperatorName.EndOpNameLoc
8065 = ReadSourceLocation(F, Record, Idx).getRawEncoding();
8066 break;
8067
8068 case DeclarationName::CXXLiteralOperatorName:
8069 DNLoc.CXXLiteralOperatorName.OpNameLoc
8070 = ReadSourceLocation(F, Record, Idx).getRawEncoding();
8071 break;
8072
8073 case DeclarationName::Identifier:
8074 case DeclarationName::ObjCZeroArgSelector:
8075 case DeclarationName::ObjCOneArgSelector:
8076 case DeclarationName::ObjCMultiArgSelector:
8077 case DeclarationName::CXXUsingDirective:
Richard Smith35845152017-02-07 01:37:30 +00008078 case DeclarationName::CXXDeductionGuideName:
Guy Benyei11169dd2012-12-18 14:30:41 +00008079 break;
8080 }
8081}
8082
8083void ASTReader::ReadDeclarationNameInfo(ModuleFile &F,
8084 DeclarationNameInfo &NameInfo,
8085 const RecordData &Record, unsigned &Idx) {
8086 NameInfo.setName(ReadDeclarationName(F, Record, Idx));
8087 NameInfo.setLoc(ReadSourceLocation(F, Record, Idx));
8088 DeclarationNameLoc DNLoc;
8089 ReadDeclarationNameLoc(F, DNLoc, NameInfo.getName(), Record, Idx);
8090 NameInfo.setInfo(DNLoc);
8091}
8092
8093void ASTReader::ReadQualifierInfo(ModuleFile &F, QualifierInfo &Info,
8094 const RecordData &Record, unsigned &Idx) {
8095 Info.QualifierLoc = ReadNestedNameSpecifierLoc(F, Record, Idx);
8096 unsigned NumTPLists = Record[Idx++];
8097 Info.NumTemplParamLists = NumTPLists;
8098 if (NumTPLists) {
8099 Info.TemplParamLists = new (Context) TemplateParameterList*[NumTPLists];
Eugene Zelenkoe95e7d52016-09-07 21:53:17 +00008100 for (unsigned i = 0; i != NumTPLists; ++i)
Guy Benyei11169dd2012-12-18 14:30:41 +00008101 Info.TemplParamLists[i] = ReadTemplateParameterList(F, Record, Idx);
8102 }
8103}
8104
8105TemplateName
David L. Jonesc4808b9e2016-12-15 20:53:26 +00008106ASTReader::ReadTemplateName(ModuleFile &F, const RecordData &Record,
Guy Benyei11169dd2012-12-18 14:30:41 +00008107 unsigned &Idx) {
8108 TemplateName::NameKind Kind = (TemplateName::NameKind)Record[Idx++];
8109 switch (Kind) {
8110 case TemplateName::Template:
8111 return TemplateName(ReadDeclAs<TemplateDecl>(F, Record, Idx));
8112
8113 case TemplateName::OverloadedTemplate: {
8114 unsigned size = Record[Idx++];
8115 UnresolvedSet<8> Decls;
8116 while (size--)
8117 Decls.addDecl(ReadDeclAs<NamedDecl>(F, Record, Idx));
8118
8119 return Context.getOverloadedTemplateName(Decls.begin(), Decls.end());
8120 }
8121
8122 case TemplateName::QualifiedTemplate: {
8123 NestedNameSpecifier *NNS = ReadNestedNameSpecifier(F, Record, Idx);
8124 bool hasTemplKeyword = Record[Idx++];
8125 TemplateDecl *Template = ReadDeclAs<TemplateDecl>(F, Record, Idx);
8126 return Context.getQualifiedTemplateName(NNS, hasTemplKeyword, Template);
8127 }
8128
8129 case TemplateName::DependentTemplate: {
8130 NestedNameSpecifier *NNS = ReadNestedNameSpecifier(F, Record, Idx);
8131 if (Record[Idx++]) // isIdentifier
8132 return Context.getDependentTemplateName(NNS,
David L. Jonesc4808b9e2016-12-15 20:53:26 +00008133 GetIdentifierInfo(F, Record,
Guy Benyei11169dd2012-12-18 14:30:41 +00008134 Idx));
8135 return Context.getDependentTemplateName(NNS,
8136 (OverloadedOperatorKind)Record[Idx++]);
8137 }
8138
8139 case TemplateName::SubstTemplateTemplateParm: {
8140 TemplateTemplateParmDecl *param
8141 = ReadDeclAs<TemplateTemplateParmDecl>(F, Record, Idx);
8142 if (!param) return TemplateName();
8143 TemplateName replacement = ReadTemplateName(F, Record, Idx);
8144 return Context.getSubstTemplateTemplateParm(param, replacement);
8145 }
David L. Jonesc4808b9e2016-12-15 20:53:26 +00008146
Guy Benyei11169dd2012-12-18 14:30:41 +00008147 case TemplateName::SubstTemplateTemplateParmPack: {
David L. Jonesc4808b9e2016-12-15 20:53:26 +00008148 TemplateTemplateParmDecl *Param
Guy Benyei11169dd2012-12-18 14:30:41 +00008149 = ReadDeclAs<TemplateTemplateParmDecl>(F, Record, Idx);
8150 if (!Param)
8151 return TemplateName();
David L. Jonesc4808b9e2016-12-15 20:53:26 +00008152
Guy Benyei11169dd2012-12-18 14:30:41 +00008153 TemplateArgument ArgPack = ReadTemplateArgument(F, Record, Idx);
8154 if (ArgPack.getKind() != TemplateArgument::Pack)
8155 return TemplateName();
David L. Jonesc4808b9e2016-12-15 20:53:26 +00008156
Guy Benyei11169dd2012-12-18 14:30:41 +00008157 return Context.getSubstTemplateTemplateParmPack(Param, ArgPack);
8158 }
8159 }
8160
8161 llvm_unreachable("Unhandled template name kind!");
8162}
8163
Richard Smith2bb3c342015-08-09 01:05:31 +00008164TemplateArgument ASTReader::ReadTemplateArgument(ModuleFile &F,
8165 const RecordData &Record,
8166 unsigned &Idx,
8167 bool Canonicalize) {
8168 if (Canonicalize) {
8169 // The caller wants a canonical template argument. Sometimes the AST only
8170 // wants template arguments in canonical form (particularly as the template
8171 // argument lists of template specializations) so ensure we preserve that
8172 // canonical form across serialization.
8173 TemplateArgument Arg = ReadTemplateArgument(F, Record, Idx, false);
8174 return Context.getCanonicalTemplateArgument(Arg);
8175 }
8176
Guy Benyei11169dd2012-12-18 14:30:41 +00008177 TemplateArgument::ArgKind Kind = (TemplateArgument::ArgKind)Record[Idx++];
8178 switch (Kind) {
8179 case TemplateArgument::Null:
8180 return TemplateArgument();
8181 case TemplateArgument::Type:
8182 return TemplateArgument(readType(F, Record, Idx));
8183 case TemplateArgument::Declaration: {
8184 ValueDecl *D = ReadDeclAs<ValueDecl>(F, Record, Idx);
David Blaikie0f62c8d2014-10-16 04:21:25 +00008185 return TemplateArgument(D, readType(F, Record, Idx));
Guy Benyei11169dd2012-12-18 14:30:41 +00008186 }
8187 case TemplateArgument::NullPtr:
8188 return TemplateArgument(readType(F, Record, Idx), /*isNullPtr*/true);
8189 case TemplateArgument::Integral: {
8190 llvm::APSInt Value = ReadAPSInt(Record, Idx);
8191 QualType T = readType(F, Record, Idx);
8192 return TemplateArgument(Context, Value, T);
8193 }
David L. Jonesc4808b9e2016-12-15 20:53:26 +00008194 case TemplateArgument::Template:
Guy Benyei11169dd2012-12-18 14:30:41 +00008195 return TemplateArgument(ReadTemplateName(F, Record, Idx));
8196 case TemplateArgument::TemplateExpansion: {
8197 TemplateName Name = ReadTemplateName(F, Record, Idx);
David Blaikie05785d12013-02-20 22:23:23 +00008198 Optional<unsigned> NumTemplateExpansions;
Guy Benyei11169dd2012-12-18 14:30:41 +00008199 if (unsigned NumExpansions = Record[Idx++])
8200 NumTemplateExpansions = NumExpansions - 1;
8201 return TemplateArgument(Name, NumTemplateExpansions);
8202 }
8203 case TemplateArgument::Expression:
8204 return TemplateArgument(ReadExpr(F));
8205 case TemplateArgument::Pack: {
8206 unsigned NumArgs = Record[Idx++];
8207 TemplateArgument *Args = new (Context) TemplateArgument[NumArgs];
8208 for (unsigned I = 0; I != NumArgs; ++I)
8209 Args[I] = ReadTemplateArgument(F, Record, Idx);
Benjamin Kramercce63472015-08-05 09:40:22 +00008210 return TemplateArgument(llvm::makeArrayRef(Args, NumArgs));
Guy Benyei11169dd2012-12-18 14:30:41 +00008211 }
8212 }
8213
8214 llvm_unreachable("Unhandled template argument kind!");
8215}
8216
8217TemplateParameterList *
8218ASTReader::ReadTemplateParameterList(ModuleFile &F,
8219 const RecordData &Record, unsigned &Idx) {
8220 SourceLocation TemplateLoc = ReadSourceLocation(F, Record, Idx);
8221 SourceLocation LAngleLoc = ReadSourceLocation(F, Record, Idx);
8222 SourceLocation RAngleLoc = ReadSourceLocation(F, Record, Idx);
8223
8224 unsigned NumParams = Record[Idx++];
8225 SmallVector<NamedDecl *, 16> Params;
8226 Params.reserve(NumParams);
8227 while (NumParams--)
8228 Params.push_back(ReadDeclAs<NamedDecl>(F, Record, Idx));
8229
Hubert Tonge4a0c0e2016-07-30 22:33:34 +00008230 // TODO: Concepts
Guy Benyei11169dd2012-12-18 14:30:41 +00008231 TemplateParameterList* TemplateParams =
8232 TemplateParameterList::Create(Context, TemplateLoc, LAngleLoc,
Hubert Tonge4a0c0e2016-07-30 22:33:34 +00008233 Params, RAngleLoc, nullptr);
Guy Benyei11169dd2012-12-18 14:30:41 +00008234 return TemplateParams;
8235}
8236
8237void
8238ASTReader::
Craig Topper5603df42013-07-05 19:34:19 +00008239ReadTemplateArgumentList(SmallVectorImpl<TemplateArgument> &TemplArgs,
Guy Benyei11169dd2012-12-18 14:30:41 +00008240 ModuleFile &F, const RecordData &Record,
Richard Smith2bb3c342015-08-09 01:05:31 +00008241 unsigned &Idx, bool Canonicalize) {
Guy Benyei11169dd2012-12-18 14:30:41 +00008242 unsigned NumTemplateArgs = Record[Idx++];
8243 TemplArgs.reserve(NumTemplateArgs);
8244 while (NumTemplateArgs--)
Richard Smith2bb3c342015-08-09 01:05:31 +00008245 TemplArgs.push_back(ReadTemplateArgument(F, Record, Idx, Canonicalize));
Guy Benyei11169dd2012-12-18 14:30:41 +00008246}
8247
8248/// \brief Read a UnresolvedSet structure.
Richard Smitha4ba74c2013-08-30 04:46:40 +00008249void ASTReader::ReadUnresolvedSet(ModuleFile &F, LazyASTUnresolvedSet &Set,
Guy Benyei11169dd2012-12-18 14:30:41 +00008250 const RecordData &Record, unsigned &Idx) {
8251 unsigned NumDecls = Record[Idx++];
8252 Set.reserve(Context, NumDecls);
8253 while (NumDecls--) {
Richard Smitha4ba74c2013-08-30 04:46:40 +00008254 DeclID ID = ReadDeclID(F, Record, Idx);
Guy Benyei11169dd2012-12-18 14:30:41 +00008255 AccessSpecifier AS = (AccessSpecifier)Record[Idx++];
Richard Smitha4ba74c2013-08-30 04:46:40 +00008256 Set.addLazyDecl(Context, ID, AS);
Guy Benyei11169dd2012-12-18 14:30:41 +00008257 }
8258}
8259
8260CXXBaseSpecifier
8261ASTReader::ReadCXXBaseSpecifier(ModuleFile &F,
8262 const RecordData &Record, unsigned &Idx) {
8263 bool isVirtual = static_cast<bool>(Record[Idx++]);
8264 bool isBaseOfClass = static_cast<bool>(Record[Idx++]);
8265 AccessSpecifier AS = static_cast<AccessSpecifier>(Record[Idx++]);
8266 bool inheritConstructors = static_cast<bool>(Record[Idx++]);
8267 TypeSourceInfo *TInfo = GetTypeSourceInfo(F, Record, Idx);
8268 SourceRange Range = ReadSourceRange(F, Record, Idx);
8269 SourceLocation EllipsisLoc = ReadSourceLocation(F, Record, Idx);
David L. Jonesc4808b9e2016-12-15 20:53:26 +00008270 CXXBaseSpecifier Result(Range, isVirtual, isBaseOfClass, AS, TInfo,
Guy Benyei11169dd2012-12-18 14:30:41 +00008271 EllipsisLoc);
8272 Result.setInheritConstructors(inheritConstructors);
8273 return Result;
8274}
8275
Richard Smithc2bb8182015-03-24 06:36:48 +00008276CXXCtorInitializer **
Guy Benyei11169dd2012-12-18 14:30:41 +00008277ASTReader::ReadCXXCtorInitializers(ModuleFile &F, const RecordData &Record,
8278 unsigned &Idx) {
Guy Benyei11169dd2012-12-18 14:30:41 +00008279 unsigned NumInitializers = Record[Idx++];
Richard Smithc2bb8182015-03-24 06:36:48 +00008280 assert(NumInitializers && "wrote ctor initializers but have no inits");
8281 auto **CtorInitializers = new (Context) CXXCtorInitializer*[NumInitializers];
8282 for (unsigned i = 0; i != NumInitializers; ++i) {
8283 TypeSourceInfo *TInfo = nullptr;
8284 bool IsBaseVirtual = false;
8285 FieldDecl *Member = nullptr;
8286 IndirectFieldDecl *IndirectMember = nullptr;
Guy Benyei11169dd2012-12-18 14:30:41 +00008287
Richard Smithc2bb8182015-03-24 06:36:48 +00008288 CtorInitializerType Type = (CtorInitializerType)Record[Idx++];
8289 switch (Type) {
8290 case CTOR_INITIALIZER_BASE:
8291 TInfo = GetTypeSourceInfo(F, Record, Idx);
8292 IsBaseVirtual = Record[Idx++];
8293 break;
Guy Benyei11169dd2012-12-18 14:30:41 +00008294
Richard Smithc2bb8182015-03-24 06:36:48 +00008295 case CTOR_INITIALIZER_DELEGATING:
8296 TInfo = GetTypeSourceInfo(F, Record, Idx);
8297 break;
Guy Benyei11169dd2012-12-18 14:30:41 +00008298
Richard Smithc2bb8182015-03-24 06:36:48 +00008299 case CTOR_INITIALIZER_MEMBER:
8300 Member = ReadDeclAs<FieldDecl>(F, Record, Idx);
8301 break;
Guy Benyei11169dd2012-12-18 14:30:41 +00008302
Richard Smithc2bb8182015-03-24 06:36:48 +00008303 case CTOR_INITIALIZER_INDIRECT_MEMBER:
8304 IndirectMember = ReadDeclAs<IndirectFieldDecl>(F, Record, Idx);
8305 break;
Guy Benyei11169dd2012-12-18 14:30:41 +00008306 }
Richard Smithc2bb8182015-03-24 06:36:48 +00008307
8308 SourceLocation MemberOrEllipsisLoc = ReadSourceLocation(F, Record, Idx);
8309 Expr *Init = ReadExpr(F);
8310 SourceLocation LParenLoc = ReadSourceLocation(F, Record, Idx);
8311 SourceLocation RParenLoc = ReadSourceLocation(F, Record, Idx);
Richard Smithc2bb8182015-03-24 06:36:48 +00008312
8313 CXXCtorInitializer *BOMInit;
Richard Smith30e304e2016-12-14 00:03:17 +00008314 if (Type == CTOR_INITIALIZER_BASE)
Richard Smithc2bb8182015-03-24 06:36:48 +00008315 BOMInit = new (Context)
8316 CXXCtorInitializer(Context, TInfo, IsBaseVirtual, LParenLoc, Init,
8317 RParenLoc, MemberOrEllipsisLoc);
Richard Smith30e304e2016-12-14 00:03:17 +00008318 else if (Type == CTOR_INITIALIZER_DELEGATING)
Richard Smithc2bb8182015-03-24 06:36:48 +00008319 BOMInit = new (Context)
8320 CXXCtorInitializer(Context, TInfo, LParenLoc, Init, RParenLoc);
Richard Smith30e304e2016-12-14 00:03:17 +00008321 else if (Member)
8322 BOMInit = new (Context)
8323 CXXCtorInitializer(Context, Member, MemberOrEllipsisLoc, LParenLoc,
8324 Init, RParenLoc);
8325 else
8326 BOMInit = new (Context)
8327 CXXCtorInitializer(Context, IndirectMember, MemberOrEllipsisLoc,
8328 LParenLoc, Init, RParenLoc);
8329
Richard Smith418ed822016-12-14 19:45:03 +00008330 if (/*IsWritten*/Record[Idx++]) {
Richard Smith30e304e2016-12-14 00:03:17 +00008331 unsigned SourceOrder = Record[Idx++];
8332 BOMInit->setSourceOrder(SourceOrder);
Richard Smithc2bb8182015-03-24 06:36:48 +00008333 }
8334
Richard Smithc2bb8182015-03-24 06:36:48 +00008335 CtorInitializers[i] = BOMInit;
Guy Benyei11169dd2012-12-18 14:30:41 +00008336 }
8337
Richard Smithc2bb8182015-03-24 06:36:48 +00008338 return CtorInitializers;
Guy Benyei11169dd2012-12-18 14:30:41 +00008339}
8340
8341NestedNameSpecifier *
8342ASTReader::ReadNestedNameSpecifier(ModuleFile &F,
8343 const RecordData &Record, unsigned &Idx) {
8344 unsigned N = Record[Idx++];
Craig Toppera13603a2014-05-22 05:54:18 +00008345 NestedNameSpecifier *NNS = nullptr, *Prev = nullptr;
Guy Benyei11169dd2012-12-18 14:30:41 +00008346 for (unsigned I = 0; I != N; ++I) {
8347 NestedNameSpecifier::SpecifierKind Kind
8348 = (NestedNameSpecifier::SpecifierKind)Record[Idx++];
8349 switch (Kind) {
8350 case NestedNameSpecifier::Identifier: {
8351 IdentifierInfo *II = GetIdentifierInfo(F, Record, Idx);
8352 NNS = NestedNameSpecifier::Create(Context, Prev, II);
8353 break;
8354 }
8355
8356 case NestedNameSpecifier::Namespace: {
8357 NamespaceDecl *NS = ReadDeclAs<NamespaceDecl>(F, Record, Idx);
8358 NNS = NestedNameSpecifier::Create(Context, Prev, NS);
8359 break;
8360 }
8361
8362 case NestedNameSpecifier::NamespaceAlias: {
8363 NamespaceAliasDecl *Alias =ReadDeclAs<NamespaceAliasDecl>(F, Record, Idx);
8364 NNS = NestedNameSpecifier::Create(Context, Prev, Alias);
8365 break;
8366 }
8367
8368 case NestedNameSpecifier::TypeSpec:
8369 case NestedNameSpecifier::TypeSpecWithTemplate: {
8370 const Type *T = readType(F, Record, Idx).getTypePtrOrNull();
8371 if (!T)
Craig Toppera13603a2014-05-22 05:54:18 +00008372 return nullptr;
8373
Guy Benyei11169dd2012-12-18 14:30:41 +00008374 bool Template = Record[Idx++];
8375 NNS = NestedNameSpecifier::Create(Context, Prev, Template, T);
8376 break;
8377 }
8378
8379 case NestedNameSpecifier::Global: {
8380 NNS = NestedNameSpecifier::GlobalSpecifier(Context);
8381 // No associated value, and there can't be a prefix.
8382 break;
8383 }
Nikola Smiljanic67860242014-09-26 00:28:20 +00008384
8385 case NestedNameSpecifier::Super: {
8386 CXXRecordDecl *RD = ReadDeclAs<CXXRecordDecl>(F, Record, Idx);
8387 NNS = NestedNameSpecifier::SuperSpecifier(Context, RD);
8388 break;
8389 }
Guy Benyei11169dd2012-12-18 14:30:41 +00008390 }
8391 Prev = NNS;
8392 }
8393 return NNS;
8394}
8395
8396NestedNameSpecifierLoc
David L. Jonesc4808b9e2016-12-15 20:53:26 +00008397ASTReader::ReadNestedNameSpecifierLoc(ModuleFile &F, const RecordData &Record,
Guy Benyei11169dd2012-12-18 14:30:41 +00008398 unsigned &Idx) {
8399 unsigned N = Record[Idx++];
8400 NestedNameSpecifierLocBuilder Builder;
8401 for (unsigned I = 0; I != N; ++I) {
8402 NestedNameSpecifier::SpecifierKind Kind
8403 = (NestedNameSpecifier::SpecifierKind)Record[Idx++];
8404 switch (Kind) {
8405 case NestedNameSpecifier::Identifier: {
David L. Jonesc4808b9e2016-12-15 20:53:26 +00008406 IdentifierInfo *II = GetIdentifierInfo(F, Record, Idx);
Guy Benyei11169dd2012-12-18 14:30:41 +00008407 SourceRange Range = ReadSourceRange(F, Record, Idx);
8408 Builder.Extend(Context, II, Range.getBegin(), Range.getEnd());
8409 break;
8410 }
8411
8412 case NestedNameSpecifier::Namespace: {
8413 NamespaceDecl *NS = ReadDeclAs<NamespaceDecl>(F, Record, Idx);
8414 SourceRange Range = ReadSourceRange(F, Record, Idx);
8415 Builder.Extend(Context, NS, Range.getBegin(), Range.getEnd());
8416 break;
8417 }
8418
8419 case NestedNameSpecifier::NamespaceAlias: {
8420 NamespaceAliasDecl *Alias =ReadDeclAs<NamespaceAliasDecl>(F, Record, Idx);
8421 SourceRange Range = ReadSourceRange(F, Record, Idx);
8422 Builder.Extend(Context, Alias, Range.getBegin(), Range.getEnd());
8423 break;
8424 }
8425
8426 case NestedNameSpecifier::TypeSpec:
8427 case NestedNameSpecifier::TypeSpecWithTemplate: {
8428 bool Template = Record[Idx++];
8429 TypeSourceInfo *T = GetTypeSourceInfo(F, Record, Idx);
8430 if (!T)
8431 return NestedNameSpecifierLoc();
8432 SourceLocation ColonColonLoc = ReadSourceLocation(F, Record, Idx);
8433
8434 // FIXME: 'template' keyword location not saved anywhere, so we fake it.
David L. Jonesc4808b9e2016-12-15 20:53:26 +00008435 Builder.Extend(Context,
Guy Benyei11169dd2012-12-18 14:30:41 +00008436 Template? T->getTypeLoc().getBeginLoc() : SourceLocation(),
8437 T->getTypeLoc(), ColonColonLoc);
8438 break;
8439 }
8440
8441 case NestedNameSpecifier::Global: {
8442 SourceLocation ColonColonLoc = ReadSourceLocation(F, Record, Idx);
8443 Builder.MakeGlobal(Context, ColonColonLoc);
8444 break;
8445 }
Nikola Smiljanic67860242014-09-26 00:28:20 +00008446
8447 case NestedNameSpecifier::Super: {
8448 CXXRecordDecl *RD = ReadDeclAs<CXXRecordDecl>(F, Record, Idx);
8449 SourceRange Range = ReadSourceRange(F, Record, Idx);
8450 Builder.MakeSuper(Context, RD, Range.getBegin(), Range.getEnd());
8451 break;
8452 }
Guy Benyei11169dd2012-12-18 14:30:41 +00008453 }
8454 }
Nikola Smiljanic67860242014-09-26 00:28:20 +00008455
Guy Benyei11169dd2012-12-18 14:30:41 +00008456 return Builder.getWithLocInContext(Context);
8457}
8458
8459SourceRange
8460ASTReader::ReadSourceRange(ModuleFile &F, const RecordData &Record,
8461 unsigned &Idx) {
8462 SourceLocation beg = ReadSourceLocation(F, Record, Idx);
8463 SourceLocation end = ReadSourceLocation(F, Record, Idx);
8464 return SourceRange(beg, end);
8465}
8466
8467/// \brief Read an integral value
8468llvm::APInt ASTReader::ReadAPInt(const RecordData &Record, unsigned &Idx) {
8469 unsigned BitWidth = Record[Idx++];
8470 unsigned NumWords = llvm::APInt::getNumWords(BitWidth);
8471 llvm::APInt Result(BitWidth, NumWords, &Record[Idx]);
8472 Idx += NumWords;
8473 return Result;
8474}
8475
8476/// \brief Read a signed integral value
8477llvm::APSInt ASTReader::ReadAPSInt(const RecordData &Record, unsigned &Idx) {
8478 bool isUnsigned = Record[Idx++];
8479 return llvm::APSInt(ReadAPInt(Record, Idx), isUnsigned);
8480}
8481
8482/// \brief Read a floating-point value
Tim Northover178723a2013-01-22 09:46:51 +00008483llvm::APFloat ASTReader::ReadAPFloat(const RecordData &Record,
8484 const llvm::fltSemantics &Sem,
8485 unsigned &Idx) {
8486 return llvm::APFloat(Sem, ReadAPInt(Record, Idx));
Guy Benyei11169dd2012-12-18 14:30:41 +00008487}
8488
8489// \brief Read a string
8490std::string ASTReader::ReadString(const RecordData &Record, unsigned &Idx) {
8491 unsigned Len = Record[Idx++];
8492 std::string Result(Record.data() + Idx, Record.data() + Idx + Len);
8493 Idx += Len;
8494 return Result;
8495}
8496
Richard Smith7ed1bc92014-12-05 22:42:13 +00008497std::string ASTReader::ReadPath(ModuleFile &F, const RecordData &Record,
8498 unsigned &Idx) {
8499 std::string Filename = ReadString(Record, Idx);
8500 ResolveImportedPath(F, Filename);
8501 return Filename;
8502}
8503
David L. Jonesc4808b9e2016-12-15 20:53:26 +00008504VersionTuple ASTReader::ReadVersionTuple(const RecordData &Record,
Guy Benyei11169dd2012-12-18 14:30:41 +00008505 unsigned &Idx) {
8506 unsigned Major = Record[Idx++];
8507 unsigned Minor = Record[Idx++];
8508 unsigned Subminor = Record[Idx++];
8509 if (Minor == 0)
8510 return VersionTuple(Major);
8511 if (Subminor == 0)
8512 return VersionTuple(Major, Minor - 1);
8513 return VersionTuple(Major, Minor - 1, Subminor - 1);
8514}
8515
David L. Jonesc4808b9e2016-12-15 20:53:26 +00008516CXXTemporary *ASTReader::ReadCXXTemporary(ModuleFile &F,
Guy Benyei11169dd2012-12-18 14:30:41 +00008517 const RecordData &Record,
8518 unsigned &Idx) {
8519 CXXDestructorDecl *Decl = ReadDeclAs<CXXDestructorDecl>(F, Record, Idx);
8520 return CXXTemporary::Create(Context, Decl);
8521}
8522
Richard Smith37a93df2017-02-18 00:32:02 +00008523DiagnosticBuilder ASTReader::Diag(unsigned DiagID) const {
Argyrios Kyrtzidisdc9fdaf2013-05-24 05:44:08 +00008524 return Diag(CurrentImportLoc, DiagID);
Guy Benyei11169dd2012-12-18 14:30:41 +00008525}
8526
Richard Smith37a93df2017-02-18 00:32:02 +00008527DiagnosticBuilder ASTReader::Diag(SourceLocation Loc, unsigned DiagID) const {
Guy Benyei11169dd2012-12-18 14:30:41 +00008528 return Diags.Report(Loc, DiagID);
8529}
8530
8531/// \brief Retrieve the identifier table associated with the
8532/// preprocessor.
8533IdentifierTable &ASTReader::getIdentifierTable() {
8534 return PP.getIdentifierTable();
8535}
8536
8537/// \brief Record that the given ID maps to the given switch-case
8538/// statement.
8539void ASTReader::RecordSwitchCaseID(SwitchCase *SC, unsigned ID) {
Craig Toppera13603a2014-05-22 05:54:18 +00008540 assert((*CurrSwitchCaseStmts)[ID] == nullptr &&
Guy Benyei11169dd2012-12-18 14:30:41 +00008541 "Already have a SwitchCase with this ID");
8542 (*CurrSwitchCaseStmts)[ID] = SC;
8543}
8544
8545/// \brief Retrieve the switch-case statement with the given ID.
8546SwitchCase *ASTReader::getSwitchCaseWithID(unsigned ID) {
Craig Toppera13603a2014-05-22 05:54:18 +00008547 assert((*CurrSwitchCaseStmts)[ID] != nullptr && "No SwitchCase with this ID");
Guy Benyei11169dd2012-12-18 14:30:41 +00008548 return (*CurrSwitchCaseStmts)[ID];
8549}
8550
8551void ASTReader::ClearSwitchCaseIDs() {
8552 CurrSwitchCaseStmts->clear();
8553}
8554
8555void ASTReader::ReadComments() {
8556 std::vector<RawComment *> Comments;
Chris Lattner7fb3bef2013-01-20 00:56:42 +00008557 for (SmallVectorImpl<std::pair<BitstreamCursor,
Guy Benyei11169dd2012-12-18 14:30:41 +00008558 serialization::ModuleFile *> >::iterator
8559 I = CommentsCursors.begin(),
8560 E = CommentsCursors.end();
8561 I != E; ++I) {
Dmitri Gribenko9ee0e302014-03-27 15:40:39 +00008562 Comments.clear();
Chris Lattner7fb3bef2013-01-20 00:56:42 +00008563 BitstreamCursor &Cursor = I->first;
Guy Benyei11169dd2012-12-18 14:30:41 +00008564 serialization::ModuleFile &F = *I->second;
8565 SavedStreamPosition SavedPosition(Cursor);
8566
8567 RecordData Record;
8568 while (true) {
Chris Lattner7fb3bef2013-01-20 00:56:42 +00008569 llvm::BitstreamEntry Entry =
8570 Cursor.advanceSkippingSubblocks(BitstreamCursor::AF_DontPopBlockAtEnd);
Dmitri Gribenko9ee0e302014-03-27 15:40:39 +00008571
Chris Lattner7fb3bef2013-01-20 00:56:42 +00008572 switch (Entry.Kind) {
8573 case llvm::BitstreamEntry::SubBlock: // Handled for us already.
8574 case llvm::BitstreamEntry::Error:
8575 Error("malformed block record in AST file");
8576 return;
8577 case llvm::BitstreamEntry::EndBlock:
8578 goto NextCursor;
8579 case llvm::BitstreamEntry::Record:
8580 // The interesting case.
Guy Benyei11169dd2012-12-18 14:30:41 +00008581 break;
Guy Benyei11169dd2012-12-18 14:30:41 +00008582 }
8583
8584 // Read a record.
8585 Record.clear();
Chris Lattner0e6c9402013-01-20 02:38:54 +00008586 switch ((CommentRecordTypes)Cursor.readRecord(Entry.ID, Record)) {
Guy Benyei11169dd2012-12-18 14:30:41 +00008587 case COMMENTS_RAW_COMMENT: {
8588 unsigned Idx = 0;
8589 SourceRange SR = ReadSourceRange(F, Record, Idx);
8590 RawComment::CommentKind Kind =
8591 (RawComment::CommentKind) Record[Idx++];
8592 bool IsTrailingComment = Record[Idx++];
8593 bool IsAlmostTrailingComment = Record[Idx++];
Dmitri Gribenkoa7d16ce2013-04-10 15:35:17 +00008594 Comments.push_back(new (Context) RawComment(
8595 SR, Kind, IsTrailingComment, IsAlmostTrailingComment,
8596 Context.getLangOpts().CommentOpts.ParseAllComments));
Guy Benyei11169dd2012-12-18 14:30:41 +00008597 break;
8598 }
8599 }
8600 }
Dmitri Gribenko9ee0e302014-03-27 15:40:39 +00008601 NextCursor:
Bruno Cardoso Lopesc23af572016-12-19 21:06:06 +00008602 // De-serialized SourceLocations get negative FileIDs for other modules,
8603 // potentially invalidating the original order. Sort it again.
8604 std::sort(Comments.begin(), Comments.end(),
8605 BeforeThanCompare<RawComment>(SourceMgr));
Dmitri Gribenko9ee0e302014-03-27 15:40:39 +00008606 Context.Comments.addDeserializedComments(Comments);
Guy Benyei11169dd2012-12-18 14:30:41 +00008607 }
Guy Benyei11169dd2012-12-18 14:30:41 +00008608}
8609
Argyrios Kyrtzidisa38cb202017-01-30 06:05:58 +00008610void ASTReader::visitInputFiles(serialization::ModuleFile &MF,
8611 bool IncludeSystem, bool Complain,
8612 llvm::function_ref<void(const serialization::InputFile &IF,
8613 bool isSystem)> Visitor) {
8614 unsigned NumUserInputs = MF.NumUserInputFiles;
8615 unsigned NumInputs = MF.InputFilesLoaded.size();
8616 assert(NumUserInputs <= NumInputs);
8617 unsigned N = IncludeSystem ? NumInputs : NumUserInputs;
8618 for (unsigned I = 0; I < N; ++I) {
8619 bool IsSystem = I >= NumUserInputs;
8620 InputFile IF = getInputFile(MF, I+1, Complain);
8621 Visitor(IF, IsSystem);
8622 }
8623}
8624
Richard Smithcd45dbc2014-04-19 03:48:30 +00008625std::string ASTReader::getOwningModuleNameForDiagnostic(const Decl *D) {
8626 // If we know the owning module, use it.
Richard Smith42413142015-05-15 20:05:43 +00008627 if (Module *M = D->getImportedOwningModule())
Richard Smithcd45dbc2014-04-19 03:48:30 +00008628 return M->getFullModuleName();
8629
8630 // Otherwise, use the name of the top-level module the decl is within.
8631 if (ModuleFile *M = getOwningModuleFile(D))
8632 return M->ModuleName;
8633
8634 // Not from a module.
8635 return "";
8636}
8637
Guy Benyei11169dd2012-12-18 14:30:41 +00008638void ASTReader::finishPendingActions() {
Richard Smith851072e2014-05-19 20:59:20 +00008639 while (!PendingIdentifierInfos.empty() ||
8640 !PendingIncompleteDeclChains.empty() || !PendingDeclChains.empty() ||
Richard Smith2b9e3e32013-10-18 06:05:18 +00008641 !PendingMacroIDs.empty() || !PendingDeclContextInfos.empty() ||
Richard Smitha0ce9c42014-07-29 23:23:27 +00008642 !PendingUpdateRecords.empty()) {
Guy Benyei11169dd2012-12-18 14:30:41 +00008643 // If any identifiers with corresponding top-level declarations have
8644 // been loaded, load those declarations now.
Craig Topper79be4cd2013-07-05 04:33:53 +00008645 typedef llvm::DenseMap<IdentifierInfo *, SmallVector<Decl *, 2> >
8646 TopLevelDeclsMap;
8647 TopLevelDeclsMap TopLevelDecls;
8648
Guy Benyei11169dd2012-12-18 14:30:41 +00008649 while (!PendingIdentifierInfos.empty()) {
Douglas Gregor6168bd22013-02-18 15:53:43 +00008650 IdentifierInfo *II = PendingIdentifierInfos.back().first;
Richard Smithf0ae3c2d2014-03-28 17:31:23 +00008651 SmallVector<uint32_t, 4> DeclIDs =
8652 std::move(PendingIdentifierInfos.back().second);
Douglas Gregorcb15f082013-02-19 18:26:28 +00008653 PendingIdentifierInfos.pop_back();
Douglas Gregor6168bd22013-02-18 15:53:43 +00008654
8655 SetGloballyVisibleDecls(II, DeclIDs, &TopLevelDecls[II]);
Guy Benyei11169dd2012-12-18 14:30:41 +00008656 }
Richard Smithf0ae3c2d2014-03-28 17:31:23 +00008657
Richard Smith851072e2014-05-19 20:59:20 +00008658 // For each decl chain that we wanted to complete while deserializing, mark
8659 // it as "still needs to be completed".
8660 for (unsigned I = 0; I != PendingIncompleteDeclChains.size(); ++I) {
8661 markIncompleteDeclChain(PendingIncompleteDeclChains[I]);
8662 }
8663 PendingIncompleteDeclChains.clear();
8664
Guy Benyei11169dd2012-12-18 14:30:41 +00008665 // Load pending declaration chains.
Richard Smithd8a83712015-08-22 01:47:18 +00008666 for (unsigned I = 0; I != PendingDeclChains.size(); ++I)
Richard Smithd61d4ac2015-08-22 20:13:39 +00008667 loadPendingDeclChain(PendingDeclChains[I].first, PendingDeclChains[I].second);
Guy Benyei11169dd2012-12-18 14:30:41 +00008668 PendingDeclChains.clear();
8669
Douglas Gregor6168bd22013-02-18 15:53:43 +00008670 // Make the most recent of the top-level declarations visible.
Craig Topper79be4cd2013-07-05 04:33:53 +00008671 for (TopLevelDeclsMap::iterator TLD = TopLevelDecls.begin(),
8672 TLDEnd = TopLevelDecls.end(); TLD != TLDEnd; ++TLD) {
Douglas Gregor6168bd22013-02-18 15:53:43 +00008673 IdentifierInfo *II = TLD->first;
8674 for (unsigned I = 0, N = TLD->second.size(); I != N; ++I) {
Argyrios Kyrtzidise5edbf92013-04-26 21:33:35 +00008675 pushExternalDeclIntoScope(cast<NamedDecl>(TLD->second[I]), II);
Douglas Gregor6168bd22013-02-18 15:53:43 +00008676 }
8677 }
8678
Guy Benyei11169dd2012-12-18 14:30:41 +00008679 // Load any pending macro definitions.
8680 for (unsigned I = 0; I != PendingMacroIDs.size(); ++I) {
Argyrios Kyrtzidiseb663da2013-03-22 21:12:57 +00008681 IdentifierInfo *II = PendingMacroIDs.begin()[I].first;
8682 SmallVector<PendingMacroInfo, 2> GlobalIDs;
8683 GlobalIDs.swap(PendingMacroIDs.begin()[I].second);
8684 // Initialize the macro history from chained-PCHs ahead of module imports.
Richard Smith49f906a2014-03-01 00:08:04 +00008685 for (unsigned IDIdx = 0, NumIDs = GlobalIDs.size(); IDIdx != NumIDs;
Argyrios Kyrtzidis719736c2013-01-19 03:14:56 +00008686 ++IDIdx) {
Argyrios Kyrtzidiseb663da2013-03-22 21:12:57 +00008687 const PendingMacroInfo &Info = GlobalIDs[IDIdx];
Manman Ren11f2a472016-08-18 17:42:15 +00008688 if (!Info.M->isModule())
Argyrios Kyrtzidiseb663da2013-03-22 21:12:57 +00008689 resolvePendingMacro(II, Info);
8690 }
8691 // Handle module imports.
Richard Smith49f906a2014-03-01 00:08:04 +00008692 for (unsigned IDIdx = 0, NumIDs = GlobalIDs.size(); IDIdx != NumIDs;
Argyrios Kyrtzidiseb663da2013-03-22 21:12:57 +00008693 ++IDIdx) {
8694 const PendingMacroInfo &Info = GlobalIDs[IDIdx];
Manman Ren11f2a472016-08-18 17:42:15 +00008695 if (Info.M->isModule())
Argyrios Kyrtzidiseb663da2013-03-22 21:12:57 +00008696 resolvePendingMacro(II, Info);
Guy Benyei11169dd2012-12-18 14:30:41 +00008697 }
8698 }
8699 PendingMacroIDs.clear();
Argyrios Kyrtzidis83a6e3b2013-02-16 00:48:59 +00008700
8701 // Wire up the DeclContexts for Decls that we delayed setting until
8702 // recursive loading is completed.
8703 while (!PendingDeclContextInfos.empty()) {
8704 PendingDeclContextInfo Info = PendingDeclContextInfos.front();
8705 PendingDeclContextInfos.pop_front();
8706 DeclContext *SemaDC = cast<DeclContext>(GetDecl(Info.SemaDC));
8707 DeclContext *LexicalDC = cast<DeclContext>(GetDecl(Info.LexicalDC));
8708 Info.D->setDeclContextsImpl(SemaDC, LexicalDC, getContext());
8709 }
Richard Smith2b9e3e32013-10-18 06:05:18 +00008710
Richard Smithd1c46742014-04-30 02:24:17 +00008711 // Perform any pending declaration updates.
Richard Smithd6db68c2014-08-07 20:58:41 +00008712 while (!PendingUpdateRecords.empty()) {
Richard Smithd1c46742014-04-30 02:24:17 +00008713 auto Update = PendingUpdateRecords.pop_back_val();
8714 ReadingKindTracker ReadingKind(Read_Decl, *this);
8715 loadDeclUpdateRecords(Update.first, Update.second);
8716 }
Guy Benyei11169dd2012-12-18 14:30:41 +00008717 }
Richard Smith8a639892015-01-24 01:07:20 +00008718
8719 // At this point, all update records for loaded decls are in place, so any
8720 // fake class definitions should have become real.
8721 assert(PendingFakeDefinitionData.empty() &&
8722 "faked up a class definition but never saw the real one");
8723
Guy Benyei11169dd2012-12-18 14:30:41 +00008724 // If we deserialized any C++ or Objective-C class definitions, any
8725 // Objective-C protocol definitions, or any redeclarable templates, make sure
David L. Jonesc4808b9e2016-12-15 20:53:26 +00008726 // that all redeclarations point to the definitions. Note that this can only
Guy Benyei11169dd2012-12-18 14:30:41 +00008727 // happen now, after the redeclaration chains have been fully wired.
Craig Topperc6914d02014-08-25 04:15:02 +00008728 for (Decl *D : PendingDefinitions) {
8729 if (TagDecl *TD = dyn_cast<TagDecl>(D)) {
Richard Smith5b21db82014-04-23 18:20:42 +00008730 if (const TagType *TagT = dyn_cast<TagType>(TD->getTypeForDecl())) {
Guy Benyei11169dd2012-12-18 14:30:41 +00008731 // Make sure that the TagType points at the definition.
8732 const_cast<TagType*>(TagT)->decl = TD;
8733 }
Richard Smith8ce51082015-03-11 01:44:51 +00008734
Craig Topperc6914d02014-08-25 04:15:02 +00008735 if (auto RD = dyn_cast<CXXRecordDecl>(D)) {
Richard Smith8ce51082015-03-11 01:44:51 +00008736 for (auto *R = getMostRecentExistingDecl(RD); R;
8737 R = R->getPreviousDecl()) {
8738 assert((R == D) ==
8739 cast<CXXRecordDecl>(R)->isThisDeclarationADefinition() &&
Richard Smith2c381642014-08-27 23:11:59 +00008740 "declaration thinks it's the definition but it isn't");
Aaron Ballman86c93902014-03-06 23:45:36 +00008741 cast<CXXRecordDecl>(R)->DefinitionData = RD->DefinitionData;
Richard Smith2c381642014-08-27 23:11:59 +00008742 }
Guy Benyei11169dd2012-12-18 14:30:41 +00008743 }
8744
8745 continue;
8746 }
Richard Smith8ce51082015-03-11 01:44:51 +00008747
Craig Topperc6914d02014-08-25 04:15:02 +00008748 if (auto ID = dyn_cast<ObjCInterfaceDecl>(D)) {
Guy Benyei11169dd2012-12-18 14:30:41 +00008749 // Make sure that the ObjCInterfaceType points at the definition.
8750 const_cast<ObjCInterfaceType *>(cast<ObjCInterfaceType>(ID->TypeForDecl))
8751 ->Decl = ID;
Richard Smith8ce51082015-03-11 01:44:51 +00008752
8753 for (auto *R = getMostRecentExistingDecl(ID); R; R = R->getPreviousDecl())
8754 cast<ObjCInterfaceDecl>(R)->Data = ID->Data;
8755
Guy Benyei11169dd2012-12-18 14:30:41 +00008756 continue;
8757 }
Richard Smith8ce51082015-03-11 01:44:51 +00008758
Craig Topperc6914d02014-08-25 04:15:02 +00008759 if (auto PD = dyn_cast<ObjCProtocolDecl>(D)) {
Richard Smith8ce51082015-03-11 01:44:51 +00008760 for (auto *R = getMostRecentExistingDecl(PD); R; R = R->getPreviousDecl())
8761 cast<ObjCProtocolDecl>(R)->Data = PD->Data;
8762
Guy Benyei11169dd2012-12-18 14:30:41 +00008763 continue;
8764 }
Richard Smith8ce51082015-03-11 01:44:51 +00008765
Craig Topperc6914d02014-08-25 04:15:02 +00008766 auto RTD = cast<RedeclarableTemplateDecl>(D)->getCanonicalDecl();
Richard Smith8ce51082015-03-11 01:44:51 +00008767 for (auto *R = getMostRecentExistingDecl(RTD); R; R = R->getPreviousDecl())
8768 cast<RedeclarableTemplateDecl>(R)->Common = RTD->Common;
Guy Benyei11169dd2012-12-18 14:30:41 +00008769 }
8770 PendingDefinitions.clear();
8771
8772 // Load the bodies of any functions or methods we've encountered. We do
8773 // this now (delayed) so that we can be sure that the declaration chains
Richard Smithb9fa9962015-08-21 03:04:33 +00008774 // have been fully wired up (hasBody relies on this).
8775 // FIXME: We shouldn't require complete redeclaration chains here.
Guy Benyei11169dd2012-12-18 14:30:41 +00008776 for (PendingBodiesMap::iterator PB = PendingBodies.begin(),
8777 PBEnd = PendingBodies.end();
8778 PB != PBEnd; ++PB) {
8779 if (FunctionDecl *FD = dyn_cast<FunctionDecl>(PB->first)) {
8780 // FIXME: Check for =delete/=default?
8781 // FIXME: Complain about ODR violations here?
Richard Smith6561f922016-09-12 21:06:40 +00008782 const FunctionDecl *Defn = nullptr;
8783 if (!getContext().getLangOpts().Modules || !FD->hasBody(Defn))
Guy Benyei11169dd2012-12-18 14:30:41 +00008784 FD->setLazyBody(PB->second);
Benjamin Kramera72a70a2016-10-17 13:00:44 +00008785 else
Richard Smith6561f922016-09-12 21:06:40 +00008786 mergeDefinitionVisibility(const_cast<FunctionDecl*>(Defn), FD);
Guy Benyei11169dd2012-12-18 14:30:41 +00008787 continue;
8788 }
8789
8790 ObjCMethodDecl *MD = cast<ObjCMethodDecl>(PB->first);
8791 if (!getContext().getLangOpts().Modules || !MD->hasBody())
8792 MD->setLazyBody(PB->second);
8793 }
8794 PendingBodies.clear();
Richard Smith42413142015-05-15 20:05:43 +00008795
8796 // Do some cleanup.
8797 for (auto *ND : PendingMergedDefinitionsToDeduplicate)
8798 getContext().deduplicateMergedDefinitonsFor(ND);
8799 PendingMergedDefinitionsToDeduplicate.clear();
Richard Smitha0ce9c42014-07-29 23:23:27 +00008800}
8801
8802void ASTReader::diagnoseOdrViolations() {
Richard Smithbb853c72014-08-13 01:23:33 +00008803 if (PendingOdrMergeFailures.empty() && PendingOdrMergeChecks.empty())
8804 return;
8805
Richard Smitha0ce9c42014-07-29 23:23:27 +00008806 // Trigger the import of the full definition of each class that had any
8807 // odr-merging problems, so we can produce better diagnostics for them.
Richard Smithbb853c72014-08-13 01:23:33 +00008808 // These updates may in turn find and diagnose some ODR failures, so take
8809 // ownership of the set first.
8810 auto OdrMergeFailures = std::move(PendingOdrMergeFailures);
8811 PendingOdrMergeFailures.clear();
8812 for (auto &Merge : OdrMergeFailures) {
Richard Smitha0ce9c42014-07-29 23:23:27 +00008813 Merge.first->buildLookup();
8814 Merge.first->decls_begin();
8815 Merge.first->bases_begin();
8816 Merge.first->vbases_begin();
8817 for (auto *RD : Merge.second) {
8818 RD->decls_begin();
8819 RD->bases_begin();
8820 RD->vbases_begin();
8821 }
8822 }
8823
8824 // For each declaration from a merged context, check that the canonical
8825 // definition of that context also contains a declaration of the same
8826 // entity.
8827 //
8828 // Caution: this loop does things that might invalidate iterators into
8829 // PendingOdrMergeChecks. Don't turn this into a range-based for loop!
8830 while (!PendingOdrMergeChecks.empty()) {
8831 NamedDecl *D = PendingOdrMergeChecks.pop_back_val();
8832
8833 // FIXME: Skip over implicit declarations for now. This matters for things
8834 // like implicitly-declared special member functions. This isn't entirely
8835 // correct; we can end up with multiple unmerged declarations of the same
8836 // implicit entity.
8837 if (D->isImplicit())
8838 continue;
8839
8840 DeclContext *CanonDef = D->getDeclContext();
Richard Smitha0ce9c42014-07-29 23:23:27 +00008841
8842 bool Found = false;
8843 const Decl *DCanon = D->getCanonicalDecl();
8844
Richard Smith01bdb7a2014-08-28 05:44:07 +00008845 for (auto RI : D->redecls()) {
8846 if (RI->getLexicalDeclContext() == CanonDef) {
8847 Found = true;
8848 break;
8849 }
8850 }
8851 if (Found)
8852 continue;
8853
Richard Smith0f4e2c42015-08-06 04:23:48 +00008854 // Quick check failed, time to do the slow thing. Note, we can't just
8855 // look up the name of D in CanonDef here, because the member that is
8856 // in CanonDef might not be found by name lookup (it might have been
8857 // replaced by a more recent declaration in the lookup table), and we
8858 // can't necessarily find it in the redeclaration chain because it might
8859 // be merely mergeable, not redeclarable.
Richard Smitha0ce9c42014-07-29 23:23:27 +00008860 llvm::SmallVector<const NamedDecl*, 4> Candidates;
Richard Smith0f4e2c42015-08-06 04:23:48 +00008861 for (auto *CanonMember : CanonDef->decls()) {
8862 if (CanonMember->getCanonicalDecl() == DCanon) {
8863 // This can happen if the declaration is merely mergeable and not
8864 // actually redeclarable (we looked for redeclarations earlier).
8865 //
8866 // FIXME: We should be able to detect this more efficiently, without
8867 // pulling in all of the members of CanonDef.
8868 Found = true;
8869 break;
Richard Smitha0ce9c42014-07-29 23:23:27 +00008870 }
Richard Smith0f4e2c42015-08-06 04:23:48 +00008871 if (auto *ND = dyn_cast<NamedDecl>(CanonMember))
8872 if (ND->getDeclName() == D->getDeclName())
8873 Candidates.push_back(ND);
Richard Smitha0ce9c42014-07-29 23:23:27 +00008874 }
8875
8876 if (!Found) {
Richard Smithd08aeb62014-08-28 01:33:39 +00008877 // The AST doesn't like TagDecls becoming invalid after they've been
8878 // completed. We only really need to mark FieldDecls as invalid here.
8879 if (!isa<TagDecl>(D))
8880 D->setInvalidDecl();
David L. Jonesc4808b9e2016-12-15 20:53:26 +00008881
Richard Smith4ab3dbd2015-02-13 22:43:51 +00008882 // Ensure we don't accidentally recursively enter deserialization while
8883 // we're producing our diagnostic.
8884 Deserializing RecursionGuard(this);
Richard Smitha0ce9c42014-07-29 23:23:27 +00008885
8886 std::string CanonDefModule =
8887 getOwningModuleNameForDiagnostic(cast<Decl>(CanonDef));
8888 Diag(D->getLocation(), diag::err_module_odr_violation_missing_decl)
8889 << D << getOwningModuleNameForDiagnostic(D)
8890 << CanonDef << CanonDefModule.empty() << CanonDefModule;
8891
8892 if (Candidates.empty())
8893 Diag(cast<Decl>(CanonDef)->getLocation(),
8894 diag::note_module_odr_violation_no_possible_decls) << D;
8895 else {
8896 for (unsigned I = 0, N = Candidates.size(); I != N; ++I)
8897 Diag(Candidates[I]->getLocation(),
8898 diag::note_module_odr_violation_possible_decl)
8899 << Candidates[I];
8900 }
8901
8902 DiagnosedOdrMergeFailures.insert(CanonDef);
8903 }
8904 }
Richard Smithcd45dbc2014-04-19 03:48:30 +00008905
Richard Smith4ab3dbd2015-02-13 22:43:51 +00008906 if (OdrMergeFailures.empty())
8907 return;
8908
8909 // Ensure we don't accidentally recursively enter deserialization while
8910 // we're producing our diagnostics.
8911 Deserializing RecursionGuard(this);
8912
Richard Smithcd45dbc2014-04-19 03:48:30 +00008913 // Issue any pending ODR-failure diagnostics.
Richard Smithbb853c72014-08-13 01:23:33 +00008914 for (auto &Merge : OdrMergeFailures) {
Richard Smitha0ce9c42014-07-29 23:23:27 +00008915 // If we've already pointed out a specific problem with this class, don't
8916 // bother issuing a general "something's different" diagnostic.
David Blaikie82e95a32014-11-19 07:49:47 +00008917 if (!DiagnosedOdrMergeFailures.insert(Merge.first).second)
Richard Smithcd45dbc2014-04-19 03:48:30 +00008918 continue;
8919
8920 bool Diagnosed = false;
8921 for (auto *RD : Merge.second) {
8922 // Multiple different declarations got merged together; tell the user
8923 // where they came from.
Richard Trieudc4cb022017-02-17 07:19:24 +00008924 if (Merge.first != RD) {
8925 // FIXME: Walk the definition, figure out what's different,
8926 // and diagnose that.
8927 if (!Diagnosed) {
8928 std::string Module = getOwningModuleNameForDiagnostic(Merge.first);
8929 Diag(Merge.first->getLocation(),
8930 diag::err_module_odr_violation_different_definitions)
Richard Trieucb6b7262017-02-17 05:54:30 +00008931 << Merge.first << Module.empty() << Module;
Richard Trieudc4cb022017-02-17 07:19:24 +00008932 Diagnosed = true;
8933 }
Richard Smithcd45dbc2014-04-19 03:48:30 +00008934
8935 Diag(RD->getLocation(),
8936 diag::note_module_odr_violation_different_definitions)
Richard Trieudc4cb022017-02-17 07:19:24 +00008937 << getOwningModuleNameForDiagnostic(RD);
Richard Smithcd45dbc2014-04-19 03:48:30 +00008938 }
8939 }
8940
8941 if (!Diagnosed) {
8942 // All definitions are updates to the same declaration. This happens if a
8943 // module instantiates the declaration of a class template specialization
8944 // and two or more other modules instantiate its definition.
8945 //
8946 // FIXME: Indicate which modules had instantiations of this definition.
8947 // FIXME: How can this even happen?
8948 Diag(Merge.first->getLocation(),
8949 diag::err_module_odr_violation_different_instantiations)
8950 << Merge.first;
8951 }
8952 }
Guy Benyei11169dd2012-12-18 14:30:41 +00008953}
8954
Richard Smithce18a182015-07-14 00:26:00 +00008955void ASTReader::StartedDeserializing() {
David L. Jonesc4808b9e2016-12-15 20:53:26 +00008956 if (++NumCurrentElementsDeserializing == 1 && ReadTimer.get())
Richard Smithce18a182015-07-14 00:26:00 +00008957 ReadTimer->startTimer();
8958}
8959
Guy Benyei11169dd2012-12-18 14:30:41 +00008960void ASTReader::FinishedDeserializing() {
8961 assert(NumCurrentElementsDeserializing &&
8962 "FinishedDeserializing not paired with StartedDeserializing");
8963 if (NumCurrentElementsDeserializing == 1) {
8964 // We decrease NumCurrentElementsDeserializing only after pending actions
8965 // are finished, to avoid recursively re-calling finishPendingActions().
8966 finishPendingActions();
8967 }
8968 --NumCurrentElementsDeserializing;
8969
Richard Smitha0ce9c42014-07-29 23:23:27 +00008970 if (NumCurrentElementsDeserializing == 0) {
Richard Smith9e2341d2015-03-23 03:25:59 +00008971 // Propagate exception specification updates along redeclaration chains.
Richard Smith7226f2a2015-03-23 19:54:56 +00008972 while (!PendingExceptionSpecUpdates.empty()) {
8973 auto Updates = std::move(PendingExceptionSpecUpdates);
8974 PendingExceptionSpecUpdates.clear();
8975 for (auto Update : Updates) {
Vassil Vassilev19765fb2016-07-22 21:08:24 +00008976 ProcessingUpdatesRAIIObj ProcessingUpdates(*this);
Richard Smith7226f2a2015-03-23 19:54:56 +00008977 auto *FPT = Update.second->getType()->castAs<FunctionProtoType>();
Richard Smith1d0f1992015-08-19 21:09:32 +00008978 auto ESI = FPT->getExtProtoInfo().ExceptionSpec;
Richard Smithd88a7f12015-09-01 20:35:42 +00008979 if (auto *Listener = Context.getASTMutationListener())
8980 Listener->ResolvedExceptionSpec(cast<FunctionDecl>(Update.second));
Richard Smith1d0f1992015-08-19 21:09:32 +00008981 for (auto *Redecl : Update.second->redecls())
8982 Context.adjustExceptionSpec(cast<FunctionDecl>(Redecl), ESI);
Richard Smith7226f2a2015-03-23 19:54:56 +00008983 }
Richard Smith9e2341d2015-03-23 03:25:59 +00008984 }
8985
Richard Smithce18a182015-07-14 00:26:00 +00008986 if (ReadTimer)
8987 ReadTimer->stopTimer();
8988
Richard Smith0f4e2c42015-08-06 04:23:48 +00008989 diagnoseOdrViolations();
8990
Richard Smith04d05b52014-03-23 00:27:18 +00008991 // We are not in recursive loading, so it's safe to pass the "interesting"
8992 // decls to the consumer.
Richard Smitha0ce9c42014-07-29 23:23:27 +00008993 if (Consumer)
8994 PassInterestingDeclsToConsumer();
Guy Benyei11169dd2012-12-18 14:30:41 +00008995 }
8996}
8997
Argyrios Kyrtzidise5edbf92013-04-26 21:33:35 +00008998void ASTReader::pushExternalDeclIntoScope(NamedDecl *D, DeclarationName Name) {
Richard Smith9e2341d2015-03-23 03:25:59 +00008999 if (IdentifierInfo *II = Name.getAsIdentifierInfo()) {
9000 // Remove any fake results before adding any real ones.
9001 auto It = PendingFakeLookupResults.find(II);
9002 if (It != PendingFakeLookupResults.end()) {
Richard Smitha534a312015-07-21 23:54:07 +00009003 for (auto *ND : It->second)
Richard Smith9e2341d2015-03-23 03:25:59 +00009004 SemaObj->IdResolver.RemoveDecl(ND);
Ben Langmuireb8bd2d2015-04-10 22:25:42 +00009005 // FIXME: this works around module+PCH performance issue.
9006 // Rather than erase the result from the map, which is O(n), just clear
9007 // the vector of NamedDecls.
9008 It->second.clear();
Richard Smith9e2341d2015-03-23 03:25:59 +00009009 }
9010 }
Argyrios Kyrtzidise5edbf92013-04-26 21:33:35 +00009011
9012 if (SemaObj->IdResolver.tryAddTopLevelDecl(D, Name) && SemaObj->TUScope) {
9013 SemaObj->TUScope->AddDecl(D);
9014 } else if (SemaObj->TUScope) {
9015 // Adding the decl to IdResolver may have failed because it was already in
9016 // (even though it was not added in scope). If it is already in, make sure
9017 // it gets in the scope as well.
9018 if (std::find(SemaObj->IdResolver.begin(Name),
9019 SemaObj->IdResolver.end(), D) != SemaObj->IdResolver.end())
9020 SemaObj->TUScope->AddDecl(D);
9021 }
9022}
9023
David Blaikie61137e12017-01-05 18:23:18 +00009024ASTReader::ASTReader(Preprocessor &PP, ASTContext &Context,
9025 const PCHContainerReader &PCHContainerRdr,
9026 ArrayRef<std::shared_ptr<ModuleFileExtension>> Extensions,
9027 StringRef isysroot, bool DisableValidation,
9028 bool AllowASTWithCompilerErrors,
9029 bool AllowConfigurationMismatch, bool ValidateSystemInputs,
9030 bool UseGlobalIndex,
9031 std::unique_ptr<llvm::Timer> ReadTimer)
9032 : Listener(DisableValidation
9033 ? cast<ASTReaderListener>(new SimpleASTReaderListener(PP))
9034 : cast<ASTReaderListener>(new PCHValidator(PP, *this))),
David Blaikie61137e12017-01-05 18:23:18 +00009035 SourceMgr(PP.getSourceManager()), FileMgr(PP.getFileManager()),
David Blaikie9d7c1ba2017-01-05 18:45:43 +00009036 PCHContainerRdr(PCHContainerRdr), Diags(PP.getDiagnostics()), PP(PP),
9037 Context(Context), ModuleMgr(PP.getFileManager(), PCHContainerRdr),
9038 DummyIdResolver(PP), ReadTimer(std::move(ReadTimer)), isysroot(isysroot),
David Blaikie61137e12017-01-05 18:23:18 +00009039 DisableValidation(DisableValidation),
Nico Weber824285e2014-05-08 04:26:47 +00009040 AllowASTWithCompilerErrors(AllowASTWithCompilerErrors),
9041 AllowConfigurationMismatch(AllowConfigurationMismatch),
9042 ValidateSystemInputs(ValidateSystemInputs),
David Blaikie9d7c1ba2017-01-05 18:45:43 +00009043 UseGlobalIndex(UseGlobalIndex), CurrSwitchCaseStmts(&SwitchCaseStmts) {
Guy Benyei11169dd2012-12-18 14:30:41 +00009044 SourceMgr.setExternalSLocEntrySource(this);
Douglas Gregor6623e1f2015-11-03 18:33:07 +00009045
9046 for (const auto &Ext : Extensions) {
9047 auto BlockName = Ext->getExtensionMetadata().BlockName;
9048 auto Known = ModuleFileExtensions.find(BlockName);
9049 if (Known != ModuleFileExtensions.end()) {
9050 Diags.Report(diag::warn_duplicate_module_file_extension)
9051 << BlockName;
9052 continue;
9053 }
9054
9055 ModuleFileExtensions.insert({BlockName, Ext});
9056 }
Guy Benyei11169dd2012-12-18 14:30:41 +00009057}
9058
9059ASTReader::~ASTReader() {
Nico Weber824285e2014-05-08 04:26:47 +00009060 if (OwnsDeserializationListener)
9061 delete DeserializationListener;
Guy Benyei11169dd2012-12-18 14:30:41 +00009062}
Richard Smith10379092016-05-06 23:14:07 +00009063
9064IdentifierResolver &ASTReader::getIdResolver() {
9065 return SemaObj ? SemaObj->IdResolver : DummyIdResolver;
9066}
David L. Jonesbe1557a2016-12-21 00:17:49 +00009067
9068unsigned ASTRecordReader::readRecord(llvm::BitstreamCursor &Cursor,
9069 unsigned AbbrevID) {
9070 Idx = 0;
9071 Record.clear();
9072 return Cursor.readRecord(AbbrevID, Record);
9073}