blob: a4da0d2ebe2be3f257f7409d633d0b5a55181422 [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.
485 ModuleFile *TopImport = *ModuleMgr.rbegin();
486 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;
947 case DeclarationName::CXXConstructorName:
948 case DeclarationName::CXXDestructorName:
949 case DeclarationName::CXXConversionFunctionName:
950 case DeclarationName::CXXUsingDirective:
951 Data = 0;
952 break;
953 }
954}
955
956unsigned DeclarationNameKey::getHash() const {
957 llvm::FoldingSetNodeID ID;
958 ID.AddInteger(Kind);
959
960 switch (Kind) {
961 case DeclarationName::Identifier:
962 case DeclarationName::CXXLiteralOperatorName:
963 ID.AddString(((IdentifierInfo*)Data)->getName());
964 break;
965 case DeclarationName::ObjCZeroArgSelector:
966 case DeclarationName::ObjCOneArgSelector:
967 case DeclarationName::ObjCMultiArgSelector:
968 ID.AddInteger(serialization::ComputeHash(Selector(Data)));
969 break;
970 case DeclarationName::CXXOperatorName:
971 ID.AddInteger((OverloadedOperatorKind)Data);
Guy Benyei11169dd2012-12-18 14:30:41 +0000972 break;
973 case DeclarationName::CXXConstructorName:
974 case DeclarationName::CXXDestructorName:
975 case DeclarationName::CXXConversionFunctionName:
976 case DeclarationName::CXXUsingDirective:
977 break;
978 }
979
980 return ID.ComputeHash();
981}
982
Richard Smithd88a7f12015-09-01 20:35:42 +0000983ModuleFile *
984ASTDeclContextNameLookupTrait::ReadFileRef(const unsigned char *&d) {
985 using namespace llvm::support;
986 uint32_t ModuleFileID = endian::readNext<uint32_t, little, unaligned>(d);
987 return Reader.getLocalModuleFile(F, ModuleFileID);
988}
989
Guy Benyei11169dd2012-12-18 14:30:41 +0000990std::pair<unsigned, unsigned>
Richard Smitha06c7e62015-08-26 23:55:49 +0000991ASTDeclContextNameLookupTrait::ReadKeyDataLength(const unsigned char *&d) {
Justin Bogner57ba0b22014-03-28 22:03:24 +0000992 using namespace llvm::support;
993 unsigned KeyLen = endian::readNext<uint16_t, little, unaligned>(d);
994 unsigned DataLen = endian::readNext<uint16_t, little, unaligned>(d);
Guy Benyei11169dd2012-12-18 14:30:41 +0000995 return std::make_pair(KeyLen, DataLen);
996}
997
Richard Smitha06c7e62015-08-26 23:55:49 +0000998ASTDeclContextNameLookupTrait::internal_key_type
999ASTDeclContextNameLookupTrait::ReadKey(const unsigned char *d, unsigned) {
Justin Bogner57ba0b22014-03-28 22:03:24 +00001000 using namespace llvm::support;
Guy Benyei11169dd2012-12-18 14:30:41 +00001001
Richard Smitha06c7e62015-08-26 23:55:49 +00001002 auto Kind = (DeclarationName::NameKind)*d++;
1003 uint64_t Data;
1004 switch (Kind) {
Guy Benyei11169dd2012-12-18 14:30:41 +00001005 case DeclarationName::Identifier:
Richard Smitha06c7e62015-08-26 23:55:49 +00001006 Data = (uint64_t)Reader.getLocalIdentifier(
Justin Bogner57ba0b22014-03-28 22:03:24 +00001007 F, endian::readNext<uint32_t, little, unaligned>(d));
Guy Benyei11169dd2012-12-18 14:30:41 +00001008 break;
1009 case DeclarationName::ObjCZeroArgSelector:
1010 case DeclarationName::ObjCOneArgSelector:
1011 case DeclarationName::ObjCMultiArgSelector:
Richard Smitha06c7e62015-08-26 23:55:49 +00001012 Data =
Justin Bogner57ba0b22014-03-28 22:03:24 +00001013 (uint64_t)Reader.getLocalSelector(
1014 F, endian::readNext<uint32_t, little, unaligned>(
1015 d)).getAsOpaquePtr();
Guy Benyei11169dd2012-12-18 14:30:41 +00001016 break;
1017 case DeclarationName::CXXOperatorName:
Richard Smitha06c7e62015-08-26 23:55:49 +00001018 Data = *d++; // OverloadedOperatorKind
Guy Benyei11169dd2012-12-18 14:30:41 +00001019 break;
1020 case DeclarationName::CXXLiteralOperatorName:
Richard Smitha06c7e62015-08-26 23:55:49 +00001021 Data = (uint64_t)Reader.getLocalIdentifier(
Justin Bogner57ba0b22014-03-28 22:03:24 +00001022 F, endian::readNext<uint32_t, little, unaligned>(d));
Guy Benyei11169dd2012-12-18 14:30:41 +00001023 break;
1024 case DeclarationName::CXXConstructorName:
1025 case DeclarationName::CXXDestructorName:
1026 case DeclarationName::CXXConversionFunctionName:
1027 case DeclarationName::CXXUsingDirective:
Richard Smitha06c7e62015-08-26 23:55:49 +00001028 Data = 0;
Guy Benyei11169dd2012-12-18 14:30:41 +00001029 break;
1030 }
1031
Richard Smitha06c7e62015-08-26 23:55:49 +00001032 return DeclarationNameKey(Kind, Data);
Guy Benyei11169dd2012-12-18 14:30:41 +00001033}
1034
Richard Smithd88a7f12015-09-01 20:35:42 +00001035void ASTDeclContextNameLookupTrait::ReadDataInto(internal_key_type,
1036 const unsigned char *d,
1037 unsigned DataLen,
1038 data_type_builder &Val) {
Justin Bogner57ba0b22014-03-28 22:03:24 +00001039 using namespace llvm::support;
Richard Smithd88a7f12015-09-01 20:35:42 +00001040 for (unsigned NumDecls = DataLen / 4; NumDecls; --NumDecls) {
1041 uint32_t LocalID = endian::readNext<uint32_t, little, unaligned>(d);
1042 Val.insert(Reader.getGlobalDeclID(F, LocalID));
1043 }
Guy Benyei11169dd2012-12-18 14:30:41 +00001044}
1045
Richard Smith0f4e2c42015-08-06 04:23:48 +00001046bool ASTReader::ReadLexicalDeclContextStorage(ModuleFile &M,
1047 BitstreamCursor &Cursor,
1048 uint64_t Offset,
1049 DeclContext *DC) {
1050 assert(Offset != 0);
1051
Guy Benyei11169dd2012-12-18 14:30:41 +00001052 SavedStreamPosition SavedPosition(Cursor);
Richard Smith0f4e2c42015-08-06 04:23:48 +00001053 Cursor.JumpToBit(Offset);
Guy Benyei11169dd2012-12-18 14:30:41 +00001054
Richard Smith0f4e2c42015-08-06 04:23:48 +00001055 RecordData Record;
1056 StringRef Blob;
1057 unsigned Code = Cursor.ReadCode();
1058 unsigned RecCode = Cursor.readRecord(Code, Record, &Blob);
1059 if (RecCode != DECL_CONTEXT_LEXICAL) {
1060 Error("Expected lexical block");
1061 return true;
Guy Benyei11169dd2012-12-18 14:30:41 +00001062 }
1063
Richard Smith82f8fcd2015-08-06 22:07:25 +00001064 assert(!isa<TranslationUnitDecl>(DC) &&
1065 "expected a TU_UPDATE_LEXICAL record for TU");
Richard Smith9c9173d2015-08-11 22:00:24 +00001066 // If we are handling a C++ class template instantiation, we can see multiple
1067 // lexical updates for the same record. It's important that we select only one
1068 // of them, so that field numbering works properly. Just pick the first one we
1069 // see.
1070 auto &Lex = LexicalDecls[DC];
1071 if (!Lex.first) {
1072 Lex = std::make_pair(
1073 &M, llvm::makeArrayRef(
1074 reinterpret_cast<const llvm::support::unaligned_uint32_t *>(
1075 Blob.data()),
1076 Blob.size() / 4));
1077 }
Richard Smith0f4e2c42015-08-06 04:23:48 +00001078 DC->setHasExternalLexicalStorage(true);
1079 return false;
1080}
Guy Benyei11169dd2012-12-18 14:30:41 +00001081
Richard Smith0f4e2c42015-08-06 04:23:48 +00001082bool ASTReader::ReadVisibleDeclContextStorage(ModuleFile &M,
1083 BitstreamCursor &Cursor,
1084 uint64_t Offset,
1085 DeclID ID) {
1086 assert(Offset != 0);
1087
1088 SavedStreamPosition SavedPosition(Cursor);
1089 Cursor.JumpToBit(Offset);
1090
1091 RecordData Record;
1092 StringRef Blob;
1093 unsigned Code = Cursor.ReadCode();
1094 unsigned RecCode = Cursor.readRecord(Code, Record, &Blob);
1095 if (RecCode != DECL_CONTEXT_VISIBLE) {
1096 Error("Expected visible lookup table block");
1097 return true;
Guy Benyei11169dd2012-12-18 14:30:41 +00001098 }
1099
Richard Smith0f4e2c42015-08-06 04:23:48 +00001100 // We can't safely determine the primary context yet, so delay attaching the
1101 // lookup table until we're done with recursive deserialization.
Richard Smithd88a7f12015-09-01 20:35:42 +00001102 auto *Data = (const unsigned char*)Blob.data();
1103 PendingVisibleUpdates[ID].push_back(PendingVisibleUpdate{&M, Data});
Guy Benyei11169dd2012-12-18 14:30:41 +00001104 return false;
1105}
1106
1107void ASTReader::Error(StringRef Msg) {
1108 Error(diag::err_fe_pch_malformed, Msg);
Richard Smithfb1e7f72015-08-14 05:02:58 +00001109 if (Context.getLangOpts().Modules && !Diags.isDiagnosticInFlight() &&
1110 !PP.getHeaderSearchInfo().getModuleCachePath().empty()) {
Douglas Gregor940e8052013-05-10 22:15:13 +00001111 Diag(diag::note_module_cache_path)
1112 << PP.getHeaderSearchInfo().getModuleCachePath();
1113 }
Guy Benyei11169dd2012-12-18 14:30:41 +00001114}
1115
1116void ASTReader::Error(unsigned DiagID,
1117 StringRef Arg1, StringRef Arg2) {
1118 if (Diags.isDiagnosticInFlight())
1119 Diags.SetDelayedDiagnostic(DiagID, Arg1, Arg2);
1120 else
1121 Diag(DiagID) << Arg1 << Arg2;
1122}
1123
1124//===----------------------------------------------------------------------===//
1125// Source Manager Deserialization
1126//===----------------------------------------------------------------------===//
1127
1128/// \brief Read the line table in the source manager block.
1129/// \returns true if there was an error.
1130bool ASTReader::ParseLineTable(ModuleFile &F,
Richard Smith7ed1bc92014-12-05 22:42:13 +00001131 const RecordData &Record) {
Guy Benyei11169dd2012-12-18 14:30:41 +00001132 unsigned Idx = 0;
1133 LineTableInfo &LineTable = SourceMgr.getLineTable();
1134
1135 // Parse the file names
1136 std::map<int, int> FileIDs;
Richard Smith63078492015-09-01 07:41:55 +00001137 for (unsigned I = 0; Record[Idx]; ++I) {
Guy Benyei11169dd2012-12-18 14:30:41 +00001138 // Extract the file name
Richard Smith7ed1bc92014-12-05 22:42:13 +00001139 auto Filename = ReadPath(F, Record, Idx);
Guy Benyei11169dd2012-12-18 14:30:41 +00001140 FileIDs[I] = LineTable.getLineTableFilenameID(Filename);
1141 }
Richard Smith63078492015-09-01 07:41:55 +00001142 ++Idx;
Guy Benyei11169dd2012-12-18 14:30:41 +00001143
1144 // Parse the line entries
1145 std::vector<LineEntry> Entries;
1146 while (Idx < Record.size()) {
1147 int FID = Record[Idx++];
1148 assert(FID >= 0 && "Serialized line entries for non-local file.");
1149 // Remap FileID from 1-based old view.
1150 FID += F.SLocEntryBaseID - 1;
1151
1152 // Extract the line entries
1153 unsigned NumEntries = Record[Idx++];
Richard Smith63078492015-09-01 07:41:55 +00001154 assert(NumEntries && "no line entries for file ID");
Guy Benyei11169dd2012-12-18 14:30:41 +00001155 Entries.clear();
1156 Entries.reserve(NumEntries);
1157 for (unsigned I = 0; I != NumEntries; ++I) {
1158 unsigned FileOffset = Record[Idx++];
1159 unsigned LineNo = Record[Idx++];
1160 int FilenameID = FileIDs[Record[Idx++]];
1161 SrcMgr::CharacteristicKind FileKind
1162 = (SrcMgr::CharacteristicKind)Record[Idx++];
1163 unsigned IncludeOffset = Record[Idx++];
1164 Entries.push_back(LineEntry::get(FileOffset, LineNo, FilenameID,
1165 FileKind, IncludeOffset));
1166 }
1167 LineTable.AddEntry(FileID::get(FID), Entries);
1168 }
1169
1170 return false;
1171}
1172
1173/// \brief Read a source manager block
1174bool ASTReader::ReadSourceManagerBlock(ModuleFile &F) {
1175 using namespace SrcMgr;
1176
Chris Lattner7fb3bef2013-01-20 00:56:42 +00001177 BitstreamCursor &SLocEntryCursor = F.SLocEntryCursor;
Guy Benyei11169dd2012-12-18 14:30:41 +00001178
1179 // Set the source-location entry cursor to the current position in
1180 // the stream. This cursor will be used to read the contents of the
1181 // source manager block initially, and then lazily read
1182 // source-location entries as needed.
1183 SLocEntryCursor = F.Stream;
1184
1185 // The stream itself is going to skip over the source manager block.
1186 if (F.Stream.SkipBlock()) {
1187 Error("malformed block record in AST file");
1188 return true;
1189 }
1190
1191 // Enter the source manager block.
1192 if (SLocEntryCursor.EnterSubBlock(SOURCE_MANAGER_BLOCK_ID)) {
1193 Error("malformed source manager block record in AST file");
1194 return true;
1195 }
1196
1197 RecordData Record;
1198 while (true) {
Chris Lattnere7b154b2013-01-19 21:39:22 +00001199 llvm::BitstreamEntry E = SLocEntryCursor.advanceSkippingSubblocks();
David L. Jonesc4808b9e2016-12-15 20:53:26 +00001200
Chris Lattnere7b154b2013-01-19 21:39:22 +00001201 switch (E.Kind) {
1202 case llvm::BitstreamEntry::SubBlock: // Handled for us already.
1203 case llvm::BitstreamEntry::Error:
1204 Error("malformed block record in AST file");
1205 return true;
1206 case llvm::BitstreamEntry::EndBlock:
Guy Benyei11169dd2012-12-18 14:30:41 +00001207 return false;
Chris Lattnere7b154b2013-01-19 21:39:22 +00001208 case llvm::BitstreamEntry::Record:
1209 // The interesting case.
1210 break;
Guy Benyei11169dd2012-12-18 14:30:41 +00001211 }
David L. Jonesc4808b9e2016-12-15 20:53:26 +00001212
Guy Benyei11169dd2012-12-18 14:30:41 +00001213 // Read a record.
Guy Benyei11169dd2012-12-18 14:30:41 +00001214 Record.clear();
Chris Lattner15c3e7d2013-01-21 18:28:26 +00001215 StringRef Blob;
1216 switch (SLocEntryCursor.readRecord(E.ID, Record, &Blob)) {
Guy Benyei11169dd2012-12-18 14:30:41 +00001217 default: // Default behavior: ignore.
1218 break;
1219
1220 case SM_SLOC_FILE_ENTRY:
1221 case SM_SLOC_BUFFER_ENTRY:
1222 case SM_SLOC_EXPANSION_ENTRY:
1223 // Once we hit one of the source location entries, we're done.
1224 return false;
1225 }
1226 }
1227}
1228
1229/// \brief If a header file is not found at the path that we expect it to be
1230/// and the PCH file was moved from its original location, try to resolve the
1231/// file by assuming that header+PCH were moved together and the header is in
1232/// the same place relative to the PCH.
1233static std::string
1234resolveFileRelativeToOriginalDir(const std::string &Filename,
1235 const std::string &OriginalDir,
1236 const std::string &CurrDir) {
1237 assert(OriginalDir != CurrDir &&
1238 "No point trying to resolve the file if the PCH dir didn't change");
1239 using namespace llvm::sys;
1240 SmallString<128> filePath(Filename);
1241 fs::make_absolute(filePath);
1242 assert(path::is_absolute(OriginalDir));
1243 SmallString<128> currPCHPath(CurrDir);
1244
1245 path::const_iterator fileDirI = path::begin(path::parent_path(filePath)),
1246 fileDirE = path::end(path::parent_path(filePath));
1247 path::const_iterator origDirI = path::begin(OriginalDir),
1248 origDirE = path::end(OriginalDir);
1249 // Skip the common path components from filePath and OriginalDir.
1250 while (fileDirI != fileDirE && origDirI != origDirE &&
1251 *fileDirI == *origDirI) {
1252 ++fileDirI;
1253 ++origDirI;
1254 }
1255 for (; origDirI != origDirE; ++origDirI)
1256 path::append(currPCHPath, "..");
1257 path::append(currPCHPath, fileDirI, fileDirE);
1258 path::append(currPCHPath, path::filename(Filename));
1259 return currPCHPath.str();
1260}
1261
1262bool ASTReader::ReadSLocEntry(int ID) {
1263 if (ID == 0)
1264 return false;
1265
1266 if (unsigned(-ID) - 2 >= getTotalNumSLocs() || ID > 0) {
1267 Error("source location entry ID out-of-range for AST file");
1268 return true;
1269 }
1270
Richard Smithaada85c2016-02-06 02:06:43 +00001271 // Local helper to read the (possibly-compressed) buffer data following the
1272 // entry record.
1273 auto ReadBuffer = [this](
1274 BitstreamCursor &SLocEntryCursor,
1275 StringRef Name) -> std::unique_ptr<llvm::MemoryBuffer> {
1276 RecordData Record;
1277 StringRef Blob;
1278 unsigned Code = SLocEntryCursor.ReadCode();
1279 unsigned RecCode = SLocEntryCursor.readRecord(Code, Record, &Blob);
1280
1281 if (RecCode == SM_SLOC_BUFFER_BLOB_COMPRESSED) {
George Rimarc39f5492017-01-17 15:45:31 +00001282 if (!llvm::zlib::isAvailable()) {
1283 Error("zlib is not available");
1284 return nullptr;
1285 }
Richard Smithaada85c2016-02-06 02:06:43 +00001286 SmallString<0> Uncompressed;
George Rimarc39f5492017-01-17 15:45:31 +00001287 if (llvm::Error E =
1288 llvm::zlib::uncompress(Blob, Uncompressed, Record[0])) {
1289 Error("could not decompress embedded file contents: " +
1290 llvm::toString(std::move(E)));
Richard Smithaada85c2016-02-06 02:06:43 +00001291 return nullptr;
1292 }
1293 return llvm::MemoryBuffer::getMemBufferCopy(Uncompressed, Name);
1294 } else if (RecCode == SM_SLOC_BUFFER_BLOB) {
1295 return llvm::MemoryBuffer::getMemBuffer(Blob.drop_back(1), Name, true);
1296 } else {
1297 Error("AST record has invalid code");
1298 return nullptr;
1299 }
1300 };
1301
Guy Benyei11169dd2012-12-18 14:30:41 +00001302 ModuleFile *F = GlobalSLocEntryMap.find(-ID)->second;
1303 F->SLocEntryCursor.JumpToBit(F->SLocEntryOffsets[ID - F->SLocEntryBaseID]);
Chris Lattner7fb3bef2013-01-20 00:56:42 +00001304 BitstreamCursor &SLocEntryCursor = F->SLocEntryCursor;
Guy Benyei11169dd2012-12-18 14:30:41 +00001305 unsigned BaseOffset = F->SLocEntryBaseOffset;
1306
1307 ++NumSLocEntriesRead;
Chris Lattnere7b154b2013-01-19 21:39:22 +00001308 llvm::BitstreamEntry Entry = SLocEntryCursor.advance();
1309 if (Entry.Kind != llvm::BitstreamEntry::Record) {
Guy Benyei11169dd2012-12-18 14:30:41 +00001310 Error("incorrectly-formatted source location entry in AST file");
1311 return true;
1312 }
David L. Jonesc4808b9e2016-12-15 20:53:26 +00001313
Guy Benyei11169dd2012-12-18 14:30:41 +00001314 RecordData Record;
Chris Lattner0e6c9402013-01-20 02:38:54 +00001315 StringRef Blob;
1316 switch (SLocEntryCursor.readRecord(Entry.ID, Record, &Blob)) {
Guy Benyei11169dd2012-12-18 14:30:41 +00001317 default:
1318 Error("incorrectly-formatted source location entry in AST file");
1319 return true;
1320
1321 case SM_SLOC_FILE_ENTRY: {
1322 // We will detect whether a file changed and return 'Failure' for it, but
1323 // we will also try to fail gracefully by setting up the SLocEntry.
1324 unsigned InputID = Record[4];
1325 InputFile IF = getInputFile(*F, InputID);
Argyrios Kyrtzidis61c3d872013-03-01 03:26:04 +00001326 const FileEntry *File = IF.getFile();
1327 bool OverriddenBuffer = IF.isOverridden();
Guy Benyei11169dd2012-12-18 14:30:41 +00001328
Argyrios Kyrtzidis61c3d872013-03-01 03:26:04 +00001329 // Note that we only check if a File was returned. If it was out-of-date
1330 // we have complained but we will continue creating a FileID to recover
1331 // gracefully.
1332 if (!File)
Guy Benyei11169dd2012-12-18 14:30:41 +00001333 return true;
1334
1335 SourceLocation IncludeLoc = ReadSourceLocation(*F, Record[1]);
1336 if (IncludeLoc.isInvalid() && F->Kind != MK_MainFile) {
1337 // This is the module's main file.
1338 IncludeLoc = getImportLocation(F);
1339 }
1340 SrcMgr::CharacteristicKind
1341 FileCharacter = (SrcMgr::CharacteristicKind)Record[2];
1342 FileID FID = SourceMgr.createFileID(File, IncludeLoc, FileCharacter,
1343 ID, BaseOffset + Record[0]);
1344 SrcMgr::FileInfo &FileInfo =
1345 const_cast<SrcMgr::FileInfo&>(SourceMgr.getSLocEntry(FID).getFile());
1346 FileInfo.NumCreatedFIDs = Record[5];
1347 if (Record[3])
1348 FileInfo.setHasLineDirectives();
1349
1350 const DeclID *FirstDecl = F->FileSortedDecls + Record[6];
1351 unsigned NumFileDecls = Record[7];
1352 if (NumFileDecls) {
1353 assert(F->FileSortedDecls && "FILE_SORTED_DECLS not encountered yet ?");
1354 FileDeclIDs[FID] = FileDeclsInfo(F, llvm::makeArrayRef(FirstDecl,
1355 NumFileDecls));
1356 }
Richard Smithaada85c2016-02-06 02:06:43 +00001357
Guy Benyei11169dd2012-12-18 14:30:41 +00001358 const SrcMgr::ContentCache *ContentCache
1359 = SourceMgr.getOrCreateContentCache(File,
1360 /*isSystemFile=*/FileCharacter != SrcMgr::C_User);
1361 if (OverriddenBuffer && !ContentCache->BufferOverridden &&
Richard Smitha8cfffa2015-11-26 02:04:16 +00001362 ContentCache->ContentsEntry == ContentCache->OrigEntry &&
1363 !ContentCache->getRawBuffer()) {
Richard Smithaada85c2016-02-06 02:06:43 +00001364 auto Buffer = ReadBuffer(SLocEntryCursor, File->getName());
1365 if (!Buffer)
Guy Benyei11169dd2012-12-18 14:30:41 +00001366 return true;
David Blaikie49cc3182014-08-27 20:54:45 +00001367 SourceMgr.overrideFileContents(File, std::move(Buffer));
Guy Benyei11169dd2012-12-18 14:30:41 +00001368 }
1369
1370 break;
1371 }
1372
1373 case SM_SLOC_BUFFER_ENTRY: {
Chris Lattner0e6c9402013-01-20 02:38:54 +00001374 const char *Name = Blob.data();
Guy Benyei11169dd2012-12-18 14:30:41 +00001375 unsigned Offset = Record[0];
1376 SrcMgr::CharacteristicKind
1377 FileCharacter = (SrcMgr::CharacteristicKind)Record[2];
1378 SourceLocation IncludeLoc = ReadSourceLocation(*F, Record[1]);
Manman Ren11f2a472016-08-18 17:42:15 +00001379 if (IncludeLoc.isInvalid() && F->isModule()) {
Guy Benyei11169dd2012-12-18 14:30:41 +00001380 IncludeLoc = getImportLocation(F);
1381 }
Guy Benyei11169dd2012-12-18 14:30:41 +00001382
Richard Smithaada85c2016-02-06 02:06:43 +00001383 auto Buffer = ReadBuffer(SLocEntryCursor, Name);
1384 if (!Buffer)
Guy Benyei11169dd2012-12-18 14:30:41 +00001385 return true;
David Blaikie50a5f972014-08-29 07:59:55 +00001386 SourceMgr.createFileID(std::move(Buffer), FileCharacter, ID,
Rafael Espindolad87f8d72014-08-27 20:03:29 +00001387 BaseOffset + Offset, IncludeLoc);
Guy Benyei11169dd2012-12-18 14:30:41 +00001388 break;
1389 }
1390
1391 case SM_SLOC_EXPANSION_ENTRY: {
1392 SourceLocation SpellingLoc = ReadSourceLocation(*F, Record[1]);
1393 SourceMgr.createExpansionLoc(SpellingLoc,
1394 ReadSourceLocation(*F, Record[2]),
1395 ReadSourceLocation(*F, Record[3]),
1396 Record[4],
1397 ID,
1398 BaseOffset + Record[0]);
1399 break;
1400 }
1401 }
1402
1403 return false;
1404}
1405
1406std::pair<SourceLocation, StringRef> ASTReader::getModuleImportLoc(int ID) {
1407 if (ID == 0)
1408 return std::make_pair(SourceLocation(), "");
1409
1410 if (unsigned(-ID) - 2 >= getTotalNumSLocs() || ID > 0) {
1411 Error("source location entry ID out-of-range for AST file");
1412 return std::make_pair(SourceLocation(), "");
1413 }
1414
1415 // Find which module file this entry lands in.
1416 ModuleFile *M = GlobalSLocEntryMap.find(-ID)->second;
Manman Ren11f2a472016-08-18 17:42:15 +00001417 if (!M->isModule())
Guy Benyei11169dd2012-12-18 14:30:41 +00001418 return std::make_pair(SourceLocation(), "");
1419
1420 // FIXME: Can we map this down to a particular submodule? That would be
1421 // ideal.
Ben Langmuirbeee15e2014-04-14 18:00:01 +00001422 return std::make_pair(M->ImportLoc, StringRef(M->ModuleName));
Guy Benyei11169dd2012-12-18 14:30:41 +00001423}
1424
1425/// \brief Find the location where the module F is imported.
1426SourceLocation ASTReader::getImportLocation(ModuleFile *F) {
1427 if (F->ImportLoc.isValid())
1428 return F->ImportLoc;
David L. Jonesc4808b9e2016-12-15 20:53:26 +00001429
Guy Benyei11169dd2012-12-18 14:30:41 +00001430 // Otherwise we have a PCH. It's considered to be "imported" at the first
1431 // location of its includer.
1432 if (F->ImportedBy.empty() || !F->ImportedBy[0]) {
Ben Langmuirbeee15e2014-04-14 18:00:01 +00001433 // Main file is the importer.
Yaron Keren8b563662015-10-03 10:46:20 +00001434 assert(SourceMgr.getMainFileID().isValid() && "missing main file");
Ben Langmuirbeee15e2014-04-14 18:00:01 +00001435 return SourceMgr.getLocForStartOfFile(SourceMgr.getMainFileID());
Guy Benyei11169dd2012-12-18 14:30:41 +00001436 }
Guy Benyei11169dd2012-12-18 14:30:41 +00001437 return F->ImportedBy[0]->FirstLoc;
1438}
1439
1440/// ReadBlockAbbrevs - Enter a subblock of the specified BlockID with the
1441/// specified cursor. Read the abbreviations that are at the top of the block
1442/// and then leave the cursor pointing into the block.
Chris Lattner7fb3bef2013-01-20 00:56:42 +00001443bool ASTReader::ReadBlockAbbrevs(BitstreamCursor &Cursor, unsigned BlockID) {
Richard Smith0516b182015-09-08 19:40:14 +00001444 if (Cursor.EnterSubBlock(BlockID))
1445 return true;
Guy Benyei11169dd2012-12-18 14:30:41 +00001446
1447 while (true) {
1448 uint64_t Offset = Cursor.GetCurrentBitNo();
1449 unsigned Code = Cursor.ReadCode();
1450
1451 // We expect all abbrevs to be at the start of the block.
1452 if (Code != llvm::bitc::DEFINE_ABBREV) {
1453 Cursor.JumpToBit(Offset);
1454 return false;
1455 }
1456 Cursor.ReadAbbrevRecord();
1457 }
1458}
1459
Richard Smithe40f2ba2013-08-07 21:41:30 +00001460Token ASTReader::ReadToken(ModuleFile &F, const RecordDataImpl &Record,
John McCallf413f5e2013-05-03 00:10:13 +00001461 unsigned &Idx) {
1462 Token Tok;
1463 Tok.startToken();
1464 Tok.setLocation(ReadSourceLocation(F, Record, Idx));
1465 Tok.setLength(Record[Idx++]);
1466 if (IdentifierInfo *II = getLocalIdentifier(F, Record[Idx++]))
1467 Tok.setIdentifierInfo(II);
1468 Tok.setKind((tok::TokenKind)Record[Idx++]);
1469 Tok.setFlag((Token::TokenFlags)Record[Idx++]);
1470 return Tok;
1471}
1472
Argyrios Kyrtzidiseb663da2013-03-22 21:12:57 +00001473MacroInfo *ASTReader::ReadMacroRecord(ModuleFile &F, uint64_t Offset) {
Chris Lattner7fb3bef2013-01-20 00:56:42 +00001474 BitstreamCursor &Stream = F.MacroCursor;
Guy Benyei11169dd2012-12-18 14:30:41 +00001475
1476 // Keep track of where we are in the stream, then jump back there
1477 // after reading this macro.
1478 SavedStreamPosition SavedPosition(Stream);
1479
1480 Stream.JumpToBit(Offset);
1481 RecordData Record;
1482 SmallVector<IdentifierInfo*, 16> MacroArgs;
Craig Toppera13603a2014-05-22 05:54:18 +00001483 MacroInfo *Macro = nullptr;
Guy Benyei11169dd2012-12-18 14:30:41 +00001484
Guy Benyei11169dd2012-12-18 14:30:41 +00001485 while (true) {
Chris Lattnerefa77172013-01-20 00:00:22 +00001486 // Advance to the next record, but if we get to the end of the block, don't
1487 // pop it (removing all the abbreviations from the cursor) since we want to
1488 // be able to reseek within the block and read entries.
Chris Lattner7fb3bef2013-01-20 00:56:42 +00001489 unsigned Flags = BitstreamCursor::AF_DontPopBlockAtEnd;
Chris Lattnerefa77172013-01-20 00:00:22 +00001490 llvm::BitstreamEntry Entry = Stream.advanceSkippingSubblocks(Flags);
David L. Jonesc4808b9e2016-12-15 20:53:26 +00001491
Chris Lattnerefa77172013-01-20 00:00:22 +00001492 switch (Entry.Kind) {
1493 case llvm::BitstreamEntry::SubBlock: // Handled for us already.
1494 case llvm::BitstreamEntry::Error:
1495 Error("malformed block record in AST file");
Argyrios Kyrtzidiseb663da2013-03-22 21:12:57 +00001496 return Macro;
Chris Lattnerefa77172013-01-20 00:00:22 +00001497 case llvm::BitstreamEntry::EndBlock:
Argyrios Kyrtzidiseb663da2013-03-22 21:12:57 +00001498 return Macro;
Chris Lattnerefa77172013-01-20 00:00:22 +00001499 case llvm::BitstreamEntry::Record:
1500 // The interesting case.
1501 break;
Guy Benyei11169dd2012-12-18 14:30:41 +00001502 }
1503
1504 // Read a record.
Guy Benyei11169dd2012-12-18 14:30:41 +00001505 Record.clear();
1506 PreprocessorRecordTypes RecType =
Chris Lattner0e6c9402013-01-20 02:38:54 +00001507 (PreprocessorRecordTypes)Stream.readRecord(Entry.ID, Record);
Guy Benyei11169dd2012-12-18 14:30:41 +00001508 switch (RecType) {
Richard Smithd7329392015-04-21 21:46:32 +00001509 case PP_MODULE_MACRO:
Argyrios Kyrtzidiseb663da2013-03-22 21:12:57 +00001510 case PP_MACRO_DIRECTIVE_HISTORY:
1511 return Macro;
1512
Guy Benyei11169dd2012-12-18 14:30:41 +00001513 case PP_MACRO_OBJECT_LIKE:
1514 case PP_MACRO_FUNCTION_LIKE: {
1515 // If we already have a macro, that means that we've hit the end
1516 // of the definition of the macro we were looking for. We're
1517 // done.
1518 if (Macro)
Argyrios Kyrtzidiseb663da2013-03-22 21:12:57 +00001519 return Macro;
Guy Benyei11169dd2012-12-18 14:30:41 +00001520
Argyrios Kyrtzidiseb663da2013-03-22 21:12:57 +00001521 unsigned NextIndex = 1; // Skip identifier ID.
1522 SubmoduleID SubModID = getGlobalSubmoduleID(F, Record[NextIndex++]);
Guy Benyei11169dd2012-12-18 14:30:41 +00001523 SourceLocation Loc = ReadSourceLocation(F, Record, NextIndex);
Argyrios Kyrtzidiseb663da2013-03-22 21:12:57 +00001524 MacroInfo *MI = PP.AllocateDeserializedMacroInfo(Loc, SubModID);
Argyrios Kyrtzidis7572be22013-01-07 19:16:23 +00001525 MI->setDefinitionEndLoc(ReadSourceLocation(F, Record, NextIndex));
Guy Benyei11169dd2012-12-18 14:30:41 +00001526 MI->setIsUsed(Record[NextIndex++]);
Argyrios Kyrtzidis9ef53ce2014-04-09 18:21:23 +00001527 MI->setUsedForHeaderGuard(Record[NextIndex++]);
Guy Benyei11169dd2012-12-18 14:30:41 +00001528
Guy Benyei11169dd2012-12-18 14:30:41 +00001529 if (RecType == PP_MACRO_FUNCTION_LIKE) {
1530 // Decode function-like macro info.
1531 bool isC99VarArgs = Record[NextIndex++];
1532 bool isGNUVarArgs = Record[NextIndex++];
1533 bool hasCommaPasting = Record[NextIndex++];
1534 MacroArgs.clear();
1535 unsigned NumArgs = Record[NextIndex++];
1536 for (unsigned i = 0; i != NumArgs; ++i)
1537 MacroArgs.push_back(getLocalIdentifier(F, Record[NextIndex++]));
1538
1539 // Install function-like macro info.
1540 MI->setIsFunctionLike();
1541 if (isC99VarArgs) MI->setIsC99Varargs();
1542 if (isGNUVarArgs) MI->setIsGNUVarargs();
1543 if (hasCommaPasting) MI->setHasCommaPasting();
Craig Topperd96b3f92015-10-22 04:59:52 +00001544 MI->setArgumentList(MacroArgs, PP.getPreprocessorAllocator());
Guy Benyei11169dd2012-12-18 14:30:41 +00001545 }
1546
Guy Benyei11169dd2012-12-18 14:30:41 +00001547 // Remember that we saw this macro last so that we add the tokens that
1548 // form its body to it.
1549 Macro = MI;
1550
1551 if (NextIndex + 1 == Record.size() && PP.getPreprocessingRecord() &&
1552 Record[NextIndex]) {
1553 // We have a macro definition. Register the association
1554 PreprocessedEntityID
1555 GlobalID = getGlobalPreprocessedEntityID(F, Record[NextIndex]);
1556 PreprocessingRecord &PPRec = *PP.getPreprocessingRecord();
Richard Smith66a81862015-05-04 02:25:31 +00001557 PreprocessingRecord::PPEntityID PPID =
1558 PPRec.getPPEntityID(GlobalID - 1, /*isLoaded=*/true);
1559 MacroDefinitionRecord *PPDef = cast_or_null<MacroDefinitionRecord>(
1560 PPRec.getPreprocessedEntity(PPID));
Argyrios Kyrtzidis832de9f2013-02-22 18:35:59 +00001561 if (PPDef)
1562 PPRec.RegisterMacroDefinition(Macro, PPDef);
Guy Benyei11169dd2012-12-18 14:30:41 +00001563 }
1564
1565 ++NumMacrosRead;
1566 break;
1567 }
1568
1569 case PP_TOKEN: {
1570 // If we see a TOKEN before a PP_MACRO_*, then the file is
1571 // erroneous, just pretend we didn't see this.
Craig Toppera13603a2014-05-22 05:54:18 +00001572 if (!Macro) break;
Guy Benyei11169dd2012-12-18 14:30:41 +00001573
John McCallf413f5e2013-05-03 00:10:13 +00001574 unsigned Idx = 0;
1575 Token Tok = ReadToken(F, Record, Idx);
Guy Benyei11169dd2012-12-18 14:30:41 +00001576 Macro->AddTokenToBody(Tok);
1577 break;
1578 }
1579 }
1580 }
1581}
1582
David L. Jonesc4808b9e2016-12-15 20:53:26 +00001583PreprocessedEntityID
Guy Benyei11169dd2012-12-18 14:30:41 +00001584ASTReader::getGlobalPreprocessedEntityID(ModuleFile &M, unsigned LocalID) const {
David L. Jonesc4808b9e2016-12-15 20:53:26 +00001585 ContinuousRangeMap<uint32_t, int, 2>::const_iterator
Guy Benyei11169dd2012-12-18 14:30:41 +00001586 I = M.PreprocessedEntityRemap.find(LocalID - NUM_PREDEF_PP_ENTITY_IDS);
David L. Jonesc4808b9e2016-12-15 20:53:26 +00001587 assert(I != M.PreprocessedEntityRemap.end()
Guy Benyei11169dd2012-12-18 14:30:41 +00001588 && "Invalid index into preprocessed entity index remap");
David L. Jonesc4808b9e2016-12-15 20:53:26 +00001589
Guy Benyei11169dd2012-12-18 14:30:41 +00001590 return LocalID + I->second;
1591}
1592
Argyrios Kyrtzidis5c2a3452013-03-06 18:12:47 +00001593unsigned HeaderFileInfoTrait::ComputeHash(internal_key_ref ikey) {
1594 return llvm::hash_combine(ikey.Size, ikey.ModTime);
Guy Benyei11169dd2012-12-18 14:30:41 +00001595}
Richard Smith7ed1bc92014-12-05 22:42:13 +00001596
David L. Jonesc4808b9e2016-12-15 20:53:26 +00001597HeaderFileInfoTrait::internal_key_type
Argyrios Kyrtzidis5c2a3452013-03-06 18:12:47 +00001598HeaderFileInfoTrait::GetInternalKey(const FileEntry *FE) {
Richard Smithe75ee0f2015-08-17 07:13:32 +00001599 internal_key_type ikey = {FE->getSize(),
1600 M.HasTimestamps ? FE->getModificationTime() : 0,
1601 FE->getName(), /*Imported*/ false};
Argyrios Kyrtzidis5c2a3452013-03-06 18:12:47 +00001602 return ikey;
1603}
David L. Jonesc4808b9e2016-12-15 20:53:26 +00001604
Argyrios Kyrtzidis5c2a3452013-03-06 18:12:47 +00001605bool HeaderFileInfoTrait::EqualKey(internal_key_ref a, internal_key_ref b) {
Richard Smithe75ee0f2015-08-17 07:13:32 +00001606 if (a.Size != b.Size || (a.ModTime && b.ModTime && a.ModTime != b.ModTime))
Guy Benyei11169dd2012-12-18 14:30:41 +00001607 return false;
1608
Mehdi Amini004b9c72016-10-10 22:52:47 +00001609 if (llvm::sys::path::is_absolute(a.Filename) && a.Filename == b.Filename)
Argyrios Kyrtzidis5c2a3452013-03-06 18:12:47 +00001610 return true;
David L. Jonesc4808b9e2016-12-15 20:53:26 +00001611
Guy Benyei11169dd2012-12-18 14:30:41 +00001612 // Determine whether the actual files are equivalent.
Argyrios Kyrtzidis2a513e82013-03-04 20:33:40 +00001613 FileManager &FileMgr = Reader.getFileManager();
Richard Smith7ed1bc92014-12-05 22:42:13 +00001614 auto GetFile = [&](const internal_key_type &Key) -> const FileEntry* {
1615 if (!Key.Imported)
1616 return FileMgr.getFile(Key.Filename);
1617
1618 std::string Resolved = Key.Filename;
1619 Reader.ResolveImportedPath(M, Resolved);
1620 return FileMgr.getFile(Resolved);
1621 };
1622
1623 const FileEntry *FEA = GetFile(a);
1624 const FileEntry *FEB = GetFile(b);
1625 return FEA && FEA == FEB;
Guy Benyei11169dd2012-12-18 14:30:41 +00001626}
David L. Jonesc4808b9e2016-12-15 20:53:26 +00001627
Guy Benyei11169dd2012-12-18 14:30:41 +00001628std::pair<unsigned, unsigned>
1629HeaderFileInfoTrait::ReadKeyDataLength(const unsigned char*& d) {
Justin Bogner57ba0b22014-03-28 22:03:24 +00001630 using namespace llvm::support;
1631 unsigned KeyLen = (unsigned) endian::readNext<uint16_t, little, unaligned>(d);
Guy Benyei11169dd2012-12-18 14:30:41 +00001632 unsigned DataLen = (unsigned) *d++;
Argyrios Kyrtzidis5c2a3452013-03-06 18:12:47 +00001633 return std::make_pair(KeyLen, DataLen);
Guy Benyei11169dd2012-12-18 14:30:41 +00001634}
Argyrios Kyrtzidis5c2a3452013-03-06 18:12:47 +00001635
1636HeaderFileInfoTrait::internal_key_type
1637HeaderFileInfoTrait::ReadKey(const unsigned char *d, unsigned) {
Justin Bogner57ba0b22014-03-28 22:03:24 +00001638 using namespace llvm::support;
Argyrios Kyrtzidis5c2a3452013-03-06 18:12:47 +00001639 internal_key_type ikey;
Justin Bogner57ba0b22014-03-28 22:03:24 +00001640 ikey.Size = off_t(endian::readNext<uint64_t, little, unaligned>(d));
1641 ikey.ModTime = time_t(endian::readNext<uint64_t, little, unaligned>(d));
Argyrios Kyrtzidis5c2a3452013-03-06 18:12:47 +00001642 ikey.Filename = (const char *)d;
Richard Smith7ed1bc92014-12-05 22:42:13 +00001643 ikey.Imported = true;
Argyrios Kyrtzidis5c2a3452013-03-06 18:12:47 +00001644 return ikey;
1645}
1646
David L. Jonesc4808b9e2016-12-15 20:53:26 +00001647HeaderFileInfoTrait::data_type
Argyrios Kyrtzidisb146baa2013-03-13 21:13:51 +00001648HeaderFileInfoTrait::ReadData(internal_key_ref key, const unsigned char *d,
Guy Benyei11169dd2012-12-18 14:30:41 +00001649 unsigned DataLen) {
1650 const unsigned char *End = d + DataLen;
Justin Bogner57ba0b22014-03-28 22:03:24 +00001651 using namespace llvm::support;
Guy Benyei11169dd2012-12-18 14:30:41 +00001652 HeaderFileInfo HFI;
1653 unsigned Flags = *d++;
Richard Smith386bb072015-08-18 23:42:23 +00001654 // FIXME: Refactor with mergeHeaderFileInfo in HeaderSearch.cpp.
1655 HFI.isImport |= (Flags >> 4) & 0x01;
1656 HFI.isPragmaOnce |= (Flags >> 3) & 0x01;
1657 HFI.DirInfo = (Flags >> 1) & 0x03;
Guy Benyei11169dd2012-12-18 14:30:41 +00001658 HFI.IndexHeaderMapHeader = Flags & 0x01;
Richard Smith386bb072015-08-18 23:42:23 +00001659 // FIXME: Find a better way to handle this. Maybe just store a
1660 // "has been included" flag?
1661 HFI.NumIncludes = std::max(endian::readNext<uint16_t, little, unaligned>(d),
1662 HFI.NumIncludes);
Justin Bogner57ba0b22014-03-28 22:03:24 +00001663 HFI.ControllingMacroID = Reader.getGlobalIdentifierID(
1664 M, endian::readNext<uint32_t, little, unaligned>(d));
1665 if (unsigned FrameworkOffset =
1666 endian::readNext<uint32_t, little, unaligned>(d)) {
David L. Jonesc4808b9e2016-12-15 20:53:26 +00001667 // The framework offset is 1 greater than the actual offset,
Guy Benyei11169dd2012-12-18 14:30:41 +00001668 // since 0 is used as an indicator for "no framework name".
1669 StringRef FrameworkName(FrameworkStrings + FrameworkOffset - 1);
1670 HFI.Framework = HS->getUniqueFrameworkName(FrameworkName);
1671 }
Richard Smith386bb072015-08-18 23:42:23 +00001672
1673 assert((End - d) % 4 == 0 &&
1674 "Wrong data length in HeaderFileInfo deserialization");
1675 while (d != End) {
Justin Bogner57ba0b22014-03-28 22:03:24 +00001676 uint32_t LocalSMID = endian::readNext<uint32_t, little, unaligned>(d);
Richard Smith386bb072015-08-18 23:42:23 +00001677 auto HeaderRole = static_cast<ModuleMap::ModuleHeaderRole>(LocalSMID & 3);
1678 LocalSMID >>= 2;
1679
1680 // This header is part of a module. Associate it with the module to enable
1681 // implicit module import.
1682 SubmoduleID GlobalSMID = Reader.getGlobalSubmoduleID(M, LocalSMID);
1683 Module *Mod = Reader.getSubmodule(GlobalSMID);
1684 FileManager &FileMgr = Reader.getFileManager();
1685 ModuleMap &ModMap =
1686 Reader.getPreprocessor().getHeaderSearchInfo().getModuleMap();
1687
1688 std::string Filename = key.Filename;
1689 if (key.Imported)
1690 Reader.ResolveImportedPath(M, Filename);
1691 // FIXME: This is not always the right filename-as-written, but we're not
1692 // going to use this information to rebuild the module, so it doesn't make
1693 // a lot of difference.
1694 Module::Header H = { key.Filename, FileMgr.getFile(Filename) };
Richard Smithd8879c82015-08-24 21:59:32 +00001695 ModMap.addHeader(Mod, H, HeaderRole, /*Imported*/true);
1696 HFI.isModuleHeader |= !(HeaderRole & ModuleMap::TextualHeader);
Argyrios Kyrtzidisb146baa2013-03-13 21:13:51 +00001697 }
1698
Guy Benyei11169dd2012-12-18 14:30:41 +00001699 // This HeaderFileInfo was externally loaded.
1700 HFI.External = true;
Richard Smithd8879c82015-08-24 21:59:32 +00001701 HFI.IsValid = true;
Guy Benyei11169dd2012-12-18 14:30:41 +00001702 return HFI;
1703}
1704
Richard Smithd7329392015-04-21 21:46:32 +00001705void ASTReader::addPendingMacro(IdentifierInfo *II,
1706 ModuleFile *M,
1707 uint64_t MacroDirectivesOffset) {
Argyrios Kyrtzidiseb663da2013-03-22 21:12:57 +00001708 assert(NumCurrentElementsDeserializing > 0 &&"Missing deserialization guard");
1709 PendingMacroIDs[II].push_back(PendingMacroInfo(M, MacroDirectivesOffset));
Guy Benyei11169dd2012-12-18 14:30:41 +00001710}
1711
1712void ASTReader::ReadDefinedMacros() {
1713 // Note that we are loading defined macros.
1714 Deserializing Macros(this);
1715
Pete Cooper57d3f142015-07-30 17:22:52 +00001716 for (auto &I : llvm::reverse(ModuleMgr)) {
1717 BitstreamCursor &MacroCursor = I->MacroCursor;
Guy Benyei11169dd2012-12-18 14:30:41 +00001718
1719 // If there was no preprocessor block, skip this file.
Peter Collingbourne77c89b62016-11-08 04:17:11 +00001720 if (MacroCursor.getBitcodeBytes().empty())
Guy Benyei11169dd2012-12-18 14:30:41 +00001721 continue;
1722
Chris Lattner7fb3bef2013-01-20 00:56:42 +00001723 BitstreamCursor Cursor = MacroCursor;
Pete Cooper57d3f142015-07-30 17:22:52 +00001724 Cursor.JumpToBit(I->MacroStartOffset);
Guy Benyei11169dd2012-12-18 14:30:41 +00001725
1726 RecordData Record;
1727 while (true) {
Chris Lattnere7b154b2013-01-19 21:39:22 +00001728 llvm::BitstreamEntry E = Cursor.advanceSkippingSubblocks();
David L. Jonesc4808b9e2016-12-15 20:53:26 +00001729
Chris Lattnere7b154b2013-01-19 21:39:22 +00001730 switch (E.Kind) {
1731 case llvm::BitstreamEntry::SubBlock: // Handled for us already.
1732 case llvm::BitstreamEntry::Error:
1733 Error("malformed block record in AST file");
1734 return;
1735 case llvm::BitstreamEntry::EndBlock:
1736 goto NextCursor;
David L. Jonesc4808b9e2016-12-15 20:53:26 +00001737
Chris Lattnere7b154b2013-01-19 21:39:22 +00001738 case llvm::BitstreamEntry::Record:
Chris Lattnere7b154b2013-01-19 21:39:22 +00001739 Record.clear();
Chris Lattner0e6c9402013-01-20 02:38:54 +00001740 switch (Cursor.readRecord(E.ID, Record)) {
Chris Lattnere7b154b2013-01-19 21:39:22 +00001741 default: // Default behavior: ignore.
1742 break;
David L. Jonesc4808b9e2016-12-15 20:53:26 +00001743
Chris Lattnere7b154b2013-01-19 21:39:22 +00001744 case PP_MACRO_OBJECT_LIKE:
Sean Callananf3682a72016-05-14 06:24:14 +00001745 case PP_MACRO_FUNCTION_LIKE: {
1746 IdentifierInfo *II = getLocalIdentifier(*I, Record[0]);
1747 if (II->isOutOfDate())
1748 updateOutOfDateIdentifier(*II);
Chris Lattnere7b154b2013-01-19 21:39:22 +00001749 break;
Sean Callananf3682a72016-05-14 06:24:14 +00001750 }
David L. Jonesc4808b9e2016-12-15 20:53:26 +00001751
Chris Lattnere7b154b2013-01-19 21:39:22 +00001752 case PP_TOKEN:
1753 // Ignore tokens.
1754 break;
Guy Benyei11169dd2012-12-18 14:30:41 +00001755 }
Guy Benyei11169dd2012-12-18 14:30:41 +00001756 break;
1757 }
1758 }
Chris Lattnere7b154b2013-01-19 21:39:22 +00001759 NextCursor: ;
Guy Benyei11169dd2012-12-18 14:30:41 +00001760 }
1761}
1762
1763namespace {
Eugene Zelenkoe95e7d52016-09-07 21:53:17 +00001764
Guy Benyei11169dd2012-12-18 14:30:41 +00001765 /// \brief Visitor class used to look up identifirs in an AST file.
1766 class IdentifierLookupVisitor {
1767 StringRef Name;
Richard Smith3b637412015-07-14 18:42:41 +00001768 unsigned NameHash;
Guy Benyei11169dd2012-12-18 14:30:41 +00001769 unsigned PriorGeneration;
Douglas Gregor00a50f72013-01-25 00:38:33 +00001770 unsigned &NumIdentifierLookups;
1771 unsigned &NumIdentifierLookupHits;
Guy Benyei11169dd2012-12-18 14:30:41 +00001772 IdentifierInfo *Found;
Douglas Gregor00a50f72013-01-25 00:38:33 +00001773
Guy Benyei11169dd2012-12-18 14:30:41 +00001774 public:
Douglas Gregor00a50f72013-01-25 00:38:33 +00001775 IdentifierLookupVisitor(StringRef Name, unsigned PriorGeneration,
1776 unsigned &NumIdentifierLookups,
1777 unsigned &NumIdentifierLookupHits)
Richard Smith3b637412015-07-14 18:42:41 +00001778 : Name(Name), NameHash(ASTIdentifierLookupTrait::ComputeHash(Name)),
1779 PriorGeneration(PriorGeneration),
Douglas Gregor00a50f72013-01-25 00:38:33 +00001780 NumIdentifierLookups(NumIdentifierLookups),
1781 NumIdentifierLookupHits(NumIdentifierLookupHits),
1782 Found()
1783 {
1784 }
Benjamin Kramer9a9efba2015-07-25 12:14:04 +00001785
1786 bool operator()(ModuleFile &M) {
Guy Benyei11169dd2012-12-18 14:30:41 +00001787 // If we've already searched this module file, skip it now.
Richard Smithbdf2d932015-07-30 03:37:16 +00001788 if (M.Generation <= PriorGeneration)
Guy Benyei11169dd2012-12-18 14:30:41 +00001789 return true;
Douglas Gregore060e572013-01-25 01:03:03 +00001790
Guy Benyei11169dd2012-12-18 14:30:41 +00001791 ASTIdentifierLookupTable *IdTable
1792 = (ASTIdentifierLookupTable *)M.IdentifierLookupTable;
1793 if (!IdTable)
1794 return false;
Benjamin Kramer9a9efba2015-07-25 12:14:04 +00001795
1796 ASTIdentifierLookupTrait Trait(IdTable->getInfoObj().getReader(), M,
Richard Smithbdf2d932015-07-30 03:37:16 +00001797 Found);
1798 ++NumIdentifierLookups;
Richard Smith3b637412015-07-14 18:42:41 +00001799 ASTIdentifierLookupTable::iterator Pos =
Richard Smithbdf2d932015-07-30 03:37:16 +00001800 IdTable->find_hashed(Name, NameHash, &Trait);
Guy Benyei11169dd2012-12-18 14:30:41 +00001801 if (Pos == IdTable->end())
1802 return false;
David L. Jonesc4808b9e2016-12-15 20:53:26 +00001803
Guy Benyei11169dd2012-12-18 14:30:41 +00001804 // Dereferencing the iterator has the effect of building the
1805 // IdentifierInfo node and populating it with the various
1806 // declarations it needs.
Richard Smithbdf2d932015-07-30 03:37:16 +00001807 ++NumIdentifierLookupHits;
1808 Found = *Pos;
Guy Benyei11169dd2012-12-18 14:30:41 +00001809 return true;
1810 }
David L. Jonesc4808b9e2016-12-15 20:53:26 +00001811
Guy Benyei11169dd2012-12-18 14:30:41 +00001812 // \brief Retrieve the identifier info found within the module
1813 // files.
1814 IdentifierInfo *getIdentifierInfo() const { return Found; }
1815 };
Eugene Zelenkoe95e7d52016-09-07 21:53:17 +00001816
1817} // end anonymous namespace
Guy Benyei11169dd2012-12-18 14:30:41 +00001818
1819void ASTReader::updateOutOfDateIdentifier(IdentifierInfo &II) {
1820 // Note that we are loading an identifier.
1821 Deserializing AnIdentifier(this);
1822
1823 unsigned PriorGeneration = 0;
1824 if (getContext().getLangOpts().Modules)
1825 PriorGeneration = IdentifierGeneration[&II];
Douglas Gregore060e572013-01-25 01:03:03 +00001826
1827 // If there is a global index, look there first to determine which modules
1828 // provably do not have any results for this identifier.
Douglas Gregor7211ac12013-01-25 23:32:03 +00001829 GlobalModuleIndex::HitSet Hits;
Craig Toppera13603a2014-05-22 05:54:18 +00001830 GlobalModuleIndex::HitSet *HitsPtr = nullptr;
Douglas Gregore060e572013-01-25 01:03:03 +00001831 if (!loadGlobalIndex()) {
Douglas Gregor7211ac12013-01-25 23:32:03 +00001832 if (GlobalIndex->lookupIdentifier(II.getName(), Hits)) {
1833 HitsPtr = &Hits;
Douglas Gregore060e572013-01-25 01:03:03 +00001834 }
1835 }
1836
Douglas Gregor7211ac12013-01-25 23:32:03 +00001837 IdentifierLookupVisitor Visitor(II.getName(), PriorGeneration,
Douglas Gregor00a50f72013-01-25 00:38:33 +00001838 NumIdentifierLookups,
1839 NumIdentifierLookupHits);
Benjamin Kramer9a9efba2015-07-25 12:14:04 +00001840 ModuleMgr.visit(Visitor, HitsPtr);
Guy Benyei11169dd2012-12-18 14:30:41 +00001841 markIdentifierUpToDate(&II);
1842}
1843
1844void ASTReader::markIdentifierUpToDate(IdentifierInfo *II) {
1845 if (!II)
1846 return;
David L. Jonesc4808b9e2016-12-15 20:53:26 +00001847
Guy Benyei11169dd2012-12-18 14:30:41 +00001848 II->setOutOfDate(false);
1849
1850 // Update the generation for this identifier.
1851 if (getContext().getLangOpts().Modules)
Richard Smith053f6c62014-05-16 23:01:30 +00001852 IdentifierGeneration[II] = getGeneration();
Guy Benyei11169dd2012-12-18 14:30:41 +00001853}
1854
Argyrios Kyrtzidiseb663da2013-03-22 21:12:57 +00001855void ASTReader::resolvePendingMacro(IdentifierInfo *II,
1856 const PendingMacroInfo &PMInfo) {
Richard Smithd7329392015-04-21 21:46:32 +00001857 ModuleFile &M = *PMInfo.M;
Argyrios Kyrtzidiseb663da2013-03-22 21:12:57 +00001858
1859 BitstreamCursor &Cursor = M.MacroCursor;
1860 SavedStreamPosition SavedPosition(Cursor);
Richard Smithd7329392015-04-21 21:46:32 +00001861 Cursor.JumpToBit(PMInfo.MacroDirectivesOffset);
Argyrios Kyrtzidiseb663da2013-03-22 21:12:57 +00001862
Richard Smith713369b2015-04-23 20:40:50 +00001863 struct ModuleMacroRecord {
1864 SubmoduleID SubModID;
1865 MacroInfo *MI;
1866 SmallVector<SubmoduleID, 8> Overrides;
1867 };
1868 llvm::SmallVector<ModuleMacroRecord, 8> ModuleMacros;
Argyrios Kyrtzidiseb663da2013-03-22 21:12:57 +00001869
Richard Smithd7329392015-04-21 21:46:32 +00001870 // We expect to see a sequence of PP_MODULE_MACRO records listing exported
1871 // macros, followed by a PP_MACRO_DIRECTIVE_HISTORY record with the complete
1872 // macro histroy.
Argyrios Kyrtzidiseb663da2013-03-22 21:12:57 +00001873 RecordData Record;
Richard Smithd7329392015-04-21 21:46:32 +00001874 while (true) {
1875 llvm::BitstreamEntry Entry =
1876 Cursor.advance(BitstreamCursor::AF_DontPopBlockAtEnd);
1877 if (Entry.Kind != llvm::BitstreamEntry::Record) {
1878 Error("malformed block record in AST file");
1879 return;
1880 }
1881
1882 Record.clear();
Aaron Ballmanc75a1922015-04-22 15:25:05 +00001883 switch ((PreprocessorRecordTypes)Cursor.readRecord(Entry.ID, Record)) {
Richard Smithd7329392015-04-21 21:46:32 +00001884 case PP_MACRO_DIRECTIVE_HISTORY:
1885 break;
1886
1887 case PP_MODULE_MACRO: {
Richard Smith713369b2015-04-23 20:40:50 +00001888 ModuleMacros.push_back(ModuleMacroRecord());
1889 auto &Info = ModuleMacros.back();
Richard Smithe56c8bc2015-04-22 00:26:11 +00001890 Info.SubModID = getGlobalSubmoduleID(M, Record[0]);
1891 Info.MI = getMacro(getGlobalMacroID(M, Record[1]));
Richard Smith713369b2015-04-23 20:40:50 +00001892 for (int I = 2, N = Record.size(); I != N; ++I)
1893 Info.Overrides.push_back(getGlobalSubmoduleID(M, Record[I]));
Richard Smithd7329392015-04-21 21:46:32 +00001894 continue;
1895 }
1896
1897 default:
1898 Error("malformed block record in AST file");
1899 return;
1900 }
1901
1902 // We found the macro directive history; that's the last record
1903 // for this macro.
1904 break;
Argyrios Kyrtzidiseb663da2013-03-22 21:12:57 +00001905 }
1906
Richard Smithd7329392015-04-21 21:46:32 +00001907 // Module macros are listed in reverse dependency order.
Richard Smithe56c8bc2015-04-22 00:26:11 +00001908 {
1909 std::reverse(ModuleMacros.begin(), ModuleMacros.end());
Richard Smithe56c8bc2015-04-22 00:26:11 +00001910 llvm::SmallVector<ModuleMacro*, 8> Overrides;
Richard Smith713369b2015-04-23 20:40:50 +00001911 for (auto &MMR : ModuleMacros) {
Richard Smithe56c8bc2015-04-22 00:26:11 +00001912 Overrides.clear();
Richard Smith713369b2015-04-23 20:40:50 +00001913 for (unsigned ModID : MMR.Overrides) {
Richard Smithb8b2ed62015-04-23 18:18:26 +00001914 Module *Mod = getSubmodule(ModID);
1915 auto *Macro = PP.getModuleMacro(Mod, II);
Richard Smithe56c8bc2015-04-22 00:26:11 +00001916 assert(Macro && "missing definition for overridden macro");
Richard Smith5dbef922015-04-22 02:09:43 +00001917 Overrides.push_back(Macro);
Richard Smithe56c8bc2015-04-22 00:26:11 +00001918 }
1919
1920 bool Inserted = false;
Richard Smith713369b2015-04-23 20:40:50 +00001921 Module *Owner = getSubmodule(MMR.SubModID);
Richard Smith20e883e2015-04-29 23:20:19 +00001922 PP.addModuleMacro(Owner, II, MMR.MI, Overrides, Inserted);
Richard Smithd7329392015-04-21 21:46:32 +00001923 }
1924 }
1925
1926 // Don't read the directive history for a module; we don't have anywhere
1927 // to put it.
Manman Ren11f2a472016-08-18 17:42:15 +00001928 if (M.isModule())
Richard Smithd7329392015-04-21 21:46:32 +00001929 return;
1930
Argyrios Kyrtzidiseb663da2013-03-22 21:12:57 +00001931 // Deserialize the macro directives history in reverse source-order.
Craig Toppera13603a2014-05-22 05:54:18 +00001932 MacroDirective *Latest = nullptr, *Earliest = nullptr;
Argyrios Kyrtzidiseb663da2013-03-22 21:12:57 +00001933 unsigned Idx = 0, N = Record.size();
1934 while (Idx < N) {
Craig Toppera13603a2014-05-22 05:54:18 +00001935 MacroDirective *MD = nullptr;
Argyrios Kyrtzidiseb663da2013-03-22 21:12:57 +00001936 SourceLocation Loc = ReadSourceLocation(M, Record, Idx);
Argyrios Kyrtzidisb6210df2013-03-26 17:17:01 +00001937 MacroDirective::Kind K = (MacroDirective::Kind)Record[Idx++];
1938 switch (K) {
1939 case MacroDirective::MD_Define: {
Richard Smith713369b2015-04-23 20:40:50 +00001940 MacroInfo *MI = getMacro(getGlobalMacroID(M, Record[Idx++]));
Richard Smith3981b172015-04-30 02:16:23 +00001941 MD = PP.AllocateDefMacroDirective(MI, Loc);
Argyrios Kyrtzidisb6210df2013-03-26 17:17:01 +00001942 break;
1943 }
Richard Smithdaa69e02014-07-25 04:40:03 +00001944 case MacroDirective::MD_Undefine: {
Richard Smith3981b172015-04-30 02:16:23 +00001945 MD = PP.AllocateUndefMacroDirective(Loc);
Argyrios Kyrtzidisb6210df2013-03-26 17:17:01 +00001946 break;
Richard Smithdaa69e02014-07-25 04:40:03 +00001947 }
1948 case MacroDirective::MD_Visibility:
Argyrios Kyrtzidisb6210df2013-03-26 17:17:01 +00001949 bool isPublic = Record[Idx++];
1950 MD = PP.AllocateVisibilityMacroDirective(Loc, isPublic);
1951 break;
1952 }
Argyrios Kyrtzidiseb663da2013-03-22 21:12:57 +00001953
1954 if (!Latest)
1955 Latest = MD;
1956 if (Earliest)
1957 Earliest->setPrevious(MD);
1958 Earliest = MD;
1959 }
1960
Richard Smithd6e8c0d2015-05-04 19:58:00 +00001961 if (Latest)
Nico Weberfd870702016-12-09 17:32:52 +00001962 PP.setLoadedMacroDirective(II, Earliest, Latest);
Argyrios Kyrtzidiseb663da2013-03-22 21:12:57 +00001963}
1964
Argyrios Kyrtzidisce9b49e2014-03-14 02:26:27 +00001965ASTReader::InputFileInfo
1966ASTReader::readInputFileInfo(ModuleFile &F, unsigned ID) {
Ben Langmuir198c1682014-03-07 07:27:49 +00001967 // Go find this input file.
1968 BitstreamCursor &Cursor = F.InputFilesCursor;
1969 SavedStreamPosition SavedPosition(Cursor);
1970 Cursor.JumpToBit(F.InputFileOffsets[ID-1]);
1971
1972 unsigned Code = Cursor.ReadCode();
1973 RecordData Record;
1974 StringRef Blob;
1975
1976 unsigned Result = Cursor.readRecord(Code, Record, &Blob);
1977 assert(static_cast<InputFileRecordTypes>(Result) == INPUT_FILE &&
1978 "invalid record type for input file");
1979 (void)Result;
1980
1981 assert(Record[0] == ID && "Bogus stored ID or offset");
Richard Smitha8cfffa2015-11-26 02:04:16 +00001982 InputFileInfo R;
1983 R.StoredSize = static_cast<off_t>(Record[1]);
1984 R.StoredTime = static_cast<time_t>(Record[2]);
1985 R.Overridden = static_cast<bool>(Record[3]);
1986 R.Transient = static_cast<bool>(Record[4]);
1987 R.Filename = Blob;
1988 ResolveImportedPath(F, R.Filename);
Hans Wennborg73945142014-03-14 17:45:06 +00001989 return R;
Ben Langmuir198c1682014-03-07 07:27:49 +00001990}
1991
Manman Renc8c94152016-10-21 23:35:03 +00001992static unsigned moduleKindForDiagnostic(ModuleKind Kind);
Argyrios Kyrtzidis61c3d872013-03-01 03:26:04 +00001993InputFile ASTReader::getInputFile(ModuleFile &F, unsigned ID, bool Complain) {
Guy Benyei11169dd2012-12-18 14:30:41 +00001994 // If this ID is bogus, just return an empty input file.
1995 if (ID == 0 || ID > F.InputFilesLoaded.size())
1996 return InputFile();
1997
1998 // If we've already loaded this input file, return it.
Argyrios Kyrtzidis61c3d872013-03-01 03:26:04 +00001999 if (F.InputFilesLoaded[ID-1].getFile())
Guy Benyei11169dd2012-12-18 14:30:41 +00002000 return F.InputFilesLoaded[ID-1];
2001
Argyrios Kyrtzidis9308f0a2014-01-08 19:13:34 +00002002 if (F.InputFilesLoaded[ID-1].isNotFound())
2003 return InputFile();
2004
Guy Benyei11169dd2012-12-18 14:30:41 +00002005 // Go find this input file.
Chris Lattner7fb3bef2013-01-20 00:56:42 +00002006 BitstreamCursor &Cursor = F.InputFilesCursor;
Guy Benyei11169dd2012-12-18 14:30:41 +00002007 SavedStreamPosition SavedPosition(Cursor);
2008 Cursor.JumpToBit(F.InputFileOffsets[ID-1]);
David L. Jonesc4808b9e2016-12-15 20:53:26 +00002009
Argyrios Kyrtzidisce9b49e2014-03-14 02:26:27 +00002010 InputFileInfo FI = readInputFileInfo(F, ID);
2011 off_t StoredSize = FI.StoredSize;
2012 time_t StoredTime = FI.StoredTime;
2013 bool Overridden = FI.Overridden;
Richard Smitha8cfffa2015-11-26 02:04:16 +00002014 bool Transient = FI.Transient;
Argyrios Kyrtzidisce9b49e2014-03-14 02:26:27 +00002015 StringRef Filename = FI.Filename;
Argyrios Kyrtzidis61c3d872013-03-01 03:26:04 +00002016
Richard Smitha8cfffa2015-11-26 02:04:16 +00002017 const FileEntry *File = FileMgr.getFile(Filename, /*OpenFile=*/false);
Ben Langmuir198c1682014-03-07 07:27:49 +00002018
2019 // If we didn't find the file, resolve it relative to the
2020 // original directory from which this AST file was created.
Craig Toppera13603a2014-05-22 05:54:18 +00002021 if (File == nullptr && !F.OriginalDir.empty() && !CurrentDir.empty() &&
Ben Langmuir198c1682014-03-07 07:27:49 +00002022 F.OriginalDir != CurrentDir) {
2023 std::string Resolved = resolveFileRelativeToOriginalDir(Filename,
2024 F.OriginalDir,
2025 CurrentDir);
2026 if (!Resolved.empty())
2027 File = FileMgr.getFile(Resolved);
2028 }
2029
2030 // For an overridden file, create a virtual file with the stored
2031 // size/timestamp.
Richard Smitha8cfffa2015-11-26 02:04:16 +00002032 if ((Overridden || Transient) && File == nullptr)
Ben Langmuir198c1682014-03-07 07:27:49 +00002033 File = FileMgr.getVirtualFile(Filename, StoredSize, StoredTime);
Ben Langmuir198c1682014-03-07 07:27:49 +00002034
Craig Toppera13603a2014-05-22 05:54:18 +00002035 if (File == nullptr) {
Ben Langmuir198c1682014-03-07 07:27:49 +00002036 if (Complain) {
2037 std::string ErrorStr = "could not find file '";
2038 ErrorStr += Filename;
Richard Smith68142212015-10-13 01:26:26 +00002039 ErrorStr += "' referenced by AST file '";
2040 ErrorStr += F.FileName;
2041 ErrorStr += "'";
Eugene Zelenkoe95e7d52016-09-07 21:53:17 +00002042 Error(ErrorStr);
Guy Benyei11169dd2012-12-18 14:30:41 +00002043 }
Ben Langmuir198c1682014-03-07 07:27:49 +00002044 // Record that we didn't find the file.
2045 F.InputFilesLoaded[ID-1] = InputFile::getNotFound();
2046 return InputFile();
2047 }
Guy Benyei11169dd2012-12-18 14:30:41 +00002048
Ben Langmuir198c1682014-03-07 07:27:49 +00002049 // Check if there was a request to override the contents of the file
2050 // that was part of the precompiled header. Overridding such a file
2051 // can lead to problems when lexing using the source locations from the
2052 // PCH.
2053 SourceManager &SM = getSourceManager();
Richard Smith64daf7b2015-12-01 03:32:49 +00002054 // FIXME: Reject if the overrides are different.
2055 if ((!Overridden && !Transient) && SM.isFileOverridden(File)) {
Ben Langmuir198c1682014-03-07 07:27:49 +00002056 if (Complain)
2057 Error(diag::err_fe_pch_file_overridden, Filename);
2058 // After emitting the diagnostic, recover by disabling the override so
2059 // that the original file will be used.
Richard Smitha8cfffa2015-11-26 02:04:16 +00002060 //
2061 // FIXME: This recovery is just as broken as the original state; there may
2062 // be another precompiled module that's using the overridden contents, or
2063 // we might be half way through parsing it. Instead, we should treat the
2064 // overridden contents as belonging to a separate FileEntry.
Ben Langmuir198c1682014-03-07 07:27:49 +00002065 SM.disableFileContentsOverride(File);
2066 // The FileEntry is a virtual file entry with the size of the contents
2067 // that would override the original contents. Set it to the original's
2068 // size/time.
2069 FileMgr.modifyFileEntry(const_cast<FileEntry*>(File),
2070 StoredSize, StoredTime);
2071 }
Guy Benyei11169dd2012-12-18 14:30:41 +00002072
Ben Langmuir198c1682014-03-07 07:27:49 +00002073 bool IsOutOfDate = false;
2074
2075 // For an overridden file, there is nothing to validate.
Richard Smith96fdab62014-10-28 16:24:08 +00002076 if (!Overridden && //
2077 (StoredSize != File->getSize() ||
Richard Smithe75ee0f2015-08-17 07:13:32 +00002078 (StoredTime && StoredTime != File->getModificationTime() &&
2079 !DisableValidation)
Ben Langmuir198c1682014-03-07 07:27:49 +00002080 )) {
2081 if (Complain) {
2082 // Build a list of the PCH imports that got us here (in reverse).
2083 SmallVector<ModuleFile *, 4> ImportStack(1, &F);
2084 while (ImportStack.back()->ImportedBy.size() > 0)
2085 ImportStack.push_back(ImportStack.back()->ImportedBy[0]);
Ben Langmuire82630d2014-01-17 00:19:09 +00002086
Ben Langmuir198c1682014-03-07 07:27:49 +00002087 // The top-level PCH is stale.
2088 StringRef TopLevelPCHName(ImportStack.back()->FileName);
Manman Renc8c94152016-10-21 23:35:03 +00002089 unsigned DiagnosticKind = moduleKindForDiagnostic(ImportStack.back()->Kind);
2090 if (DiagnosticKind == 0)
2091 Error(diag::err_fe_pch_file_modified, Filename, TopLevelPCHName);
2092 else if (DiagnosticKind == 1)
2093 Error(diag::err_fe_module_file_modified, Filename, TopLevelPCHName);
2094 else
2095 Error(diag::err_fe_ast_file_modified, Filename, TopLevelPCHName);
Ben Langmuire82630d2014-01-17 00:19:09 +00002096
Ben Langmuir198c1682014-03-07 07:27:49 +00002097 // Print the import stack.
2098 if (ImportStack.size() > 1 && !Diags.isDiagnosticInFlight()) {
2099 Diag(diag::note_pch_required_by)
2100 << Filename << ImportStack[0]->FileName;
2101 for (unsigned I = 1; I < ImportStack.size(); ++I)
Ben Langmuire82630d2014-01-17 00:19:09 +00002102 Diag(diag::note_pch_required_by)
Ben Langmuir198c1682014-03-07 07:27:49 +00002103 << ImportStack[I-1]->FileName << ImportStack[I]->FileName;
Douglas Gregor7029ce12013-03-19 00:28:20 +00002104 }
2105
Ben Langmuir198c1682014-03-07 07:27:49 +00002106 if (!Diags.isDiagnosticInFlight())
2107 Diag(diag::note_pch_rebuild_required) << TopLevelPCHName;
Guy Benyei11169dd2012-12-18 14:30:41 +00002108 }
2109
Ben Langmuir198c1682014-03-07 07:27:49 +00002110 IsOutOfDate = true;
Guy Benyei11169dd2012-12-18 14:30:41 +00002111 }
Richard Smitha8cfffa2015-11-26 02:04:16 +00002112 // FIXME: If the file is overridden and we've already opened it,
2113 // issue an error (or split it into a separate FileEntry).
Guy Benyei11169dd2012-12-18 14:30:41 +00002114
Richard Smitha8cfffa2015-11-26 02:04:16 +00002115 InputFile IF = InputFile(File, Overridden || Transient, IsOutOfDate);
Ben Langmuir198c1682014-03-07 07:27:49 +00002116
2117 // Note that we've loaded this input file.
2118 F.InputFilesLoaded[ID-1] = IF;
2119 return IF;
Guy Benyei11169dd2012-12-18 14:30:41 +00002120}
2121
Richard Smith7ed1bc92014-12-05 22:42:13 +00002122/// \brief If we are loading a relocatable PCH or module file, and the filename
2123/// is not an absolute path, add the system or module root to the beginning of
2124/// the file name.
2125void ASTReader::ResolveImportedPath(ModuleFile &M, std::string &Filename) {
2126 // Resolve relative to the base directory, if we have one.
2127 if (!M.BaseDirectory.empty())
2128 return ResolveImportedPath(Filename, M.BaseDirectory);
Guy Benyei11169dd2012-12-18 14:30:41 +00002129}
2130
Richard Smith7ed1bc92014-12-05 22:42:13 +00002131void ASTReader::ResolveImportedPath(std::string &Filename, StringRef Prefix) {
Guy Benyei11169dd2012-12-18 14:30:41 +00002132 if (Filename.empty() || llvm::sys::path::is_absolute(Filename))
2133 return;
2134
Richard Smith7ed1bc92014-12-05 22:42:13 +00002135 SmallString<128> Buffer;
2136 llvm::sys::path::append(Buffer, Prefix, Filename);
2137 Filename.assign(Buffer.begin(), Buffer.end());
Guy Benyei11169dd2012-12-18 14:30:41 +00002138}
2139
Richard Smith0f99d6a2015-08-09 08:48:41 +00002140static bool isDiagnosedResult(ASTReader::ASTReadResult ARR, unsigned Caps) {
2141 switch (ARR) {
2142 case ASTReader::Failure: return true;
2143 case ASTReader::Missing: return !(Caps & ASTReader::ARR_Missing);
2144 case ASTReader::OutOfDate: return !(Caps & ASTReader::ARR_OutOfDate);
2145 case ASTReader::VersionMismatch: return !(Caps & ASTReader::ARR_VersionMismatch);
2146 case ASTReader::ConfigurationMismatch:
2147 return !(Caps & ASTReader::ARR_ConfigurationMismatch);
2148 case ASTReader::HadErrors: return true;
2149 case ASTReader::Success: return false;
2150 }
2151
2152 llvm_unreachable("unknown ASTReadResult");
2153}
2154
Richard Smith0516b182015-09-08 19:40:14 +00002155ASTReader::ASTReadResult ASTReader::ReadOptionsBlock(
2156 BitstreamCursor &Stream, unsigned ClientLoadCapabilities,
2157 bool AllowCompatibleConfigurationMismatch, ASTReaderListener &Listener,
Manman Ren47a44452016-07-26 17:12:17 +00002158 std::string &SuggestedPredefines, bool ValidateDiagnosticOptions) {
Richard Smith0516b182015-09-08 19:40:14 +00002159 if (Stream.EnterSubBlock(OPTIONS_BLOCK_ID))
2160 return Failure;
2161
2162 // Read all of the records in the options block.
2163 RecordData Record;
2164 ASTReadResult Result = Success;
Eugene Zelenkoe95e7d52016-09-07 21:53:17 +00002165 while (true) {
Richard Smith0516b182015-09-08 19:40:14 +00002166 llvm::BitstreamEntry Entry = Stream.advance();
David L. Jonesc4808b9e2016-12-15 20:53:26 +00002167
Richard Smith0516b182015-09-08 19:40:14 +00002168 switch (Entry.Kind) {
2169 case llvm::BitstreamEntry::Error:
2170 case llvm::BitstreamEntry::SubBlock:
2171 return Failure;
2172
2173 case llvm::BitstreamEntry::EndBlock:
2174 return Result;
2175
2176 case llvm::BitstreamEntry::Record:
2177 // The interesting case.
2178 break;
2179 }
2180
2181 // Read and process a record.
2182 Record.clear();
2183 switch ((OptionsRecordTypes)Stream.readRecord(Entry.ID, Record)) {
2184 case LANGUAGE_OPTIONS: {
2185 bool Complain = (ClientLoadCapabilities & ARR_ConfigurationMismatch) == 0;
2186 if (ParseLanguageOptions(Record, Complain, Listener,
2187 AllowCompatibleConfigurationMismatch))
2188 Result = ConfigurationMismatch;
2189 break;
2190 }
2191
2192 case TARGET_OPTIONS: {
2193 bool Complain = (ClientLoadCapabilities & ARR_ConfigurationMismatch) == 0;
2194 if (ParseTargetOptions(Record, Complain, Listener,
2195 AllowCompatibleConfigurationMismatch))
2196 Result = ConfigurationMismatch;
2197 break;
2198 }
2199
2200 case DIAGNOSTIC_OPTIONS: {
2201 bool Complain = (ClientLoadCapabilities & ARR_OutOfDate) == 0;
Manman Ren47a44452016-07-26 17:12:17 +00002202 if (ValidateDiagnosticOptions &&
2203 !AllowCompatibleConfigurationMismatch &&
Richard Smith0516b182015-09-08 19:40:14 +00002204 ParseDiagnosticOptions(Record, Complain, Listener))
2205 return OutOfDate;
2206 break;
2207 }
2208
2209 case FILE_SYSTEM_OPTIONS: {
2210 bool Complain = (ClientLoadCapabilities & ARR_ConfigurationMismatch) == 0;
2211 if (!AllowCompatibleConfigurationMismatch &&
2212 ParseFileSystemOptions(Record, Complain, Listener))
2213 Result = ConfigurationMismatch;
2214 break;
2215 }
2216
2217 case HEADER_SEARCH_OPTIONS: {
2218 bool Complain = (ClientLoadCapabilities & ARR_ConfigurationMismatch) == 0;
2219 if (!AllowCompatibleConfigurationMismatch &&
2220 ParseHeaderSearchOptions(Record, Complain, Listener))
2221 Result = ConfigurationMismatch;
2222 break;
2223 }
2224
2225 case PREPROCESSOR_OPTIONS:
2226 bool Complain = (ClientLoadCapabilities & ARR_ConfigurationMismatch) == 0;
2227 if (!AllowCompatibleConfigurationMismatch &&
2228 ParsePreprocessorOptions(Record, Complain, Listener,
2229 SuggestedPredefines))
2230 Result = ConfigurationMismatch;
2231 break;
2232 }
2233 }
2234}
2235
Guy Benyei11169dd2012-12-18 14:30:41 +00002236ASTReader::ASTReadResult
2237ASTReader::ReadControlBlock(ModuleFile &F,
Dmitri Gribenkof8579502013-01-12 19:30:44 +00002238 SmallVectorImpl<ImportedModule> &Loaded,
Ben Langmuirbeee15e2014-04-14 18:00:01 +00002239 const ModuleFile *ImportedBy,
Guy Benyei11169dd2012-12-18 14:30:41 +00002240 unsigned ClientLoadCapabilities) {
Chris Lattner7fb3bef2013-01-20 00:56:42 +00002241 BitstreamCursor &Stream = F.Stream;
Richard Smith8a308ec2015-11-05 00:54:55 +00002242 ASTReadResult Result = Success;
Guy Benyei11169dd2012-12-18 14:30:41 +00002243
2244 if (Stream.EnterSubBlock(CONTROL_BLOCK_ID)) {
2245 Error("malformed block record in AST file");
2246 return Failure;
2247 }
2248
2249 // Read all of the records and blocks in the control block.
2250 RecordData Record;
Richard Smitha1825302014-10-23 22:18:29 +00002251 unsigned NumInputs = 0;
2252 unsigned NumUserInputs = 0;
Eugene Zelenkoe95e7d52016-09-07 21:53:17 +00002253 while (true) {
Chris Lattnere7b154b2013-01-19 21:39:22 +00002254 llvm::BitstreamEntry Entry = Stream.advance();
David L. Jonesc4808b9e2016-12-15 20:53:26 +00002255
Chris Lattnere7b154b2013-01-19 21:39:22 +00002256 switch (Entry.Kind) {
2257 case llvm::BitstreamEntry::Error:
2258 Error("malformed block record in AST file");
2259 return Failure;
Dmitri Gribenkof430da42014-02-12 10:33:14 +00002260 case llvm::BitstreamEntry::EndBlock: {
2261 // Validate input files.
2262 const HeaderSearchOptions &HSOpts =
2263 PP.getHeaderSearchInfo().getHeaderSearchOpts();
Ben Langmuircb69b572014-03-07 06:40:32 +00002264
Richard Smitha1825302014-10-23 22:18:29 +00002265 // All user input files reside at the index range [0, NumUserInputs), and
Richard Smith0f99d6a2015-08-09 08:48:41 +00002266 // system input files reside at [NumUserInputs, NumInputs). For explicitly
2267 // loaded module files, ignore missing inputs.
Manman Ren11f2a472016-08-18 17:42:15 +00002268 if (!DisableValidation && F.Kind != MK_ExplicitModule &&
2269 F.Kind != MK_PrebuiltModule) {
Guy Benyei11169dd2012-12-18 14:30:41 +00002270 bool Complain = (ClientLoadCapabilities & ARR_OutOfDate) == 0;
Ben Langmuircb69b572014-03-07 06:40:32 +00002271
Dmitri Gribenkof430da42014-02-12 10:33:14 +00002272 // If we are reading a module, we will create a verification timestamp,
2273 // so we verify all input files. Otherwise, verify only user input
2274 // files.
Ben Langmuircb69b572014-03-07 06:40:32 +00002275
2276 unsigned N = NumUserInputs;
2277 if (ValidateSystemInputs ||
Richard Smithe842a472014-10-22 02:05:46 +00002278 (HSOpts.ModulesValidateOncePerBuildSession &&
Ben Langmuiracb803e2014-11-10 22:13:10 +00002279 F.InputFilesValidationTimestamp <= HSOpts.BuildSessionTimestamp &&
Richard Smithe842a472014-10-22 02:05:46 +00002280 F.Kind == MK_ImplicitModule))
Ben Langmuircb69b572014-03-07 06:40:32 +00002281 N = NumInputs;
2282
Ben Langmuir3d4417c2014-02-07 17:31:11 +00002283 for (unsigned I = 0; I < N; ++I) {
Argyrios Kyrtzidis61c3d872013-03-01 03:26:04 +00002284 InputFile IF = getInputFile(F, I+1, Complain);
2285 if (!IF.getFile() || IF.isOutOfDate())
Guy Benyei11169dd2012-12-18 14:30:41 +00002286 return OutOfDate;
Argyrios Kyrtzidis61c3d872013-03-01 03:26:04 +00002287 }
Guy Benyei11169dd2012-12-18 14:30:41 +00002288 }
Ben Langmuircb69b572014-03-07 06:40:32 +00002289
Argyrios Kyrtzidis6d0753d2014-03-14 03:07:38 +00002290 if (Listener)
Richard Smith216a3bd2015-08-13 17:57:10 +00002291 Listener->visitModuleFile(F.FileName, F.Kind);
Argyrios Kyrtzidis6d0753d2014-03-14 03:07:38 +00002292
Ben Langmuircb69b572014-03-07 06:40:32 +00002293 if (Listener && Listener->needsInputFileVisitation()) {
2294 unsigned N = Listener->needsSystemInputFileVisitation() ? NumInputs
2295 : NumUserInputs;
Argyrios Kyrtzidis68ccbe02014-03-14 02:26:31 +00002296 for (unsigned I = 0; I < N; ++I) {
2297 bool IsSystem = I >= NumUserInputs;
2298 InputFileInfo FI = readInputFileInfo(F, I+1);
Richard Smith216a3bd2015-08-13 17:57:10 +00002299 Listener->visitInputFile(FI.Filename, IsSystem, FI.Overridden,
Manman Ren11f2a472016-08-18 17:42:15 +00002300 F.Kind == MK_ExplicitModule ||
2301 F.Kind == MK_PrebuiltModule);
Argyrios Kyrtzidis68ccbe02014-03-14 02:26:31 +00002302 }
Ben Langmuircb69b572014-03-07 06:40:32 +00002303 }
2304
Richard Smith8a308ec2015-11-05 00:54:55 +00002305 return Result;
Dmitri Gribenkof430da42014-02-12 10:33:14 +00002306 }
2307
Chris Lattnere7b154b2013-01-19 21:39:22 +00002308 case llvm::BitstreamEntry::SubBlock:
2309 switch (Entry.ID) {
Guy Benyei11169dd2012-12-18 14:30:41 +00002310 case INPUT_FILES_BLOCK_ID:
2311 F.InputFilesCursor = Stream;
2312 if (Stream.SkipBlock() || // Skip with the main cursor
2313 // Read the abbreviations
2314 ReadBlockAbbrevs(F.InputFilesCursor, INPUT_FILES_BLOCK_ID)) {
2315 Error("malformed block record in AST file");
2316 return Failure;
2317 }
2318 continue;
Richard Smith0516b182015-09-08 19:40:14 +00002319
2320 case OPTIONS_BLOCK_ID:
2321 // If we're reading the first module for this group, check its options
2322 // are compatible with ours. For modules it imports, no further checking
2323 // is required, because we checked them when we built it.
2324 if (Listener && !ImportedBy) {
2325 // Should we allow the configuration of the module file to differ from
2326 // the configuration of the current translation unit in a compatible
2327 // way?
2328 //
2329 // FIXME: Allow this for files explicitly specified with -include-pch.
2330 bool AllowCompatibleConfigurationMismatch =
Manman Ren11f2a472016-08-18 17:42:15 +00002331 F.Kind == MK_ExplicitModule || F.Kind == MK_PrebuiltModule;
Manman Ren47a44452016-07-26 17:12:17 +00002332 const HeaderSearchOptions &HSOpts =
2333 PP.getHeaderSearchInfo().getHeaderSearchOpts();
Richard Smith0516b182015-09-08 19:40:14 +00002334
Richard Smith8a308ec2015-11-05 00:54:55 +00002335 Result = ReadOptionsBlock(Stream, ClientLoadCapabilities,
2336 AllowCompatibleConfigurationMismatch,
Manman Ren47a44452016-07-26 17:12:17 +00002337 *Listener, SuggestedPredefines,
2338 HSOpts.ModulesValidateDiagnosticOptions);
Richard Smith0516b182015-09-08 19:40:14 +00002339 if (Result == Failure) {
2340 Error("malformed block record in AST file");
2341 return Result;
2342 }
2343
Richard Smith8a308ec2015-11-05 00:54:55 +00002344 if (DisableValidation ||
2345 (AllowConfigurationMismatch && Result == ConfigurationMismatch))
2346 Result = Success;
2347
Ben Langmuir9b1e442e2016-02-11 18:54:02 +00002348 // If we can't load the module, exit early since we likely
2349 // will rebuild the module anyway. The stream may be in the
2350 // middle of a block.
2351 if (Result != Success)
Richard Smith0516b182015-09-08 19:40:14 +00002352 return Result;
2353 } else if (Stream.SkipBlock()) {
2354 Error("malformed block record in AST file");
2355 return Failure;
2356 }
2357 continue;
David L. Jonesc4808b9e2016-12-15 20:53:26 +00002358
Guy Benyei11169dd2012-12-18 14:30:41 +00002359 default:
Chris Lattnere7b154b2013-01-19 21:39:22 +00002360 if (Stream.SkipBlock()) {
2361 Error("malformed block record in AST file");
2362 return Failure;
2363 }
2364 continue;
Guy Benyei11169dd2012-12-18 14:30:41 +00002365 }
David L. Jonesc4808b9e2016-12-15 20:53:26 +00002366
Chris Lattnere7b154b2013-01-19 21:39:22 +00002367 case llvm::BitstreamEntry::Record:
2368 // The interesting case.
2369 break;
Guy Benyei11169dd2012-12-18 14:30:41 +00002370 }
2371
2372 // Read and process a record.
2373 Record.clear();
Chris Lattner0e6c9402013-01-20 02:38:54 +00002374 StringRef Blob;
2375 switch ((ControlRecordTypes)Stream.readRecord(Entry.ID, Record, &Blob)) {
Guy Benyei11169dd2012-12-18 14:30:41 +00002376 case METADATA: {
2377 if (Record[0] != VERSION_MAJOR && !DisableValidation) {
2378 if ((ClientLoadCapabilities & ARR_VersionMismatch) == 0)
Dmitri Gribenko2228cd32014-02-11 15:40:09 +00002379 Diag(Record[0] < VERSION_MAJOR? diag::err_pch_version_too_old
2380 : diag::err_pch_version_too_new);
Guy Benyei11169dd2012-12-18 14:30:41 +00002381 return VersionMismatch;
2382 }
2383
Richard Smithe75ee0f2015-08-17 07:13:32 +00002384 bool hasErrors = Record[6];
Guy Benyei11169dd2012-12-18 14:30:41 +00002385 if (hasErrors && !DisableValidation && !AllowASTWithCompilerErrors) {
2386 Diag(diag::err_pch_with_compiler_errors);
2387 return HadErrors;
2388 }
Argyrios Kyrtzidis70ec1c72016-07-13 20:35:26 +00002389 if (hasErrors) {
2390 Diags.ErrorOccurred = true;
2391 Diags.UncompilableErrorOccurred = true;
2392 Diags.UnrecoverableErrorOccurred = true;
2393 }
Guy Benyei11169dd2012-12-18 14:30:41 +00002394
2395 F.RelocatablePCH = Record[4];
Richard Smith7ed1bc92014-12-05 22:42:13 +00002396 // Relative paths in a relocatable PCH are relative to our sysroot.
2397 if (F.RelocatablePCH)
2398 F.BaseDirectory = isysroot.empty() ? "/" : isysroot;
Guy Benyei11169dd2012-12-18 14:30:41 +00002399
Richard Smithe75ee0f2015-08-17 07:13:32 +00002400 F.HasTimestamps = Record[5];
2401
Guy Benyei11169dd2012-12-18 14:30:41 +00002402 const std::string &CurBranch = getClangFullRepositoryVersion();
Chris Lattner0e6c9402013-01-20 02:38:54 +00002403 StringRef ASTBranch = Blob;
Guy Benyei11169dd2012-12-18 14:30:41 +00002404 if (StringRef(CurBranch) != ASTBranch && !DisableValidation) {
2405 if ((ClientLoadCapabilities & ARR_VersionMismatch) == 0)
Dmitri Gribenko2228cd32014-02-11 15:40:09 +00002406 Diag(diag::err_pch_different_branch) << ASTBranch << CurBranch;
Guy Benyei11169dd2012-12-18 14:30:41 +00002407 return VersionMismatch;
2408 }
2409 break;
2410 }
2411
Ben Langmuir487ea142014-10-23 18:05:36 +00002412 case SIGNATURE:
2413 assert((!F.Signature || F.Signature == Record[0]) && "signature changed");
2414 F.Signature = Record[0];
2415 break;
2416
Guy Benyei11169dd2012-12-18 14:30:41 +00002417 case IMPORTS: {
David L. Jonesc4808b9e2016-12-15 20:53:26 +00002418 // Load each of the imported PCH files.
Guy Benyei11169dd2012-12-18 14:30:41 +00002419 unsigned Idx = 0, N = Record.size();
2420 while (Idx < N) {
2421 // Read information about the AST file.
2422 ModuleKind ImportedKind = (ModuleKind)Record[Idx++];
2423 // The import location will be the local one for now; we will adjust
2424 // all import locations of module imports after the global source
Richard Smithb22a1d12016-03-27 20:13:24 +00002425 // location info are setup, in ReadAST.
Guy Benyei11169dd2012-12-18 14:30:41 +00002426 SourceLocation ImportLoc =
Richard Smithb22a1d12016-03-27 20:13:24 +00002427 ReadUntranslatedSourceLocation(Record[Idx++]);
Douglas Gregor7029ce12013-03-19 00:28:20 +00002428 off_t StoredSize = (off_t)Record[Idx++];
2429 time_t StoredModTime = (time_t)Record[Idx++];
Ben Langmuir487ea142014-10-23 18:05:36 +00002430 ASTFileSignature StoredSignature = Record[Idx++];
Richard Smith7ed1bc92014-12-05 22:42:13 +00002431 auto ImportedFile = ReadPath(F, Record, Idx);
Guy Benyei11169dd2012-12-18 14:30:41 +00002432
Richard Smith0f99d6a2015-08-09 08:48:41 +00002433 // If our client can't cope with us being out of date, we can't cope with
2434 // our dependency being missing.
2435 unsigned Capabilities = ClientLoadCapabilities;
2436 if ((ClientLoadCapabilities & ARR_OutOfDate) == 0)
2437 Capabilities &= ~ARR_Missing;
2438
Guy Benyei11169dd2012-12-18 14:30:41 +00002439 // Load the AST file.
Richard Smith0f99d6a2015-08-09 08:48:41 +00002440 auto Result = ReadASTCore(ImportedFile, ImportedKind, ImportLoc, &F,
2441 Loaded, StoredSize, StoredModTime,
2442 StoredSignature, Capabilities);
2443
2444 // If we diagnosed a problem, produce a backtrace.
2445 if (isDiagnosedResult(Result, Capabilities))
2446 Diag(diag::note_module_file_imported_by)
2447 << F.FileName << !F.ModuleName.empty() << F.ModuleName;
2448
2449 switch (Result) {
Guy Benyei11169dd2012-12-18 14:30:41 +00002450 case Failure: return Failure;
2451 // If we have to ignore the dependency, we'll have to ignore this too.
Douglas Gregor2f1806e2013-03-19 00:38:50 +00002452 case Missing:
Guy Benyei11169dd2012-12-18 14:30:41 +00002453 case OutOfDate: return OutOfDate;
2454 case VersionMismatch: return VersionMismatch;
2455 case ConfigurationMismatch: return ConfigurationMismatch;
2456 case HadErrors: return HadErrors;
2457 case Success: break;
2458 }
2459 }
2460 break;
2461 }
2462
Guy Benyei11169dd2012-12-18 14:30:41 +00002463 case ORIGINAL_FILE:
2464 F.OriginalSourceFileID = FileID::get(Record[0]);
Chris Lattner0e6c9402013-01-20 02:38:54 +00002465 F.ActualOriginalSourceFileName = Blob;
Guy Benyei11169dd2012-12-18 14:30:41 +00002466 F.OriginalSourceFileName = F.ActualOriginalSourceFileName;
Richard Smith7ed1bc92014-12-05 22:42:13 +00002467 ResolveImportedPath(F, F.OriginalSourceFileName);
Guy Benyei11169dd2012-12-18 14:30:41 +00002468 break;
2469
2470 case ORIGINAL_FILE_ID:
2471 F.OriginalSourceFileID = FileID::get(Record[0]);
2472 break;
2473
2474 case ORIGINAL_PCH_DIR:
Chris Lattner0e6c9402013-01-20 02:38:54 +00002475 F.OriginalDir = Blob;
Guy Benyei11169dd2012-12-18 14:30:41 +00002476 break;
2477
Ben Langmuirbeee15e2014-04-14 18:00:01 +00002478 case MODULE_NAME:
2479 F.ModuleName = Blob;
Ben Langmuir4f5212a2014-04-14 22:12:44 +00002480 if (Listener)
2481 Listener->ReadModuleName(F.ModuleName);
Ben Langmuirbeee15e2014-04-14 18:00:01 +00002482 break;
2483
Richard Smith223d3f22014-12-06 03:21:08 +00002484 case MODULE_DIRECTORY: {
2485 assert(!F.ModuleName.empty() &&
2486 "MODULE_DIRECTORY found before MODULE_NAME");
2487 // If we've already loaded a module map file covering this module, we may
2488 // have a better path for it (relative to the current build).
2489 Module *M = PP.getHeaderSearchInfo().lookupModule(F.ModuleName);
2490 if (M && M->Directory) {
2491 // If we're implicitly loading a module, the base directory can't
2492 // change between the build and use.
Manman Ren11f2a472016-08-18 17:42:15 +00002493 if (F.Kind != MK_ExplicitModule && F.Kind != MK_PrebuiltModule) {
Richard Smith223d3f22014-12-06 03:21:08 +00002494 const DirectoryEntry *BuildDir =
2495 PP.getFileManager().getDirectory(Blob);
2496 if (!BuildDir || BuildDir != M->Directory) {
2497 if ((ClientLoadCapabilities & ARR_OutOfDate) == 0)
2498 Diag(diag::err_imported_module_relocated)
2499 << F.ModuleName << Blob << M->Directory->getName();
2500 return OutOfDate;
2501 }
2502 }
2503 F.BaseDirectory = M->Directory->getName();
2504 } else {
2505 F.BaseDirectory = Blob;
2506 }
Richard Smith7ed1bc92014-12-05 22:42:13 +00002507 break;
Richard Smith223d3f22014-12-06 03:21:08 +00002508 }
Richard Smith7ed1bc92014-12-05 22:42:13 +00002509
Ben Langmuirbeee15e2014-04-14 18:00:01 +00002510 case MODULE_MAP_FILE:
Ben Langmuir4b8a9e92014-08-12 16:42:33 +00002511 if (ASTReadResult Result =
2512 ReadModuleMapFileBlock(Record, F, ImportedBy, ClientLoadCapabilities))
2513 return Result;
Ben Langmuir264ea152014-11-08 00:06:39 +00002514 break;
2515
Justin Bognerca9c0cc2015-06-21 20:32:36 +00002516 case INPUT_FILE_OFFSETS:
Richard Smitha1825302014-10-23 22:18:29 +00002517 NumInputs = Record[0];
2518 NumUserInputs = Record[1];
Justin Bogner4c183242015-06-21 20:32:40 +00002519 F.InputFileOffsets =
2520 (const llvm::support::unaligned_uint64_t *)Blob.data();
Richard Smitha1825302014-10-23 22:18:29 +00002521 F.InputFilesLoaded.resize(NumInputs);
Guy Benyei11169dd2012-12-18 14:30:41 +00002522 break;
2523 }
2524 }
Guy Benyei11169dd2012-12-18 14:30:41 +00002525}
2526
Ben Langmuir2c9af442014-04-10 17:57:43 +00002527ASTReader::ASTReadResult
2528ASTReader::ReadASTBlock(ModuleFile &F, unsigned ClientLoadCapabilities) {
Chris Lattner7fb3bef2013-01-20 00:56:42 +00002529 BitstreamCursor &Stream = F.Stream;
Guy Benyei11169dd2012-12-18 14:30:41 +00002530
2531 if (Stream.EnterSubBlock(AST_BLOCK_ID)) {
2532 Error("malformed block record in AST file");
Ben Langmuir2c9af442014-04-10 17:57:43 +00002533 return Failure;
Guy Benyei11169dd2012-12-18 14:30:41 +00002534 }
2535
2536 // Read all of the records and blocks for the AST file.
2537 RecordData Record;
Eugene Zelenkoe95e7d52016-09-07 21:53:17 +00002538 while (true) {
Chris Lattnere7b154b2013-01-19 21:39:22 +00002539 llvm::BitstreamEntry Entry = Stream.advance();
David L. Jonesc4808b9e2016-12-15 20:53:26 +00002540
Chris Lattnere7b154b2013-01-19 21:39:22 +00002541 switch (Entry.Kind) {
2542 case llvm::BitstreamEntry::Error:
2543 Error("error at end of module block in AST file");
Ben Langmuir2c9af442014-04-10 17:57:43 +00002544 return Failure;
Chris Lattnere7b154b2013-01-19 21:39:22 +00002545 case llvm::BitstreamEntry::EndBlock: {
Richard Smithc0fbba72013-04-03 22:49:41 +00002546 // Outside of C++, we do not store a lookup map for the translation unit.
2547 // Instead, mark it as needing a lookup map to be built if this module
2548 // contains any declarations lexically within it (which it always does!).
2549 // This usually has no cost, since we very rarely need the lookup map for
2550 // the translation unit outside C++.
Guy Benyei11169dd2012-12-18 14:30:41 +00002551 DeclContext *DC = Context.getTranslationUnitDecl();
Richard Smithc0fbba72013-04-03 22:49:41 +00002552 if (DC->hasExternalLexicalStorage() &&
2553 !getContext().getLangOpts().CPlusPlus)
Guy Benyei11169dd2012-12-18 14:30:41 +00002554 DC->setMustBuildLookupTable();
David L. Jonesc4808b9e2016-12-15 20:53:26 +00002555
Ben Langmuir2c9af442014-04-10 17:57:43 +00002556 return Success;
Guy Benyei11169dd2012-12-18 14:30:41 +00002557 }
Chris Lattnere7b154b2013-01-19 21:39:22 +00002558 case llvm::BitstreamEntry::SubBlock:
2559 switch (Entry.ID) {
Guy Benyei11169dd2012-12-18 14:30:41 +00002560 case DECLTYPES_BLOCK_ID:
2561 // We lazily load the decls block, but we want to set up the
2562 // DeclsCursor cursor to point into it. Clone our current bitcode
2563 // cursor to it, enter the block and read the abbrevs in that block.
2564 // With the main cursor, we just skip over it.
2565 F.DeclsCursor = Stream;
2566 if (Stream.SkipBlock() || // Skip with the main cursor.
2567 // Read the abbrevs.
2568 ReadBlockAbbrevs(F.DeclsCursor, DECLTYPES_BLOCK_ID)) {
2569 Error("malformed block record in AST file");
Ben Langmuir2c9af442014-04-10 17:57:43 +00002570 return Failure;
Guy Benyei11169dd2012-12-18 14:30:41 +00002571 }
2572 break;
Richard Smithb9eab6d2014-03-20 19:44:17 +00002573
Guy Benyei11169dd2012-12-18 14:30:41 +00002574 case PREPROCESSOR_BLOCK_ID:
2575 F.MacroCursor = Stream;
2576 if (!PP.getExternalSource())
2577 PP.setExternalSource(this);
David L. Jonesc4808b9e2016-12-15 20:53:26 +00002578
Guy Benyei11169dd2012-12-18 14:30:41 +00002579 if (Stream.SkipBlock() ||
2580 ReadBlockAbbrevs(F.MacroCursor, PREPROCESSOR_BLOCK_ID)) {
2581 Error("malformed block record in AST file");
Ben Langmuir2c9af442014-04-10 17:57:43 +00002582 return Failure;
Guy Benyei11169dd2012-12-18 14:30:41 +00002583 }
2584 F.MacroStartOffset = F.MacroCursor.GetCurrentBitNo();
2585 break;
David L. Jonesc4808b9e2016-12-15 20:53:26 +00002586
Guy Benyei11169dd2012-12-18 14:30:41 +00002587 case PREPROCESSOR_DETAIL_BLOCK_ID:
2588 F.PreprocessorDetailCursor = Stream;
2589 if (Stream.SkipBlock() ||
Chris Lattnere7b154b2013-01-19 21:39:22 +00002590 ReadBlockAbbrevs(F.PreprocessorDetailCursor,
Guy Benyei11169dd2012-12-18 14:30:41 +00002591 PREPROCESSOR_DETAIL_BLOCK_ID)) {
Chris Lattnere7b154b2013-01-19 21:39:22 +00002592 Error("malformed preprocessor detail record in AST file");
Ben Langmuir2c9af442014-04-10 17:57:43 +00002593 return Failure;
Chris Lattnere7b154b2013-01-19 21:39:22 +00002594 }
Guy Benyei11169dd2012-12-18 14:30:41 +00002595 F.PreprocessorDetailStartOffset
Chris Lattnere7b154b2013-01-19 21:39:22 +00002596 = F.PreprocessorDetailCursor.GetCurrentBitNo();
David L. Jonesc4808b9e2016-12-15 20:53:26 +00002597
Guy Benyei11169dd2012-12-18 14:30:41 +00002598 if (!PP.getPreprocessingRecord())
2599 PP.createPreprocessingRecord();
2600 if (!PP.getPreprocessingRecord()->getExternalSource())
2601 PP.getPreprocessingRecord()->SetExternalSource(*this);
2602 break;
David L. Jonesc4808b9e2016-12-15 20:53:26 +00002603
Guy Benyei11169dd2012-12-18 14:30:41 +00002604 case SOURCE_MANAGER_BLOCK_ID:
2605 if (ReadSourceManagerBlock(F))
Ben Langmuir2c9af442014-04-10 17:57:43 +00002606 return Failure;
Guy Benyei11169dd2012-12-18 14:30:41 +00002607 break;
David L. Jonesc4808b9e2016-12-15 20:53:26 +00002608
Guy Benyei11169dd2012-12-18 14:30:41 +00002609 case SUBMODULE_BLOCK_ID:
Ben Langmuir2c9af442014-04-10 17:57:43 +00002610 if (ASTReadResult Result = ReadSubmoduleBlock(F, ClientLoadCapabilities))
2611 return Result;
Guy Benyei11169dd2012-12-18 14:30:41 +00002612 break;
David L. Jonesc4808b9e2016-12-15 20:53:26 +00002613
Guy Benyei11169dd2012-12-18 14:30:41 +00002614 case COMMENTS_BLOCK_ID: {
Chris Lattner7fb3bef2013-01-20 00:56:42 +00002615 BitstreamCursor C = Stream;
Guy Benyei11169dd2012-12-18 14:30:41 +00002616 if (Stream.SkipBlock() ||
2617 ReadBlockAbbrevs(C, COMMENTS_BLOCK_ID)) {
2618 Error("malformed comments block in AST file");
Ben Langmuir2c9af442014-04-10 17:57:43 +00002619 return Failure;
Guy Benyei11169dd2012-12-18 14:30:41 +00002620 }
2621 CommentsCursors.push_back(std::make_pair(C, &F));
2622 break;
2623 }
David L. Jonesc4808b9e2016-12-15 20:53:26 +00002624
Guy Benyei11169dd2012-12-18 14:30:41 +00002625 default:
Chris Lattnere7b154b2013-01-19 21:39:22 +00002626 if (Stream.SkipBlock()) {
2627 Error("malformed block record in AST file");
Ben Langmuir2c9af442014-04-10 17:57:43 +00002628 return Failure;
Chris Lattnere7b154b2013-01-19 21:39:22 +00002629 }
2630 break;
Guy Benyei11169dd2012-12-18 14:30:41 +00002631 }
2632 continue;
David L. Jonesc4808b9e2016-12-15 20:53:26 +00002633
Chris Lattnere7b154b2013-01-19 21:39:22 +00002634 case llvm::BitstreamEntry::Record:
2635 // The interesting case.
2636 break;
Guy Benyei11169dd2012-12-18 14:30:41 +00002637 }
2638
2639 // Read and process a record.
2640 Record.clear();
Chris Lattner0e6c9402013-01-20 02:38:54 +00002641 StringRef Blob;
2642 switch ((ASTRecordTypes)Stream.readRecord(Entry.ID, Record, &Blob)) {
Guy Benyei11169dd2012-12-18 14:30:41 +00002643 default: // Default behavior: ignore.
2644 break;
2645
2646 case TYPE_OFFSET: {
2647 if (F.LocalNumTypes != 0) {
2648 Error("duplicate TYPE_OFFSET record in AST file");
Ben Langmuir2c9af442014-04-10 17:57:43 +00002649 return Failure;
Guy Benyei11169dd2012-12-18 14:30:41 +00002650 }
Chris Lattner0e6c9402013-01-20 02:38:54 +00002651 F.TypeOffsets = (const uint32_t *)Blob.data();
Guy Benyei11169dd2012-12-18 14:30:41 +00002652 F.LocalNumTypes = Record[0];
2653 unsigned LocalBaseTypeIndex = Record[1];
2654 F.BaseTypeIndex = getTotalNumTypes();
David L. Jonesc4808b9e2016-12-15 20:53:26 +00002655
Guy Benyei11169dd2012-12-18 14:30:41 +00002656 if (F.LocalNumTypes > 0) {
2657 // Introduce the global -> local mapping for types within this module.
2658 GlobalTypeMap.insert(std::make_pair(getTotalNumTypes(), &F));
David L. Jonesc4808b9e2016-12-15 20:53:26 +00002659
Guy Benyei11169dd2012-12-18 14:30:41 +00002660 // Introduce the local -> global mapping for types within this module.
2661 F.TypeRemap.insertOrReplace(
David L. Jonesc4808b9e2016-12-15 20:53:26 +00002662 std::make_pair(LocalBaseTypeIndex,
Guy Benyei11169dd2012-12-18 14:30:41 +00002663 F.BaseTypeIndex - LocalBaseTypeIndex));
Ben Langmuir52ca6782014-10-20 16:27:32 +00002664
2665 TypesLoaded.resize(TypesLoaded.size() + F.LocalNumTypes);
Guy Benyei11169dd2012-12-18 14:30:41 +00002666 }
2667 break;
2668 }
David L. Jonesc4808b9e2016-12-15 20:53:26 +00002669
Guy Benyei11169dd2012-12-18 14:30:41 +00002670 case DECL_OFFSET: {
2671 if (F.LocalNumDecls != 0) {
2672 Error("duplicate DECL_OFFSET record in AST file");
Ben Langmuir2c9af442014-04-10 17:57:43 +00002673 return Failure;
Guy Benyei11169dd2012-12-18 14:30:41 +00002674 }
Chris Lattner0e6c9402013-01-20 02:38:54 +00002675 F.DeclOffsets = (const DeclOffset *)Blob.data();
Guy Benyei11169dd2012-12-18 14:30:41 +00002676 F.LocalNumDecls = Record[0];
2677 unsigned LocalBaseDeclID = Record[1];
2678 F.BaseDeclID = getTotalNumDecls();
David L. Jonesc4808b9e2016-12-15 20:53:26 +00002679
Guy Benyei11169dd2012-12-18 14:30:41 +00002680 if (F.LocalNumDecls > 0) {
David L. Jonesc4808b9e2016-12-15 20:53:26 +00002681 // Introduce the global -> local mapping for declarations within this
Guy Benyei11169dd2012-12-18 14:30:41 +00002682 // module.
2683 GlobalDeclMap.insert(
2684 std::make_pair(getTotalNumDecls() + NUM_PREDEF_DECL_IDS, &F));
David L. Jonesc4808b9e2016-12-15 20:53:26 +00002685
Guy Benyei11169dd2012-12-18 14:30:41 +00002686 // Introduce the local -> global mapping for declarations within this
2687 // module.
2688 F.DeclRemap.insertOrReplace(
2689 std::make_pair(LocalBaseDeclID, F.BaseDeclID - LocalBaseDeclID));
David L. Jonesc4808b9e2016-12-15 20:53:26 +00002690
Guy Benyei11169dd2012-12-18 14:30:41 +00002691 // Introduce the global -> local mapping for declarations within this
2692 // module.
2693 F.GlobalToLocalDeclIDs[&F] = LocalBaseDeclID;
Ben Langmuirfe971d92014-08-16 04:54:18 +00002694
Ben Langmuir52ca6782014-10-20 16:27:32 +00002695 DeclsLoaded.resize(DeclsLoaded.size() + F.LocalNumDecls);
2696 }
Guy Benyei11169dd2012-12-18 14:30:41 +00002697 break;
2698 }
David L. Jonesc4808b9e2016-12-15 20:53:26 +00002699
Guy Benyei11169dd2012-12-18 14:30:41 +00002700 case TU_UPDATE_LEXICAL: {
2701 DeclContext *TU = Context.getTranslationUnitDecl();
Richard Smith82f8fcd2015-08-06 22:07:25 +00002702 LexicalContents Contents(
2703 reinterpret_cast<const llvm::support::unaligned_uint32_t *>(
2704 Blob.data()),
2705 static_cast<unsigned int>(Blob.size() / 4));
2706 TULexicalDecls.push_back(std::make_pair(&F, Contents));
Guy Benyei11169dd2012-12-18 14:30:41 +00002707 TU->setHasExternalLexicalStorage(true);
2708 break;
2709 }
2710
2711 case UPDATE_VISIBLE: {
2712 unsigned Idx = 0;
2713 serialization::DeclID ID = ReadDeclID(F, Record, Idx);
Richard Smith0f4e2c42015-08-06 04:23:48 +00002714 auto *Data = (const unsigned char*)Blob.data();
Richard Smithd88a7f12015-09-01 20:35:42 +00002715 PendingVisibleUpdates[ID].push_back(PendingVisibleUpdate{&F, Data});
Richard Smith0f4e2c42015-08-06 04:23:48 +00002716 // If we've already loaded the decl, perform the updates when we finish
2717 // loading this block.
2718 if (Decl *D = GetExistingDecl(ID))
2719 PendingUpdateRecords.push_back(std::make_pair(ID, D));
Guy Benyei11169dd2012-12-18 14:30:41 +00002720 break;
2721 }
2722
2723 case IDENTIFIER_TABLE:
Chris Lattner0e6c9402013-01-20 02:38:54 +00002724 F.IdentifierTableData = Blob.data();
Guy Benyei11169dd2012-12-18 14:30:41 +00002725 if (Record[0]) {
Justin Bognerda4e6502014-04-14 16:34:29 +00002726 F.IdentifierLookupTable = ASTIdentifierLookupTable::Create(
2727 (const unsigned char *)F.IdentifierTableData + Record[0],
2728 (const unsigned char *)F.IdentifierTableData + sizeof(uint32_t),
2729 (const unsigned char *)F.IdentifierTableData,
2730 ASTIdentifierLookupTrait(*this, F));
David L. Jonesc4808b9e2016-12-15 20:53:26 +00002731
Guy Benyei11169dd2012-12-18 14:30:41 +00002732 PP.getIdentifierTable().setExternalIdentifierLookup(this);
2733 }
2734 break;
2735
2736 case IDENTIFIER_OFFSET: {
2737 if (F.LocalNumIdentifiers != 0) {
2738 Error("duplicate IDENTIFIER_OFFSET record in AST file");
Ben Langmuir2c9af442014-04-10 17:57:43 +00002739 return Failure;
Guy Benyei11169dd2012-12-18 14:30:41 +00002740 }
Chris Lattner0e6c9402013-01-20 02:38:54 +00002741 F.IdentifierOffsets = (const uint32_t *)Blob.data();
Guy Benyei11169dd2012-12-18 14:30:41 +00002742 F.LocalNumIdentifiers = Record[0];
2743 unsigned LocalBaseIdentifierID = Record[1];
2744 F.BaseIdentifierID = getTotalNumIdentifiers();
David L. Jonesc4808b9e2016-12-15 20:53:26 +00002745
Guy Benyei11169dd2012-12-18 14:30:41 +00002746 if (F.LocalNumIdentifiers > 0) {
2747 // Introduce the global -> local mapping for identifiers within this
2748 // module.
David L. Jonesc4808b9e2016-12-15 20:53:26 +00002749 GlobalIdentifierMap.insert(std::make_pair(getTotalNumIdentifiers() + 1,
Guy Benyei11169dd2012-12-18 14:30:41 +00002750 &F));
David L. Jonesc4808b9e2016-12-15 20:53:26 +00002751
Guy Benyei11169dd2012-12-18 14:30:41 +00002752 // Introduce the local -> global mapping for identifiers within this
2753 // module.
2754 F.IdentifierRemap.insertOrReplace(
2755 std::make_pair(LocalBaseIdentifierID,
2756 F.BaseIdentifierID - LocalBaseIdentifierID));
Ben Langmuirfe971d92014-08-16 04:54:18 +00002757
Ben Langmuir52ca6782014-10-20 16:27:32 +00002758 IdentifiersLoaded.resize(IdentifiersLoaded.size()
2759 + F.LocalNumIdentifiers);
2760 }
Guy Benyei11169dd2012-12-18 14:30:41 +00002761 break;
2762 }
2763
Richard Smith33e0f7e2015-07-22 02:08:40 +00002764 case INTERESTING_IDENTIFIERS:
2765 F.PreloadIdentifierOffsets.assign(Record.begin(), Record.end());
2766 break;
2767
Ben Langmuir332aafe2014-01-31 01:06:56 +00002768 case EAGERLY_DESERIALIZED_DECLS:
Richard Smith9e2341d2015-03-23 03:25:59 +00002769 // FIXME: Skip reading this record if our ASTConsumer doesn't care
2770 // about "interesting" decls (for instance, if we're building a module).
Guy Benyei11169dd2012-12-18 14:30:41 +00002771 for (unsigned I = 0, N = Record.size(); I != N; ++I)
Ben Langmuir332aafe2014-01-31 01:06:56 +00002772 EagerlyDeserializedDecls.push_back(getGlobalDeclID(F, Record[I]));
Guy Benyei11169dd2012-12-18 14:30:41 +00002773 break;
2774
2775 case SPECIAL_TYPES:
Douglas Gregor44180f82013-02-01 23:45:03 +00002776 if (SpecialTypes.empty()) {
2777 for (unsigned I = 0, N = Record.size(); I != N; ++I)
2778 SpecialTypes.push_back(getGlobalTypeID(F, Record[I]));
2779 break;
2780 }
2781
2782 if (SpecialTypes.size() != Record.size()) {
2783 Error("invalid special-types record");
Ben Langmuir2c9af442014-04-10 17:57:43 +00002784 return Failure;
Douglas Gregor44180f82013-02-01 23:45:03 +00002785 }
2786
2787 for (unsigned I = 0, N = Record.size(); I != N; ++I) {
2788 serialization::TypeID ID = getGlobalTypeID(F, Record[I]);
2789 if (!SpecialTypes[I])
2790 SpecialTypes[I] = ID;
2791 // FIXME: If ID && SpecialTypes[I] != ID, do we need a separate
2792 // merge step?
2793 }
Guy Benyei11169dd2012-12-18 14:30:41 +00002794 break;
2795
2796 case STATISTICS:
2797 TotalNumStatements += Record[0];
2798 TotalNumMacros += Record[1];
2799 TotalLexicalDeclContexts += Record[2];
2800 TotalVisibleDeclContexts += Record[3];
2801 break;
2802
2803 case UNUSED_FILESCOPED_DECLS:
2804 for (unsigned I = 0, N = Record.size(); I != N; ++I)
2805 UnusedFileScopedDecls.push_back(getGlobalDeclID(F, Record[I]));
2806 break;
2807
2808 case DELEGATING_CTORS:
2809 for (unsigned I = 0, N = Record.size(); I != N; ++I)
2810 DelegatingCtorDecls.push_back(getGlobalDeclID(F, Record[I]));
2811 break;
2812
2813 case WEAK_UNDECLARED_IDENTIFIERS:
2814 if (Record.size() % 4 != 0) {
2815 Error("invalid weak identifiers record");
Ben Langmuir2c9af442014-04-10 17:57:43 +00002816 return Failure;
Guy Benyei11169dd2012-12-18 14:30:41 +00002817 }
David L. Jonesc4808b9e2016-12-15 20:53:26 +00002818
2819 // FIXME: Ignore weak undeclared identifiers from non-original PCH
Guy Benyei11169dd2012-12-18 14:30:41 +00002820 // files. This isn't the way to do it :)
2821 WeakUndeclaredIdentifiers.clear();
David L. Jonesc4808b9e2016-12-15 20:53:26 +00002822
Guy Benyei11169dd2012-12-18 14:30:41 +00002823 // Translate the weak, undeclared identifiers into global IDs.
2824 for (unsigned I = 0, N = Record.size(); I < N; /* in loop */) {
2825 WeakUndeclaredIdentifiers.push_back(
2826 getGlobalIdentifierID(F, Record[I++]));
2827 WeakUndeclaredIdentifiers.push_back(
2828 getGlobalIdentifierID(F, Record[I++]));
2829 WeakUndeclaredIdentifiers.push_back(
2830 ReadSourceLocation(F, Record, I).getRawEncoding());
2831 WeakUndeclaredIdentifiers.push_back(Record[I++]);
2832 }
2833 break;
2834
Guy Benyei11169dd2012-12-18 14:30:41 +00002835 case SELECTOR_OFFSETS: {
Chris Lattner0e6c9402013-01-20 02:38:54 +00002836 F.SelectorOffsets = (const uint32_t *)Blob.data();
Guy Benyei11169dd2012-12-18 14:30:41 +00002837 F.LocalNumSelectors = Record[0];
2838 unsigned LocalBaseSelectorID = Record[1];
2839 F.BaseSelectorID = getTotalNumSelectors();
David L. Jonesc4808b9e2016-12-15 20:53:26 +00002840
Guy Benyei11169dd2012-12-18 14:30:41 +00002841 if (F.LocalNumSelectors > 0) {
David L. Jonesc4808b9e2016-12-15 20:53:26 +00002842 // Introduce the global -> local mapping for selectors within this
Guy Benyei11169dd2012-12-18 14:30:41 +00002843 // module.
2844 GlobalSelectorMap.insert(std::make_pair(getTotalNumSelectors()+1, &F));
David L. Jonesc4808b9e2016-12-15 20:53:26 +00002845
2846 // Introduce the local -> global mapping for selectors within this
Guy Benyei11169dd2012-12-18 14:30:41 +00002847 // module.
2848 F.SelectorRemap.insertOrReplace(
2849 std::make_pair(LocalBaseSelectorID,
2850 F.BaseSelectorID - LocalBaseSelectorID));
Ben Langmuir52ca6782014-10-20 16:27:32 +00002851
2852 SelectorsLoaded.resize(SelectorsLoaded.size() + F.LocalNumSelectors);
Guy Benyei11169dd2012-12-18 14:30:41 +00002853 }
2854 break;
2855 }
David L. Jonesc4808b9e2016-12-15 20:53:26 +00002856
Guy Benyei11169dd2012-12-18 14:30:41 +00002857 case METHOD_POOL:
Chris Lattner0e6c9402013-01-20 02:38:54 +00002858 F.SelectorLookupTableData = (const unsigned char *)Blob.data();
Guy Benyei11169dd2012-12-18 14:30:41 +00002859 if (Record[0])
2860 F.SelectorLookupTable
2861 = ASTSelectorLookupTable::Create(
2862 F.SelectorLookupTableData + Record[0],
2863 F.SelectorLookupTableData,
2864 ASTSelectorLookupTrait(*this, F));
2865 TotalNumMethodPoolEntries += Record[1];
2866 break;
2867
2868 case REFERENCED_SELECTOR_POOL:
2869 if (!Record.empty()) {
2870 for (unsigned Idx = 0, N = Record.size() - 1; Idx < N; /* in loop */) {
David L. Jonesc4808b9e2016-12-15 20:53:26 +00002871 ReferencedSelectorsData.push_back(getGlobalSelectorID(F,
Guy Benyei11169dd2012-12-18 14:30:41 +00002872 Record[Idx++]));
2873 ReferencedSelectorsData.push_back(ReadSourceLocation(F, Record, Idx).
2874 getRawEncoding());
2875 }
2876 }
2877 break;
2878
2879 case PP_COUNTER_VALUE:
2880 if (!Record.empty() && Listener)
2881 Listener->ReadCounter(F, Record[0]);
2882 break;
David L. Jonesc4808b9e2016-12-15 20:53:26 +00002883
Guy Benyei11169dd2012-12-18 14:30:41 +00002884 case FILE_SORTED_DECLS:
Chris Lattner0e6c9402013-01-20 02:38:54 +00002885 F.FileSortedDecls = (const DeclID *)Blob.data();
Guy Benyei11169dd2012-12-18 14:30:41 +00002886 F.NumFileSortedDecls = Record[0];
2887 break;
2888
2889 case SOURCE_LOCATION_OFFSETS: {
Chris Lattner0e6c9402013-01-20 02:38:54 +00002890 F.SLocEntryOffsets = (const uint32_t *)Blob.data();
Guy Benyei11169dd2012-12-18 14:30:41 +00002891 F.LocalNumSLocEntries = Record[0];
2892 unsigned SLocSpaceSize = Record[1];
Benjamin Kramer867ea1d2014-03-02 13:01:17 +00002893 std::tie(F.SLocEntryBaseID, F.SLocEntryBaseOffset) =
Ben Langmuir52ca6782014-10-20 16:27:32 +00002894 SourceMgr.AllocateLoadedSLocEntries(F.LocalNumSLocEntries,
Guy Benyei11169dd2012-12-18 14:30:41 +00002895 SLocSpaceSize);
Richard Smith78d81ec2015-08-12 22:25:24 +00002896 if (!F.SLocEntryBaseID) {
2897 Error("ran out of source locations");
2898 break;
2899 }
Guy Benyei11169dd2012-12-18 14:30:41 +00002900 // Make our entry in the range map. BaseID is negative and growing, so
2901 // we invert it. Because we invert it, though, we need the other end of
2902 // the range.
2903 unsigned RangeStart =
2904 unsigned(-F.SLocEntryBaseID) - F.LocalNumSLocEntries + 1;
2905 GlobalSLocEntryMap.insert(std::make_pair(RangeStart, &F));
2906 F.FirstLoc = SourceLocation::getFromRawEncoding(F.SLocEntryBaseOffset);
2907
2908 // SLocEntryBaseOffset is lower than MaxLoadedOffset and decreasing.
2909 assert((F.SLocEntryBaseOffset & (1U << 31U)) == 0);
2910 GlobalSLocOffsetMap.insert(
2911 std::make_pair(SourceManager::MaxLoadedOffset - F.SLocEntryBaseOffset
2912 - SLocSpaceSize,&F));
2913
2914 // Initialize the remapping table.
2915 // Invalid stays invalid.
Richard Smithb9eab6d2014-03-20 19:44:17 +00002916 F.SLocRemap.insertOrReplace(std::make_pair(0U, 0));
Guy Benyei11169dd2012-12-18 14:30:41 +00002917 // This module. Base was 2 when being compiled.
Richard Smithb9eab6d2014-03-20 19:44:17 +00002918 F.SLocRemap.insertOrReplace(std::make_pair(2U,
Guy Benyei11169dd2012-12-18 14:30:41 +00002919 static_cast<int>(F.SLocEntryBaseOffset - 2)));
David L. Jonesc4808b9e2016-12-15 20:53:26 +00002920
Guy Benyei11169dd2012-12-18 14:30:41 +00002921 TotalNumSLocEntries += F.LocalNumSLocEntries;
2922 break;
2923 }
2924
2925 case MODULE_OFFSET_MAP: {
2926 // Additional remapping information.
Chris Lattner0e6c9402013-01-20 02:38:54 +00002927 const unsigned char *Data = (const unsigned char*)Blob.data();
2928 const unsigned char *DataEnd = Data + Blob.size();
Richard Smithb9eab6d2014-03-20 19:44:17 +00002929
2930 // If we see this entry before SOURCE_LOCATION_OFFSETS, add placeholders.
2931 if (F.SLocRemap.find(0) == F.SLocRemap.end()) {
2932 F.SLocRemap.insert(std::make_pair(0U, 0));
2933 F.SLocRemap.insert(std::make_pair(2U, 1));
2934 }
2935
Guy Benyei11169dd2012-12-18 14:30:41 +00002936 // Continuous range maps we may be updating in our module.
Ben Langmuir785180e2014-10-20 16:27:30 +00002937 typedef ContinuousRangeMap<uint32_t, int, 2>::Builder
2938 RemapBuilder;
2939 RemapBuilder SLocRemap(F.SLocRemap);
2940 RemapBuilder IdentifierRemap(F.IdentifierRemap);
2941 RemapBuilder MacroRemap(F.MacroRemap);
2942 RemapBuilder PreprocessedEntityRemap(F.PreprocessedEntityRemap);
2943 RemapBuilder SubmoduleRemap(F.SubmoduleRemap);
2944 RemapBuilder SelectorRemap(F.SelectorRemap);
2945 RemapBuilder DeclRemap(F.DeclRemap);
2946 RemapBuilder TypeRemap(F.TypeRemap);
Guy Benyei11169dd2012-12-18 14:30:41 +00002947
Richard Smithd8879c82015-08-24 21:59:32 +00002948 while (Data < DataEnd) {
Justin Bogner57ba0b22014-03-28 22:03:24 +00002949 using namespace llvm::support;
2950 uint16_t Len = endian::readNext<uint16_t, little, unaligned>(Data);
Guy Benyei11169dd2012-12-18 14:30:41 +00002951 StringRef Name = StringRef((const char*)Data, Len);
2952 Data += Len;
2953 ModuleFile *OM = ModuleMgr.lookup(Name);
2954 if (!OM) {
2955 Error("SourceLocation remap refers to unknown module");
Ben Langmuir2c9af442014-04-10 17:57:43 +00002956 return Failure;
Guy Benyei11169dd2012-12-18 14:30:41 +00002957 }
2958
Justin Bogner57ba0b22014-03-28 22:03:24 +00002959 uint32_t SLocOffset =
2960 endian::readNext<uint32_t, little, unaligned>(Data);
2961 uint32_t IdentifierIDOffset =
2962 endian::readNext<uint32_t, little, unaligned>(Data);
2963 uint32_t MacroIDOffset =
2964 endian::readNext<uint32_t, little, unaligned>(Data);
2965 uint32_t PreprocessedEntityIDOffset =
2966 endian::readNext<uint32_t, little, unaligned>(Data);
2967 uint32_t SubmoduleIDOffset =
2968 endian::readNext<uint32_t, little, unaligned>(Data);
2969 uint32_t SelectorIDOffset =
2970 endian::readNext<uint32_t, little, unaligned>(Data);
2971 uint32_t DeclIDOffset =
2972 endian::readNext<uint32_t, little, unaligned>(Data);
2973 uint32_t TypeIndexOffset =
2974 endian::readNext<uint32_t, little, unaligned>(Data);
2975
Ben Langmuir785180e2014-10-20 16:27:30 +00002976 uint32_t None = std::numeric_limits<uint32_t>::max();
2977
2978 auto mapOffset = [&](uint32_t Offset, uint32_t BaseOffset,
2979 RemapBuilder &Remap) {
2980 if (Offset != None)
2981 Remap.insert(std::make_pair(Offset,
2982 static_cast<int>(BaseOffset - Offset)));
2983 };
2984 mapOffset(SLocOffset, OM->SLocEntryBaseOffset, SLocRemap);
2985 mapOffset(IdentifierIDOffset, OM->BaseIdentifierID, IdentifierRemap);
2986 mapOffset(MacroIDOffset, OM->BaseMacroID, MacroRemap);
2987 mapOffset(PreprocessedEntityIDOffset, OM->BasePreprocessedEntityID,
2988 PreprocessedEntityRemap);
2989 mapOffset(SubmoduleIDOffset, OM->BaseSubmoduleID, SubmoduleRemap);
2990 mapOffset(SelectorIDOffset, OM->BaseSelectorID, SelectorRemap);
2991 mapOffset(DeclIDOffset, OM->BaseDeclID, DeclRemap);
2992 mapOffset(TypeIndexOffset, OM->BaseTypeIndex, TypeRemap);
Guy Benyei11169dd2012-12-18 14:30:41 +00002993
2994 // Global -> local mappings.
2995 F.GlobalToLocalDeclIDs[OM] = DeclIDOffset;
2996 }
2997 break;
2998 }
2999
3000 case SOURCE_MANAGER_LINE_TABLE:
3001 if (ParseLineTable(F, Record))
Ben Langmuir2c9af442014-04-10 17:57:43 +00003002 return Failure;
Guy Benyei11169dd2012-12-18 14:30:41 +00003003 break;
3004
3005 case SOURCE_LOCATION_PRELOADS: {
3006 // Need to transform from the local view (1-based IDs) to the global view,
3007 // which is based off F.SLocEntryBaseID.
3008 if (!F.PreloadSLocEntries.empty()) {
3009 Error("Multiple SOURCE_LOCATION_PRELOADS records in AST file");
Ben Langmuir2c9af442014-04-10 17:57:43 +00003010 return Failure;
Guy Benyei11169dd2012-12-18 14:30:41 +00003011 }
David L. Jonesc4808b9e2016-12-15 20:53:26 +00003012
Guy Benyei11169dd2012-12-18 14:30:41 +00003013 F.PreloadSLocEntries.swap(Record);
3014 break;
3015 }
3016
3017 case EXT_VECTOR_DECLS:
3018 for (unsigned I = 0, N = Record.size(); I != N; ++I)
3019 ExtVectorDecls.push_back(getGlobalDeclID(F, Record[I]));
3020 break;
3021
3022 case VTABLE_USES:
3023 if (Record.size() % 3 != 0) {
3024 Error("Invalid VTABLE_USES record");
Ben Langmuir2c9af442014-04-10 17:57:43 +00003025 return Failure;
Guy Benyei11169dd2012-12-18 14:30:41 +00003026 }
David L. Jonesc4808b9e2016-12-15 20:53:26 +00003027
Guy Benyei11169dd2012-12-18 14:30:41 +00003028 // Later tables overwrite earlier ones.
3029 // FIXME: Modules will have some trouble with this. This is clearly not
3030 // the right way to do this.
3031 VTableUses.clear();
David L. Jonesc4808b9e2016-12-15 20:53:26 +00003032
Guy Benyei11169dd2012-12-18 14:30:41 +00003033 for (unsigned Idx = 0, N = Record.size(); Idx != N; /* In loop */) {
3034 VTableUses.push_back(getGlobalDeclID(F, Record[Idx++]));
3035 VTableUses.push_back(
3036 ReadSourceLocation(F, Record, Idx).getRawEncoding());
3037 VTableUses.push_back(Record[Idx++]);
3038 }
3039 break;
3040
Guy Benyei11169dd2012-12-18 14:30:41 +00003041 case PENDING_IMPLICIT_INSTANTIATIONS:
3042 if (PendingInstantiations.size() % 2 != 0) {
3043 Error("Invalid existing PendingInstantiations");
Ben Langmuir2c9af442014-04-10 17:57:43 +00003044 return Failure;
Guy Benyei11169dd2012-12-18 14:30:41 +00003045 }
3046
3047 if (Record.size() % 2 != 0) {
3048 Error("Invalid PENDING_IMPLICIT_INSTANTIATIONS block");
Ben Langmuir2c9af442014-04-10 17:57:43 +00003049 return Failure;
Guy Benyei11169dd2012-12-18 14:30:41 +00003050 }
3051
3052 for (unsigned I = 0, N = Record.size(); I != N; /* in loop */) {
3053 PendingInstantiations.push_back(getGlobalDeclID(F, Record[I++]));
3054 PendingInstantiations.push_back(
3055 ReadSourceLocation(F, Record, I).getRawEncoding());
3056 }
3057 break;
3058
3059 case SEMA_DECL_REFS:
Richard Smith96269c52016-09-29 22:49:46 +00003060 if (Record.size() != 3) {
Richard Smith3d8e97e2013-10-18 06:54:39 +00003061 Error("Invalid SEMA_DECL_REFS block");
Ben Langmuir2c9af442014-04-10 17:57:43 +00003062 return Failure;
Richard Smith3d8e97e2013-10-18 06:54:39 +00003063 }
Guy Benyei11169dd2012-12-18 14:30:41 +00003064 for (unsigned I = 0, N = Record.size(); I != N; ++I)
3065 SemaDeclRefs.push_back(getGlobalDeclID(F, Record[I]));
3066 break;
3067
3068 case PPD_ENTITIES_OFFSETS: {
Chris Lattner0e6c9402013-01-20 02:38:54 +00003069 F.PreprocessedEntityOffsets = (const PPEntityOffset *)Blob.data();
3070 assert(Blob.size() % sizeof(PPEntityOffset) == 0);
3071 F.NumPreprocessedEntities = Blob.size() / sizeof(PPEntityOffset);
Guy Benyei11169dd2012-12-18 14:30:41 +00003072
3073 unsigned LocalBasePreprocessedEntityID = Record[0];
David L. Jonesc4808b9e2016-12-15 20:53:26 +00003074
Guy Benyei11169dd2012-12-18 14:30:41 +00003075 unsigned StartingID;
3076 if (!PP.getPreprocessingRecord())
3077 PP.createPreprocessingRecord();
3078 if (!PP.getPreprocessingRecord()->getExternalSource())
3079 PP.getPreprocessingRecord()->SetExternalSource(*this);
David L. Jonesc4808b9e2016-12-15 20:53:26 +00003080 StartingID
Guy Benyei11169dd2012-12-18 14:30:41 +00003081 = PP.getPreprocessingRecord()
Ben Langmuir52ca6782014-10-20 16:27:32 +00003082 ->allocateLoadedEntities(F.NumPreprocessedEntities);
Guy Benyei11169dd2012-12-18 14:30:41 +00003083 F.BasePreprocessedEntityID = StartingID;
3084
3085 if (F.NumPreprocessedEntities > 0) {
3086 // Introduce the global -> local mapping for preprocessed entities in
3087 // this module.
3088 GlobalPreprocessedEntityMap.insert(std::make_pair(StartingID, &F));
David L. Jonesc4808b9e2016-12-15 20:53:26 +00003089
Guy Benyei11169dd2012-12-18 14:30:41 +00003090 // Introduce the local -> global mapping for preprocessed entities in
3091 // this module.
3092 F.PreprocessedEntityRemap.insertOrReplace(
3093 std::make_pair(LocalBasePreprocessedEntityID,
3094 F.BasePreprocessedEntityID - LocalBasePreprocessedEntityID));
3095 }
3096
3097 break;
3098 }
David L. Jonesc4808b9e2016-12-15 20:53:26 +00003099
Guy Benyei11169dd2012-12-18 14:30:41 +00003100 case DECL_UPDATE_OFFSETS: {
3101 if (Record.size() % 2 != 0) {
3102 Error("invalid DECL_UPDATE_OFFSETS block in AST file");
Ben Langmuir2c9af442014-04-10 17:57:43 +00003103 return Failure;
Guy Benyei11169dd2012-12-18 14:30:41 +00003104 }
Richard Smithcd45dbc2014-04-19 03:48:30 +00003105 for (unsigned I = 0, N = Record.size(); I != N; I += 2) {
3106 GlobalDeclID ID = getGlobalDeclID(F, Record[I]);
3107 DeclUpdateOffsets[ID].push_back(std::make_pair(&F, Record[I + 1]));
3108
3109 // If we've already loaded the decl, perform the updates when we finish
3110 // loading this block.
3111 if (Decl *D = GetExistingDecl(ID))
3112 PendingUpdateRecords.push_back(std::make_pair(ID, D));
3113 }
Guy Benyei11169dd2012-12-18 14:30:41 +00003114 break;
3115 }
3116
Guy Benyei11169dd2012-12-18 14:30:41 +00003117 case OBJC_CATEGORIES_MAP: {
3118 if (F.LocalNumObjCCategoriesInMap != 0) {
3119 Error("duplicate OBJC_CATEGORIES_MAP record in AST file");
Ben Langmuir2c9af442014-04-10 17:57:43 +00003120 return Failure;
Guy Benyei11169dd2012-12-18 14:30:41 +00003121 }
David L. Jonesc4808b9e2016-12-15 20:53:26 +00003122
Guy Benyei11169dd2012-12-18 14:30:41 +00003123 F.LocalNumObjCCategoriesInMap = Record[0];
Chris Lattner0e6c9402013-01-20 02:38:54 +00003124 F.ObjCCategoriesMap = (const ObjCCategoriesInfo *)Blob.data();
Guy Benyei11169dd2012-12-18 14:30:41 +00003125 break;
3126 }
David L. Jonesc4808b9e2016-12-15 20:53:26 +00003127
Guy Benyei11169dd2012-12-18 14:30:41 +00003128 case OBJC_CATEGORIES:
3129 F.ObjCCategories.swap(Record);
3130 break;
Richard Smithc2bb8182015-03-24 06:36:48 +00003131
Guy Benyei11169dd2012-12-18 14:30:41 +00003132 case DIAG_PRAGMA_MAPPINGS:
3133 if (F.PragmaDiagMappings.empty())
3134 F.PragmaDiagMappings.swap(Record);
3135 else
3136 F.PragmaDiagMappings.insert(F.PragmaDiagMappings.end(),
3137 Record.begin(), Record.end());
3138 break;
David L. Jonesc4808b9e2016-12-15 20:53:26 +00003139
Guy Benyei11169dd2012-12-18 14:30:41 +00003140 case CUDA_SPECIAL_DECL_REFS:
3141 // Later tables overwrite earlier ones.
3142 // FIXME: Modules will have trouble with this.
3143 CUDASpecialDeclRefs.clear();
3144 for (unsigned I = 0, N = Record.size(); I != N; ++I)
3145 CUDASpecialDeclRefs.push_back(getGlobalDeclID(F, Record[I]));
3146 break;
3147
3148 case HEADER_SEARCH_TABLE: {
Chris Lattner0e6c9402013-01-20 02:38:54 +00003149 F.HeaderFileInfoTableData = Blob.data();
Guy Benyei11169dd2012-12-18 14:30:41 +00003150 F.LocalNumHeaderFileInfos = Record[1];
Guy Benyei11169dd2012-12-18 14:30:41 +00003151 if (Record[0]) {
3152 F.HeaderFileInfoTable
3153 = HeaderFileInfoLookupTable::Create(
3154 (const unsigned char *)F.HeaderFileInfoTableData + Record[0],
3155 (const unsigned char *)F.HeaderFileInfoTableData,
David L. Jonesc4808b9e2016-12-15 20:53:26 +00003156 HeaderFileInfoTrait(*this, F,
Guy Benyei11169dd2012-12-18 14:30:41 +00003157 &PP.getHeaderSearchInfo(),
Chris Lattner0e6c9402013-01-20 02:38:54 +00003158 Blob.data() + Record[2]));
David L. Jonesc4808b9e2016-12-15 20:53:26 +00003159
Guy Benyei11169dd2012-12-18 14:30:41 +00003160 PP.getHeaderSearchInfo().SetExternalSource(this);
3161 if (!PP.getHeaderSearchInfo().getExternalLookup())
3162 PP.getHeaderSearchInfo().SetExternalLookup(this);
3163 }
3164 break;
3165 }
David L. Jonesc4808b9e2016-12-15 20:53:26 +00003166
Guy Benyei11169dd2012-12-18 14:30:41 +00003167 case FP_PRAGMA_OPTIONS:
3168 // Later tables overwrite earlier ones.
3169 FPPragmaOptions.swap(Record);
3170 break;
3171
3172 case OPENCL_EXTENSIONS:
Yaxun Liu5b746652016-12-18 05:18:55 +00003173 for (unsigned I = 0, E = Record.size(); I != E; ) {
3174 auto Name = ReadString(Record, I);
3175 auto &Opt = OpenCLExtensions.OptMap[Name];
Yaxun Liucc2741c2016-12-18 06:35:06 +00003176 Opt.Supported = Record[I++] != 0;
3177 Opt.Enabled = Record[I++] != 0;
Yaxun Liu5b746652016-12-18 05:18:55 +00003178 Opt.Avail = Record[I++];
3179 Opt.Core = Record[I++];
3180 }
3181 break;
3182
3183 case OPENCL_EXTENSION_TYPES:
3184 for (unsigned I = 0, E = Record.size(); I != E;) {
3185 auto TypeID = static_cast<::TypeID>(Record[I++]);
3186 auto *Type = GetType(TypeID).getTypePtr();
3187 auto NumExt = static_cast<unsigned>(Record[I++]);
3188 for (unsigned II = 0; II != NumExt; ++II) {
3189 auto Ext = ReadString(Record, I);
3190 OpenCLTypeExtMap[Type].insert(Ext);
3191 }
3192 }
3193 break;
3194
3195 case OPENCL_EXTENSION_DECLS:
3196 for (unsigned I = 0, E = Record.size(); I != E;) {
3197 auto DeclID = static_cast<::DeclID>(Record[I++]);
3198 auto *Decl = GetDecl(DeclID);
3199 auto NumExt = static_cast<unsigned>(Record[I++]);
3200 for (unsigned II = 0; II != NumExt; ++II) {
3201 auto Ext = ReadString(Record, I);
3202 OpenCLDeclExtMap[Decl].insert(Ext);
3203 }
3204 }
Guy Benyei11169dd2012-12-18 14:30:41 +00003205 break;
3206
3207 case TENTATIVE_DEFINITIONS:
3208 for (unsigned I = 0, N = Record.size(); I != N; ++I)
3209 TentativeDefinitions.push_back(getGlobalDeclID(F, Record[I]));
3210 break;
David L. Jonesc4808b9e2016-12-15 20:53:26 +00003211
Guy Benyei11169dd2012-12-18 14:30:41 +00003212 case KNOWN_NAMESPACES:
3213 for (unsigned I = 0, N = Record.size(); I != N; ++I)
3214 KnownNamespaces.push_back(getGlobalDeclID(F, Record[I]));
3215 break;
Nick Lewycky8334af82013-01-26 00:35:08 +00003216
Nick Lewycky9c7eb1d2013-02-01 08:13:20 +00003217 case UNDEFINED_BUT_USED:
3218 if (UndefinedButUsed.size() % 2 != 0) {
3219 Error("Invalid existing UndefinedButUsed");
Ben Langmuir2c9af442014-04-10 17:57:43 +00003220 return Failure;
Nick Lewycky8334af82013-01-26 00:35:08 +00003221 }
3222
3223 if (Record.size() % 2 != 0) {
Nick Lewycky9c7eb1d2013-02-01 08:13:20 +00003224 Error("invalid undefined-but-used record");
Ben Langmuir2c9af442014-04-10 17:57:43 +00003225 return Failure;
Nick Lewycky8334af82013-01-26 00:35:08 +00003226 }
3227 for (unsigned I = 0, N = Record.size(); I != N; /* in loop */) {
Nick Lewycky9c7eb1d2013-02-01 08:13:20 +00003228 UndefinedButUsed.push_back(getGlobalDeclID(F, Record[I++]));
3229 UndefinedButUsed.push_back(
Nick Lewycky8334af82013-01-26 00:35:08 +00003230 ReadSourceLocation(F, Record, I).getRawEncoding());
3231 }
3232 break;
Ismail Pazarbasie5768d12015-05-18 19:59:11 +00003233 case DELETE_EXPRS_TO_ANALYZE:
3234 for (unsigned I = 0, N = Record.size(); I != N;) {
3235 DelayedDeleteExprs.push_back(getGlobalDeclID(F, Record[I++]));
3236 const uint64_t Count = Record[I++];
3237 DelayedDeleteExprs.push_back(Count);
3238 for (uint64_t C = 0; C < Count; ++C) {
3239 DelayedDeleteExprs.push_back(ReadSourceLocation(F, Record, I).getRawEncoding());
3240 bool IsArrayForm = Record[I++] == 1;
3241 DelayedDeleteExprs.push_back(IsArrayForm);
3242 }
3243 }
3244 break;
Nick Lewycky8334af82013-01-26 00:35:08 +00003245
Guy Benyei11169dd2012-12-18 14:30:41 +00003246 case IMPORTED_MODULES: {
Manman Ren11f2a472016-08-18 17:42:15 +00003247 if (!F.isModule()) {
Guy Benyei11169dd2012-12-18 14:30:41 +00003248 // If we aren't loading a module (which has its own exports), make
3249 // all of the imported modules visible.
3250 // FIXME: Deal with macros-only imports.
Richard Smith56be7542014-03-21 00:33:59 +00003251 for (unsigned I = 0, N = Record.size(); I != N; /**/) {
3252 unsigned GlobalID = getGlobalSubmoduleID(F, Record[I++]);
3253 SourceLocation Loc = ReadSourceLocation(F, Record, I);
Graydon Hoare9c982442017-01-18 20:36:59 +00003254 if (GlobalID) {
Aaron Ballman4f45b712014-03-21 15:22:56 +00003255 ImportedModules.push_back(ImportedSubmodule(GlobalID, Loc));
Graydon Hoare9c982442017-01-18 20:36:59 +00003256 if (DeserializationListener)
3257 DeserializationListener->ModuleImportRead(GlobalID, Loc);
3258 }
Guy Benyei11169dd2012-12-18 14:30:41 +00003259 }
3260 }
3261 break;
3262 }
3263
Guy Benyei11169dd2012-12-18 14:30:41 +00003264 case MACRO_OFFSET: {
3265 if (F.LocalNumMacros != 0) {
3266 Error("duplicate MACRO_OFFSET record in AST file");
Ben Langmuir2c9af442014-04-10 17:57:43 +00003267 return Failure;
Guy Benyei11169dd2012-12-18 14:30:41 +00003268 }
Chris Lattner0e6c9402013-01-20 02:38:54 +00003269 F.MacroOffsets = (const uint32_t *)Blob.data();
Guy Benyei11169dd2012-12-18 14:30:41 +00003270 F.LocalNumMacros = Record[0];
3271 unsigned LocalBaseMacroID = Record[1];
3272 F.BaseMacroID = getTotalNumMacros();
3273
3274 if (F.LocalNumMacros > 0) {
3275 // Introduce the global -> local mapping for macros within this module.
3276 GlobalMacroMap.insert(std::make_pair(getTotalNumMacros() + 1, &F));
3277
3278 // Introduce the local -> global mapping for macros within this module.
3279 F.MacroRemap.insertOrReplace(
3280 std::make_pair(LocalBaseMacroID,
3281 F.BaseMacroID - LocalBaseMacroID));
Ben Langmuir52ca6782014-10-20 16:27:32 +00003282
3283 MacrosLoaded.resize(MacrosLoaded.size() + F.LocalNumMacros);
Guy Benyei11169dd2012-12-18 14:30:41 +00003284 }
3285 break;
3286 }
3287
Richard Smithe40f2ba2013-08-07 21:41:30 +00003288 case LATE_PARSED_TEMPLATE: {
3289 LateParsedTemplates.append(Record.begin(), Record.end());
3290 break;
3291 }
Dario Domizioli13a0a382014-05-23 12:13:25 +00003292
3293 case OPTIMIZE_PRAGMA_OPTIONS:
3294 if (Record.size() != 1) {
3295 Error("invalid pragma optimize record");
3296 return Failure;
3297 }
3298 OptimizeOffPragmaLocation = ReadSourceLocation(F, Record[0]);
3299 break;
Nico Weber72889432014-09-06 01:25:55 +00003300
Nico Weber779355f2016-03-02 23:22:00 +00003301 case MSSTRUCT_PRAGMA_OPTIONS:
3302 if (Record.size() != 1) {
3303 Error("invalid pragma ms_struct record");
3304 return Failure;
3305 }
3306 PragmaMSStructState = Record[0];
3307 break;
3308
Nico Weber42932312016-03-03 00:17:35 +00003309 case POINTERS_TO_MEMBERS_PRAGMA_OPTIONS:
3310 if (Record.size() != 2) {
3311 Error("invalid pragma ms_struct record");
3312 return Failure;
3313 }
3314 PragmaMSPointersToMembersState = Record[0];
3315 PointersToMembersPragmaLocation = ReadSourceLocation(F, Record[1]);
3316 break;
3317
Nico Weber72889432014-09-06 01:25:55 +00003318 case UNUSED_LOCAL_TYPEDEF_NAME_CANDIDATES:
3319 for (unsigned I = 0, N = Record.size(); I != N; ++I)
3320 UnusedLocalTypedefNameCandidates.push_back(
3321 getGlobalDeclID(F, Record[I]));
3322 break;
Justin Lebar67a78a62016-10-08 22:15:58 +00003323
3324 case CUDA_PRAGMA_FORCE_HOST_DEVICE_DEPTH:
3325 if (Record.size() != 1) {
3326 Error("invalid cuda pragma options record");
3327 return Failure;
3328 }
3329 ForceCUDAHostDeviceDepth = Record[0];
3330 break;
Guy Benyei11169dd2012-12-18 14:30:41 +00003331 }
3332 }
Guy Benyei11169dd2012-12-18 14:30:41 +00003333}
3334
Ben Langmuir4b8a9e92014-08-12 16:42:33 +00003335ASTReader::ASTReadResult
3336ASTReader::ReadModuleMapFileBlock(RecordData &Record, ModuleFile &F,
3337 const ModuleFile *ImportedBy,
3338 unsigned ClientLoadCapabilities) {
3339 unsigned Idx = 0;
Richard Smith7ed1bc92014-12-05 22:42:13 +00003340 F.ModuleMapPath = ReadPath(F, Record, Idx);
Ben Langmuir4b8a9e92014-08-12 16:42:33 +00003341
Manman Ren11f2a472016-08-18 17:42:15 +00003342 if (F.Kind == MK_ExplicitModule || F.Kind == MK_PrebuiltModule) {
Richard Smithe842a472014-10-22 02:05:46 +00003343 // For an explicitly-loaded module, we don't care whether the original
3344 // module map file exists or matches.
3345 return Success;
3346 }
3347
Ben Langmuir4b8a9e92014-08-12 16:42:33 +00003348 // Try to resolve ModuleName in the current header search context and
3349 // verify that it is found in the same module map file as we saved. If the
3350 // top-level AST file is a main file, skip this check because there is no
3351 // usable header search context.
3352 assert(!F.ModuleName.empty() &&
Richard Smithe842a472014-10-22 02:05:46 +00003353 "MODULE_NAME should come before MODULE_MAP_FILE");
3354 if (F.Kind == MK_ImplicitModule &&
3355 (*ModuleMgr.begin())->Kind != MK_MainFile) {
3356 // An implicitly-loaded module file should have its module listed in some
3357 // module map file that we've already loaded.
Ben Langmuir4b8a9e92014-08-12 16:42:33 +00003358 Module *M = PP.getHeaderSearchInfo().lookupModule(F.ModuleName);
Richard Smithe842a472014-10-22 02:05:46 +00003359 auto &Map = PP.getHeaderSearchInfo().getModuleMap();
3360 const FileEntry *ModMap = M ? Map.getModuleMapFileForUniquing(M) : nullptr;
3361 if (!ModMap) {
Ben Langmuir4b8a9e92014-08-12 16:42:33 +00003362 assert(ImportedBy && "top-level import should be verified");
Richard Smith0f99d6a2015-08-09 08:48:41 +00003363 if ((ClientLoadCapabilities & ARR_OutOfDate) == 0) {
3364 if (auto *ASTFE = M ? M->getASTFile() : nullptr)
3365 // This module was defined by an imported (explicit) module.
3366 Diag(diag::err_module_file_conflict) << F.ModuleName << F.FileName
3367 << ASTFE->getName();
3368 else
3369 // This module was built with a different module map.
3370 Diag(diag::err_imported_module_not_found)
3371 << F.ModuleName << F.FileName << ImportedBy->FileName
3372 << F.ModuleMapPath;
3373 }
3374 return OutOfDate;
Ben Langmuir4b8a9e92014-08-12 16:42:33 +00003375 }
3376
Richard Smithe842a472014-10-22 02:05:46 +00003377 assert(M->Name == F.ModuleName && "found module with different name");
3378
Ben Langmuir4b8a9e92014-08-12 16:42:33 +00003379 // Check the primary module map file.
Ben Langmuir4b8a9e92014-08-12 16:42:33 +00003380 const FileEntry *StoredModMap = FileMgr.getFile(F.ModuleMapPath);
Ben Langmuir4b8a9e92014-08-12 16:42:33 +00003381 if (StoredModMap == nullptr || StoredModMap != ModMap) {
3382 assert(ModMap && "found module is missing module map file");
Ben Langmuir4b8a9e92014-08-12 16:42:33 +00003383 assert(ImportedBy && "top-level import should be verified");
3384 if ((ClientLoadCapabilities & ARR_OutOfDate) == 0)
3385 Diag(diag::err_imported_module_modmap_changed)
3386 << F.ModuleName << ImportedBy->FileName
3387 << ModMap->getName() << F.ModuleMapPath;
3388 return OutOfDate;
3389 }
3390
3391 llvm::SmallPtrSet<const FileEntry *, 1> AdditionalStoredMaps;
3392 for (unsigned I = 0, N = Record[Idx++]; I < N; ++I) {
3393 // FIXME: we should use input files rather than storing names.
Richard Smith7ed1bc92014-12-05 22:42:13 +00003394 std::string Filename = ReadPath(F, Record, Idx);
Ben Langmuir4b8a9e92014-08-12 16:42:33 +00003395 const FileEntry *F =
3396 FileMgr.getFile(Filename, false, false);
3397 if (F == nullptr) {
3398 if ((ClientLoadCapabilities & ARR_OutOfDate) == 0)
3399 Error("could not find file '" + Filename +"' referenced by AST file");
3400 return OutOfDate;
3401 }
3402 AdditionalStoredMaps.insert(F);
3403 }
3404
3405 // Check any additional module map files (e.g. module.private.modulemap)
3406 // that are not in the pcm.
3407 if (auto *AdditionalModuleMaps = Map.getAdditionalModuleMapFiles(M)) {
3408 for (const FileEntry *ModMap : *AdditionalModuleMaps) {
3409 // Remove files that match
3410 // Note: SmallPtrSet::erase is really remove
3411 if (!AdditionalStoredMaps.erase(ModMap)) {
3412 if ((ClientLoadCapabilities & ARR_OutOfDate) == 0)
3413 Diag(diag::err_module_different_modmap)
3414 << F.ModuleName << /*new*/0 << ModMap->getName();
3415 return OutOfDate;
3416 }
3417 }
3418 }
3419
3420 // Check any additional module map files that are in the pcm, but not
3421 // found in header search. Cases that match are already removed.
3422 for (const FileEntry *ModMap : AdditionalStoredMaps) {
3423 if ((ClientLoadCapabilities & ARR_OutOfDate) == 0)
3424 Diag(diag::err_module_different_modmap)
3425 << F.ModuleName << /*not new*/1 << ModMap->getName();
3426 return OutOfDate;
3427 }
3428 }
3429
3430 if (Listener)
3431 Listener->ReadModuleMapFile(F.ModuleMapPath);
3432 return Success;
3433}
3434
3435
Douglas Gregorc1489562013-02-12 23:36:21 +00003436/// \brief Move the given method to the back of the global list of methods.
3437static void moveMethodToBackOfGlobalList(Sema &S, ObjCMethodDecl *Method) {
3438 // Find the entry for this selector in the method pool.
3439 Sema::GlobalMethodPool::iterator Known
3440 = S.MethodPool.find(Method->getSelector());
3441 if (Known == S.MethodPool.end())
3442 return;
3443
3444 // Retrieve the appropriate method list.
3445 ObjCMethodList &Start = Method->isInstanceMethod()? Known->second.first
3446 : Known->second.second;
3447 bool Found = false;
Argyrios Kyrtzidisd3da6e02013-04-17 00:08:58 +00003448 for (ObjCMethodList *List = &Start; List; List = List->getNext()) {
Douglas Gregorc1489562013-02-12 23:36:21 +00003449 if (!Found) {
Nico Weber2e0c8f72014-12-27 03:58:08 +00003450 if (List->getMethod() == Method) {
Douglas Gregorc1489562013-02-12 23:36:21 +00003451 Found = true;
3452 } else {
3453 // Keep searching.
3454 continue;
3455 }
3456 }
3457
Argyrios Kyrtzidisd3da6e02013-04-17 00:08:58 +00003458 if (List->getNext())
Nico Weber2e0c8f72014-12-27 03:58:08 +00003459 List->setMethod(List->getNext()->getMethod());
Douglas Gregorc1489562013-02-12 23:36:21 +00003460 else
Nico Weber2e0c8f72014-12-27 03:58:08 +00003461 List->setMethod(Method);
Douglas Gregorc1489562013-02-12 23:36:21 +00003462 }
3463}
3464
Richard Smithde711422015-04-23 21:20:19 +00003465void ASTReader::makeNamesVisible(const HiddenNames &Names, Module *Owner) {
Richard Smith10434f32015-05-02 02:08:26 +00003466 assert(Owner->NameVisibility != Module::Hidden && "nothing to make visible?");
Richard Smith20e883e2015-04-29 23:20:19 +00003467 for (Decl *D : Names) {
Richard Smith49f906a2014-03-01 00:08:04 +00003468 bool wasHidden = D->Hidden;
3469 D->Hidden = false;
Guy Benyei11169dd2012-12-18 14:30:41 +00003470
Richard Smith49f906a2014-03-01 00:08:04 +00003471 if (wasHidden && SemaObj) {
3472 if (ObjCMethodDecl *Method = dyn_cast<ObjCMethodDecl>(D)) {
3473 moveMethodToBackOfGlobalList(*SemaObj, Method);
Douglas Gregorc1489562013-02-12 23:36:21 +00003474 }
Guy Benyei11169dd2012-12-18 14:30:41 +00003475 }
3476 }
3477}
3478
Richard Smith49f906a2014-03-01 00:08:04 +00003479void ASTReader::makeModuleVisible(Module *Mod,
Argyrios Kyrtzidis125df052013-02-01 16:36:12 +00003480 Module::NameVisibilityKind NameVisibility,
Richard Smitha7e2cc62015-05-01 01:53:09 +00003481 SourceLocation ImportLoc) {
Guy Benyei11169dd2012-12-18 14:30:41 +00003482 llvm::SmallPtrSet<Module *, 4> Visited;
Dmitri Gribenkof8579502013-01-12 19:30:44 +00003483 SmallVector<Module *, 4> Stack;
Robert Wilhelm25284cc2013-08-23 16:11:15 +00003484 Stack.push_back(Mod);
Guy Benyei11169dd2012-12-18 14:30:41 +00003485 while (!Stack.empty()) {
Robert Wilhelm25284cc2013-08-23 16:11:15 +00003486 Mod = Stack.pop_back_val();
Guy Benyei11169dd2012-12-18 14:30:41 +00003487
3488 if (NameVisibility <= Mod->NameVisibility) {
Robert Wilhelm25284cc2013-08-23 16:11:15 +00003489 // This module already has this level of visibility (or greater), so
Guy Benyei11169dd2012-12-18 14:30:41 +00003490 // there is nothing more to do.
3491 continue;
3492 }
Richard Smith49f906a2014-03-01 00:08:04 +00003493
Guy Benyei11169dd2012-12-18 14:30:41 +00003494 if (!Mod->isAvailable()) {
3495 // Modules that aren't available cannot be made visible.
3496 continue;
3497 }
3498
3499 // Update the module's name visibility.
3500 Mod->NameVisibility = NameVisibility;
Richard Smith49f906a2014-03-01 00:08:04 +00003501
Guy Benyei11169dd2012-12-18 14:30:41 +00003502 // If we've already deserialized any names from this module,
3503 // mark them as visible.
3504 HiddenNamesMapType::iterator Hidden = HiddenNamesMap.find(Mod);
3505 if (Hidden != HiddenNamesMap.end()) {
Richard Smith57721ac2014-07-21 04:10:40 +00003506 auto HiddenNames = std::move(*Hidden);
Guy Benyei11169dd2012-12-18 14:30:41 +00003507 HiddenNamesMap.erase(Hidden);
Richard Smithde711422015-04-23 21:20:19 +00003508 makeNamesVisible(HiddenNames.second, HiddenNames.first);
Richard Smith57721ac2014-07-21 04:10:40 +00003509 assert(HiddenNamesMap.find(Mod) == HiddenNamesMap.end() &&
3510 "making names visible added hidden names");
Guy Benyei11169dd2012-12-18 14:30:41 +00003511 }
Dmitri Gribenkoe9bcf5b2013-11-04 21:51:33 +00003512
Guy Benyei11169dd2012-12-18 14:30:41 +00003513 // Push any exported modules onto the stack to be marked as visible.
Argyrios Kyrtzidis8739f7b2013-02-19 19:34:40 +00003514 SmallVector<Module *, 16> Exports;
3515 Mod->getExportedModules(Exports);
3516 for (SmallVectorImpl<Module *>::iterator
3517 I = Exports.begin(), E = Exports.end(); I != E; ++I) {
3518 Module *Exported = *I;
David Blaikie82e95a32014-11-19 07:49:47 +00003519 if (Visited.insert(Exported).second)
Argyrios Kyrtzidis8739f7b2013-02-19 19:34:40 +00003520 Stack.push_back(Exported);
Guy Benyei11169dd2012-12-18 14:30:41 +00003521 }
3522 }
3523}
3524
Richard Smith6561f922016-09-12 21:06:40 +00003525/// We've merged the definition \p MergedDef into the existing definition
3526/// \p Def. Ensure that \p Def is made visible whenever \p MergedDef is made
3527/// visible.
3528void ASTReader::mergeDefinitionVisibility(NamedDecl *Def,
3529 NamedDecl *MergedDef) {
Benjamin Kramera72a70a2016-10-17 13:00:44 +00003530 // FIXME: This doesn't correctly handle the case where MergedDef is visible
3531 // in modules other than its owning module. We should instead give the
3532 // ASTContext a list of merged definitions for Def.
Richard Smith6561f922016-09-12 21:06:40 +00003533 if (Def->isHidden()) {
3534 // If MergedDef is visible or becomes visible, make the definition visible.
Benjamin Kramera72a70a2016-10-17 13:00:44 +00003535 if (!MergedDef->isHidden())
3536 Def->Hidden = false;
3537 else if (getContext().getLangOpts().ModulesLocalVisibility) {
3538 getContext().mergeDefinitionIntoModule(
3539 Def, MergedDef->getImportedOwningModule(),
3540 /*NotifyListeners*/ false);
3541 PendingMergedDefinitionsToDeduplicate.insert(Def);
3542 } else {
3543 auto SubmoduleID = MergedDef->getOwningModuleID();
3544 assert(SubmoduleID && "hidden definition in no module");
3545 HiddenNamesMap[getSubmodule(SubmoduleID)].push_back(Def);
3546 }
Richard Smith6561f922016-09-12 21:06:40 +00003547 }
3548}
3549
Douglas Gregore060e572013-01-25 01:03:03 +00003550bool ASTReader::loadGlobalIndex() {
3551 if (GlobalIndex)
3552 return false;
3553
3554 if (TriedLoadingGlobalIndex || !UseGlobalIndex ||
3555 !Context.getLangOpts().Modules)
3556 return true;
David L. Jonesc4808b9e2016-12-15 20:53:26 +00003557
Douglas Gregore060e572013-01-25 01:03:03 +00003558 // Try to load the global index.
3559 TriedLoadingGlobalIndex = true;
3560 StringRef ModuleCachePath
3561 = getPreprocessor().getHeaderSearchInfo().getModuleCachePath();
3562 std::pair<GlobalModuleIndex *, GlobalModuleIndex::ErrorCode> Result
Douglas Gregor7029ce12013-03-19 00:28:20 +00003563 = GlobalModuleIndex::readIndex(ModuleCachePath);
Douglas Gregore060e572013-01-25 01:03:03 +00003564 if (!Result.first)
3565 return true;
3566
3567 GlobalIndex.reset(Result.first);
Douglas Gregor7211ac12013-01-25 23:32:03 +00003568 ModuleMgr.setGlobalIndex(GlobalIndex.get());
Douglas Gregore060e572013-01-25 01:03:03 +00003569 return false;
3570}
3571
3572bool ASTReader::isGlobalIndexUnavailable() const {
3573 return Context.getLangOpts().Modules && UseGlobalIndex &&
3574 !hasGlobalIndex() && TriedLoadingGlobalIndex;
3575}
3576
Dmitri Gribenkof430da42014-02-12 10:33:14 +00003577static void updateModuleTimestamp(ModuleFile &MF) {
3578 // Overwrite the timestamp file contents so that file's mtime changes.
3579 std::string TimestampFilename = MF.getTimestampFilename();
Rafael Espindoladae941a2014-08-25 18:17:04 +00003580 std::error_code EC;
3581 llvm::raw_fd_ostream OS(TimestampFilename, EC, llvm::sys::fs::F_Text);
3582 if (EC)
Dmitri Gribenkof430da42014-02-12 10:33:14 +00003583 return;
3584 OS << "Timestamp file\n";
3585}
3586
Douglas Gregor6623e1f2015-11-03 18:33:07 +00003587/// \brief Given a cursor at the start of an AST file, scan ahead and drop the
3588/// cursor into the start of the given block ID, returning false on success and
3589/// true on failure.
3590static bool SkipCursorToBlock(BitstreamCursor &Cursor, unsigned BlockID) {
Eugene Zelenkoe95e7d52016-09-07 21:53:17 +00003591 while (true) {
Douglas Gregor6623e1f2015-11-03 18:33:07 +00003592 llvm::BitstreamEntry Entry = Cursor.advance();
3593 switch (Entry.Kind) {
3594 case llvm::BitstreamEntry::Error:
3595 case llvm::BitstreamEntry::EndBlock:
3596 return true;
3597
3598 case llvm::BitstreamEntry::Record:
3599 // Ignore top-level records.
3600 Cursor.skipRecord(Entry.ID);
3601 break;
3602
3603 case llvm::BitstreamEntry::SubBlock:
3604 if (Entry.ID == BlockID) {
3605 if (Cursor.EnterSubBlock(BlockID))
3606 return true;
3607 // Found it!
3608 return false;
3609 }
3610
3611 if (Cursor.SkipBlock())
3612 return true;
3613 }
3614 }
3615}
3616
Benjamin Kramer0772c422016-02-13 13:42:54 +00003617ASTReader::ASTReadResult ASTReader::ReadAST(StringRef FileName,
Guy Benyei11169dd2012-12-18 14:30:41 +00003618 ModuleKind Type,
3619 SourceLocation ImportLoc,
Graydon Hoaree7196af2016-12-09 21:45:49 +00003620 unsigned ClientLoadCapabilities,
3621 SmallVectorImpl<ImportedSubmodule> *Imported) {
Argyrios Kyrtzidisdc9fdaf2013-05-24 05:44:08 +00003622 llvm::SaveAndRestore<SourceLocation>
3623 SetCurImportLocRAII(CurrentImportLoc, ImportLoc);
3624
Richard Smithd1c46742014-04-30 02:24:17 +00003625 // Defer any pending actions until we get to the end of reading the AST file.
3626 Deserializing AnASTFile(this);
3627
Guy Benyei11169dd2012-12-18 14:30:41 +00003628 // Bump the generation number.
Richard Smith053f6c62014-05-16 23:01:30 +00003629 unsigned PreviousGeneration = incrementGeneration(Context);
Guy Benyei11169dd2012-12-18 14:30:41 +00003630
3631 unsigned NumModules = ModuleMgr.size();
Dmitri Gribenkof8579502013-01-12 19:30:44 +00003632 SmallVector<ImportedModule, 4> Loaded;
Guy Benyei11169dd2012-12-18 14:30:41 +00003633 switch(ASTReadResult ReadResult = ReadASTCore(FileName, Type, ImportLoc,
Craig Toppera13603a2014-05-22 05:54:18 +00003634 /*ImportedBy=*/nullptr, Loaded,
Ben Langmuir487ea142014-10-23 18:05:36 +00003635 0, 0, 0,
Guy Benyei11169dd2012-12-18 14:30:41 +00003636 ClientLoadCapabilities)) {
3637 case Failure:
Douglas Gregor7029ce12013-03-19 00:28:20 +00003638 case Missing:
Guy Benyei11169dd2012-12-18 14:30:41 +00003639 case OutOfDate:
3640 case VersionMismatch:
3641 case ConfigurationMismatch:
Ben Langmuir9801b252014-06-20 00:24:56 +00003642 case HadErrors: {
3643 llvm::SmallPtrSet<ModuleFile *, 4> LoadedSet;
3644 for (const ImportedModule &IM : Loaded)
3645 LoadedSet.insert(IM.Mod);
3646
Douglas Gregor7029ce12013-03-19 00:28:20 +00003647 ModuleMgr.removeModules(ModuleMgr.begin() + NumModules, ModuleMgr.end(),
Ben Langmuir9801b252014-06-20 00:24:56 +00003648 LoadedSet,
Douglas Gregor7029ce12013-03-19 00:28:20 +00003649 Context.getLangOpts().Modules
3650 ? &PP.getHeaderSearchInfo().getModuleMap()
Craig Toppera13603a2014-05-22 05:54:18 +00003651 : nullptr);
Douglas Gregore060e572013-01-25 01:03:03 +00003652
3653 // If we find that any modules are unusable, the global index is going
3654 // to be out-of-date. Just remove it.
3655 GlobalIndex.reset();
Craig Toppera13603a2014-05-22 05:54:18 +00003656 ModuleMgr.setGlobalIndex(nullptr);
Guy Benyei11169dd2012-12-18 14:30:41 +00003657 return ReadResult;
Ben Langmuir9801b252014-06-20 00:24:56 +00003658 }
Guy Benyei11169dd2012-12-18 14:30:41 +00003659 case Success:
3660 break;
3661 }
3662
3663 // Here comes stuff that we only do once the entire chain is loaded.
3664
3665 // Load the AST blocks of all of the modules that we loaded.
Dmitri Gribenkof8579502013-01-12 19:30:44 +00003666 for (SmallVectorImpl<ImportedModule>::iterator M = Loaded.begin(),
3667 MEnd = Loaded.end();
Guy Benyei11169dd2012-12-18 14:30:41 +00003668 M != MEnd; ++M) {
3669 ModuleFile &F = *M->Mod;
3670
3671 // Read the AST block.
Ben Langmuir2c9af442014-04-10 17:57:43 +00003672 if (ASTReadResult Result = ReadASTBlock(F, ClientLoadCapabilities))
3673 return Result;
Guy Benyei11169dd2012-12-18 14:30:41 +00003674
Douglas Gregor6623e1f2015-11-03 18:33:07 +00003675 // Read the extension blocks.
3676 while (!SkipCursorToBlock(F.Stream, EXTENSION_BLOCK_ID)) {
3677 if (ASTReadResult Result = ReadExtensionBlock(F))
3678 return Result;
3679 }
3680
David L. Jonesc4808b9e2016-12-15 20:53:26 +00003681 // Once read, set the ModuleFile bit base offset and update the size in
Guy Benyei11169dd2012-12-18 14:30:41 +00003682 // bits of all files we've seen.
3683 F.GlobalBitOffset = TotalModulesSizeInBits;
3684 TotalModulesSizeInBits += F.SizeInBits;
3685 GlobalBitOffsetsMap.insert(std::make_pair(F.GlobalBitOffset, &F));
David L. Jonesc4808b9e2016-12-15 20:53:26 +00003686
Guy Benyei11169dd2012-12-18 14:30:41 +00003687 // Preload SLocEntries.
3688 for (unsigned I = 0, N = F.PreloadSLocEntries.size(); I != N; ++I) {
3689 int Index = int(F.PreloadSLocEntries[I] - 1) + F.SLocEntryBaseID;
3690 // Load it through the SourceManager and don't call ReadSLocEntry()
3691 // directly because the entry may have already been loaded in which case
3692 // calling ReadSLocEntry() directly would trigger an assertion in
3693 // SourceManager.
3694 SourceMgr.getLoadedSLocEntryByID(Index);
3695 }
Richard Smith33e0f7e2015-07-22 02:08:40 +00003696
3697 // Preload all the pending interesting identifiers by marking them out of
3698 // date.
3699 for (auto Offset : F.PreloadIdentifierOffsets) {
3700 const unsigned char *Data = reinterpret_cast<const unsigned char *>(
3701 F.IdentifierTableData + Offset);
3702
3703 ASTIdentifierLookupTrait Trait(*this, F);
3704 auto KeyDataLen = Trait.ReadKeyDataLength(Data);
3705 auto Key = Trait.ReadKey(Data, KeyDataLen.first);
Richard Smith79bf9202015-08-24 03:33:22 +00003706 auto &II = PP.getIdentifierTable().getOwn(Key);
3707 II.setOutOfDate(true);
3708
3709 // Mark this identifier as being from an AST file so that we can track
3710 // whether we need to serialize it.
Richard Smitheb4b58f62016-02-05 01:40:54 +00003711 markIdentifierFromAST(*this, II);
Richard Smith79bf9202015-08-24 03:33:22 +00003712
3713 // Associate the ID with the identifier so that the writer can reuse it.
3714 auto ID = Trait.ReadIdentifierID(Data + KeyDataLen.first);
3715 SetIdentifierInfo(ID, &II);
Richard Smith33e0f7e2015-07-22 02:08:40 +00003716 }
Guy Benyei11169dd2012-12-18 14:30:41 +00003717 }
3718
Douglas Gregor603cd862013-03-22 18:50:14 +00003719 // Setup the import locations and notify the module manager that we've
3720 // committed to these module files.
Dmitri Gribenkof8579502013-01-12 19:30:44 +00003721 for (SmallVectorImpl<ImportedModule>::iterator M = Loaded.begin(),
3722 MEnd = Loaded.end();
Guy Benyei11169dd2012-12-18 14:30:41 +00003723 M != MEnd; ++M) {
3724 ModuleFile &F = *M->Mod;
Douglas Gregor603cd862013-03-22 18:50:14 +00003725
3726 ModuleMgr.moduleFileAccepted(&F);
3727
3728 // Set the import location.
Argyrios Kyrtzidis71c1af82013-02-01 16:36:14 +00003729 F.DirectImportLoc = ImportLoc;
Richard Smithb22a1d12016-03-27 20:13:24 +00003730 // FIXME: We assume that locations from PCH / preamble do not need
3731 // any translation.
Guy Benyei11169dd2012-12-18 14:30:41 +00003732 if (!M->ImportedBy)
3733 F.ImportLoc = M->ImportLoc;
3734 else
Richard Smithb22a1d12016-03-27 20:13:24 +00003735 F.ImportLoc = TranslateSourceLocation(*M->ImportedBy, M->ImportLoc);
Guy Benyei11169dd2012-12-18 14:30:41 +00003736 }
3737
Richard Smith33e0f7e2015-07-22 02:08:40 +00003738 if (!Context.getLangOpts().CPlusPlus ||
Manman Ren11f2a472016-08-18 17:42:15 +00003739 (Type != MK_ImplicitModule && Type != MK_ExplicitModule &&
3740 Type != MK_PrebuiltModule)) {
Richard Smith33e0f7e2015-07-22 02:08:40 +00003741 // Mark all of the identifiers in the identifier table as being out of date,
3742 // so that various accessors know to check the loaded modules when the
3743 // identifier is used.
3744 //
3745 // For C++ modules, we don't need information on many identifiers (just
3746 // those that provide macros or are poisoned), so we mark all of
3747 // the interesting ones via PreloadIdentifierOffsets.
3748 for (IdentifierTable::iterator Id = PP.getIdentifierTable().begin(),
3749 IdEnd = PP.getIdentifierTable().end();
3750 Id != IdEnd; ++Id)
3751 Id->second->setOutOfDate(true);
3752 }
Manman Rena0f31a02016-04-29 19:04:05 +00003753 // Mark selectors as out of date.
3754 for (auto Sel : SelectorGeneration)
3755 SelectorOutOfDate[Sel.first] = true;
David L. Jonesc4808b9e2016-12-15 20:53:26 +00003756
Guy Benyei11169dd2012-12-18 14:30:41 +00003757 // Resolve any unresolved module exports.
Douglas Gregorfb912652013-03-20 21:10:35 +00003758 for (unsigned I = 0, N = UnresolvedModuleRefs.size(); I != N; ++I) {
3759 UnresolvedModuleRef &Unresolved = UnresolvedModuleRefs[I];
Guy Benyei11169dd2012-12-18 14:30:41 +00003760 SubmoduleID GlobalID = getGlobalSubmoduleID(*Unresolved.File,Unresolved.ID);
3761 Module *ResolvedMod = getSubmodule(GlobalID);
Douglas Gregorfb912652013-03-20 21:10:35 +00003762
3763 switch (Unresolved.Kind) {
3764 case UnresolvedModuleRef::Conflict:
3765 if (ResolvedMod) {
3766 Module::Conflict Conflict;
3767 Conflict.Other = ResolvedMod;
3768 Conflict.Message = Unresolved.String.str();
3769 Unresolved.Mod->Conflicts.push_back(Conflict);
3770 }
3771 continue;
3772
3773 case UnresolvedModuleRef::Import:
Guy Benyei11169dd2012-12-18 14:30:41 +00003774 if (ResolvedMod)
Richard Smith38477db2015-05-02 00:45:56 +00003775 Unresolved.Mod->Imports.insert(ResolvedMod);
Guy Benyei11169dd2012-12-18 14:30:41 +00003776 continue;
Guy Benyei11169dd2012-12-18 14:30:41 +00003777
Douglas Gregorfb912652013-03-20 21:10:35 +00003778 case UnresolvedModuleRef::Export:
3779 if (ResolvedMod || Unresolved.IsWildcard)
3780 Unresolved.Mod->Exports.push_back(
3781 Module::ExportDecl(ResolvedMod, Unresolved.IsWildcard));
3782 continue;
3783 }
Guy Benyei11169dd2012-12-18 14:30:41 +00003784 }
Douglas Gregorfb912652013-03-20 21:10:35 +00003785 UnresolvedModuleRefs.clear();
Daniel Jasperba7f2f72013-09-24 09:14:14 +00003786
Graydon Hoaree7196af2016-12-09 21:45:49 +00003787 if (Imported)
3788 Imported->append(ImportedModules.begin(),
3789 ImportedModules.end());
3790
Daniel Jasperba7f2f72013-09-24 09:14:14 +00003791 // FIXME: How do we load the 'use'd modules? They may not be submodules.
3792 // Might be unnecessary as use declarations are only used to build the
3793 // module itself.
David L. Jonesc4808b9e2016-12-15 20:53:26 +00003794
Guy Benyei11169dd2012-12-18 14:30:41 +00003795 InitializeContext();
3796
Richard Smith3d8e97e2013-10-18 06:54:39 +00003797 if (SemaObj)
3798 UpdateSema();
3799
Guy Benyei11169dd2012-12-18 14:30:41 +00003800 if (DeserializationListener)
3801 DeserializationListener->ReaderInitialized(this);
3802
3803 ModuleFile &PrimaryModule = ModuleMgr.getPrimaryModule();
Yaron Keren8b563662015-10-03 10:46:20 +00003804 if (PrimaryModule.OriginalSourceFileID.isValid()) {
David L. Jonesc4808b9e2016-12-15 20:53:26 +00003805 PrimaryModule.OriginalSourceFileID
Guy Benyei11169dd2012-12-18 14:30:41 +00003806 = FileID::get(PrimaryModule.SLocEntryBaseID
3807 + PrimaryModule.OriginalSourceFileID.getOpaqueValue() - 1);
3808
3809 // If this AST file is a precompiled preamble, then set the
3810 // preamble file ID of the source manager to the file source file
3811 // from which the preamble was built.
3812 if (Type == MK_Preamble) {
3813 SourceMgr.setPreambleFileID(PrimaryModule.OriginalSourceFileID);
3814 } else if (Type == MK_MainFile) {
3815 SourceMgr.setMainFileID(PrimaryModule.OriginalSourceFileID);
3816 }
3817 }
David L. Jonesc4808b9e2016-12-15 20:53:26 +00003818
Guy Benyei11169dd2012-12-18 14:30:41 +00003819 // For any Objective-C class definitions we have already loaded, make sure
3820 // that we load any additional categories.
3821 for (unsigned I = 0, N = ObjCClassesLoaded.size(); I != N; ++I) {
David L. Jonesc4808b9e2016-12-15 20:53:26 +00003822 loadObjCCategories(ObjCClassesLoaded[I]->getGlobalID(),
Guy Benyei11169dd2012-12-18 14:30:41 +00003823 ObjCClassesLoaded[I],
3824 PreviousGeneration);
3825 }
Douglas Gregore060e572013-01-25 01:03:03 +00003826
Dmitri Gribenkof430da42014-02-12 10:33:14 +00003827 if (PP.getHeaderSearchInfo()
3828 .getHeaderSearchOpts()
3829 .ModulesValidateOncePerBuildSession) {
3830 // Now we are certain that the module and all modules it depends on are
3831 // up to date. Create or update timestamp files for modules that are
3832 // located in the module cache (not for PCH files that could be anywhere
3833 // in the filesystem).
3834 for (unsigned I = 0, N = Loaded.size(); I != N; ++I) {
3835 ImportedModule &M = Loaded[I];
Richard Smithe842a472014-10-22 02:05:46 +00003836 if (M.Mod->Kind == MK_ImplicitModule) {
Dmitri Gribenkof430da42014-02-12 10:33:14 +00003837 updateModuleTimestamp(*M.Mod);
3838 }
3839 }
3840 }
3841
Guy Benyei11169dd2012-12-18 14:30:41 +00003842 return Success;
3843}
3844
Peter Collingbourne77c89b62016-11-08 04:17:11 +00003845static ASTFileSignature readASTFileSignature(StringRef PCH);
Ben Langmuir487ea142014-10-23 18:05:36 +00003846
Ben Langmuir70a1b812015-03-24 04:43:52 +00003847/// \brief Whether \p Stream starts with the AST/PCH file magic number 'CPCH'.
3848static bool startsWithASTFileMagic(BitstreamCursor &Stream) {
Peter Collingbourne028eb5a2016-11-02 00:08:19 +00003849 return Stream.canSkipToPos(4) &&
3850 Stream.Read(8) == 'C' &&
Ben Langmuir70a1b812015-03-24 04:43:52 +00003851 Stream.Read(8) == 'P' &&
3852 Stream.Read(8) == 'C' &&
3853 Stream.Read(8) == 'H';
3854}
3855
Richard Smith0f99d6a2015-08-09 08:48:41 +00003856static unsigned moduleKindForDiagnostic(ModuleKind Kind) {
3857 switch (Kind) {
3858 case MK_PCH:
3859 return 0; // PCH
3860 case MK_ImplicitModule:
3861 case MK_ExplicitModule:
Manman Ren11f2a472016-08-18 17:42:15 +00003862 case MK_PrebuiltModule:
Richard Smith0f99d6a2015-08-09 08:48:41 +00003863 return 1; // module
3864 case MK_MainFile:
3865 case MK_Preamble:
3866 return 2; // main source file
3867 }
3868 llvm_unreachable("unknown module kind");
3869}
3870
Guy Benyei11169dd2012-12-18 14:30:41 +00003871ASTReader::ASTReadResult
3872ASTReader::ReadASTCore(StringRef FileName,
3873 ModuleKind Type,
3874 SourceLocation ImportLoc,
3875 ModuleFile *ImportedBy,
Dmitri Gribenkof8579502013-01-12 19:30:44 +00003876 SmallVectorImpl<ImportedModule> &Loaded,
Douglas Gregor7029ce12013-03-19 00:28:20 +00003877 off_t ExpectedSize, time_t ExpectedModTime,
Ben Langmuir487ea142014-10-23 18:05:36 +00003878 ASTFileSignature ExpectedSignature,
Guy Benyei11169dd2012-12-18 14:30:41 +00003879 unsigned ClientLoadCapabilities) {
3880 ModuleFile *M;
Guy Benyei11169dd2012-12-18 14:30:41 +00003881 std::string ErrorStr;
Douglas Gregor7029ce12013-03-19 00:28:20 +00003882 ModuleManager::AddModuleResult AddResult
3883 = ModuleMgr.addModule(FileName, Type, ImportLoc, ImportedBy,
Richard Smith053f6c62014-05-16 23:01:30 +00003884 getGeneration(), ExpectedSize, ExpectedModTime,
Ben Langmuir487ea142014-10-23 18:05:36 +00003885 ExpectedSignature, readASTFileSignature,
Douglas Gregor7029ce12013-03-19 00:28:20 +00003886 M, ErrorStr);
Guy Benyei11169dd2012-12-18 14:30:41 +00003887
Douglas Gregor7029ce12013-03-19 00:28:20 +00003888 switch (AddResult) {
3889 case ModuleManager::AlreadyLoaded:
3890 return Success;
3891
3892 case ModuleManager::NewlyLoaded:
3893 // Load module file below.
3894 break;
3895
3896 case ModuleManager::Missing:
Richard Smithe842a472014-10-22 02:05:46 +00003897 // The module file was missing; if the client can handle that, return
Douglas Gregor7029ce12013-03-19 00:28:20 +00003898 // it.
3899 if (ClientLoadCapabilities & ARR_Missing)
3900 return Missing;
3901
3902 // Otherwise, return an error.
Richard Smith0f99d6a2015-08-09 08:48:41 +00003903 Diag(diag::err_module_file_not_found) << moduleKindForDiagnostic(Type)
Adrian Prantlb3b5a732016-08-29 20:46:59 +00003904 << FileName << !ErrorStr.empty()
Richard Smith0f99d6a2015-08-09 08:48:41 +00003905 << ErrorStr;
Douglas Gregor7029ce12013-03-19 00:28:20 +00003906 return Failure;
3907
3908 case ModuleManager::OutOfDate:
3909 // We couldn't load the module file because it is out-of-date. If the
3910 // client can handle out-of-date, return it.
3911 if (ClientLoadCapabilities & ARR_OutOfDate)
3912 return OutOfDate;
3913
3914 // Otherwise, return an error.
Richard Smith0f99d6a2015-08-09 08:48:41 +00003915 Diag(diag::err_module_file_out_of_date) << moduleKindForDiagnostic(Type)
Adrian Prantl9a06a882016-08-29 20:46:56 +00003916 << FileName << !ErrorStr.empty()
Richard Smith0f99d6a2015-08-09 08:48:41 +00003917 << ErrorStr;
Guy Benyei11169dd2012-12-18 14:30:41 +00003918 return Failure;
3919 }
3920
Douglas Gregor7029ce12013-03-19 00:28:20 +00003921 assert(M && "Missing module file");
Guy Benyei11169dd2012-12-18 14:30:41 +00003922
3923 // FIXME: This seems rather a hack. Should CurrentDir be part of the
3924 // module?
3925 if (FileName != "-") {
3926 CurrentDir = llvm::sys::path::parent_path(FileName);
3927 if (CurrentDir.empty()) CurrentDir = ".";
3928 }
3929
3930 ModuleFile &F = *M;
Chris Lattner7fb3bef2013-01-20 00:56:42 +00003931 BitstreamCursor &Stream = F.Stream;
Peter Collingbourne77c89b62016-11-08 04:17:11 +00003932 Stream = BitstreamCursor(PCHContainerRdr.ExtractPCH(*F.Buffer));
Adrian Prantlcbc368c2015-02-25 02:44:04 +00003933 F.SizeInBits = F.Buffer->getBufferSize() * 8;
David L. Jonesc4808b9e2016-12-15 20:53:26 +00003934
Guy Benyei11169dd2012-12-18 14:30:41 +00003935 // Sniff for the signature.
Ben Langmuir70a1b812015-03-24 04:43:52 +00003936 if (!startsWithASTFileMagic(Stream)) {
Richard Smith0f99d6a2015-08-09 08:48:41 +00003937 Diag(diag::err_module_file_invalid) << moduleKindForDiagnostic(Type)
3938 << FileName;
Guy Benyei11169dd2012-12-18 14:30:41 +00003939 return Failure;
3940 }
3941
3942 // This is used for compatibility with older PCH formats.
3943 bool HaveReadControlBlock = false;
Eugene Zelenkoe95e7d52016-09-07 21:53:17 +00003944 while (true) {
Chris Lattnerefa77172013-01-20 00:00:22 +00003945 llvm::BitstreamEntry Entry = Stream.advance();
David L. Jonesc4808b9e2016-12-15 20:53:26 +00003946
Chris Lattnerefa77172013-01-20 00:00:22 +00003947 switch (Entry.Kind) {
3948 case llvm::BitstreamEntry::Error:
Chris Lattnerefa77172013-01-20 00:00:22 +00003949 case llvm::BitstreamEntry::Record:
Douglas Gregor6623e1f2015-11-03 18:33:07 +00003950 case llvm::BitstreamEntry::EndBlock:
Guy Benyei11169dd2012-12-18 14:30:41 +00003951 Error("invalid record at top-level of AST file");
3952 return Failure;
David L. Jonesc4808b9e2016-12-15 20:53:26 +00003953
Chris Lattnerefa77172013-01-20 00:00:22 +00003954 case llvm::BitstreamEntry::SubBlock:
3955 break;
Guy Benyei11169dd2012-12-18 14:30:41 +00003956 }
3957
Chris Lattnerefa77172013-01-20 00:00:22 +00003958 switch (Entry.ID) {
Guy Benyei11169dd2012-12-18 14:30:41 +00003959 case CONTROL_BLOCK_ID:
3960 HaveReadControlBlock = true;
Ben Langmuirbeee15e2014-04-14 18:00:01 +00003961 switch (ReadControlBlock(F, Loaded, ImportedBy, ClientLoadCapabilities)) {
Guy Benyei11169dd2012-12-18 14:30:41 +00003962 case Success:
Richard Smith0f99d6a2015-08-09 08:48:41 +00003963 // Check that we didn't try to load a non-module AST file as a module.
3964 //
3965 // FIXME: Should we also perform the converse check? Loading a module as
3966 // a PCH file sort of works, but it's a bit wonky.
Manman Ren11f2a472016-08-18 17:42:15 +00003967 if ((Type == MK_ImplicitModule || Type == MK_ExplicitModule ||
3968 Type == MK_PrebuiltModule) &&
Richard Smith0f99d6a2015-08-09 08:48:41 +00003969 F.ModuleName.empty()) {
3970 auto Result = (Type == MK_ImplicitModule) ? OutOfDate : Failure;
3971 if (Result != OutOfDate ||
3972 (ClientLoadCapabilities & ARR_OutOfDate) == 0)
3973 Diag(diag::err_module_file_not_module) << FileName;
3974 return Result;
3975 }
Guy Benyei11169dd2012-12-18 14:30:41 +00003976 break;
3977
3978 case Failure: return Failure;
Douglas Gregor7029ce12013-03-19 00:28:20 +00003979 case Missing: return Missing;
Guy Benyei11169dd2012-12-18 14:30:41 +00003980 case OutOfDate: return OutOfDate;
3981 case VersionMismatch: return VersionMismatch;
3982 case ConfigurationMismatch: return ConfigurationMismatch;
3983 case HadErrors: return HadErrors;
3984 }
3985 break;
Richard Smithf8c32552015-09-02 17:45:54 +00003986
Guy Benyei11169dd2012-12-18 14:30:41 +00003987 case AST_BLOCK_ID:
3988 if (!HaveReadControlBlock) {
3989 if ((ClientLoadCapabilities & ARR_VersionMismatch) == 0)
Dmitri Gribenko2228cd32014-02-11 15:40:09 +00003990 Diag(diag::err_pch_version_too_old);
Guy Benyei11169dd2012-12-18 14:30:41 +00003991 return VersionMismatch;
3992 }
3993
3994 // Record that we've loaded this module.
3995 Loaded.push_back(ImportedModule(M, ImportedBy, ImportLoc));
3996 return Success;
3997
3998 default:
3999 if (Stream.SkipBlock()) {
4000 Error("malformed block record in AST file");
4001 return Failure;
4002 }
4003 break;
4004 }
4005 }
Douglas Gregor6623e1f2015-11-03 18:33:07 +00004006
4007 return Success;
4008}
4009
4010/// Parse a record and blob containing module file extension metadata.
4011static bool parseModuleFileExtensionMetadata(
4012 const SmallVectorImpl<uint64_t> &Record,
4013 StringRef Blob,
4014 ModuleFileExtensionMetadata &Metadata) {
4015 if (Record.size() < 4) return true;
4016
4017 Metadata.MajorVersion = Record[0];
4018 Metadata.MinorVersion = Record[1];
4019
4020 unsigned BlockNameLen = Record[2];
4021 unsigned UserInfoLen = Record[3];
4022
4023 if (BlockNameLen + UserInfoLen > Blob.size()) return true;
4024
4025 Metadata.BlockName = std::string(Blob.data(), Blob.data() + BlockNameLen);
4026 Metadata.UserInfo = std::string(Blob.data() + BlockNameLen,
4027 Blob.data() + BlockNameLen + UserInfoLen);
4028 return false;
4029}
4030
4031ASTReader::ASTReadResult ASTReader::ReadExtensionBlock(ModuleFile &F) {
4032 BitstreamCursor &Stream = F.Stream;
4033
4034 RecordData Record;
4035 while (true) {
4036 llvm::BitstreamEntry Entry = Stream.advance();
4037 switch (Entry.Kind) {
4038 case llvm::BitstreamEntry::SubBlock:
4039 if (Stream.SkipBlock())
4040 return Failure;
4041
4042 continue;
4043
4044 case llvm::BitstreamEntry::EndBlock:
4045 return Success;
4046
4047 case llvm::BitstreamEntry::Error:
4048 return HadErrors;
4049
4050 case llvm::BitstreamEntry::Record:
4051 break;
4052 }
4053
4054 Record.clear();
4055 StringRef Blob;
4056 unsigned RecCode = Stream.readRecord(Entry.ID, Record, &Blob);
4057 switch (RecCode) {
4058 case EXTENSION_METADATA: {
4059 ModuleFileExtensionMetadata Metadata;
4060 if (parseModuleFileExtensionMetadata(Record, Blob, Metadata))
4061 return Failure;
4062
4063 // Find a module file extension with this block name.
4064 auto Known = ModuleFileExtensions.find(Metadata.BlockName);
4065 if (Known == ModuleFileExtensions.end()) break;
4066
4067 // Form a reader.
4068 if (auto Reader = Known->second->createExtensionReader(Metadata, *this,
4069 F, Stream)) {
4070 F.ExtensionReaders.push_back(std::move(Reader));
4071 }
4072
4073 break;
4074 }
4075 }
4076 }
4077
4078 return Success;
Guy Benyei11169dd2012-12-18 14:30:41 +00004079}
4080
Richard Smitha7e2cc62015-05-01 01:53:09 +00004081void ASTReader::InitializeContext() {
Guy Benyei11169dd2012-12-18 14:30:41 +00004082 // If there's a listener, notify them that we "read" the translation unit.
4083 if (DeserializationListener)
David L. Jonesc4808b9e2016-12-15 20:53:26 +00004084 DeserializationListener->DeclRead(PREDEF_DECL_TRANSLATION_UNIT_ID,
Guy Benyei11169dd2012-12-18 14:30:41 +00004085 Context.getTranslationUnitDecl());
4086
Guy Benyei11169dd2012-12-18 14:30:41 +00004087 // FIXME: Find a better way to deal with collisions between these
4088 // built-in types. Right now, we just ignore the problem.
David L. Jonesc4808b9e2016-12-15 20:53:26 +00004089
Guy Benyei11169dd2012-12-18 14:30:41 +00004090 // Load the special types.
4091 if (SpecialTypes.size() >= NumSpecialTypeIDs) {
4092 if (unsigned String = SpecialTypes[SPECIAL_TYPE_CF_CONSTANT_STRING]) {
4093 if (!Context.CFConstantStringTypeDecl)
4094 Context.setCFConstantStringType(GetType(String));
4095 }
David L. Jonesc4808b9e2016-12-15 20:53:26 +00004096
Guy Benyei11169dd2012-12-18 14:30:41 +00004097 if (unsigned File = SpecialTypes[SPECIAL_TYPE_FILE]) {
4098 QualType FileType = GetType(File);
4099 if (FileType.isNull()) {
4100 Error("FILE type is NULL");
4101 return;
4102 }
David L. Jonesc4808b9e2016-12-15 20:53:26 +00004103
Guy Benyei11169dd2012-12-18 14:30:41 +00004104 if (!Context.FILEDecl) {
4105 if (const TypedefType *Typedef = FileType->getAs<TypedefType>())
4106 Context.setFILEDecl(Typedef->getDecl());
4107 else {
4108 const TagType *Tag = FileType->getAs<TagType>();
4109 if (!Tag) {
4110 Error("Invalid FILE type in AST file");
4111 return;
4112 }
4113 Context.setFILEDecl(Tag->getDecl());
4114 }
4115 }
4116 }
David L. Jonesc4808b9e2016-12-15 20:53:26 +00004117
Guy Benyei11169dd2012-12-18 14:30:41 +00004118 if (unsigned Jmp_buf = SpecialTypes[SPECIAL_TYPE_JMP_BUF]) {
4119 QualType Jmp_bufType = GetType(Jmp_buf);
4120 if (Jmp_bufType.isNull()) {
4121 Error("jmp_buf type is NULL");
4122 return;
4123 }
David L. Jonesc4808b9e2016-12-15 20:53:26 +00004124
Guy Benyei11169dd2012-12-18 14:30:41 +00004125 if (!Context.jmp_bufDecl) {
4126 if (const TypedefType *Typedef = Jmp_bufType->getAs<TypedefType>())
4127 Context.setjmp_bufDecl(Typedef->getDecl());
4128 else {
4129 const TagType *Tag = Jmp_bufType->getAs<TagType>();
4130 if (!Tag) {
4131 Error("Invalid jmp_buf type in AST file");
4132 return;
4133 }
4134 Context.setjmp_bufDecl(Tag->getDecl());
4135 }
4136 }
4137 }
David L. Jonesc4808b9e2016-12-15 20:53:26 +00004138
Guy Benyei11169dd2012-12-18 14:30:41 +00004139 if (unsigned Sigjmp_buf = SpecialTypes[SPECIAL_TYPE_SIGJMP_BUF]) {
4140 QualType Sigjmp_bufType = GetType(Sigjmp_buf);
4141 if (Sigjmp_bufType.isNull()) {
4142 Error("sigjmp_buf type is NULL");
4143 return;
4144 }
David L. Jonesc4808b9e2016-12-15 20:53:26 +00004145
Guy Benyei11169dd2012-12-18 14:30:41 +00004146 if (!Context.sigjmp_bufDecl) {
4147 if (const TypedefType *Typedef = Sigjmp_bufType->getAs<TypedefType>())
4148 Context.setsigjmp_bufDecl(Typedef->getDecl());
4149 else {
4150 const TagType *Tag = Sigjmp_bufType->getAs<TagType>();
4151 assert(Tag && "Invalid sigjmp_buf type in AST file");
4152 Context.setsigjmp_bufDecl(Tag->getDecl());
4153 }
4154 }
4155 }
4156
4157 if (unsigned ObjCIdRedef
4158 = SpecialTypes[SPECIAL_TYPE_OBJC_ID_REDEFINITION]) {
4159 if (Context.ObjCIdRedefinitionType.isNull())
4160 Context.ObjCIdRedefinitionType = GetType(ObjCIdRedef);
4161 }
4162
4163 if (unsigned ObjCClassRedef
4164 = SpecialTypes[SPECIAL_TYPE_OBJC_CLASS_REDEFINITION]) {
4165 if (Context.ObjCClassRedefinitionType.isNull())
4166 Context.ObjCClassRedefinitionType = GetType(ObjCClassRedef);
4167 }
4168
4169 if (unsigned ObjCSelRedef
4170 = SpecialTypes[SPECIAL_TYPE_OBJC_SEL_REDEFINITION]) {
4171 if (Context.ObjCSelRedefinitionType.isNull())
4172 Context.ObjCSelRedefinitionType = GetType(ObjCSelRedef);
4173 }
4174
4175 if (unsigned Ucontext_t = SpecialTypes[SPECIAL_TYPE_UCONTEXT_T]) {
4176 QualType Ucontext_tType = GetType(Ucontext_t);
4177 if (Ucontext_tType.isNull()) {
4178 Error("ucontext_t type is NULL");
4179 return;
4180 }
4181
4182 if (!Context.ucontext_tDecl) {
4183 if (const TypedefType *Typedef = Ucontext_tType->getAs<TypedefType>())
4184 Context.setucontext_tDecl(Typedef->getDecl());
4185 else {
4186 const TagType *Tag = Ucontext_tType->getAs<TagType>();
4187 assert(Tag && "Invalid ucontext_t type in AST file");
4188 Context.setucontext_tDecl(Tag->getDecl());
4189 }
4190 }
4191 }
4192 }
David L. Jonesc4808b9e2016-12-15 20:53:26 +00004193
Guy Benyei11169dd2012-12-18 14:30:41 +00004194 ReadPragmaDiagnosticMappings(Context.getDiagnostics());
4195
4196 // If there were any CUDA special declarations, deserialize them.
4197 if (!CUDASpecialDeclRefs.empty()) {
4198 assert(CUDASpecialDeclRefs.size() == 1 && "More decl refs than expected!");
4199 Context.setcudaConfigureCallDecl(
4200 cast<FunctionDecl>(GetDecl(CUDASpecialDeclRefs[0])));
4201 }
Richard Smith56be7542014-03-21 00:33:59 +00004202
Guy Benyei11169dd2012-12-18 14:30:41 +00004203 // Re-export any modules that were imported by a non-module AST file.
Richard Smitha7e2cc62015-05-01 01:53:09 +00004204 // FIXME: This does not make macro-only imports visible again.
Richard Smith56be7542014-03-21 00:33:59 +00004205 for (auto &Import : ImportedModules) {
Richard Smitha7e2cc62015-05-01 01:53:09 +00004206 if (Module *Imported = getSubmodule(Import.ID)) {
Argyrios Kyrtzidis125df052013-02-01 16:36:12 +00004207 makeModuleVisible(Imported, Module::AllVisible,
Richard Smitha7e2cc62015-05-01 01:53:09 +00004208 /*ImportLoc=*/Import.ImportLoc);
Ben Langmuir6d25fdc2016-02-11 17:04:42 +00004209 if (Import.ImportLoc.isValid())
4210 PP.makeModuleVisible(Imported, Import.ImportLoc);
4211 // FIXME: should we tell Sema to make the module visible too?
Richard Smitha7e2cc62015-05-01 01:53:09 +00004212 }
Guy Benyei11169dd2012-12-18 14:30:41 +00004213 }
4214 ImportedModules.clear();
4215}
4216
4217void ASTReader::finalizeForWriting() {
Richard Smithde711422015-04-23 21:20:19 +00004218 // Nothing to do for now.
Guy Benyei11169dd2012-12-18 14:30:41 +00004219}
4220
Peter Collingbourne77c89b62016-11-08 04:17:11 +00004221/// \brief Reads and return the signature record from \p PCH's control block, or
4222/// else returns 0.
4223static ASTFileSignature readASTFileSignature(StringRef PCH) {
4224 BitstreamCursor Stream(PCH);
Ben Langmuir70a1b812015-03-24 04:43:52 +00004225 if (!startsWithASTFileMagic(Stream))
Ben Langmuir487ea142014-10-23 18:05:36 +00004226 return 0;
Ben Langmuir487ea142014-10-23 18:05:36 +00004227
4228 // Scan for the CONTROL_BLOCK_ID block.
4229 if (SkipCursorToBlock(Stream, CONTROL_BLOCK_ID))
4230 return 0;
4231
4232 // Scan for SIGNATURE inside the control block.
4233 ASTReader::RecordData Record;
Eugene Zelenkoe95e7d52016-09-07 21:53:17 +00004234 while (true) {
Ben Langmuir487ea142014-10-23 18:05:36 +00004235 llvm::BitstreamEntry Entry = Stream.advanceSkippingSubblocks();
Simon Pilgrim0b33f112016-11-16 16:11:08 +00004236 if (Entry.Kind != llvm::BitstreamEntry::Record)
Ben Langmuir487ea142014-10-23 18:05:36 +00004237 return 0;
4238
4239 Record.clear();
4240 StringRef Blob;
4241 if (SIGNATURE == Stream.readRecord(Entry.ID, Record, &Blob))
4242 return Record[0];
4243 }
4244}
4245
Guy Benyei11169dd2012-12-18 14:30:41 +00004246/// \brief Retrieve the name of the original source file name
4247/// directly from the AST file, without actually loading the AST
4248/// file.
Adrian Prantlbb165fb2015-06-20 18:53:08 +00004249std::string ASTReader::getOriginalSourceFile(
4250 const std::string &ASTFileName, FileManager &FileMgr,
Adrian Prantlfb2398d2015-07-17 01:19:54 +00004251 const PCHContainerReader &PCHContainerRdr, DiagnosticsEngine &Diags) {
Guy Benyei11169dd2012-12-18 14:30:41 +00004252 // Open the AST file.
Benjamin Kramera8857962014-10-26 22:44:13 +00004253 auto Buffer = FileMgr.getBufferForFile(ASTFileName);
Guy Benyei11169dd2012-12-18 14:30:41 +00004254 if (!Buffer) {
Benjamin Kramera8857962014-10-26 22:44:13 +00004255 Diags.Report(diag::err_fe_unable_to_read_pch_file)
4256 << ASTFileName << Buffer.getError().message();
Guy Benyei11169dd2012-12-18 14:30:41 +00004257 return std::string();
4258 }
4259
4260 // Initialize the stream
Peter Collingbourne77c89b62016-11-08 04:17:11 +00004261 BitstreamCursor Stream(PCHContainerRdr.ExtractPCH(**Buffer));
Guy Benyei11169dd2012-12-18 14:30:41 +00004262
4263 // Sniff for the signature.
Ben Langmuir70a1b812015-03-24 04:43:52 +00004264 if (!startsWithASTFileMagic(Stream)) {
Guy Benyei11169dd2012-12-18 14:30:41 +00004265 Diags.Report(diag::err_fe_not_a_pch_file) << ASTFileName;
4266 return std::string();
4267 }
David L. Jonesc4808b9e2016-12-15 20:53:26 +00004268
Chris Lattnere7b154b2013-01-19 21:39:22 +00004269 // Scan for the CONTROL_BLOCK_ID block.
Argyrios Kyrtzidisc4cd2c42013-05-06 19:23:40 +00004270 if (SkipCursorToBlock(Stream, CONTROL_BLOCK_ID)) {
Chris Lattner7fb3bef2013-01-20 00:56:42 +00004271 Diags.Report(diag::err_fe_pch_malformed_block) << ASTFileName;
4272 return std::string();
Chris Lattnere7b154b2013-01-19 21:39:22 +00004273 }
Guy Benyei11169dd2012-12-18 14:30:41 +00004274
Chris Lattner7fb3bef2013-01-20 00:56:42 +00004275 // Scan for ORIGINAL_FILE inside the control block.
4276 RecordData Record;
Eugene Zelenkoe95e7d52016-09-07 21:53:17 +00004277 while (true) {
Chris Lattner7fb3bef2013-01-20 00:56:42 +00004278 llvm::BitstreamEntry Entry = Stream.advanceSkippingSubblocks();
Chris Lattnere7b154b2013-01-19 21:39:22 +00004279 if (Entry.Kind == llvm::BitstreamEntry::EndBlock)
4280 return std::string();
David L. Jonesc4808b9e2016-12-15 20:53:26 +00004281
Chris Lattnere7b154b2013-01-19 21:39:22 +00004282 if (Entry.Kind != llvm::BitstreamEntry::Record) {
4283 Diags.Report(diag::err_fe_pch_malformed_block) << ASTFileName;
4284 return std::string();
Guy Benyei11169dd2012-12-18 14:30:41 +00004285 }
David L. Jonesc4808b9e2016-12-15 20:53:26 +00004286
Guy Benyei11169dd2012-12-18 14:30:41 +00004287 Record.clear();
Chris Lattner0e6c9402013-01-20 02:38:54 +00004288 StringRef Blob;
4289 if (Stream.readRecord(Entry.ID, Record, &Blob) == ORIGINAL_FILE)
4290 return Blob.str();
Guy Benyei11169dd2012-12-18 14:30:41 +00004291 }
Guy Benyei11169dd2012-12-18 14:30:41 +00004292}
4293
4294namespace {
Eugene Zelenkoe95e7d52016-09-07 21:53:17 +00004295
Guy Benyei11169dd2012-12-18 14:30:41 +00004296 class SimplePCHValidator : public ASTReaderListener {
4297 const LangOptions &ExistingLangOpts;
4298 const TargetOptions &ExistingTargetOpts;
4299 const PreprocessorOptions &ExistingPPOpts;
Argyrios Kyrtzidisbd0b6512015-02-19 20:12:20 +00004300 std::string ExistingModuleCachePath;
Guy Benyei11169dd2012-12-18 14:30:41 +00004301 FileManager &FileMgr;
Argyrios Kyrtzidisbd0b6512015-02-19 20:12:20 +00004302
Guy Benyei11169dd2012-12-18 14:30:41 +00004303 public:
4304 SimplePCHValidator(const LangOptions &ExistingLangOpts,
4305 const TargetOptions &ExistingTargetOpts,
4306 const PreprocessorOptions &ExistingPPOpts,
Argyrios Kyrtzidisbd0b6512015-02-19 20:12:20 +00004307 StringRef ExistingModuleCachePath,
Guy Benyei11169dd2012-12-18 14:30:41 +00004308 FileManager &FileMgr)
4309 : ExistingLangOpts(ExistingLangOpts),
4310 ExistingTargetOpts(ExistingTargetOpts),
4311 ExistingPPOpts(ExistingPPOpts),
Argyrios Kyrtzidisbd0b6512015-02-19 20:12:20 +00004312 ExistingModuleCachePath(ExistingModuleCachePath),
Guy Benyei11169dd2012-12-18 14:30:41 +00004313 FileMgr(FileMgr)
4314 {
4315 }
4316
Richard Smith1e2cf0d2014-10-31 02:28:58 +00004317 bool ReadLanguageOptions(const LangOptions &LangOpts, bool Complain,
4318 bool AllowCompatibleDifferences) override {
4319 return checkLanguageOptions(ExistingLangOpts, LangOpts, nullptr,
4320 AllowCompatibleDifferences);
Guy Benyei11169dd2012-12-18 14:30:41 +00004321 }
Eugene Zelenkoe95e7d52016-09-07 21:53:17 +00004322
Chandler Carruth0d745bc2015-03-14 04:47:43 +00004323 bool ReadTargetOptions(const TargetOptions &TargetOpts, bool Complain,
4324 bool AllowCompatibleDifferences) override {
4325 return checkTargetOptions(ExistingTargetOpts, TargetOpts, nullptr,
4326 AllowCompatibleDifferences);
Guy Benyei11169dd2012-12-18 14:30:41 +00004327 }
Eugene Zelenkoe95e7d52016-09-07 21:53:17 +00004328
Argyrios Kyrtzidisbd0b6512015-02-19 20:12:20 +00004329 bool ReadHeaderSearchOptions(const HeaderSearchOptions &HSOpts,
4330 StringRef SpecificModuleCachePath,
4331 bool Complain) override {
4332 return checkHeaderSearchOptions(HSOpts, SpecificModuleCachePath,
4333 ExistingModuleCachePath,
4334 nullptr, ExistingLangOpts);
4335 }
Eugene Zelenkoe95e7d52016-09-07 21:53:17 +00004336
Craig Topper3e89dfe2014-03-13 02:13:41 +00004337 bool ReadPreprocessorOptions(const PreprocessorOptions &PPOpts,
4338 bool Complain,
4339 std::string &SuggestedPredefines) override {
Craig Toppera13603a2014-05-22 05:54:18 +00004340 return checkPreprocessorOptions(ExistingPPOpts, PPOpts, nullptr, FileMgr,
Argyrios Kyrtzidisd3afa0c2013-04-26 21:33:40 +00004341 SuggestedPredefines, ExistingLangOpts);
Guy Benyei11169dd2012-12-18 14:30:41 +00004342 }
4343 };
Eugene Zelenkoe95e7d52016-09-07 21:53:17 +00004344
4345} // end anonymous namespace
Guy Benyei11169dd2012-12-18 14:30:41 +00004346
Adrian Prantlbb165fb2015-06-20 18:53:08 +00004347bool ASTReader::readASTFileControlBlock(
4348 StringRef Filename, FileManager &FileMgr,
Adrian Prantlfb2398d2015-07-17 01:19:54 +00004349 const PCHContainerReader &PCHContainerRdr,
Douglas Gregor6623e1f2015-11-03 18:33:07 +00004350 bool FindModuleFileExtensions,
Manman Ren47a44452016-07-26 17:12:17 +00004351 ASTReaderListener &Listener, bool ValidateDiagnosticOptions) {
Guy Benyei11169dd2012-12-18 14:30:41 +00004352 // Open the AST file.
Richard Smith7f330cd2015-03-18 01:42:29 +00004353 // FIXME: This allows use of the VFS; we do not allow use of the
4354 // VFS when actually loading a module.
Benjamin Kramera8857962014-10-26 22:44:13 +00004355 auto Buffer = FileMgr.getBufferForFile(Filename);
Guy Benyei11169dd2012-12-18 14:30:41 +00004356 if (!Buffer) {
4357 return true;
4358 }
4359
4360 // Initialize the stream
Peter Collingbourne77c89b62016-11-08 04:17:11 +00004361 BitstreamCursor Stream(PCHContainerRdr.ExtractPCH(**Buffer));
Guy Benyei11169dd2012-12-18 14:30:41 +00004362
4363 // Sniff for the signature.
Ben Langmuir70a1b812015-03-24 04:43:52 +00004364 if (!startsWithASTFileMagic(Stream))
Guy Benyei11169dd2012-12-18 14:30:41 +00004365 return true;
Guy Benyei11169dd2012-12-18 14:30:41 +00004366
Chris Lattner7fb3bef2013-01-20 00:56:42 +00004367 // Scan for the CONTROL_BLOCK_ID block.
Argyrios Kyrtzidisc4cd2c42013-05-06 19:23:40 +00004368 if (SkipCursorToBlock(Stream, CONTROL_BLOCK_ID))
Chris Lattner7fb3bef2013-01-20 00:56:42 +00004369 return true;
Argyrios Kyrtzidisc4cd2c42013-05-06 19:23:40 +00004370
4371 bool NeedsInputFiles = Listener.needsInputFileVisitation();
Ben Langmuircb69b572014-03-07 06:40:32 +00004372 bool NeedsSystemInputFiles = Listener.needsSystemInputFileVisitation();
Richard Smithd4b230b2014-10-27 23:01:16 +00004373 bool NeedsImports = Listener.needsImportVisitation();
Argyrios Kyrtzidisc4cd2c42013-05-06 19:23:40 +00004374 BitstreamCursor InputFilesCursor;
Argyrios Kyrtzidisc4cd2c42013-05-06 19:23:40 +00004375
Guy Benyei11169dd2012-12-18 14:30:41 +00004376 RecordData Record;
Richard Smith7ed1bc92014-12-05 22:42:13 +00004377 std::string ModuleDir;
Douglas Gregor6623e1f2015-11-03 18:33:07 +00004378 bool DoneWithControlBlock = false;
4379 while (!DoneWithControlBlock) {
Richard Smith0516b182015-09-08 19:40:14 +00004380 llvm::BitstreamEntry Entry = Stream.advance();
4381
4382 switch (Entry.Kind) {
4383 case llvm::BitstreamEntry::SubBlock: {
4384 switch (Entry.ID) {
4385 case OPTIONS_BLOCK_ID: {
4386 std::string IgnoredSuggestedPredefines;
4387 if (ReadOptionsBlock(Stream, ARR_ConfigurationMismatch | ARR_OutOfDate,
4388 /*AllowCompatibleConfigurationMismatch*/ false,
Manman Ren47a44452016-07-26 17:12:17 +00004389 Listener, IgnoredSuggestedPredefines,
4390 ValidateDiagnosticOptions) != Success)
Richard Smith0516b182015-09-08 19:40:14 +00004391 return true;
4392 break;
4393 }
4394
4395 case INPUT_FILES_BLOCK_ID:
4396 InputFilesCursor = Stream;
4397 if (Stream.SkipBlock() ||
4398 (NeedsInputFiles &&
4399 ReadBlockAbbrevs(InputFilesCursor, INPUT_FILES_BLOCK_ID)))
4400 return true;
4401 break;
4402
4403 default:
4404 if (Stream.SkipBlock())
4405 return true;
4406 break;
4407 }
4408
4409 continue;
4410 }
4411
4412 case llvm::BitstreamEntry::EndBlock:
Douglas Gregor6623e1f2015-11-03 18:33:07 +00004413 DoneWithControlBlock = true;
4414 break;
Richard Smith0516b182015-09-08 19:40:14 +00004415
4416 case llvm::BitstreamEntry::Error:
Chris Lattner7fb3bef2013-01-20 00:56:42 +00004417 return true;
Richard Smith0516b182015-09-08 19:40:14 +00004418
4419 case llvm::BitstreamEntry::Record:
4420 break;
4421 }
4422
Douglas Gregor6623e1f2015-11-03 18:33:07 +00004423 if (DoneWithControlBlock) break;
4424
Guy Benyei11169dd2012-12-18 14:30:41 +00004425 Record.clear();
Chris Lattner0e6c9402013-01-20 02:38:54 +00004426 StringRef Blob;
4427 unsigned RecCode = Stream.readRecord(Entry.ID, Record, &Blob);
Chris Lattner7fb3bef2013-01-20 00:56:42 +00004428 switch ((ControlRecordTypes)RecCode) {
4429 case METADATA: {
4430 if (Record[0] != VERSION_MAJOR)
4431 return true;
Guy Benyei11169dd2012-12-18 14:30:41 +00004432
Douglas Gregorbf7fc9c2013-03-27 16:47:18 +00004433 if (Listener.ReadFullVersionInformation(Blob))
Chris Lattner7fb3bef2013-01-20 00:56:42 +00004434 return true;
David L. Jonesc4808b9e2016-12-15 20:53:26 +00004435
Chris Lattner7fb3bef2013-01-20 00:56:42 +00004436 break;
4437 }
Ben Langmuir4f5212a2014-04-14 22:12:44 +00004438 case MODULE_NAME:
4439 Listener.ReadModuleName(Blob);
4440 break;
Richard Smith7ed1bc92014-12-05 22:42:13 +00004441 case MODULE_DIRECTORY:
4442 ModuleDir = Blob;
4443 break;
Ben Langmuir4b8a9e92014-08-12 16:42:33 +00004444 case MODULE_MAP_FILE: {
4445 unsigned Idx = 0;
Richard Smith7ed1bc92014-12-05 22:42:13 +00004446 auto Path = ReadString(Record, Idx);
4447 ResolveImportedPath(Path, ModuleDir);
4448 Listener.ReadModuleMapFile(Path);
Ben Langmuir4f5212a2014-04-14 22:12:44 +00004449 break;
Ben Langmuir4b8a9e92014-08-12 16:42:33 +00004450 }
Argyrios Kyrtzidisc4cd2c42013-05-06 19:23:40 +00004451 case INPUT_FILE_OFFSETS: {
4452 if (!NeedsInputFiles)
4453 break;
4454
4455 unsigned NumInputFiles = Record[0];
4456 unsigned NumUserFiles = Record[1];
Richard Smithec216502015-02-13 19:48:37 +00004457 const uint64_t *InputFileOffs = (const uint64_t *)Blob.data();
Argyrios Kyrtzidisc4cd2c42013-05-06 19:23:40 +00004458 for (unsigned I = 0; I != NumInputFiles; ++I) {
4459 // Go find this input file.
4460 bool isSystemFile = I >= NumUserFiles;
Ben Langmuircb69b572014-03-07 06:40:32 +00004461
4462 if (isSystemFile && !NeedsSystemInputFiles)
4463 break; // the rest are system input files
4464
Argyrios Kyrtzidisc4cd2c42013-05-06 19:23:40 +00004465 BitstreamCursor &Cursor = InputFilesCursor;
4466 SavedStreamPosition SavedPosition(Cursor);
4467 Cursor.JumpToBit(InputFileOffs[I]);
4468
4469 unsigned Code = Cursor.ReadCode();
4470 RecordData Record;
4471 StringRef Blob;
4472 bool shouldContinue = false;
4473 switch ((InputFileRecordTypes)Cursor.readRecord(Code, Record, &Blob)) {
4474 case INPUT_FILE:
Argyrios Kyrtzidis68ccbe02014-03-14 02:26:31 +00004475 bool Overridden = static_cast<bool>(Record[3]);
Richard Smith7ed1bc92014-12-05 22:42:13 +00004476 std::string Filename = Blob;
4477 ResolveImportedPath(Filename, ModuleDir);
Richard Smith216a3bd2015-08-13 17:57:10 +00004478 shouldContinue = Listener.visitInputFile(
4479 Filename, isSystemFile, Overridden, /*IsExplicitModule*/false);
Argyrios Kyrtzidisc4cd2c42013-05-06 19:23:40 +00004480 break;
4481 }
4482 if (!shouldContinue)
4483 break;
4484 }
4485 break;
4486 }
4487
Richard Smithd4b230b2014-10-27 23:01:16 +00004488 case IMPORTS: {
4489 if (!NeedsImports)
4490 break;
4491
4492 unsigned Idx = 0, N = Record.size();
4493 while (Idx < N) {
4494 // Read information about the AST file.
Richard Smith79c98cc2014-10-27 23:25:15 +00004495 Idx += 5; // ImportLoc, Size, ModTime, Signature
Richard Smith7ed1bc92014-12-05 22:42:13 +00004496 std::string Filename = ReadString(Record, Idx);
4497 ResolveImportedPath(Filename, ModuleDir);
4498 Listener.visitImport(Filename);
Richard Smithd4b230b2014-10-27 23:01:16 +00004499 }
4500 break;
4501 }
4502
Chris Lattner7fb3bef2013-01-20 00:56:42 +00004503 default:
4504 // No other validation to perform.
4505 break;
Guy Benyei11169dd2012-12-18 14:30:41 +00004506 }
4507 }
Douglas Gregor6623e1f2015-11-03 18:33:07 +00004508
4509 // Look for module file extension blocks, if requested.
4510 if (FindModuleFileExtensions) {
4511 while (!SkipCursorToBlock(Stream, EXTENSION_BLOCK_ID)) {
4512 bool DoneWithExtensionBlock = false;
4513 while (!DoneWithExtensionBlock) {
4514 llvm::BitstreamEntry Entry = Stream.advance();
4515
4516 switch (Entry.Kind) {
4517 case llvm::BitstreamEntry::SubBlock:
4518 if (Stream.SkipBlock())
4519 return true;
4520
4521 continue;
4522
4523 case llvm::BitstreamEntry::EndBlock:
4524 DoneWithExtensionBlock = true;
4525 continue;
4526
4527 case llvm::BitstreamEntry::Error:
4528 return true;
4529
4530 case llvm::BitstreamEntry::Record:
4531 break;
4532 }
4533
4534 Record.clear();
4535 StringRef Blob;
4536 unsigned RecCode = Stream.readRecord(Entry.ID, Record, &Blob);
4537 switch (RecCode) {
4538 case EXTENSION_METADATA: {
4539 ModuleFileExtensionMetadata Metadata;
4540 if (parseModuleFileExtensionMetadata(Record, Blob, Metadata))
4541 return true;
4542
4543 Listener.readModuleFileExtension(Metadata);
4544 break;
4545 }
4546 }
4547 }
4548 }
4549 }
4550
4551 return false;
Guy Benyei11169dd2012-12-18 14:30:41 +00004552}
4553
Adrian Prantlbb165fb2015-06-20 18:53:08 +00004554bool ASTReader::isAcceptableASTFile(
4555 StringRef Filename, FileManager &FileMgr,
Adrian Prantlfb2398d2015-07-17 01:19:54 +00004556 const PCHContainerReader &PCHContainerRdr, const LangOptions &LangOpts,
Adrian Prantlbb165fb2015-06-20 18:53:08 +00004557 const TargetOptions &TargetOpts, const PreprocessorOptions &PPOpts,
4558 std::string ExistingModuleCachePath) {
Argyrios Kyrtzidisbd0b6512015-02-19 20:12:20 +00004559 SimplePCHValidator validator(LangOpts, TargetOpts, PPOpts,
4560 ExistingModuleCachePath, FileMgr);
Adrian Prantlfb2398d2015-07-17 01:19:54 +00004561 return !readASTFileControlBlock(Filename, FileMgr, PCHContainerRdr,
Douglas Gregor6623e1f2015-11-03 18:33:07 +00004562 /*FindModuleFileExtensions=*/false,
Manman Ren47a44452016-07-26 17:12:17 +00004563 validator,
4564 /*ValidateDiagnosticOptions=*/true);
Guy Benyei11169dd2012-12-18 14:30:41 +00004565}
4566
Ben Langmuir2c9af442014-04-10 17:57:43 +00004567ASTReader::ASTReadResult
4568ASTReader::ReadSubmoduleBlock(ModuleFile &F, unsigned ClientLoadCapabilities) {
Guy Benyei11169dd2012-12-18 14:30:41 +00004569 // Enter the submodule block.
4570 if (F.Stream.EnterSubBlock(SUBMODULE_BLOCK_ID)) {
4571 Error("malformed submodule block record in AST file");
Ben Langmuir2c9af442014-04-10 17:57:43 +00004572 return Failure;
Guy Benyei11169dd2012-12-18 14:30:41 +00004573 }
4574
4575 ModuleMap &ModMap = PP.getHeaderSearchInfo().getModuleMap();
4576 bool First = true;
Craig Toppera13603a2014-05-22 05:54:18 +00004577 Module *CurrentModule = nullptr;
Guy Benyei11169dd2012-12-18 14:30:41 +00004578 RecordData Record;
4579 while (true) {
Chris Lattner7fb3bef2013-01-20 00:56:42 +00004580 llvm::BitstreamEntry Entry = F.Stream.advanceSkippingSubblocks();
David L. Jonesc4808b9e2016-12-15 20:53:26 +00004581
Chris Lattner7fb3bef2013-01-20 00:56:42 +00004582 switch (Entry.Kind) {
4583 case llvm::BitstreamEntry::SubBlock: // Handled for us already.
4584 case llvm::BitstreamEntry::Error:
4585 Error("malformed block record in AST file");
Ben Langmuir2c9af442014-04-10 17:57:43 +00004586 return Failure;
Chris Lattner7fb3bef2013-01-20 00:56:42 +00004587 case llvm::BitstreamEntry::EndBlock:
Ben Langmuir2c9af442014-04-10 17:57:43 +00004588 return Success;
Chris Lattner7fb3bef2013-01-20 00:56:42 +00004589 case llvm::BitstreamEntry::Record:
4590 // The interesting case.
4591 break;
Guy Benyei11169dd2012-12-18 14:30:41 +00004592 }
Chris Lattner7fb3bef2013-01-20 00:56:42 +00004593
Guy Benyei11169dd2012-12-18 14:30:41 +00004594 // Read a record.
Chris Lattner0e6c9402013-01-20 02:38:54 +00004595 StringRef Blob;
Guy Benyei11169dd2012-12-18 14:30:41 +00004596 Record.clear();
Richard Smith03478d92014-10-23 22:12:14 +00004597 auto Kind = F.Stream.readRecord(Entry.ID, Record, &Blob);
4598
4599 if ((Kind == SUBMODULE_METADATA) != First) {
4600 Error("submodule metadata record should be at beginning of block");
4601 return Failure;
4602 }
4603 First = false;
4604
4605 // Submodule information is only valid if we have a current module.
4606 // FIXME: Should we error on these cases?
4607 if (!CurrentModule && Kind != SUBMODULE_METADATA &&
4608 Kind != SUBMODULE_DEFINITION)
4609 continue;
4610
4611 switch (Kind) {
Guy Benyei11169dd2012-12-18 14:30:41 +00004612 default: // Default behavior: ignore.
4613 break;
Guy Benyei11169dd2012-12-18 14:30:41 +00004614
Richard Smith03478d92014-10-23 22:12:14 +00004615 case SUBMODULE_DEFINITION: {
Douglas Gregor8d932422013-03-20 03:59:18 +00004616 if (Record.size() < 8) {
Guy Benyei11169dd2012-12-18 14:30:41 +00004617 Error("malformed module definition");
Ben Langmuir2c9af442014-04-10 17:57:43 +00004618 return Failure;
Guy Benyei11169dd2012-12-18 14:30:41 +00004619 }
Richard Smith03478d92014-10-23 22:12:14 +00004620
Chris Lattner0e6c9402013-01-20 02:38:54 +00004621 StringRef Name = Blob;
Richard Smith9bca2982014-03-08 00:03:56 +00004622 unsigned Idx = 0;
4623 SubmoduleID GlobalID = getGlobalSubmoduleID(F, Record[Idx++]);
4624 SubmoduleID Parent = getGlobalSubmoduleID(F, Record[Idx++]);
4625 bool IsFramework = Record[Idx++];
4626 bool IsExplicit = Record[Idx++];
4627 bool IsSystem = Record[Idx++];
4628 bool IsExternC = Record[Idx++];
4629 bool InferSubmodules = Record[Idx++];
4630 bool InferExplicitSubmodules = Record[Idx++];
4631 bool InferExportWildcard = Record[Idx++];
4632 bool ConfigMacrosExhaustive = Record[Idx++];
Douglas Gregor8d932422013-03-20 03:59:18 +00004633
Ben Langmuirbeee15e2014-04-14 18:00:01 +00004634 Module *ParentModule = nullptr;
Ben Langmuir9d6448b2014-08-09 00:57:23 +00004635 if (Parent)
Guy Benyei11169dd2012-12-18 14:30:41 +00004636 ParentModule = getSubmodule(Parent);
Ben Langmuirbeee15e2014-04-14 18:00:01 +00004637
Guy Benyei11169dd2012-12-18 14:30:41 +00004638 // Retrieve this (sub)module from the module map, creating it if
4639 // necessary.
Ben Langmuir9d6448b2014-08-09 00:57:23 +00004640 CurrentModule = ModMap.findOrCreateModule(Name, ParentModule, IsFramework,
Guy Benyei11169dd2012-12-18 14:30:41 +00004641 IsExplicit).first;
Ben Langmuir9d6448b2014-08-09 00:57:23 +00004642
4643 // FIXME: set the definition loc for CurrentModule, or call
4644 // ModMap.setInferredModuleAllowedBy()
4645
Guy Benyei11169dd2012-12-18 14:30:41 +00004646 SubmoduleID GlobalIndex = GlobalID - NUM_PREDEF_SUBMODULE_IDS;
4647 if (GlobalIndex >= SubmodulesLoaded.size() ||
4648 SubmodulesLoaded[GlobalIndex]) {
4649 Error("too many submodules");
Ben Langmuir2c9af442014-04-10 17:57:43 +00004650 return Failure;
Guy Benyei11169dd2012-12-18 14:30:41 +00004651 }
Douglas Gregor8a114ab2013-02-06 22:40:31 +00004652
Douglas Gregor7029ce12013-03-19 00:28:20 +00004653 if (!ParentModule) {
4654 if (const FileEntry *CurFile = CurrentModule->getASTFile()) {
4655 if (CurFile != F.File) {
4656 if (!Diags.isDiagnosticInFlight()) {
4657 Diag(diag::err_module_file_conflict)
4658 << CurrentModule->getTopLevelModuleName()
4659 << CurFile->getName()
4660 << F.File->getName();
4661 }
Ben Langmuir2c9af442014-04-10 17:57:43 +00004662 return Failure;
Douglas Gregor8a114ab2013-02-06 22:40:31 +00004663 }
Douglas Gregor8a114ab2013-02-06 22:40:31 +00004664 }
Douglas Gregor7029ce12013-03-19 00:28:20 +00004665
4666 CurrentModule->setASTFile(F.File);
Douglas Gregor8a114ab2013-02-06 22:40:31 +00004667 }
Ben Langmuirbeee15e2014-04-14 18:00:01 +00004668
Adrian Prantl15bcf702015-06-30 17:39:43 +00004669 CurrentModule->Signature = F.Signature;
Guy Benyei11169dd2012-12-18 14:30:41 +00004670 CurrentModule->IsFromModuleFile = true;
4671 CurrentModule->IsSystem = IsSystem || CurrentModule->IsSystem;
Richard Smith9bca2982014-03-08 00:03:56 +00004672 CurrentModule->IsExternC = IsExternC;
Guy Benyei11169dd2012-12-18 14:30:41 +00004673 CurrentModule->InferSubmodules = InferSubmodules;
4674 CurrentModule->InferExplicitSubmodules = InferExplicitSubmodules;
4675 CurrentModule->InferExportWildcard = InferExportWildcard;
Douglas Gregor8d932422013-03-20 03:59:18 +00004676 CurrentModule->ConfigMacrosExhaustive = ConfigMacrosExhaustive;
Guy Benyei11169dd2012-12-18 14:30:41 +00004677 if (DeserializationListener)
4678 DeserializationListener->ModuleRead(GlobalID, CurrentModule);
David L. Jonesc4808b9e2016-12-15 20:53:26 +00004679
Guy Benyei11169dd2012-12-18 14:30:41 +00004680 SubmodulesLoaded[GlobalIndex] = CurrentModule;
Douglas Gregor6ddfca92013-01-14 17:21:00 +00004681
Richard Smith8a3e39a2016-03-28 21:31:09 +00004682 // Clear out data that will be replaced by what is in the module file.
Douglas Gregor6ddfca92013-01-14 17:21:00 +00004683 CurrentModule->LinkLibraries.clear();
Douglas Gregor8d932422013-03-20 03:59:18 +00004684 CurrentModule->ConfigMacros.clear();
Douglas Gregorfb912652013-03-20 21:10:35 +00004685 CurrentModule->UnresolvedConflicts.clear();
4686 CurrentModule->Conflicts.clear();
Richard Smith8a3e39a2016-03-28 21:31:09 +00004687
4688 // The module is available unless it's missing a requirement; relevant
4689 // requirements will be (re-)added by SUBMODULE_REQUIRES records.
4690 // Missing headers that were present when the module was built do not
4691 // make it unavailable -- if we got this far, this must be an explicitly
4692 // imported module file.
4693 CurrentModule->Requirements.clear();
4694 CurrentModule->MissingHeaders.clear();
4695 CurrentModule->IsMissingRequirement =
4696 ParentModule && ParentModule->IsMissingRequirement;
4697 CurrentModule->IsAvailable = !CurrentModule->IsMissingRequirement;
Guy Benyei11169dd2012-12-18 14:30:41 +00004698 break;
4699 }
Richard Smith8a3e39a2016-03-28 21:31:09 +00004700
Guy Benyei11169dd2012-12-18 14:30:41 +00004701 case SUBMODULE_UMBRELLA_HEADER: {
Richard Smith2b63d152015-05-16 02:28:53 +00004702 std::string Filename = Blob;
4703 ResolveImportedPath(F, Filename);
4704 if (auto *Umbrella = PP.getFileManager().getFile(Filename)) {
Guy Benyei11169dd2012-12-18 14:30:41 +00004705 if (!CurrentModule->getUmbrellaHeader())
Richard Smith2b63d152015-05-16 02:28:53 +00004706 ModMap.setUmbrellaHeader(CurrentModule, Umbrella, Blob);
4707 else if (CurrentModule->getUmbrellaHeader().Entry != Umbrella) {
Ben Langmuirbc35fbe2015-02-20 21:46:39 +00004708 // This can be a spurious difference caused by changing the VFS to
4709 // point to a different copy of the file, and it is too late to
4710 // to rebuild safely.
4711 // FIXME: If we wrote the virtual paths instead of the 'real' paths,
4712 // after input file validation only real problems would remain and we
4713 // could just error. For now, assume it's okay.
4714 break;
Guy Benyei11169dd2012-12-18 14:30:41 +00004715 }
4716 }
4717 break;
4718 }
David L. Jonesc4808b9e2016-12-15 20:53:26 +00004719
Richard Smith202210b2014-10-24 20:23:01 +00004720 case SUBMODULE_HEADER:
4721 case SUBMODULE_EXCLUDED_HEADER:
4722 case SUBMODULE_PRIVATE_HEADER:
4723 // We lazily associate headers with their modules via the HeaderInfo table.
Argyrios Kyrtzidisb146baa2013-03-13 21:13:51 +00004724 // FIXME: Re-evaluate this section; maybe only store InputFile IDs instead
4725 // of complete filenames or remove it entirely.
Richard Smith202210b2014-10-24 20:23:01 +00004726 break;
Guy Benyei11169dd2012-12-18 14:30:41 +00004727
Richard Smith202210b2014-10-24 20:23:01 +00004728 case SUBMODULE_TEXTUAL_HEADER:
4729 case SUBMODULE_PRIVATE_TEXTUAL_HEADER:
4730 // FIXME: Textual headers are not marked in the HeaderInfo table. Load
4731 // them here.
4732 break;
Lawrence Crowlb53e5482013-06-20 21:14:14 +00004733
Guy Benyei11169dd2012-12-18 14:30:41 +00004734 case SUBMODULE_TOPHEADER: {
Argyrios Kyrtzidis3c5305c2013-03-13 21:13:43 +00004735 CurrentModule->addTopHeaderFilename(Blob);
Guy Benyei11169dd2012-12-18 14:30:41 +00004736 break;
4737 }
4738
4739 case SUBMODULE_UMBRELLA_DIR: {
Richard Smith2b63d152015-05-16 02:28:53 +00004740 std::string Dirname = Blob;
4741 ResolveImportedPath(F, Dirname);
4742 if (auto *Umbrella = PP.getFileManager().getDirectory(Dirname)) {
Guy Benyei11169dd2012-12-18 14:30:41 +00004743 if (!CurrentModule->getUmbrellaDir())
Richard Smith2b63d152015-05-16 02:28:53 +00004744 ModMap.setUmbrellaDir(CurrentModule, Umbrella, Blob);
4745 else if (CurrentModule->getUmbrellaDir().Entry != Umbrella) {
Ben Langmuir2c9af442014-04-10 17:57:43 +00004746 if ((ClientLoadCapabilities & ARR_OutOfDate) == 0)
4747 Error("mismatched umbrella directories in submodule");
4748 return OutOfDate;
Guy Benyei11169dd2012-12-18 14:30:41 +00004749 }
4750 }
4751 break;
4752 }
David L. Jonesc4808b9e2016-12-15 20:53:26 +00004753
Guy Benyei11169dd2012-12-18 14:30:41 +00004754 case SUBMODULE_METADATA: {
Guy Benyei11169dd2012-12-18 14:30:41 +00004755 F.BaseSubmoduleID = getTotalNumSubmodules();
4756 F.LocalNumSubmodules = Record[0];
4757 unsigned LocalBaseSubmoduleID = Record[1];
4758 if (F.LocalNumSubmodules > 0) {
David L. Jonesc4808b9e2016-12-15 20:53:26 +00004759 // Introduce the global -> local mapping for submodules within this
Guy Benyei11169dd2012-12-18 14:30:41 +00004760 // module.
4761 GlobalSubmoduleMap.insert(std::make_pair(getTotalNumSubmodules()+1,&F));
David L. Jonesc4808b9e2016-12-15 20:53:26 +00004762
4763 // Introduce the local -> global mapping for submodules within this
Guy Benyei11169dd2012-12-18 14:30:41 +00004764 // module.
4765 F.SubmoduleRemap.insertOrReplace(
4766 std::make_pair(LocalBaseSubmoduleID,
4767 F.BaseSubmoduleID - LocalBaseSubmoduleID));
Ben Langmuirfe971d92014-08-16 04:54:18 +00004768
Ben Langmuir52ca6782014-10-20 16:27:32 +00004769 SubmodulesLoaded.resize(SubmodulesLoaded.size() + F.LocalNumSubmodules);
4770 }
Guy Benyei11169dd2012-12-18 14:30:41 +00004771 break;
4772 }
David L. Jonesc4808b9e2016-12-15 20:53:26 +00004773
Guy Benyei11169dd2012-12-18 14:30:41 +00004774 case SUBMODULE_IMPORTS: {
Guy Benyei11169dd2012-12-18 14:30:41 +00004775 for (unsigned Idx = 0; Idx != Record.size(); ++Idx) {
Douglas Gregorfb912652013-03-20 21:10:35 +00004776 UnresolvedModuleRef Unresolved;
Guy Benyei11169dd2012-12-18 14:30:41 +00004777 Unresolved.File = &F;
4778 Unresolved.Mod = CurrentModule;
4779 Unresolved.ID = Record[Idx];
Douglas Gregorfb912652013-03-20 21:10:35 +00004780 Unresolved.Kind = UnresolvedModuleRef::Import;
Guy Benyei11169dd2012-12-18 14:30:41 +00004781 Unresolved.IsWildcard = false;
Douglas Gregorfb912652013-03-20 21:10:35 +00004782 UnresolvedModuleRefs.push_back(Unresolved);
Guy Benyei11169dd2012-12-18 14:30:41 +00004783 }
4784 break;
4785 }
4786
4787 case SUBMODULE_EXPORTS: {
Guy Benyei11169dd2012-12-18 14:30:41 +00004788 for (unsigned Idx = 0; Idx + 1 < Record.size(); Idx += 2) {
Douglas Gregorfb912652013-03-20 21:10:35 +00004789 UnresolvedModuleRef Unresolved;
Guy Benyei11169dd2012-12-18 14:30:41 +00004790 Unresolved.File = &F;
4791 Unresolved.Mod = CurrentModule;
4792 Unresolved.ID = Record[Idx];
Douglas Gregorfb912652013-03-20 21:10:35 +00004793 Unresolved.Kind = UnresolvedModuleRef::Export;
Guy Benyei11169dd2012-12-18 14:30:41 +00004794 Unresolved.IsWildcard = Record[Idx + 1];
Douglas Gregorfb912652013-03-20 21:10:35 +00004795 UnresolvedModuleRefs.push_back(Unresolved);
Guy Benyei11169dd2012-12-18 14:30:41 +00004796 }
David L. Jonesc4808b9e2016-12-15 20:53:26 +00004797
4798 // Once we've loaded the set of exports, there's no reason to keep
Guy Benyei11169dd2012-12-18 14:30:41 +00004799 // the parsed, unresolved exports around.
4800 CurrentModule->UnresolvedExports.clear();
4801 break;
4802 }
4803 case SUBMODULE_REQUIRES: {
Richard Smitha3feee22013-10-28 22:18:19 +00004804 CurrentModule->addRequirement(Blob, Record[0], Context.getLangOpts(),
Guy Benyei11169dd2012-12-18 14:30:41 +00004805 Context.getTargetInfo());
4806 break;
4807 }
Douglas Gregor6ddfca92013-01-14 17:21:00 +00004808
4809 case SUBMODULE_LINK_LIBRARY:
Douglas Gregor6ddfca92013-01-14 17:21:00 +00004810 CurrentModule->LinkLibraries.push_back(
Chris Lattner0e6c9402013-01-20 02:38:54 +00004811 Module::LinkLibrary(Blob, Record[0]));
Douglas Gregor6ddfca92013-01-14 17:21:00 +00004812 break;
Douglas Gregor35b13ec2013-03-20 00:22:05 +00004813
4814 case SUBMODULE_CONFIG_MACRO:
Douglas Gregor35b13ec2013-03-20 00:22:05 +00004815 CurrentModule->ConfigMacros.push_back(Blob.str());
4816 break;
Douglas Gregorfb912652013-03-20 21:10:35 +00004817
4818 case SUBMODULE_CONFLICT: {
Douglas Gregorfb912652013-03-20 21:10:35 +00004819 UnresolvedModuleRef Unresolved;
4820 Unresolved.File = &F;
4821 Unresolved.Mod = CurrentModule;
4822 Unresolved.ID = Record[0];
4823 Unresolved.Kind = UnresolvedModuleRef::Conflict;
4824 Unresolved.IsWildcard = false;
4825 Unresolved.String = Blob;
4826 UnresolvedModuleRefs.push_back(Unresolved);
4827 break;
4828 }
Richard Smithdc1f0422016-07-20 19:10:16 +00004829
4830 case SUBMODULE_INITIALIZERS:
4831 SmallVector<uint32_t, 16> Inits;
4832 for (auto &ID : Record)
4833 Inits.push_back(getGlobalDeclID(F, ID));
4834 Context.addLazyModuleInitializers(CurrentModule, Inits);
4835 break;
Guy Benyei11169dd2012-12-18 14:30:41 +00004836 }
4837 }
4838}
4839
4840/// \brief Parse the record that corresponds to a LangOptions data
4841/// structure.
4842///
4843/// This routine parses the language options from the AST file and then gives
4844/// them to the AST listener if one is set.
4845///
4846/// \returns true if the listener deems the file unacceptable, false otherwise.
4847bool ASTReader::ParseLanguageOptions(const RecordData &Record,
4848 bool Complain,
Richard Smith1e2cf0d2014-10-31 02:28:58 +00004849 ASTReaderListener &Listener,
4850 bool AllowCompatibleDifferences) {
Guy Benyei11169dd2012-12-18 14:30:41 +00004851 LangOptions LangOpts;
4852 unsigned Idx = 0;
4853#define LANGOPT(Name, Bits, Default, Description) \
4854 LangOpts.Name = Record[Idx++];
4855#define ENUM_LANGOPT(Name, Type, Bits, Default, Description) \
4856 LangOpts.set##Name(static_cast<LangOptions::Type>(Record[Idx++]));
4857#include "clang/Basic/LangOptions.def"
Alexey Samsonovedf99a92014-11-07 22:29:38 +00004858#define SANITIZER(NAME, ID) \
4859 LangOpts.Sanitize.set(SanitizerKind::ID, Record[Idx++]);
Will Dietzf54319c2013-01-18 11:30:38 +00004860#include "clang/Basic/Sanitizers.def"
Guy Benyei11169dd2012-12-18 14:30:41 +00004861
Ben Langmuircd98cb72015-06-23 18:20:18 +00004862 for (unsigned N = Record[Idx++]; N; --N)
4863 LangOpts.ModuleFeatures.push_back(ReadString(Record, Idx));
4864
Guy Benyei11169dd2012-12-18 14:30:41 +00004865 ObjCRuntime::Kind runtimeKind = (ObjCRuntime::Kind) Record[Idx++];
4866 VersionTuple runtimeVersion = ReadVersionTuple(Record, Idx);
4867 LangOpts.ObjCRuntime = ObjCRuntime(runtimeKind, runtimeVersion);
Dmitri Gribenkoacf2e782013-02-22 14:21:27 +00004868
Ben Langmuird4a667a2015-06-23 18:20:23 +00004869 LangOpts.CurrentModule = ReadString(Record, Idx);
Dmitri Gribenkoacf2e782013-02-22 14:21:27 +00004870
4871 // Comment options.
4872 for (unsigned N = Record[Idx++]; N; --N) {
4873 LangOpts.CommentOpts.BlockCommandNames.push_back(
4874 ReadString(Record, Idx));
4875 }
Dmitri Gribenkoa7d16ce2013-04-10 15:35:17 +00004876 LangOpts.CommentOpts.ParseAllComments = Record[Idx++];
Dmitri Gribenkoacf2e782013-02-22 14:21:27 +00004877
Samuel Antaoee8fb302016-01-06 13:42:12 +00004878 // OpenMP offloading options.
4879 for (unsigned N = Record[Idx++]; N; --N) {
4880 LangOpts.OMPTargetTriples.push_back(llvm::Triple(ReadString(Record, Idx)));
4881 }
4882
4883 LangOpts.OMPHostIRFile = ReadString(Record, Idx);
4884
Richard Smith1e2cf0d2014-10-31 02:28:58 +00004885 return Listener.ReadLanguageOptions(LangOpts, Complain,
4886 AllowCompatibleDifferences);
Guy Benyei11169dd2012-12-18 14:30:41 +00004887}
4888
Chandler Carruth0d745bc2015-03-14 04:47:43 +00004889bool ASTReader::ParseTargetOptions(const RecordData &Record, bool Complain,
4890 ASTReaderListener &Listener,
4891 bool AllowCompatibleDifferences) {
Guy Benyei11169dd2012-12-18 14:30:41 +00004892 unsigned Idx = 0;
4893 TargetOptions TargetOpts;
4894 TargetOpts.Triple = ReadString(Record, Idx);
4895 TargetOpts.CPU = ReadString(Record, Idx);
4896 TargetOpts.ABI = ReadString(Record, Idx);
Guy Benyei11169dd2012-12-18 14:30:41 +00004897 for (unsigned N = Record[Idx++]; N; --N) {
4898 TargetOpts.FeaturesAsWritten.push_back(ReadString(Record, Idx));
4899 }
4900 for (unsigned N = Record[Idx++]; N; --N) {
4901 TargetOpts.Features.push_back(ReadString(Record, Idx));
4902 }
4903
Chandler Carruth0d745bc2015-03-14 04:47:43 +00004904 return Listener.ReadTargetOptions(TargetOpts, Complain,
4905 AllowCompatibleDifferences);
Guy Benyei11169dd2012-12-18 14:30:41 +00004906}
4907
4908bool ASTReader::ParseDiagnosticOptions(const RecordData &Record, bool Complain,
4909 ASTReaderListener &Listener) {
Ben Langmuirb92de022014-04-29 16:25:26 +00004910 IntrusiveRefCntPtr<DiagnosticOptions> DiagOpts(new DiagnosticOptions);
Guy Benyei11169dd2012-12-18 14:30:41 +00004911 unsigned Idx = 0;
Ben Langmuirb92de022014-04-29 16:25:26 +00004912#define DIAGOPT(Name, Bits, Default) DiagOpts->Name = Record[Idx++];
Guy Benyei11169dd2012-12-18 14:30:41 +00004913#define ENUM_DIAGOPT(Name, Type, Bits, Default) \
Ben Langmuirb92de022014-04-29 16:25:26 +00004914 DiagOpts->set##Name(static_cast<Type>(Record[Idx++]));
Guy Benyei11169dd2012-12-18 14:30:41 +00004915#include "clang/Basic/DiagnosticOptions.def"
4916
Richard Smith3be1cb22014-08-07 00:24:21 +00004917 for (unsigned N = Record[Idx++]; N; --N)
Ben Langmuirb92de022014-04-29 16:25:26 +00004918 DiagOpts->Warnings.push_back(ReadString(Record, Idx));
Richard Smith3be1cb22014-08-07 00:24:21 +00004919 for (unsigned N = Record[Idx++]; N; --N)
4920 DiagOpts->Remarks.push_back(ReadString(Record, Idx));
Guy Benyei11169dd2012-12-18 14:30:41 +00004921
4922 return Listener.ReadDiagnosticOptions(DiagOpts, Complain);
4923}
4924
4925bool ASTReader::ParseFileSystemOptions(const RecordData &Record, bool Complain,
4926 ASTReaderListener &Listener) {
4927 FileSystemOptions FSOpts;
4928 unsigned Idx = 0;
4929 FSOpts.WorkingDir = ReadString(Record, Idx);
4930 return Listener.ReadFileSystemOptions(FSOpts, Complain);
4931}
4932
4933bool ASTReader::ParseHeaderSearchOptions(const RecordData &Record,
4934 bool Complain,
4935 ASTReaderListener &Listener) {
4936 HeaderSearchOptions HSOpts;
4937 unsigned Idx = 0;
4938 HSOpts.Sysroot = ReadString(Record, Idx);
4939
4940 // Include entries.
4941 for (unsigned N = Record[Idx++]; N; --N) {
4942 std::string Path = ReadString(Record, Idx);
4943 frontend::IncludeDirGroup Group
4944 = static_cast<frontend::IncludeDirGroup>(Record[Idx++]);
Guy Benyei11169dd2012-12-18 14:30:41 +00004945 bool IsFramework = Record[Idx++];
4946 bool IgnoreSysRoot = Record[Idx++];
Benjamin Kramer3204b152015-05-29 19:42:19 +00004947 HSOpts.UserEntries.emplace_back(std::move(Path), Group, IsFramework,
4948 IgnoreSysRoot);
Guy Benyei11169dd2012-12-18 14:30:41 +00004949 }
4950
4951 // System header prefixes.
4952 for (unsigned N = Record[Idx++]; N; --N) {
4953 std::string Prefix = ReadString(Record, Idx);
4954 bool IsSystemHeader = Record[Idx++];
Benjamin Kramer3204b152015-05-29 19:42:19 +00004955 HSOpts.SystemHeaderPrefixes.emplace_back(std::move(Prefix), IsSystemHeader);
Guy Benyei11169dd2012-12-18 14:30:41 +00004956 }
4957
4958 HSOpts.ResourceDir = ReadString(Record, Idx);
4959 HSOpts.ModuleCachePath = ReadString(Record, Idx);
Argyrios Kyrtzidis1594c152014-03-03 08:12:05 +00004960 HSOpts.ModuleUserBuildPath = ReadString(Record, Idx);
Guy Benyei11169dd2012-12-18 14:30:41 +00004961 HSOpts.DisableModuleHash = Record[Idx++];
4962 HSOpts.UseBuiltinIncludes = Record[Idx++];
4963 HSOpts.UseStandardSystemIncludes = Record[Idx++];
4964 HSOpts.UseStandardCXXIncludes = Record[Idx++];
4965 HSOpts.UseLibcxx = Record[Idx++];
Argyrios Kyrtzidisbd0b6512015-02-19 20:12:20 +00004966 std::string SpecificModuleCachePath = ReadString(Record, Idx);
Guy Benyei11169dd2012-12-18 14:30:41 +00004967
Argyrios Kyrtzidisbd0b6512015-02-19 20:12:20 +00004968 return Listener.ReadHeaderSearchOptions(HSOpts, SpecificModuleCachePath,
4969 Complain);
Guy Benyei11169dd2012-12-18 14:30:41 +00004970}
4971
4972bool ASTReader::ParsePreprocessorOptions(const RecordData &Record,
4973 bool Complain,
4974 ASTReaderListener &Listener,
4975 std::string &SuggestedPredefines) {
4976 PreprocessorOptions PPOpts;
4977 unsigned Idx = 0;
4978
4979 // Macro definitions/undefs
4980 for (unsigned N = Record[Idx++]; N; --N) {
4981 std::string Macro = ReadString(Record, Idx);
4982 bool IsUndef = Record[Idx++];
4983 PPOpts.Macros.push_back(std::make_pair(Macro, IsUndef));
4984 }
4985
4986 // Includes
4987 for (unsigned N = Record[Idx++]; N; --N) {
4988 PPOpts.Includes.push_back(ReadString(Record, Idx));
4989 }
4990
4991 // Macro Includes
4992 for (unsigned N = Record[Idx++]; N; --N) {
4993 PPOpts.MacroIncludes.push_back(ReadString(Record, Idx));
4994 }
4995
4996 PPOpts.UsePredefines = Record[Idx++];
Argyrios Kyrtzidisd3afa0c2013-04-26 21:33:40 +00004997 PPOpts.DetailedRecord = Record[Idx++];
Guy Benyei11169dd2012-12-18 14:30:41 +00004998 PPOpts.ImplicitPCHInclude = ReadString(Record, Idx);
4999 PPOpts.ImplicitPTHInclude = ReadString(Record, Idx);
5000 PPOpts.ObjCXXARCStandardLibrary =
5001 static_cast<ObjCXXARCStandardLibraryKind>(Record[Idx++]);
5002 SuggestedPredefines.clear();
5003 return Listener.ReadPreprocessorOptions(PPOpts, Complain,
5004 SuggestedPredefines);
5005}
5006
5007std::pair<ModuleFile *, unsigned>
5008ASTReader::getModulePreprocessedEntity(unsigned GlobalIndex) {
5009 GlobalPreprocessedEntityMapType::iterator
5010 I = GlobalPreprocessedEntityMap.find(GlobalIndex);
David L. Jonesc4808b9e2016-12-15 20:53:26 +00005011 assert(I != GlobalPreprocessedEntityMap.end() &&
Guy Benyei11169dd2012-12-18 14:30:41 +00005012 "Corrupted global preprocessed entity map");
5013 ModuleFile *M = I->second;
5014 unsigned LocalIndex = GlobalIndex - M->BasePreprocessedEntityID;
5015 return std::make_pair(M, LocalIndex);
5016}
5017
Benjamin Kramerb4ef6682015-02-06 17:25:10 +00005018llvm::iterator_range<PreprocessingRecord::iterator>
Guy Benyei11169dd2012-12-18 14:30:41 +00005019ASTReader::getModulePreprocessedEntities(ModuleFile &Mod) const {
5020 if (PreprocessingRecord *PPRec = PP.getPreprocessingRecord())
5021 return PPRec->getIteratorsForLoadedRange(Mod.BasePreprocessedEntityID,
5022 Mod.NumPreprocessedEntities);
5023
Benjamin Kramerb4ef6682015-02-06 17:25:10 +00005024 return llvm::make_range(PreprocessingRecord::iterator(),
5025 PreprocessingRecord::iterator());
Guy Benyei11169dd2012-12-18 14:30:41 +00005026}
5027
Benjamin Kramerb4ef6682015-02-06 17:25:10 +00005028llvm::iterator_range<ASTReader::ModuleDeclIterator>
Guy Benyei11169dd2012-12-18 14:30:41 +00005029ASTReader::getModuleFileLevelDecls(ModuleFile &Mod) {
Benjamin Kramerb4ef6682015-02-06 17:25:10 +00005030 return llvm::make_range(
5031 ModuleDeclIterator(this, &Mod, Mod.FileSortedDecls),
5032 ModuleDeclIterator(this, &Mod,
5033 Mod.FileSortedDecls + Mod.NumFileSortedDecls));
Guy Benyei11169dd2012-12-18 14:30:41 +00005034}
5035
5036PreprocessedEntity *ASTReader::ReadPreprocessedEntity(unsigned Index) {
5037 PreprocessedEntityID PPID = Index+1;
5038 std::pair<ModuleFile *, unsigned> PPInfo = getModulePreprocessedEntity(Index);
5039 ModuleFile &M = *PPInfo.first;
5040 unsigned LocalIndex = PPInfo.second;
5041 const PPEntityOffset &PPOffs = M.PreprocessedEntityOffsets[LocalIndex];
5042
Guy Benyei11169dd2012-12-18 14:30:41 +00005043 if (!PP.getPreprocessingRecord()) {
5044 Error("no preprocessing record");
Craig Toppera13603a2014-05-22 05:54:18 +00005045 return nullptr;
Guy Benyei11169dd2012-12-18 14:30:41 +00005046 }
David L. Jonesc4808b9e2016-12-15 20:53:26 +00005047
5048 SavedStreamPosition SavedPosition(M.PreprocessorDetailCursor);
Chris Lattner7fb3bef2013-01-20 00:56:42 +00005049 M.PreprocessorDetailCursor.JumpToBit(PPOffs.BitOffset);
5050
5051 llvm::BitstreamEntry Entry =
5052 M.PreprocessorDetailCursor.advance(BitstreamCursor::AF_DontPopBlockAtEnd);
5053 if (Entry.Kind != llvm::BitstreamEntry::Record)
Craig Toppera13603a2014-05-22 05:54:18 +00005054 return nullptr;
Chris Lattner7fb3bef2013-01-20 00:56:42 +00005055
Guy Benyei11169dd2012-12-18 14:30:41 +00005056 // Read the record.
Richard Smithcb34bd32016-03-27 07:28:06 +00005057 SourceRange Range(TranslateSourceLocation(M, PPOffs.getBegin()),
5058 TranslateSourceLocation(M, PPOffs.getEnd()));
Guy Benyei11169dd2012-12-18 14:30:41 +00005059 PreprocessingRecord &PPRec = *PP.getPreprocessingRecord();
Chris Lattner0e6c9402013-01-20 02:38:54 +00005060 StringRef Blob;
Guy Benyei11169dd2012-12-18 14:30:41 +00005061 RecordData Record;
5062 PreprocessorDetailRecordTypes RecType =
Chris Lattner0e6c9402013-01-20 02:38:54 +00005063 (PreprocessorDetailRecordTypes)M.PreprocessorDetailCursor.readRecord(
5064 Entry.ID, Record, &Blob);
Guy Benyei11169dd2012-12-18 14:30:41 +00005065 switch (RecType) {
5066 case PPD_MACRO_EXPANSION: {
5067 bool isBuiltin = Record[0];
Craig Toppera13603a2014-05-22 05:54:18 +00005068 IdentifierInfo *Name = nullptr;
Richard Smith66a81862015-05-04 02:25:31 +00005069 MacroDefinitionRecord *Def = nullptr;
Guy Benyei11169dd2012-12-18 14:30:41 +00005070 if (isBuiltin)
5071 Name = getLocalIdentifier(M, Record[1]);
5072 else {
Richard Smith66a81862015-05-04 02:25:31 +00005073 PreprocessedEntityID GlobalID =
5074 getGlobalPreprocessedEntityID(M, Record[1]);
5075 Def = cast<MacroDefinitionRecord>(
5076 PPRec.getLoadedPreprocessedEntity(GlobalID - 1));
Guy Benyei11169dd2012-12-18 14:30:41 +00005077 }
5078
5079 MacroExpansion *ME;
5080 if (isBuiltin)
5081 ME = new (PPRec) MacroExpansion(Name, Range);
5082 else
5083 ME = new (PPRec) MacroExpansion(Def, Range);
5084
5085 return ME;
5086 }
David L. Jonesc4808b9e2016-12-15 20:53:26 +00005087
Guy Benyei11169dd2012-12-18 14:30:41 +00005088 case PPD_MACRO_DEFINITION: {
5089 // Decode the identifier info and then check again; if the macro is
5090 // still defined and associated with the identifier,
5091 IdentifierInfo *II = getLocalIdentifier(M, Record[0]);
Richard Smith66a81862015-05-04 02:25:31 +00005092 MacroDefinitionRecord *MD = new (PPRec) MacroDefinitionRecord(II, Range);
Guy Benyei11169dd2012-12-18 14:30:41 +00005093
5094 if (DeserializationListener)
5095 DeserializationListener->MacroDefinitionRead(PPID, MD);
5096
5097 return MD;
5098 }
David L. Jonesc4808b9e2016-12-15 20:53:26 +00005099
Guy Benyei11169dd2012-12-18 14:30:41 +00005100 case PPD_INCLUSION_DIRECTIVE: {
Chris Lattner0e6c9402013-01-20 02:38:54 +00005101 const char *FullFileNameStart = Blob.data() + Record[0];
5102 StringRef FullFileName(FullFileNameStart, Blob.size() - Record[0]);
Craig Toppera13603a2014-05-22 05:54:18 +00005103 const FileEntry *File = nullptr;
Guy Benyei11169dd2012-12-18 14:30:41 +00005104 if (!FullFileName.empty())
5105 File = PP.getFileManager().getFile(FullFileName);
David L. Jonesc4808b9e2016-12-15 20:53:26 +00005106
Guy Benyei11169dd2012-12-18 14:30:41 +00005107 // FIXME: Stable encoding
5108 InclusionDirective::InclusionKind Kind
5109 = static_cast<InclusionDirective::InclusionKind>(Record[2]);
5110 InclusionDirective *ID
5111 = new (PPRec) InclusionDirective(PPRec, Kind,
Chris Lattner0e6c9402013-01-20 02:38:54 +00005112 StringRef(Blob.data(), Record[0]),
Guy Benyei11169dd2012-12-18 14:30:41 +00005113 Record[1], Record[3],
5114 File,
5115 Range);
5116 return ID;
5117 }
5118 }
5119
5120 llvm_unreachable("Invalid PreprocessorDetailRecordTypes");
5121}
5122
5123/// \brief \arg SLocMapI points at a chunk of a module that contains no
5124/// preprocessed entities or the entities it contains are not the ones we are
5125/// looking for. Find the next module that contains entities and return the ID
5126/// of the first entry.
5127PreprocessedEntityID ASTReader::findNextPreprocessedEntity(
5128 GlobalSLocOffsetMapType::const_iterator SLocMapI) const {
5129 ++SLocMapI;
5130 for (GlobalSLocOffsetMapType::const_iterator
5131 EndI = GlobalSLocOffsetMap.end(); SLocMapI != EndI; ++SLocMapI) {
5132 ModuleFile &M = *SLocMapI->second;
5133 if (M.NumPreprocessedEntities)
5134 return M.BasePreprocessedEntityID;
5135 }
5136
5137 return getTotalNumPreprocessedEntities();
5138}
5139
5140namespace {
5141
Guy Benyei11169dd2012-12-18 14:30:41 +00005142struct PPEntityComp {
5143 const ASTReader &Reader;
5144 ModuleFile &M;
5145
5146 PPEntityComp(const ASTReader &Reader, ModuleFile &M) : Reader(Reader), M(M) { }
5147
5148 bool operator()(const PPEntityOffset &L, const PPEntityOffset &R) const {
5149 SourceLocation LHS = getLoc(L);
5150 SourceLocation RHS = getLoc(R);
5151 return Reader.getSourceManager().isBeforeInTranslationUnit(LHS, RHS);
5152 }
5153
5154 bool operator()(const PPEntityOffset &L, SourceLocation RHS) const {
5155 SourceLocation LHS = getLoc(L);
5156 return Reader.getSourceManager().isBeforeInTranslationUnit(LHS, RHS);
5157 }
5158
5159 bool operator()(SourceLocation LHS, const PPEntityOffset &R) const {
5160 SourceLocation RHS = getLoc(R);
5161 return Reader.getSourceManager().isBeforeInTranslationUnit(LHS, RHS);
5162 }
5163
5164 SourceLocation getLoc(const PPEntityOffset &PPE) const {
Richard Smithb22a1d12016-03-27 20:13:24 +00005165 return Reader.TranslateSourceLocation(M, PPE.getBegin());
Guy Benyei11169dd2012-12-18 14:30:41 +00005166 }
5167};
5168
Eugene Zelenkoe95e7d52016-09-07 21:53:17 +00005169} // end anonymous namespace
Guy Benyei11169dd2012-12-18 14:30:41 +00005170
Alp Toker2e9ce4c2014-05-16 18:59:21 +00005171PreprocessedEntityID ASTReader::findPreprocessedEntity(SourceLocation Loc,
5172 bool EndsAfter) const {
5173 if (SourceMgr.isLocalSourceLocation(Loc))
Guy Benyei11169dd2012-12-18 14:30:41 +00005174 return getTotalNumPreprocessedEntities();
5175
Alp Toker2e9ce4c2014-05-16 18:59:21 +00005176 GlobalSLocOffsetMapType::const_iterator SLocMapI = GlobalSLocOffsetMap.find(
5177 SourceManager::MaxLoadedOffset - Loc.getOffset() - 1);
Guy Benyei11169dd2012-12-18 14:30:41 +00005178 assert(SLocMapI != GlobalSLocOffsetMap.end() &&
5179 "Corrupted global sloc offset map");
5180
5181 if (SLocMapI->second->NumPreprocessedEntities == 0)
5182 return findNextPreprocessedEntity(SLocMapI);
5183
5184 ModuleFile &M = *SLocMapI->second;
5185 typedef const PPEntityOffset *pp_iterator;
5186 pp_iterator pp_begin = M.PreprocessedEntityOffsets;
5187 pp_iterator pp_end = pp_begin + M.NumPreprocessedEntities;
5188
5189 size_t Count = M.NumPreprocessedEntities;
5190 size_t Half;
5191 pp_iterator First = pp_begin;
5192 pp_iterator PPI;
5193
Alp Toker2e9ce4c2014-05-16 18:59:21 +00005194 if (EndsAfter) {
5195 PPI = std::upper_bound(pp_begin, pp_end, Loc,
Richard Smithb22a1d12016-03-27 20:13:24 +00005196 PPEntityComp(*this, M));
Alp Toker2e9ce4c2014-05-16 18:59:21 +00005197 } else {
5198 // Do a binary search manually instead of using std::lower_bound because
5199 // The end locations of entities may be unordered (when a macro expansion
5200 // is inside another macro argument), but for this case it is not important
5201 // whether we get the first macro expansion or its containing macro.
5202 while (Count > 0) {
5203 Half = Count / 2;
5204 PPI = First;
5205 std::advance(PPI, Half);
Richard Smithb22a1d12016-03-27 20:13:24 +00005206 if (SourceMgr.isBeforeInTranslationUnit(
5207 TranslateSourceLocation(M, PPI->getEnd()), Loc)) {
Alp Toker2e9ce4c2014-05-16 18:59:21 +00005208 First = PPI;
5209 ++First;
5210 Count = Count - Half - 1;
5211 } else
5212 Count = Half;
5213 }
Guy Benyei11169dd2012-12-18 14:30:41 +00005214 }
5215
5216 if (PPI == pp_end)
5217 return findNextPreprocessedEntity(SLocMapI);
5218
5219 return M.BasePreprocessedEntityID + (PPI - pp_begin);
5220}
5221
Guy Benyei11169dd2012-12-18 14:30:41 +00005222/// \brief Returns a pair of [Begin, End) indices of preallocated
5223/// preprocessed entities that \arg Range encompasses.
5224std::pair<unsigned, unsigned>
5225 ASTReader::findPreprocessedEntitiesInRange(SourceRange Range) {
5226 if (Range.isInvalid())
5227 return std::make_pair(0,0);
5228 assert(!SourceMgr.isBeforeInTranslationUnit(Range.getEnd(),Range.getBegin()));
5229
Alp Toker2e9ce4c2014-05-16 18:59:21 +00005230 PreprocessedEntityID BeginID =
5231 findPreprocessedEntity(Range.getBegin(), false);
5232 PreprocessedEntityID EndID = findPreprocessedEntity(Range.getEnd(), true);
Guy Benyei11169dd2012-12-18 14:30:41 +00005233 return std::make_pair(BeginID, EndID);
5234}
5235
5236/// \brief Optionally returns true or false if the preallocated preprocessed
5237/// entity with index \arg Index came from file \arg FID.
David Blaikie05785d12013-02-20 22:23:23 +00005238Optional<bool> ASTReader::isPreprocessedEntityInFileID(unsigned Index,
Guy Benyei11169dd2012-12-18 14:30:41 +00005239 FileID FID) {
5240 if (FID.isInvalid())
5241 return false;
5242
5243 std::pair<ModuleFile *, unsigned> PPInfo = getModulePreprocessedEntity(Index);
5244 ModuleFile &M = *PPInfo.first;
5245 unsigned LocalIndex = PPInfo.second;
5246 const PPEntityOffset &PPOffs = M.PreprocessedEntityOffsets[LocalIndex];
David L. Jonesc4808b9e2016-12-15 20:53:26 +00005247
Richard Smithcb34bd32016-03-27 07:28:06 +00005248 SourceLocation Loc = TranslateSourceLocation(M, PPOffs.getBegin());
Guy Benyei11169dd2012-12-18 14:30:41 +00005249 if (Loc.isInvalid())
5250 return false;
David L. Jonesc4808b9e2016-12-15 20:53:26 +00005251
Guy Benyei11169dd2012-12-18 14:30:41 +00005252 if (SourceMgr.isInFileID(SourceMgr.getFileLoc(Loc), FID))
5253 return true;
5254 else
5255 return false;
5256}
5257
5258namespace {
Eugene Zelenkoe95e7d52016-09-07 21:53:17 +00005259
Guy Benyei11169dd2012-12-18 14:30:41 +00005260 /// \brief Visitor used to search for information about a header file.
5261 class HeaderFileInfoVisitor {
Guy Benyei11169dd2012-12-18 14:30:41 +00005262 const FileEntry *FE;
David L. Jonesc4808b9e2016-12-15 20:53:26 +00005263
David Blaikie05785d12013-02-20 22:23:23 +00005264 Optional<HeaderFileInfo> HFI;
David L. Jonesc4808b9e2016-12-15 20:53:26 +00005265
Guy Benyei11169dd2012-12-18 14:30:41 +00005266 public:
Argyrios Kyrtzidis61a38962013-03-06 18:12:44 +00005267 explicit HeaderFileInfoVisitor(const FileEntry *FE)
5268 : FE(FE) { }
Benjamin Kramer9a9efba2015-07-25 12:14:04 +00005269
5270 bool operator()(ModuleFile &M) {
Guy Benyei11169dd2012-12-18 14:30:41 +00005271 HeaderFileInfoLookupTable *Table
5272 = static_cast<HeaderFileInfoLookupTable *>(M.HeaderFileInfoTable);
5273 if (!Table)
5274 return false;
5275
5276 // Look in the on-disk hash table for an entry for this file name.
Richard Smithbdf2d932015-07-30 03:37:16 +00005277 HeaderFileInfoLookupTable::iterator Pos = Table->find(FE);
Guy Benyei11169dd2012-12-18 14:30:41 +00005278 if (Pos == Table->end())
5279 return false;
5280
Richard Smithbdf2d932015-07-30 03:37:16 +00005281 HFI = *Pos;
Guy Benyei11169dd2012-12-18 14:30:41 +00005282 return true;
5283 }
David L. Jonesc4808b9e2016-12-15 20:53:26 +00005284
David Blaikie05785d12013-02-20 22:23:23 +00005285 Optional<HeaderFileInfo> getHeaderFileInfo() const { return HFI; }
Guy Benyei11169dd2012-12-18 14:30:41 +00005286 };
Eugene Zelenkoe95e7d52016-09-07 21:53:17 +00005287
5288} // end anonymous namespace
Guy Benyei11169dd2012-12-18 14:30:41 +00005289
5290HeaderFileInfo ASTReader::GetHeaderFileInfo(const FileEntry *FE) {
Argyrios Kyrtzidis61a38962013-03-06 18:12:44 +00005291 HeaderFileInfoVisitor Visitor(FE);
Benjamin Kramer9a9efba2015-07-25 12:14:04 +00005292 ModuleMgr.visit(Visitor);
Argyrios Kyrtzidis1054bbf2013-05-08 23:46:55 +00005293 if (Optional<HeaderFileInfo> HFI = Visitor.getHeaderFileInfo())
Guy Benyei11169dd2012-12-18 14:30:41 +00005294 return *HFI;
David L. Jonesc4808b9e2016-12-15 20:53:26 +00005295
Guy Benyei11169dd2012-12-18 14:30:41 +00005296 return HeaderFileInfo();
5297}
5298
5299void ASTReader::ReadPragmaDiagnosticMappings(DiagnosticsEngine &Diag) {
5300 // FIXME: Make it work properly with modules.
Dmitri Gribenkof8579502013-01-12 19:30:44 +00005301 SmallVector<DiagnosticsEngine::DiagState *, 32> DiagStates;
Guy Benyei11169dd2012-12-18 14:30:41 +00005302 for (ModuleIterator I = ModuleMgr.begin(), E = ModuleMgr.end(); I != E; ++I) {
5303 ModuleFile &F = *(*I);
5304 unsigned Idx = 0;
5305 DiagStates.clear();
5306 assert(!Diag.DiagStates.empty());
5307 DiagStates.push_back(&Diag.DiagStates.front()); // the command-line one.
5308 while (Idx < F.PragmaDiagMappings.size()) {
5309 SourceLocation Loc = ReadSourceLocation(F, F.PragmaDiagMappings[Idx++]);
5310 unsigned DiagStateID = F.PragmaDiagMappings[Idx++];
5311 if (DiagStateID != 0) {
5312 Diag.DiagStatePoints.push_back(
5313 DiagnosticsEngine::DiagStatePoint(DiagStates[DiagStateID-1],
5314 FullSourceLoc(Loc, SourceMgr)));
5315 continue;
5316 }
David L. Jonesc4808b9e2016-12-15 20:53:26 +00005317
Guy Benyei11169dd2012-12-18 14:30:41 +00005318 assert(DiagStateID == 0);
5319 // A new DiagState was created here.
5320 Diag.DiagStates.push_back(*Diag.GetCurDiagState());
5321 DiagnosticsEngine::DiagState *NewState = &Diag.DiagStates.back();
5322 DiagStates.push_back(NewState);
5323 Diag.DiagStatePoints.push_back(
5324 DiagnosticsEngine::DiagStatePoint(NewState,
5325 FullSourceLoc(Loc, SourceMgr)));
Eugene Zelenkoe95e7d52016-09-07 21:53:17 +00005326 while (true) {
Guy Benyei11169dd2012-12-18 14:30:41 +00005327 assert(Idx < F.PragmaDiagMappings.size() &&
5328 "Invalid data, didn't find '-1' marking end of diag/map pairs");
5329 if (Idx >= F.PragmaDiagMappings.size()) {
5330 break; // Something is messed up but at least avoid infinite loop in
5331 // release build.
5332 }
5333 unsigned DiagID = F.PragmaDiagMappings[Idx++];
5334 if (DiagID == (unsigned)-1) {
5335 break; // no more diag/map pairs for this location.
5336 }
Alp Tokerc726c362014-06-10 09:31:37 +00005337 diag::Severity Map = (diag::Severity)F.PragmaDiagMappings[Idx++];
5338 DiagnosticMapping Mapping = Diag.makeUserMapping(Map, Loc);
5339 Diag.GetCurDiagState()->setMapping(DiagID, Mapping);
Guy Benyei11169dd2012-12-18 14:30:41 +00005340 }
5341 }
5342 }
5343}
5344
5345/// \brief Get the correct cursor and offset for loading a type.
5346ASTReader::RecordLocation ASTReader::TypeCursorForIndex(unsigned Index) {
5347 GlobalTypeMapType::iterator I = GlobalTypeMap.find(Index);
5348 assert(I != GlobalTypeMap.end() && "Corrupted global type map");
5349 ModuleFile *M = I->second;
5350 return RecordLocation(M, M->TypeOffsets[Index - M->BaseTypeIndex]);
5351}
5352
5353/// \brief Read and return the type with the given index..
5354///
5355/// The index is the type ID, shifted and minus the number of predefs. This
5356/// routine actually reads the record corresponding to the type at the given
5357/// location. It is a helper routine for GetType, which deals with reading type
5358/// IDs.
5359QualType ASTReader::readTypeRecord(unsigned Index) {
5360 RecordLocation Loc = TypeCursorForIndex(Index);
Chris Lattner7fb3bef2013-01-20 00:56:42 +00005361 BitstreamCursor &DeclsCursor = Loc.F->DeclsCursor;
Guy Benyei11169dd2012-12-18 14:30:41 +00005362
5363 // Keep track of where we are in the stream, then jump back there
5364 // after reading this type.
5365 SavedStreamPosition SavedPosition(DeclsCursor);
5366
5367 ReadingKindTracker ReadingKind(Read_Type, *this);
5368
5369 // Note that we are loading a type record.
5370 Deserializing AType(this);
5371
5372 unsigned Idx = 0;
5373 DeclsCursor.JumpToBit(Loc.Offset);
5374 RecordData Record;
5375 unsigned Code = DeclsCursor.ReadCode();
Chris Lattner0e6c9402013-01-20 02:38:54 +00005376 switch ((TypeCode)DeclsCursor.readRecord(Code, Record)) {
Guy Benyei11169dd2012-12-18 14:30:41 +00005377 case TYPE_EXT_QUAL: {
5378 if (Record.size() != 2) {
5379 Error("Incorrect encoding of extended qualifier type");
5380 return QualType();
5381 }
5382 QualType Base = readType(*Loc.F, Record, Idx);
5383 Qualifiers Quals = Qualifiers::fromOpaqueValue(Record[Idx++]);
5384 return Context.getQualifiedType(Base, Quals);
5385 }
5386
5387 case TYPE_COMPLEX: {
5388 if (Record.size() != 1) {
5389 Error("Incorrect encoding of complex type");
5390 return QualType();
5391 }
5392 QualType ElemType = readType(*Loc.F, Record, Idx);
5393 return Context.getComplexType(ElemType);
5394 }
5395
5396 case TYPE_POINTER: {
5397 if (Record.size() != 1) {
5398 Error("Incorrect encoding of pointer type");
5399 return QualType();
5400 }
5401 QualType PointeeType = readType(*Loc.F, Record, Idx);
5402 return Context.getPointerType(PointeeType);
5403 }
5404
Reid Kleckner8a365022013-06-24 17:51:48 +00005405 case TYPE_DECAYED: {
5406 if (Record.size() != 1) {
5407 Error("Incorrect encoding of decayed type");
5408 return QualType();
5409 }
5410 QualType OriginalType = readType(*Loc.F, Record, Idx);
5411 QualType DT = Context.getAdjustedParameterType(OriginalType);
5412 if (!isa<DecayedType>(DT))
5413 Error("Decayed type does not decay");
5414 return DT;
5415 }
5416
Reid Kleckner0503a872013-12-05 01:23:43 +00005417 case TYPE_ADJUSTED: {
5418 if (Record.size() != 2) {
5419 Error("Incorrect encoding of adjusted type");
5420 return QualType();
5421 }
5422 QualType OriginalTy = readType(*Loc.F, Record, Idx);
5423 QualType AdjustedTy = readType(*Loc.F, Record, Idx);
5424 return Context.getAdjustedType(OriginalTy, AdjustedTy);
5425 }
5426
Guy Benyei11169dd2012-12-18 14:30:41 +00005427 case TYPE_BLOCK_POINTER: {
5428 if (Record.size() != 1) {
5429 Error("Incorrect encoding of block pointer type");
5430 return QualType();
5431 }
5432 QualType PointeeType = readType(*Loc.F, Record, Idx);
5433 return Context.getBlockPointerType(PointeeType);
5434 }
5435
5436 case TYPE_LVALUE_REFERENCE: {
5437 if (Record.size() != 2) {
5438 Error("Incorrect encoding of lvalue reference type");
5439 return QualType();
5440 }
5441 QualType PointeeType = readType(*Loc.F, Record, Idx);
5442 return Context.getLValueReferenceType(PointeeType, Record[1]);
5443 }
5444
5445 case TYPE_RVALUE_REFERENCE: {
5446 if (Record.size() != 1) {
5447 Error("Incorrect encoding of rvalue reference type");
5448 return QualType();
5449 }
5450 QualType PointeeType = readType(*Loc.F, Record, Idx);
5451 return Context.getRValueReferenceType(PointeeType);
5452 }
5453
5454 case TYPE_MEMBER_POINTER: {
5455 if (Record.size() != 2) {
5456 Error("Incorrect encoding of member pointer type");
5457 return QualType();
5458 }
5459 QualType PointeeType = readType(*Loc.F, Record, Idx);
5460 QualType ClassType = readType(*Loc.F, Record, Idx);
5461 if (PointeeType.isNull() || ClassType.isNull())
5462 return QualType();
David L. Jonesc4808b9e2016-12-15 20:53:26 +00005463
Guy Benyei11169dd2012-12-18 14:30:41 +00005464 return Context.getMemberPointerType(PointeeType, ClassType.getTypePtr());
5465 }
5466
5467 case TYPE_CONSTANT_ARRAY: {
5468 QualType ElementType = readType(*Loc.F, Record, Idx);
5469 ArrayType::ArraySizeModifier ASM = (ArrayType::ArraySizeModifier)Record[1];
5470 unsigned IndexTypeQuals = Record[2];
5471 unsigned Idx = 3;
5472 llvm::APInt Size = ReadAPInt(Record, Idx);
5473 return Context.getConstantArrayType(ElementType, Size,
5474 ASM, IndexTypeQuals);
5475 }
5476
5477 case TYPE_INCOMPLETE_ARRAY: {
5478 QualType ElementType = readType(*Loc.F, Record, Idx);
5479 ArrayType::ArraySizeModifier ASM = (ArrayType::ArraySizeModifier)Record[1];
5480 unsigned IndexTypeQuals = Record[2];
5481 return Context.getIncompleteArrayType(ElementType, ASM, IndexTypeQuals);
5482 }
5483
5484 case TYPE_VARIABLE_ARRAY: {
5485 QualType ElementType = readType(*Loc.F, Record, Idx);
5486 ArrayType::ArraySizeModifier ASM = (ArrayType::ArraySizeModifier)Record[1];
5487 unsigned IndexTypeQuals = Record[2];
5488 SourceLocation LBLoc = ReadSourceLocation(*Loc.F, Record[3]);
5489 SourceLocation RBLoc = ReadSourceLocation(*Loc.F, Record[4]);
5490 return Context.getVariableArrayType(ElementType, ReadExpr(*Loc.F),
5491 ASM, IndexTypeQuals,
5492 SourceRange(LBLoc, RBLoc));
5493 }
5494
5495 case TYPE_VECTOR: {
5496 if (Record.size() != 3) {
5497 Error("incorrect encoding of vector type in AST file");
5498 return QualType();
5499 }
5500
5501 QualType ElementType = readType(*Loc.F, Record, Idx);
5502 unsigned NumElements = Record[1];
5503 unsigned VecKind = Record[2];
5504 return Context.getVectorType(ElementType, NumElements,
5505 (VectorType::VectorKind)VecKind);
5506 }
5507
5508 case TYPE_EXT_VECTOR: {
5509 if (Record.size() != 3) {
5510 Error("incorrect encoding of extended vector type in AST file");
5511 return QualType();
5512 }
5513
5514 QualType ElementType = readType(*Loc.F, Record, Idx);
5515 unsigned NumElements = Record[1];
5516 return Context.getExtVectorType(ElementType, NumElements);
5517 }
5518
5519 case TYPE_FUNCTION_NO_PROTO: {
5520 if (Record.size() != 6) {
5521 Error("incorrect encoding of no-proto function type");
5522 return QualType();
5523 }
5524 QualType ResultType = readType(*Loc.F, Record, Idx);
5525 FunctionType::ExtInfo Info(Record[1], Record[2], Record[3],
5526 (CallingConv)Record[4], Record[5]);
5527 return Context.getFunctionNoProtoType(ResultType, Info);
5528 }
5529
5530 case TYPE_FUNCTION_PROTO: {
5531 QualType ResultType = readType(*Loc.F, Record, Idx);
5532
5533 FunctionProtoType::ExtProtoInfo EPI;
5534 EPI.ExtInfo = FunctionType::ExtInfo(/*noreturn*/ Record[1],
5535 /*hasregparm*/ Record[2],
5536 /*regparm*/ Record[3],
5537 static_cast<CallingConv>(Record[4]),
5538 /*produces*/ Record[5]);
5539
5540 unsigned Idx = 6;
Guy Benyei11169dd2012-12-18 14:30:41 +00005541
5542 EPI.Variadic = Record[Idx++];
5543 EPI.HasTrailingReturn = Record[Idx++];
5544 EPI.TypeQuals = Record[Idx++];
5545 EPI.RefQualifier = static_cast<RefQualifierKind>(Record[Idx++]);
Richard Smith564417a2014-03-20 21:47:22 +00005546 SmallVector<QualType, 8> ExceptionStorage;
Richard Smith8acb4282014-07-31 21:57:55 +00005547 readExceptionSpec(*Loc.F, ExceptionStorage, EPI.ExceptionSpec, Record, Idx);
Richard Smith01b2cb42014-07-26 06:37:51 +00005548
5549 unsigned NumParams = Record[Idx++];
5550 SmallVector<QualType, 16> ParamTypes;
5551 for (unsigned I = 0; I != NumParams; ++I)
5552 ParamTypes.push_back(readType(*Loc.F, Record, Idx));
5553
John McCall18afab72016-03-01 00:49:02 +00005554 SmallVector<FunctionProtoType::ExtParameterInfo, 4> ExtParameterInfos;
5555 if (Idx != Record.size()) {
5556 for (unsigned I = 0; I != NumParams; ++I)
5557 ExtParameterInfos.push_back(
5558 FunctionProtoType::ExtParameterInfo
5559 ::getFromOpaqueValue(Record[Idx++]));
5560 EPI.ExtParameterInfos = ExtParameterInfos.data();
5561 }
5562
5563 assert(Idx == Record.size());
5564
Jordan Rose5c382722013-03-08 21:51:21 +00005565 return Context.getFunctionType(ResultType, ParamTypes, EPI);
Guy Benyei11169dd2012-12-18 14:30:41 +00005566 }
5567
5568 case TYPE_UNRESOLVED_USING: {
5569 unsigned Idx = 0;
5570 return Context.getTypeDeclType(
5571 ReadDeclAs<UnresolvedUsingTypenameDecl>(*Loc.F, Record, Idx));
5572 }
David L. Jonesc4808b9e2016-12-15 20:53:26 +00005573
Guy Benyei11169dd2012-12-18 14:30:41 +00005574 case TYPE_TYPEDEF: {
5575 if (Record.size() != 2) {
5576 Error("incorrect encoding of typedef type");
5577 return QualType();
5578 }
5579 unsigned Idx = 0;
5580 TypedefNameDecl *Decl = ReadDeclAs<TypedefNameDecl>(*Loc.F, Record, Idx);
5581 QualType Canonical = readType(*Loc.F, Record, Idx);
5582 if (!Canonical.isNull())
5583 Canonical = Context.getCanonicalType(Canonical);
5584 return Context.getTypedefType(Decl, Canonical);
5585 }
5586
5587 case TYPE_TYPEOF_EXPR:
5588 return Context.getTypeOfExprType(ReadExpr(*Loc.F));
5589
5590 case TYPE_TYPEOF: {
5591 if (Record.size() != 1) {
5592 Error("incorrect encoding of typeof(type) in AST file");
5593 return QualType();
5594 }
5595 QualType UnderlyingType = readType(*Loc.F, Record, Idx);
5596 return Context.getTypeOfType(UnderlyingType);
5597 }
5598
5599 case TYPE_DECLTYPE: {
5600 QualType UnderlyingType = readType(*Loc.F, Record, Idx);
5601 return Context.getDecltypeType(ReadExpr(*Loc.F), UnderlyingType);
5602 }
5603
5604 case TYPE_UNARY_TRANSFORM: {
5605 QualType BaseType = readType(*Loc.F, Record, Idx);
5606 QualType UnderlyingType = readType(*Loc.F, Record, Idx);
5607 UnaryTransformType::UTTKind UKind = (UnaryTransformType::UTTKind)Record[2];
5608 return Context.getUnaryTransformType(BaseType, UnderlyingType, UKind);
5609 }
5610
Richard Smith74aeef52013-04-26 16:15:35 +00005611 case TYPE_AUTO: {
5612 QualType Deduced = readType(*Loc.F, Record, Idx);
Richard Smithe301ba22015-11-11 02:02:15 +00005613 AutoTypeKeyword Keyword = (AutoTypeKeyword)Record[Idx++];
Richard Smith27d807c2013-04-30 13:56:41 +00005614 bool IsDependent = Deduced.isNull() ? Record[Idx++] : false;
Richard Smithe301ba22015-11-11 02:02:15 +00005615 return Context.getAutoType(Deduced, Keyword, IsDependent);
Richard Smith74aeef52013-04-26 16:15:35 +00005616 }
Guy Benyei11169dd2012-12-18 14:30:41 +00005617
5618 case TYPE_RECORD: {
5619 if (Record.size() != 2) {
5620 Error("incorrect encoding of record type");
5621 return QualType();
5622 }
5623 unsigned Idx = 0;
5624 bool IsDependent = Record[Idx++];
5625 RecordDecl *RD = ReadDeclAs<RecordDecl>(*Loc.F, Record, Idx);
5626 RD = cast_or_null<RecordDecl>(RD->getCanonicalDecl());
5627 QualType T = Context.getRecordType(RD);
5628 const_cast<Type*>(T.getTypePtr())->setDependent(IsDependent);
5629 return T;
5630 }
5631
5632 case TYPE_ENUM: {
5633 if (Record.size() != 2) {
5634 Error("incorrect encoding of enum type");
5635 return QualType();
5636 }
5637 unsigned Idx = 0;
5638 bool IsDependent = Record[Idx++];
5639 QualType T
5640 = Context.getEnumType(ReadDeclAs<EnumDecl>(*Loc.F, Record, Idx));
5641 const_cast<Type*>(T.getTypePtr())->setDependent(IsDependent);
5642 return T;
5643 }
5644
5645 case TYPE_ATTRIBUTED: {
5646 if (Record.size() != 3) {
5647 Error("incorrect encoding of attributed type");
5648 return QualType();
5649 }
5650 QualType modifiedType = readType(*Loc.F, Record, Idx);
5651 QualType equivalentType = readType(*Loc.F, Record, Idx);
5652 AttributedType::Kind kind = static_cast<AttributedType::Kind>(Record[2]);
5653 return Context.getAttributedType(kind, modifiedType, equivalentType);
5654 }
5655
5656 case TYPE_PAREN: {
5657 if (Record.size() != 1) {
5658 Error("incorrect encoding of paren type");
5659 return QualType();
5660 }
5661 QualType InnerType = readType(*Loc.F, Record, Idx);
5662 return Context.getParenType(InnerType);
5663 }
5664
5665 case TYPE_PACK_EXPANSION: {
5666 if (Record.size() != 2) {
5667 Error("incorrect encoding of pack expansion type");
5668 return QualType();
5669 }
5670 QualType Pattern = readType(*Loc.F, Record, Idx);
5671 if (Pattern.isNull())
5672 return QualType();
David Blaikie05785d12013-02-20 22:23:23 +00005673 Optional<unsigned> NumExpansions;
Guy Benyei11169dd2012-12-18 14:30:41 +00005674 if (Record[1])
5675 NumExpansions = Record[1] - 1;
5676 return Context.getPackExpansionType(Pattern, NumExpansions);
5677 }
5678
5679 case TYPE_ELABORATED: {
5680 unsigned Idx = 0;
5681 ElaboratedTypeKeyword Keyword = (ElaboratedTypeKeyword)Record[Idx++];
5682 NestedNameSpecifier *NNS = ReadNestedNameSpecifier(*Loc.F, Record, Idx);
5683 QualType NamedType = readType(*Loc.F, Record, Idx);
5684 return Context.getElaboratedType(Keyword, NNS, NamedType);
5685 }
5686
5687 case TYPE_OBJC_INTERFACE: {
5688 unsigned Idx = 0;
5689 ObjCInterfaceDecl *ItfD
5690 = ReadDeclAs<ObjCInterfaceDecl>(*Loc.F, Record, Idx);
5691 return Context.getObjCInterfaceType(ItfD->getCanonicalDecl());
5692 }
5693
Manman Rene6be26c2016-09-13 17:25:08 +00005694 case TYPE_OBJC_TYPE_PARAM: {
5695 unsigned Idx = 0;
5696 ObjCTypeParamDecl *Decl
5697 = ReadDeclAs<ObjCTypeParamDecl>(*Loc.F, Record, Idx);
5698 unsigned NumProtos = Record[Idx++];
5699 SmallVector<ObjCProtocolDecl*, 4> Protos;
5700 for (unsigned I = 0; I != NumProtos; ++I)
5701 Protos.push_back(ReadDeclAs<ObjCProtocolDecl>(*Loc.F, Record, Idx));
5702 return Context.getObjCTypeParamType(Decl, Protos);
5703 }
Guy Benyei11169dd2012-12-18 14:30:41 +00005704 case TYPE_OBJC_OBJECT: {
5705 unsigned Idx = 0;
5706 QualType Base = readType(*Loc.F, Record, Idx);
Douglas Gregore9d95f12015-07-07 03:57:35 +00005707 unsigned NumTypeArgs = Record[Idx++];
5708 SmallVector<QualType, 4> TypeArgs;
5709 for (unsigned I = 0; I != NumTypeArgs; ++I)
5710 TypeArgs.push_back(readType(*Loc.F, Record, Idx));
Guy Benyei11169dd2012-12-18 14:30:41 +00005711 unsigned NumProtos = Record[Idx++];
5712 SmallVector<ObjCProtocolDecl*, 4> Protos;
5713 for (unsigned I = 0; I != NumProtos; ++I)
5714 Protos.push_back(ReadDeclAs<ObjCProtocolDecl>(*Loc.F, Record, Idx));
Douglas Gregorab209d82015-07-07 03:58:42 +00005715 bool IsKindOf = Record[Idx++];
5716 return Context.getObjCObjectType(Base, TypeArgs, Protos, IsKindOf);
Guy Benyei11169dd2012-12-18 14:30:41 +00005717 }
5718
5719 case TYPE_OBJC_OBJECT_POINTER: {
5720 unsigned Idx = 0;
5721 QualType Pointee = readType(*Loc.F, Record, Idx);
5722 return Context.getObjCObjectPointerType(Pointee);
5723 }
5724
5725 case TYPE_SUBST_TEMPLATE_TYPE_PARM: {
5726 unsigned Idx = 0;
5727 QualType Parm = readType(*Loc.F, Record, Idx);
5728 QualType Replacement = readType(*Loc.F, Record, Idx);
Stephan Tolksdorfe96f8b32014-03-15 10:23:27 +00005729 return Context.getSubstTemplateTypeParmType(
5730 cast<TemplateTypeParmType>(Parm),
5731 Context.getCanonicalType(Replacement));
Guy Benyei11169dd2012-12-18 14:30:41 +00005732 }
5733
5734 case TYPE_SUBST_TEMPLATE_TYPE_PARM_PACK: {
5735 unsigned Idx = 0;
5736 QualType Parm = readType(*Loc.F, Record, Idx);
5737 TemplateArgument ArgPack = ReadTemplateArgument(*Loc.F, Record, Idx);
5738 return Context.getSubstTemplateTypeParmPackType(
5739 cast<TemplateTypeParmType>(Parm),
5740 ArgPack);
5741 }
5742
5743 case TYPE_INJECTED_CLASS_NAME: {
5744 CXXRecordDecl *D = ReadDeclAs<CXXRecordDecl>(*Loc.F, Record, Idx);
5745 QualType TST = readType(*Loc.F, Record, Idx); // probably derivable
5746 // FIXME: ASTContext::getInjectedClassNameType is not currently suitable
5747 // for AST reading, too much interdependencies.
Richard Smith6377f8f2014-10-21 21:15:18 +00005748 const Type *T = nullptr;
5749 for (auto *DI = D; DI; DI = DI->getPreviousDecl()) {
5750 if (const Type *Existing = DI->getTypeForDecl()) {
5751 T = Existing;
5752 break;
5753 }
5754 }
5755 if (!T) {
Richard Smithf17fdbd2014-04-24 02:25:27 +00005756 T = new (Context, TypeAlignment) InjectedClassNameType(D, TST);
Richard Smith6377f8f2014-10-21 21:15:18 +00005757 for (auto *DI = D; DI; DI = DI->getPreviousDecl())
5758 DI->setTypeForDecl(T);
5759 }
Richard Smithf17fdbd2014-04-24 02:25:27 +00005760 return QualType(T, 0);
Guy Benyei11169dd2012-12-18 14:30:41 +00005761 }
5762
5763 case TYPE_TEMPLATE_TYPE_PARM: {
5764 unsigned Idx = 0;
5765 unsigned Depth = Record[Idx++];
5766 unsigned Index = Record[Idx++];
5767 bool Pack = Record[Idx++];
5768 TemplateTypeParmDecl *D
5769 = ReadDeclAs<TemplateTypeParmDecl>(*Loc.F, Record, Idx);
5770 return Context.getTemplateTypeParmType(Depth, Index, Pack, D);
5771 }
5772
5773 case TYPE_DEPENDENT_NAME: {
5774 unsigned Idx = 0;
5775 ElaboratedTypeKeyword Keyword = (ElaboratedTypeKeyword)Record[Idx++];
5776 NestedNameSpecifier *NNS = ReadNestedNameSpecifier(*Loc.F, Record, Idx);
Richard Smithbdf2d932015-07-30 03:37:16 +00005777 const IdentifierInfo *Name = GetIdentifierInfo(*Loc.F, Record, Idx);
Guy Benyei11169dd2012-12-18 14:30:41 +00005778 QualType Canon = readType(*Loc.F, Record, Idx);
5779 if (!Canon.isNull())
5780 Canon = Context.getCanonicalType(Canon);
5781 return Context.getDependentNameType(Keyword, NNS, Name, Canon);
5782 }
5783
5784 case TYPE_DEPENDENT_TEMPLATE_SPECIALIZATION: {
5785 unsigned Idx = 0;
5786 ElaboratedTypeKeyword Keyword = (ElaboratedTypeKeyword)Record[Idx++];
5787 NestedNameSpecifier *NNS = ReadNestedNameSpecifier(*Loc.F, Record, Idx);
Richard Smithbdf2d932015-07-30 03:37:16 +00005788 const IdentifierInfo *Name = GetIdentifierInfo(*Loc.F, Record, Idx);
Guy Benyei11169dd2012-12-18 14:30:41 +00005789 unsigned NumArgs = Record[Idx++];
5790 SmallVector<TemplateArgument, 8> Args;
5791 Args.reserve(NumArgs);
5792 while (NumArgs--)
5793 Args.push_back(ReadTemplateArgument(*Loc.F, Record, Idx));
5794 return Context.getDependentTemplateSpecializationType(Keyword, NNS, Name,
David Majnemer6fbeee32016-07-07 04:43:07 +00005795 Args);
Guy Benyei11169dd2012-12-18 14:30:41 +00005796 }
5797
5798 case TYPE_DEPENDENT_SIZED_ARRAY: {
5799 unsigned Idx = 0;
5800
5801 // ArrayType
5802 QualType ElementType = readType(*Loc.F, Record, Idx);
5803 ArrayType::ArraySizeModifier ASM
5804 = (ArrayType::ArraySizeModifier)Record[Idx++];
5805 unsigned IndexTypeQuals = Record[Idx++];
5806
5807 // DependentSizedArrayType
5808 Expr *NumElts = ReadExpr(*Loc.F);
5809 SourceRange Brackets = ReadSourceRange(*Loc.F, Record, Idx);
5810
5811 return Context.getDependentSizedArrayType(ElementType, NumElts, ASM,
5812 IndexTypeQuals, Brackets);
5813 }
5814
5815 case TYPE_TEMPLATE_SPECIALIZATION: {
5816 unsigned Idx = 0;
5817 bool IsDependent = Record[Idx++];
5818 TemplateName Name = ReadTemplateName(*Loc.F, Record, Idx);
5819 SmallVector<TemplateArgument, 8> Args;
5820 ReadTemplateArgumentList(Args, *Loc.F, Record, Idx);
5821 QualType Underlying = readType(*Loc.F, Record, Idx);
5822 QualType T;
5823 if (Underlying.isNull())
David Majnemer6fbeee32016-07-07 04:43:07 +00005824 T = Context.getCanonicalTemplateSpecializationType(Name, Args);
Guy Benyei11169dd2012-12-18 14:30:41 +00005825 else
David Majnemer6fbeee32016-07-07 04:43:07 +00005826 T = Context.getTemplateSpecializationType(Name, Args, Underlying);
Guy Benyei11169dd2012-12-18 14:30:41 +00005827 const_cast<Type*>(T.getTypePtr())->setDependent(IsDependent);
5828 return T;
5829 }
5830
5831 case TYPE_ATOMIC: {
5832 if (Record.size() != 1) {
5833 Error("Incorrect encoding of atomic type");
5834 return QualType();
5835 }
5836 QualType ValueType = readType(*Loc.F, Record, Idx);
5837 return Context.getAtomicType(ValueType);
5838 }
Xiuli Pan9c14e282016-01-09 12:53:17 +00005839
Joey Goulye3c85de2016-12-01 11:30:49 +00005840 case TYPE_PIPE: {
5841 if (Record.size() != 2) {
Xiuli Pan9c14e282016-01-09 12:53:17 +00005842 Error("Incorrect encoding of pipe type");
5843 return QualType();
5844 }
5845
5846 // Reading the pipe element type.
5847 QualType ElementType = readType(*Loc.F, Record, Idx);
Joey Goulye3c85de2016-12-01 11:30:49 +00005848 unsigned ReadOnly = Record[1];
5849 return Context.getPipeType(ElementType, ReadOnly);
Joey Gouly5788b782016-11-18 14:10:54 +00005850 }
5851
Guy Benyei11169dd2012-12-18 14:30:41 +00005852 }
5853 llvm_unreachable("Invalid TypeCode!");
5854}
5855
Richard Smith564417a2014-03-20 21:47:22 +00005856void ASTReader::readExceptionSpec(ModuleFile &ModuleFile,
5857 SmallVectorImpl<QualType> &Exceptions,
Richard Smith8acb4282014-07-31 21:57:55 +00005858 FunctionProtoType::ExceptionSpecInfo &ESI,
Richard Smith564417a2014-03-20 21:47:22 +00005859 const RecordData &Record, unsigned &Idx) {
5860 ExceptionSpecificationType EST =
5861 static_cast<ExceptionSpecificationType>(Record[Idx++]);
Richard Smith8acb4282014-07-31 21:57:55 +00005862 ESI.Type = EST;
Richard Smith564417a2014-03-20 21:47:22 +00005863 if (EST == EST_Dynamic) {
Richard Smith8acb4282014-07-31 21:57:55 +00005864 for (unsigned I = 0, N = Record[Idx++]; I != N; ++I)
Richard Smith564417a2014-03-20 21:47:22 +00005865 Exceptions.push_back(readType(ModuleFile, Record, Idx));
Richard Smith8acb4282014-07-31 21:57:55 +00005866 ESI.Exceptions = Exceptions;
Richard Smith564417a2014-03-20 21:47:22 +00005867 } else if (EST == EST_ComputedNoexcept) {
Richard Smith8acb4282014-07-31 21:57:55 +00005868 ESI.NoexceptExpr = ReadExpr(ModuleFile);
Richard Smith564417a2014-03-20 21:47:22 +00005869 } else if (EST == EST_Uninstantiated) {
Richard Smith8acb4282014-07-31 21:57:55 +00005870 ESI.SourceDecl = ReadDeclAs<FunctionDecl>(ModuleFile, Record, Idx);
5871 ESI.SourceTemplate = ReadDeclAs<FunctionDecl>(ModuleFile, Record, Idx);
Richard Smith564417a2014-03-20 21:47:22 +00005872 } else if (EST == EST_Unevaluated) {
Richard Smith8acb4282014-07-31 21:57:55 +00005873 ESI.SourceDecl = ReadDeclAs<FunctionDecl>(ModuleFile, Record, Idx);
Richard Smith564417a2014-03-20 21:47:22 +00005874 }
5875}
5876
Guy Benyei11169dd2012-12-18 14:30:41 +00005877class clang::TypeLocReader : public TypeLocVisitor<TypeLocReader> {
David L. Jonesbe1557a2016-12-21 00:17:49 +00005878 ModuleFile *F;
5879 ASTReader *Reader;
5880 const ASTReader::RecordData &Record;
Guy Benyei11169dd2012-12-18 14:30:41 +00005881 unsigned &Idx;
5882
David L. Jonesc4808b9e2016-12-15 20:53:26 +00005883 SourceLocation ReadSourceLocation() {
David L. Jonesbe1557a2016-12-21 00:17:49 +00005884 return Reader->ReadSourceLocation(*F, Record, Idx);
5885 }
5886
5887 TypeSourceInfo *GetTypeSourceInfo() {
5888 return Reader->GetTypeSourceInfo(*F, Record, Idx);
5889 }
5890
5891 NestedNameSpecifierLoc ReadNestedNameSpecifierLoc() {
5892 return Reader->ReadNestedNameSpecifierLoc(*F, Record, Idx);
Guy Benyei11169dd2012-12-18 14:30:41 +00005893 }
5894
Guy Benyei11169dd2012-12-18 14:30:41 +00005895public:
David L. Jonesbe1557a2016-12-21 00:17:49 +00005896 TypeLocReader(ModuleFile &F, ASTReader &Reader,
Guy Benyei11169dd2012-12-18 14:30:41 +00005897 const ASTReader::RecordData &Record, unsigned &Idx)
David L. Jonesbe1557a2016-12-21 00:17:49 +00005898 : F(&F), Reader(&Reader), Record(Record), Idx(Idx) {}
Guy Benyei11169dd2012-12-18 14:30:41 +00005899
5900 // We want compile-time assurance that we've enumerated all of
5901 // these, so unfortunately we have to declare them first, then
5902 // define them out-of-line.
5903#define ABSTRACT_TYPELOC(CLASS, PARENT)
5904#define TYPELOC(CLASS, PARENT) \
5905 void Visit##CLASS##TypeLoc(CLASS##TypeLoc TyLoc);
5906#include "clang/AST/TypeLocNodes.def"
5907
5908 void VisitFunctionTypeLoc(FunctionTypeLoc);
5909 void VisitArrayTypeLoc(ArrayTypeLoc);
5910};
5911
5912void TypeLocReader::VisitQualifiedTypeLoc(QualifiedTypeLoc TL) {
5913 // nothing to do
5914}
Eugene Zelenkoe95e7d52016-09-07 21:53:17 +00005915
Guy Benyei11169dd2012-12-18 14:30:41 +00005916void TypeLocReader::VisitBuiltinTypeLoc(BuiltinTypeLoc TL) {
David L. Jonesc4808b9e2016-12-15 20:53:26 +00005917 TL.setBuiltinLoc(ReadSourceLocation());
Guy Benyei11169dd2012-12-18 14:30:41 +00005918 if (TL.needsExtraLocalData()) {
David L. Jonesbe1557a2016-12-21 00:17:49 +00005919 TL.setWrittenTypeSpec(static_cast<DeclSpec::TST>(Record[Idx++]));
5920 TL.setWrittenSignSpec(static_cast<DeclSpec::TSS>(Record[Idx++]));
5921 TL.setWrittenWidthSpec(static_cast<DeclSpec::TSW>(Record[Idx++]));
5922 TL.setModeAttr(Record[Idx++]);
Guy Benyei11169dd2012-12-18 14:30:41 +00005923 }
5924}
Eugene Zelenkoe95e7d52016-09-07 21:53:17 +00005925
Guy Benyei11169dd2012-12-18 14:30:41 +00005926void TypeLocReader::VisitComplexTypeLoc(ComplexTypeLoc TL) {
David L. Jonesc4808b9e2016-12-15 20:53:26 +00005927 TL.setNameLoc(ReadSourceLocation());
Guy Benyei11169dd2012-12-18 14:30:41 +00005928}
Eugene Zelenkoe95e7d52016-09-07 21:53:17 +00005929
Guy Benyei11169dd2012-12-18 14:30:41 +00005930void TypeLocReader::VisitPointerTypeLoc(PointerTypeLoc TL) {
David L. Jonesc4808b9e2016-12-15 20:53:26 +00005931 TL.setStarLoc(ReadSourceLocation());
Guy Benyei11169dd2012-12-18 14:30:41 +00005932}
Eugene Zelenkoe95e7d52016-09-07 21:53:17 +00005933
Reid Kleckner8a365022013-06-24 17:51:48 +00005934void TypeLocReader::VisitDecayedTypeLoc(DecayedTypeLoc TL) {
5935 // nothing to do
5936}
Eugene Zelenkoe95e7d52016-09-07 21:53:17 +00005937
Reid Kleckner0503a872013-12-05 01:23:43 +00005938void TypeLocReader::VisitAdjustedTypeLoc(AdjustedTypeLoc TL) {
5939 // nothing to do
5940}
Eugene Zelenkoe95e7d52016-09-07 21:53:17 +00005941
Guy Benyei11169dd2012-12-18 14:30:41 +00005942void TypeLocReader::VisitBlockPointerTypeLoc(BlockPointerTypeLoc TL) {
David L. Jonesc4808b9e2016-12-15 20:53:26 +00005943 TL.setCaretLoc(ReadSourceLocation());
Guy Benyei11169dd2012-12-18 14:30:41 +00005944}
Eugene Zelenkoe95e7d52016-09-07 21:53:17 +00005945
Guy Benyei11169dd2012-12-18 14:30:41 +00005946void TypeLocReader::VisitLValueReferenceTypeLoc(LValueReferenceTypeLoc TL) {
David L. Jonesc4808b9e2016-12-15 20:53:26 +00005947 TL.setAmpLoc(ReadSourceLocation());
Guy Benyei11169dd2012-12-18 14:30:41 +00005948}
Eugene Zelenkoe95e7d52016-09-07 21:53:17 +00005949
Guy Benyei11169dd2012-12-18 14:30:41 +00005950void TypeLocReader::VisitRValueReferenceTypeLoc(RValueReferenceTypeLoc TL) {
David L. Jonesc4808b9e2016-12-15 20:53:26 +00005951 TL.setAmpAmpLoc(ReadSourceLocation());
Guy Benyei11169dd2012-12-18 14:30:41 +00005952}
Eugene Zelenkoe95e7d52016-09-07 21:53:17 +00005953
Guy Benyei11169dd2012-12-18 14:30:41 +00005954void TypeLocReader::VisitMemberPointerTypeLoc(MemberPointerTypeLoc TL) {
David L. Jonesc4808b9e2016-12-15 20:53:26 +00005955 TL.setStarLoc(ReadSourceLocation());
David L. Jonesbe1557a2016-12-21 00:17:49 +00005956 TL.setClassTInfo(GetTypeSourceInfo());
Guy Benyei11169dd2012-12-18 14:30:41 +00005957}
Eugene Zelenkoe95e7d52016-09-07 21:53:17 +00005958
Guy Benyei11169dd2012-12-18 14:30:41 +00005959void TypeLocReader::VisitArrayTypeLoc(ArrayTypeLoc TL) {
David L. Jonesc4808b9e2016-12-15 20:53:26 +00005960 TL.setLBracketLoc(ReadSourceLocation());
5961 TL.setRBracketLoc(ReadSourceLocation());
David L. Jonesbe1557a2016-12-21 00:17:49 +00005962 if (Record[Idx++])
5963 TL.setSizeExpr(Reader->ReadExpr(*F));
Guy Benyei11169dd2012-12-18 14:30:41 +00005964 else
Craig Toppera13603a2014-05-22 05:54:18 +00005965 TL.setSizeExpr(nullptr);
Guy Benyei11169dd2012-12-18 14:30:41 +00005966}
Eugene Zelenkoe95e7d52016-09-07 21:53:17 +00005967
Guy Benyei11169dd2012-12-18 14:30:41 +00005968void TypeLocReader::VisitConstantArrayTypeLoc(ConstantArrayTypeLoc TL) {
5969 VisitArrayTypeLoc(TL);
5970}
Eugene Zelenkoe95e7d52016-09-07 21:53:17 +00005971
Guy Benyei11169dd2012-12-18 14:30:41 +00005972void TypeLocReader::VisitIncompleteArrayTypeLoc(IncompleteArrayTypeLoc TL) {
5973 VisitArrayTypeLoc(TL);
5974}
Eugene Zelenkoe95e7d52016-09-07 21:53:17 +00005975
Guy Benyei11169dd2012-12-18 14:30:41 +00005976void TypeLocReader::VisitVariableArrayTypeLoc(VariableArrayTypeLoc TL) {
5977 VisitArrayTypeLoc(TL);
5978}
Eugene Zelenkoe95e7d52016-09-07 21:53:17 +00005979
Guy Benyei11169dd2012-12-18 14:30:41 +00005980void TypeLocReader::VisitDependentSizedArrayTypeLoc(
5981 DependentSizedArrayTypeLoc TL) {
5982 VisitArrayTypeLoc(TL);
5983}
Eugene Zelenkoe95e7d52016-09-07 21:53:17 +00005984
Guy Benyei11169dd2012-12-18 14:30:41 +00005985void TypeLocReader::VisitDependentSizedExtVectorTypeLoc(
5986 DependentSizedExtVectorTypeLoc TL) {
David L. Jonesc4808b9e2016-12-15 20:53:26 +00005987 TL.setNameLoc(ReadSourceLocation());
Guy Benyei11169dd2012-12-18 14:30:41 +00005988}
Eugene Zelenkoe95e7d52016-09-07 21:53:17 +00005989
Guy Benyei11169dd2012-12-18 14:30:41 +00005990void TypeLocReader::VisitVectorTypeLoc(VectorTypeLoc TL) {
David L. Jonesc4808b9e2016-12-15 20:53:26 +00005991 TL.setNameLoc(ReadSourceLocation());
Guy Benyei11169dd2012-12-18 14:30:41 +00005992}
Eugene Zelenkoe95e7d52016-09-07 21:53:17 +00005993
Guy Benyei11169dd2012-12-18 14:30:41 +00005994void TypeLocReader::VisitExtVectorTypeLoc(ExtVectorTypeLoc TL) {
David L. Jonesc4808b9e2016-12-15 20:53:26 +00005995 TL.setNameLoc(ReadSourceLocation());
Guy Benyei11169dd2012-12-18 14:30:41 +00005996}
Eugene Zelenkoe95e7d52016-09-07 21:53:17 +00005997
Guy Benyei11169dd2012-12-18 14:30:41 +00005998void TypeLocReader::VisitFunctionTypeLoc(FunctionTypeLoc TL) {
David L. Jonesc4808b9e2016-12-15 20:53:26 +00005999 TL.setLocalRangeBegin(ReadSourceLocation());
6000 TL.setLParenLoc(ReadSourceLocation());
6001 TL.setRParenLoc(ReadSourceLocation());
Malcolm Parsonsa3220ce2017-01-12 16:11:28 +00006002 TL.setExceptionSpecRange(SourceRange(Reader->ReadSourceLocation(*F, Record, Idx),
6003 Reader->ReadSourceLocation(*F, Record, Idx)));
David L. Jonesc4808b9e2016-12-15 20:53:26 +00006004 TL.setLocalRangeEnd(ReadSourceLocation());
Alp Tokerb3fd5cf2014-01-21 00:32:38 +00006005 for (unsigned i = 0, e = TL.getNumParams(); i != e; ++i) {
David L. Jonesbe1557a2016-12-21 00:17:49 +00006006 TL.setParam(i, Reader->ReadDeclAs<ParmVarDecl>(*F, Record, Idx));
Guy Benyei11169dd2012-12-18 14:30:41 +00006007 }
6008}
Eugene Zelenkoe95e7d52016-09-07 21:53:17 +00006009
Guy Benyei11169dd2012-12-18 14:30:41 +00006010void TypeLocReader::VisitFunctionProtoTypeLoc(FunctionProtoTypeLoc TL) {
6011 VisitFunctionTypeLoc(TL);
6012}
Eugene Zelenkoe95e7d52016-09-07 21:53:17 +00006013
Guy Benyei11169dd2012-12-18 14:30:41 +00006014void TypeLocReader::VisitFunctionNoProtoTypeLoc(FunctionNoProtoTypeLoc TL) {
6015 VisitFunctionTypeLoc(TL);
6016}
6017void TypeLocReader::VisitUnresolvedUsingTypeLoc(UnresolvedUsingTypeLoc TL) {
David L. Jonesc4808b9e2016-12-15 20:53:26 +00006018 TL.setNameLoc(ReadSourceLocation());
Guy Benyei11169dd2012-12-18 14:30:41 +00006019}
6020void TypeLocReader::VisitTypedefTypeLoc(TypedefTypeLoc TL) {
David L. Jonesc4808b9e2016-12-15 20:53:26 +00006021 TL.setNameLoc(ReadSourceLocation());
Guy Benyei11169dd2012-12-18 14:30:41 +00006022}
6023void TypeLocReader::VisitTypeOfExprTypeLoc(TypeOfExprTypeLoc TL) {
David L. Jonesc4808b9e2016-12-15 20:53:26 +00006024 TL.setTypeofLoc(ReadSourceLocation());
6025 TL.setLParenLoc(ReadSourceLocation());
6026 TL.setRParenLoc(ReadSourceLocation());
Guy Benyei11169dd2012-12-18 14:30:41 +00006027}
6028void TypeLocReader::VisitTypeOfTypeLoc(TypeOfTypeLoc TL) {
David L. Jonesc4808b9e2016-12-15 20:53:26 +00006029 TL.setTypeofLoc(ReadSourceLocation());
6030 TL.setLParenLoc(ReadSourceLocation());
6031 TL.setRParenLoc(ReadSourceLocation());
David L. Jonesbe1557a2016-12-21 00:17:49 +00006032 TL.setUnderlyingTInfo(GetTypeSourceInfo());
Guy Benyei11169dd2012-12-18 14:30:41 +00006033}
6034void TypeLocReader::VisitDecltypeTypeLoc(DecltypeTypeLoc TL) {
David L. Jonesc4808b9e2016-12-15 20:53:26 +00006035 TL.setNameLoc(ReadSourceLocation());
Guy Benyei11169dd2012-12-18 14:30:41 +00006036}
Eugene Zelenkoe95e7d52016-09-07 21:53:17 +00006037
Guy Benyei11169dd2012-12-18 14:30:41 +00006038void TypeLocReader::VisitUnaryTransformTypeLoc(UnaryTransformTypeLoc TL) {
David L. Jonesc4808b9e2016-12-15 20:53:26 +00006039 TL.setKWLoc(ReadSourceLocation());
6040 TL.setLParenLoc(ReadSourceLocation());
6041 TL.setRParenLoc(ReadSourceLocation());
David L. Jonesbe1557a2016-12-21 00:17:49 +00006042 TL.setUnderlyingTInfo(GetTypeSourceInfo());
Guy Benyei11169dd2012-12-18 14:30:41 +00006043}
Eugene Zelenkoe95e7d52016-09-07 21:53:17 +00006044
Guy Benyei11169dd2012-12-18 14:30:41 +00006045void TypeLocReader::VisitAutoTypeLoc(AutoTypeLoc TL) {
David L. Jonesc4808b9e2016-12-15 20:53:26 +00006046 TL.setNameLoc(ReadSourceLocation());
Guy Benyei11169dd2012-12-18 14:30:41 +00006047}
Eugene Zelenkoe95e7d52016-09-07 21:53:17 +00006048
Guy Benyei11169dd2012-12-18 14:30:41 +00006049void TypeLocReader::VisitRecordTypeLoc(RecordTypeLoc TL) {
David L. Jonesc4808b9e2016-12-15 20:53:26 +00006050 TL.setNameLoc(ReadSourceLocation());
Guy Benyei11169dd2012-12-18 14:30:41 +00006051}
Eugene Zelenkoe95e7d52016-09-07 21:53:17 +00006052
Guy Benyei11169dd2012-12-18 14:30:41 +00006053void TypeLocReader::VisitEnumTypeLoc(EnumTypeLoc TL) {
David L. Jonesc4808b9e2016-12-15 20:53:26 +00006054 TL.setNameLoc(ReadSourceLocation());
Guy Benyei11169dd2012-12-18 14:30:41 +00006055}
Eugene Zelenkoe95e7d52016-09-07 21:53:17 +00006056
Guy Benyei11169dd2012-12-18 14:30:41 +00006057void TypeLocReader::VisitAttributedTypeLoc(AttributedTypeLoc TL) {
David L. Jonesc4808b9e2016-12-15 20:53:26 +00006058 TL.setAttrNameLoc(ReadSourceLocation());
Guy Benyei11169dd2012-12-18 14:30:41 +00006059 if (TL.hasAttrOperand()) {
6060 SourceRange range;
David L. Jonesc4808b9e2016-12-15 20:53:26 +00006061 range.setBegin(ReadSourceLocation());
6062 range.setEnd(ReadSourceLocation());
Guy Benyei11169dd2012-12-18 14:30:41 +00006063 TL.setAttrOperandParensRange(range);
6064 }
6065 if (TL.hasAttrExprOperand()) {
David L. Jonesbe1557a2016-12-21 00:17:49 +00006066 if (Record[Idx++])
6067 TL.setAttrExprOperand(Reader->ReadExpr(*F));
Guy Benyei11169dd2012-12-18 14:30:41 +00006068 else
Craig Toppera13603a2014-05-22 05:54:18 +00006069 TL.setAttrExprOperand(nullptr);
Guy Benyei11169dd2012-12-18 14:30:41 +00006070 } else if (TL.hasAttrEnumOperand())
David L. Jonesc4808b9e2016-12-15 20:53:26 +00006071 TL.setAttrEnumOperandLoc(ReadSourceLocation());
Guy Benyei11169dd2012-12-18 14:30:41 +00006072}
Eugene Zelenkoe95e7d52016-09-07 21:53:17 +00006073
Guy Benyei11169dd2012-12-18 14:30:41 +00006074void TypeLocReader::VisitTemplateTypeParmTypeLoc(TemplateTypeParmTypeLoc TL) {
David L. Jonesc4808b9e2016-12-15 20:53:26 +00006075 TL.setNameLoc(ReadSourceLocation());
Guy Benyei11169dd2012-12-18 14:30:41 +00006076}
Eugene Zelenkoe95e7d52016-09-07 21:53:17 +00006077
Guy Benyei11169dd2012-12-18 14:30:41 +00006078void TypeLocReader::VisitSubstTemplateTypeParmTypeLoc(
6079 SubstTemplateTypeParmTypeLoc TL) {
David L. Jonesc4808b9e2016-12-15 20:53:26 +00006080 TL.setNameLoc(ReadSourceLocation());
Guy Benyei11169dd2012-12-18 14:30:41 +00006081}
6082void TypeLocReader::VisitSubstTemplateTypeParmPackTypeLoc(
6083 SubstTemplateTypeParmPackTypeLoc TL) {
David L. Jonesc4808b9e2016-12-15 20:53:26 +00006084 TL.setNameLoc(ReadSourceLocation());
Guy Benyei11169dd2012-12-18 14:30:41 +00006085}
6086void TypeLocReader::VisitTemplateSpecializationTypeLoc(
6087 TemplateSpecializationTypeLoc TL) {
David L. Jonesc4808b9e2016-12-15 20:53:26 +00006088 TL.setTemplateKeywordLoc(ReadSourceLocation());
6089 TL.setTemplateNameLoc(ReadSourceLocation());
6090 TL.setLAngleLoc(ReadSourceLocation());
6091 TL.setRAngleLoc(ReadSourceLocation());
Guy Benyei11169dd2012-12-18 14:30:41 +00006092 for (unsigned i = 0, e = TL.getNumArgs(); i != e; ++i)
David L. Jonesbe1557a2016-12-21 00:17:49 +00006093 TL.setArgLocInfo(
6094 i,
6095 Reader->GetTemplateArgumentLocInfo(
6096 *F, TL.getTypePtr()->getArg(i).getKind(), Record, Idx));
Guy Benyei11169dd2012-12-18 14:30:41 +00006097}
6098void TypeLocReader::VisitParenTypeLoc(ParenTypeLoc TL) {
David L. Jonesc4808b9e2016-12-15 20:53:26 +00006099 TL.setLParenLoc(ReadSourceLocation());
6100 TL.setRParenLoc(ReadSourceLocation());
Guy Benyei11169dd2012-12-18 14:30:41 +00006101}
Eugene Zelenkoe95e7d52016-09-07 21:53:17 +00006102
Guy Benyei11169dd2012-12-18 14:30:41 +00006103void TypeLocReader::VisitElaboratedTypeLoc(ElaboratedTypeLoc TL) {
David L. Jonesc4808b9e2016-12-15 20:53:26 +00006104 TL.setElaboratedKeywordLoc(ReadSourceLocation());
David L. Jonesbe1557a2016-12-21 00:17:49 +00006105 TL.setQualifierLoc(ReadNestedNameSpecifierLoc());
Guy Benyei11169dd2012-12-18 14:30:41 +00006106}
Eugene Zelenkoe95e7d52016-09-07 21:53:17 +00006107
Guy Benyei11169dd2012-12-18 14:30:41 +00006108void TypeLocReader::VisitInjectedClassNameTypeLoc(InjectedClassNameTypeLoc TL) {
David L. Jonesc4808b9e2016-12-15 20:53:26 +00006109 TL.setNameLoc(ReadSourceLocation());
Guy Benyei11169dd2012-12-18 14:30:41 +00006110}
Eugene Zelenkoe95e7d52016-09-07 21:53:17 +00006111
Guy Benyei11169dd2012-12-18 14:30:41 +00006112void TypeLocReader::VisitDependentNameTypeLoc(DependentNameTypeLoc TL) {
David L. Jonesc4808b9e2016-12-15 20:53:26 +00006113 TL.setElaboratedKeywordLoc(ReadSourceLocation());
David L. Jonesbe1557a2016-12-21 00:17:49 +00006114 TL.setQualifierLoc(ReadNestedNameSpecifierLoc());
David L. Jonesc4808b9e2016-12-15 20:53:26 +00006115 TL.setNameLoc(ReadSourceLocation());
Guy Benyei11169dd2012-12-18 14:30:41 +00006116}
Eugene Zelenkoe95e7d52016-09-07 21:53:17 +00006117
Guy Benyei11169dd2012-12-18 14:30:41 +00006118void TypeLocReader::VisitDependentTemplateSpecializationTypeLoc(
6119 DependentTemplateSpecializationTypeLoc TL) {
David L. Jonesc4808b9e2016-12-15 20:53:26 +00006120 TL.setElaboratedKeywordLoc(ReadSourceLocation());
David L. Jonesbe1557a2016-12-21 00:17:49 +00006121 TL.setQualifierLoc(ReadNestedNameSpecifierLoc());
David L. Jonesc4808b9e2016-12-15 20:53:26 +00006122 TL.setTemplateKeywordLoc(ReadSourceLocation());
6123 TL.setTemplateNameLoc(ReadSourceLocation());
6124 TL.setLAngleLoc(ReadSourceLocation());
6125 TL.setRAngleLoc(ReadSourceLocation());
Guy Benyei11169dd2012-12-18 14:30:41 +00006126 for (unsigned I = 0, E = TL.getNumArgs(); I != E; ++I)
David L. Jonesbe1557a2016-12-21 00:17:49 +00006127 TL.setArgLocInfo(
6128 I,
6129 Reader->GetTemplateArgumentLocInfo(
6130 *F, TL.getTypePtr()->getArg(I).getKind(), Record, Idx));
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::VisitPackExpansionTypeLoc(PackExpansionTypeLoc TL) {
David L. Jonesc4808b9e2016-12-15 20:53:26 +00006134 TL.setEllipsisLoc(ReadSourceLocation());
Guy Benyei11169dd2012-12-18 14:30:41 +00006135}
Eugene Zelenkoe95e7d52016-09-07 21:53:17 +00006136
Guy Benyei11169dd2012-12-18 14:30:41 +00006137void TypeLocReader::VisitObjCInterfaceTypeLoc(ObjCInterfaceTypeLoc TL) {
David L. Jonesc4808b9e2016-12-15 20:53:26 +00006138 TL.setNameLoc(ReadSourceLocation());
Guy Benyei11169dd2012-12-18 14:30:41 +00006139}
Eugene Zelenkoe95e7d52016-09-07 21:53:17 +00006140
Manman Rene6be26c2016-09-13 17:25:08 +00006141void TypeLocReader::VisitObjCTypeParamTypeLoc(ObjCTypeParamTypeLoc TL) {
6142 if (TL.getNumProtocols()) {
David L. Jonesc4808b9e2016-12-15 20:53:26 +00006143 TL.setProtocolLAngleLoc(ReadSourceLocation());
6144 TL.setProtocolRAngleLoc(ReadSourceLocation());
Manman Rene6be26c2016-09-13 17:25:08 +00006145 }
6146 for (unsigned i = 0, e = TL.getNumProtocols(); i != e; ++i)
David L. Jonesc4808b9e2016-12-15 20:53:26 +00006147 TL.setProtocolLoc(i, ReadSourceLocation());
Manman Rene6be26c2016-09-13 17:25:08 +00006148}
6149
Guy Benyei11169dd2012-12-18 14:30:41 +00006150void TypeLocReader::VisitObjCObjectTypeLoc(ObjCObjectTypeLoc TL) {
David L. Jonesbe1557a2016-12-21 00:17:49 +00006151 TL.setHasBaseTypeAsWritten(Record[Idx++]);
David L. Jonesc4808b9e2016-12-15 20:53:26 +00006152 TL.setTypeArgsLAngleLoc(ReadSourceLocation());
6153 TL.setTypeArgsRAngleLoc(ReadSourceLocation());
Douglas Gregore9d95f12015-07-07 03:57:35 +00006154 for (unsigned i = 0, e = TL.getNumTypeArgs(); i != e; ++i)
David L. Jonesbe1557a2016-12-21 00:17:49 +00006155 TL.setTypeArgTInfo(i, GetTypeSourceInfo());
David L. Jonesc4808b9e2016-12-15 20:53:26 +00006156 TL.setProtocolLAngleLoc(ReadSourceLocation());
6157 TL.setProtocolRAngleLoc(ReadSourceLocation());
Guy Benyei11169dd2012-12-18 14:30:41 +00006158 for (unsigned i = 0, e = TL.getNumProtocols(); i != e; ++i)
David L. Jonesc4808b9e2016-12-15 20:53:26 +00006159 TL.setProtocolLoc(i, ReadSourceLocation());
Guy Benyei11169dd2012-12-18 14:30:41 +00006160}
Eugene Zelenkoe95e7d52016-09-07 21:53:17 +00006161
Guy Benyei11169dd2012-12-18 14:30:41 +00006162void TypeLocReader::VisitObjCObjectPointerTypeLoc(ObjCObjectPointerTypeLoc TL) {
David L. Jonesc4808b9e2016-12-15 20:53:26 +00006163 TL.setStarLoc(ReadSourceLocation());
Guy Benyei11169dd2012-12-18 14:30:41 +00006164}
Eugene Zelenkoe95e7d52016-09-07 21:53:17 +00006165
Guy Benyei11169dd2012-12-18 14:30:41 +00006166void TypeLocReader::VisitAtomicTypeLoc(AtomicTypeLoc TL) {
David L. Jonesc4808b9e2016-12-15 20:53:26 +00006167 TL.setKWLoc(ReadSourceLocation());
6168 TL.setLParenLoc(ReadSourceLocation());
6169 TL.setRParenLoc(ReadSourceLocation());
Guy Benyei11169dd2012-12-18 14:30:41 +00006170}
Eugene Zelenkoe95e7d52016-09-07 21:53:17 +00006171
Xiuli Pan9c14e282016-01-09 12:53:17 +00006172void TypeLocReader::VisitPipeTypeLoc(PipeTypeLoc TL) {
David L. Jonesc4808b9e2016-12-15 20:53:26 +00006173 TL.setKWLoc(ReadSourceLocation());
Xiuli Pan9c14e282016-01-09 12:53:17 +00006174}
Guy Benyei11169dd2012-12-18 14:30:41 +00006175
David L. Jonesbe1557a2016-12-21 00:17:49 +00006176TypeSourceInfo *
6177ASTReader::GetTypeSourceInfo(ModuleFile &F, const ASTReader::RecordData &Record,
6178 unsigned &Idx) {
Guy Benyei11169dd2012-12-18 14:30:41 +00006179 QualType InfoTy = readType(F, Record, Idx);
6180 if (InfoTy.isNull())
Craig Toppera13603a2014-05-22 05:54:18 +00006181 return nullptr;
Guy Benyei11169dd2012-12-18 14:30:41 +00006182
6183 TypeSourceInfo *TInfo = getContext().CreateTypeSourceInfo(InfoTy);
David L. Jonesbe1557a2016-12-21 00:17:49 +00006184 TypeLocReader TLR(F, *this, Record, Idx);
Guy Benyei11169dd2012-12-18 14:30:41 +00006185 for (TypeLoc TL = TInfo->getTypeLoc(); !TL.isNull(); TL = TL.getNextTypeLoc())
6186 TLR.Visit(TL);
6187 return TInfo;
6188}
6189
6190QualType ASTReader::GetType(TypeID ID) {
6191 unsigned FastQuals = ID & Qualifiers::FastMask;
6192 unsigned Index = ID >> Qualifiers::FastWidth;
6193
6194 if (Index < NUM_PREDEF_TYPE_IDS) {
6195 QualType T;
6196 switch ((PredefinedTypeIDs)Index) {
Alexey Baderbdf7c842015-09-15 12:18:29 +00006197 case PREDEF_TYPE_NULL_ID:
6198 return QualType();
6199 case PREDEF_TYPE_VOID_ID:
6200 T = Context.VoidTy;
6201 break;
6202 case PREDEF_TYPE_BOOL_ID:
6203 T = Context.BoolTy;
6204 break;
Guy Benyei11169dd2012-12-18 14:30:41 +00006205
6206 case PREDEF_TYPE_CHAR_U_ID:
6207 case PREDEF_TYPE_CHAR_S_ID:
6208 // FIXME: Check that the signedness of CharTy is correct!
6209 T = Context.CharTy;
6210 break;
6211
Alexey Baderbdf7c842015-09-15 12:18:29 +00006212 case PREDEF_TYPE_UCHAR_ID:
6213 T = Context.UnsignedCharTy;
6214 break;
6215 case PREDEF_TYPE_USHORT_ID:
6216 T = Context.UnsignedShortTy;
6217 break;
6218 case PREDEF_TYPE_UINT_ID:
6219 T = Context.UnsignedIntTy;
6220 break;
6221 case PREDEF_TYPE_ULONG_ID:
6222 T = Context.UnsignedLongTy;
6223 break;
6224 case PREDEF_TYPE_ULONGLONG_ID:
6225 T = Context.UnsignedLongLongTy;
6226 break;
6227 case PREDEF_TYPE_UINT128_ID:
6228 T = Context.UnsignedInt128Ty;
6229 break;
6230 case PREDEF_TYPE_SCHAR_ID:
6231 T = Context.SignedCharTy;
6232 break;
6233 case PREDEF_TYPE_WCHAR_ID:
6234 T = Context.WCharTy;
6235 break;
6236 case PREDEF_TYPE_SHORT_ID:
6237 T = Context.ShortTy;
6238 break;
6239 case PREDEF_TYPE_INT_ID:
6240 T = Context.IntTy;
6241 break;
6242 case PREDEF_TYPE_LONG_ID:
6243 T = Context.LongTy;
6244 break;
6245 case PREDEF_TYPE_LONGLONG_ID:
6246 T = Context.LongLongTy;
6247 break;
6248 case PREDEF_TYPE_INT128_ID:
6249 T = Context.Int128Ty;
6250 break;
6251 case PREDEF_TYPE_HALF_ID:
6252 T = Context.HalfTy;
6253 break;
6254 case PREDEF_TYPE_FLOAT_ID:
6255 T = Context.FloatTy;
6256 break;
6257 case PREDEF_TYPE_DOUBLE_ID:
6258 T = Context.DoubleTy;
6259 break;
6260 case PREDEF_TYPE_LONGDOUBLE_ID:
6261 T = Context.LongDoubleTy;
6262 break;
Nemanja Ivanovicbb1ea2d2016-05-09 08:52:33 +00006263 case PREDEF_TYPE_FLOAT128_ID:
6264 T = Context.Float128Ty;
6265 break;
Alexey Baderbdf7c842015-09-15 12:18:29 +00006266 case PREDEF_TYPE_OVERLOAD_ID:
6267 T = Context.OverloadTy;
6268 break;
6269 case PREDEF_TYPE_BOUND_MEMBER:
6270 T = Context.BoundMemberTy;
6271 break;
6272 case PREDEF_TYPE_PSEUDO_OBJECT:
6273 T = Context.PseudoObjectTy;
6274 break;
6275 case PREDEF_TYPE_DEPENDENT_ID:
6276 T = Context.DependentTy;
6277 break;
6278 case PREDEF_TYPE_UNKNOWN_ANY:
6279 T = Context.UnknownAnyTy;
6280 break;
6281 case PREDEF_TYPE_NULLPTR_ID:
6282 T = Context.NullPtrTy;
6283 break;
6284 case PREDEF_TYPE_CHAR16_ID:
6285 T = Context.Char16Ty;
6286 break;
6287 case PREDEF_TYPE_CHAR32_ID:
6288 T = Context.Char32Ty;
6289 break;
6290 case PREDEF_TYPE_OBJC_ID:
6291 T = Context.ObjCBuiltinIdTy;
6292 break;
6293 case PREDEF_TYPE_OBJC_CLASS:
6294 T = Context.ObjCBuiltinClassTy;
6295 break;
6296 case PREDEF_TYPE_OBJC_SEL:
6297 T = Context.ObjCBuiltinSelTy;
6298 break;
Alexey Bader954ba212016-04-08 13:40:33 +00006299#define IMAGE_TYPE(ImgType, Id, SingletonId, Access, Suffix) \
6300 case PREDEF_TYPE_##Id##_ID: \
6301 T = Context.SingletonId; \
Alexey Baderbdf7c842015-09-15 12:18:29 +00006302 break;
Alexey Baderb62f1442016-04-13 08:33:41 +00006303#include "clang/Basic/OpenCLImageTypes.def"
Alexey Baderbdf7c842015-09-15 12:18:29 +00006304 case PREDEF_TYPE_SAMPLER_ID:
6305 T = Context.OCLSamplerTy;
6306 break;
6307 case PREDEF_TYPE_EVENT_ID:
6308 T = Context.OCLEventTy;
6309 break;
Alexey Bader9c8453f2015-09-15 11:18:52 +00006310 case PREDEF_TYPE_CLK_EVENT_ID:
6311 T = Context.OCLClkEventTy;
6312 break;
6313 case PREDEF_TYPE_QUEUE_ID:
6314 T = Context.OCLQueueTy;
6315 break;
6316 case PREDEF_TYPE_NDRANGE_ID:
6317 T = Context.OCLNDRangeTy;
6318 break;
6319 case PREDEF_TYPE_RESERVE_ID_ID:
6320 T = Context.OCLReserveIDTy;
6321 break;
Alexey Baderbdf7c842015-09-15 12:18:29 +00006322 case PREDEF_TYPE_AUTO_DEDUCT:
6323 T = Context.getAutoDeductType();
6324 break;
6325
6326 case PREDEF_TYPE_AUTO_RREF_DEDUCT:
6327 T = Context.getAutoRRefDeductType();
Guy Benyei11169dd2012-12-18 14:30:41 +00006328 break;
6329
6330 case PREDEF_TYPE_ARC_UNBRIDGED_CAST:
6331 T = Context.ARCUnbridgedCastTy;
6332 break;
6333
Guy Benyei11169dd2012-12-18 14:30:41 +00006334 case PREDEF_TYPE_BUILTIN_FN:
6335 T = Context.BuiltinFnTy;
6336 break;
Alexey Bataev1a3320e2015-08-25 14:24:04 +00006337
6338 case PREDEF_TYPE_OMP_ARRAY_SECTION:
6339 T = Context.OMPArraySectionTy;
6340 break;
Guy Benyei11169dd2012-12-18 14:30:41 +00006341 }
6342
6343 assert(!T.isNull() && "Unknown predefined type");
6344 return T.withFastQualifiers(FastQuals);
6345 }
6346
6347 Index -= NUM_PREDEF_TYPE_IDS;
6348 assert(Index < TypesLoaded.size() && "Type index out-of-range");
6349 if (TypesLoaded[Index].isNull()) {
6350 TypesLoaded[Index] = readTypeRecord(Index);
6351 if (TypesLoaded[Index].isNull())
6352 return QualType();
6353
6354 TypesLoaded[Index]->setFromAST();
6355 if (DeserializationListener)
6356 DeserializationListener->TypeRead(TypeIdx::fromTypeID(ID),
6357 TypesLoaded[Index]);
6358 }
6359
6360 return TypesLoaded[Index].withFastQualifiers(FastQuals);
6361}
6362
6363QualType ASTReader::getLocalType(ModuleFile &F, unsigned LocalID) {
6364 return GetType(getGlobalTypeID(F, LocalID));
6365}
6366
David L. Jonesc4808b9e2016-12-15 20:53:26 +00006367serialization::TypeID
Guy Benyei11169dd2012-12-18 14:30:41 +00006368ASTReader::getGlobalTypeID(ModuleFile &F, unsigned LocalID) const {
6369 unsigned FastQuals = LocalID & Qualifiers::FastMask;
6370 unsigned LocalIndex = LocalID >> Qualifiers::FastWidth;
David L. Jonesc4808b9e2016-12-15 20:53:26 +00006371
Guy Benyei11169dd2012-12-18 14:30:41 +00006372 if (LocalIndex < NUM_PREDEF_TYPE_IDS)
6373 return LocalID;
6374
6375 ContinuousRangeMap<uint32_t, int, 2>::iterator I
6376 = F.TypeRemap.find(LocalIndex - NUM_PREDEF_TYPE_IDS);
6377 assert(I != F.TypeRemap.end() && "Invalid index into type index remap");
David L. Jonesc4808b9e2016-12-15 20:53:26 +00006378
Guy Benyei11169dd2012-12-18 14:30:41 +00006379 unsigned GlobalIndex = LocalIndex + I->second;
6380 return (GlobalIndex << Qualifiers::FastWidth) | FastQuals;
6381}
6382
6383TemplateArgumentLocInfo
6384ASTReader::GetTemplateArgumentLocInfo(ModuleFile &F,
6385 TemplateArgument::ArgKind Kind,
6386 const RecordData &Record,
6387 unsigned &Index) {
6388 switch (Kind) {
6389 case TemplateArgument::Expression:
6390 return ReadExpr(F);
6391 case TemplateArgument::Type:
6392 return GetTypeSourceInfo(F, Record, Index);
6393 case TemplateArgument::Template: {
David L. Jonesc4808b9e2016-12-15 20:53:26 +00006394 NestedNameSpecifierLoc QualifierLoc = ReadNestedNameSpecifierLoc(F, Record,
Guy Benyei11169dd2012-12-18 14:30:41 +00006395 Index);
6396 SourceLocation TemplateNameLoc = ReadSourceLocation(F, Record, Index);
6397 return TemplateArgumentLocInfo(QualifierLoc, TemplateNameLoc,
6398 SourceLocation());
6399 }
6400 case TemplateArgument::TemplateExpansion: {
David L. Jonesc4808b9e2016-12-15 20:53:26 +00006401 NestedNameSpecifierLoc QualifierLoc = ReadNestedNameSpecifierLoc(F, Record,
Guy Benyei11169dd2012-12-18 14:30:41 +00006402 Index);
6403 SourceLocation TemplateNameLoc = ReadSourceLocation(F, Record, Index);
6404 SourceLocation EllipsisLoc = ReadSourceLocation(F, Record, Index);
David L. Jonesc4808b9e2016-12-15 20:53:26 +00006405 return TemplateArgumentLocInfo(QualifierLoc, TemplateNameLoc,
Guy Benyei11169dd2012-12-18 14:30:41 +00006406 EllipsisLoc);
6407 }
6408 case TemplateArgument::Null:
6409 case TemplateArgument::Integral:
6410 case TemplateArgument::Declaration:
6411 case TemplateArgument::NullPtr:
6412 case TemplateArgument::Pack:
6413 // FIXME: Is this right?
6414 return TemplateArgumentLocInfo();
6415 }
6416 llvm_unreachable("unexpected template argument loc");
6417}
6418
6419TemplateArgumentLoc
6420ASTReader::ReadTemplateArgumentLoc(ModuleFile &F,
6421 const RecordData &Record, unsigned &Index) {
6422 TemplateArgument Arg = ReadTemplateArgument(F, Record, Index);
6423
6424 if (Arg.getKind() == TemplateArgument::Expression) {
6425 if (Record[Index++]) // bool InfoHasSameExpr.
6426 return TemplateArgumentLoc(Arg, TemplateArgumentLocInfo(Arg.getAsExpr()));
6427 }
6428 return TemplateArgumentLoc(Arg, GetTemplateArgumentLocInfo(F, Arg.getKind(),
6429 Record, Index));
6430}
6431
Enea Zaffanella6dbe1872013-08-10 07:24:53 +00006432const ASTTemplateArgumentListInfo*
6433ASTReader::ReadASTTemplateArgumentListInfo(ModuleFile &F,
6434 const RecordData &Record,
6435 unsigned &Index) {
6436 SourceLocation LAngleLoc = ReadSourceLocation(F, Record, Index);
6437 SourceLocation RAngleLoc = ReadSourceLocation(F, Record, Index);
6438 unsigned NumArgsAsWritten = Record[Index++];
6439 TemplateArgumentListInfo TemplArgsInfo(LAngleLoc, RAngleLoc);
6440 for (unsigned i = 0; i != NumArgsAsWritten; ++i)
6441 TemplArgsInfo.addArgument(ReadTemplateArgumentLoc(F, Record, Index));
6442 return ASTTemplateArgumentListInfo::Create(getContext(), TemplArgsInfo);
6443}
6444
Guy Benyei11169dd2012-12-18 14:30:41 +00006445Decl *ASTReader::GetExternalDecl(uint32_t ID) {
6446 return GetDecl(ID);
6447}
6448
Richard Smith50895422015-01-31 03:04:55 +00006449template<typename TemplateSpecializationDecl>
6450static void completeRedeclChainForTemplateSpecialization(Decl *D) {
6451 if (auto *TSD = dyn_cast<TemplateSpecializationDecl>(D))
6452 TSD->getSpecializedTemplate()->LoadLazySpecializations();
6453}
6454
Richard Smith053f6c62014-05-16 23:01:30 +00006455void ASTReader::CompleteRedeclChain(const Decl *D) {
Richard Smith851072e2014-05-19 20:59:20 +00006456 if (NumCurrentElementsDeserializing) {
6457 // We arrange to not care about the complete redeclaration chain while we're
6458 // deserializing. Just remember that the AST has marked this one as complete
6459 // but that it's not actually complete yet, so we know we still need to
6460 // complete it later.
6461 PendingIncompleteDeclChains.push_back(const_cast<Decl*>(D));
6462 return;
6463 }
6464
Richard Smith053f6c62014-05-16 23:01:30 +00006465 const DeclContext *DC = D->getDeclContext()->getRedeclContext();
6466
Richard Smith053f6c62014-05-16 23:01:30 +00006467 // If this is a named declaration, complete it by looking it up
6468 // within its context.
6469 //
Richard Smith01bdb7a2014-08-28 05:44:07 +00006470 // FIXME: Merging a function definition should merge
Richard Smith053f6c62014-05-16 23:01:30 +00006471 // all mergeable entities within it.
6472 if (isa<TranslationUnitDecl>(DC) || isa<NamespaceDecl>(DC) ||
6473 isa<CXXRecordDecl>(DC) || isa<EnumDecl>(DC)) {
6474 if (DeclarationName Name = cast<NamedDecl>(D)->getDeclName()) {
Richard Smitha534a312015-07-21 23:54:07 +00006475 if (!getContext().getLangOpts().CPlusPlus &&
6476 isa<TranslationUnitDecl>(DC)) {
Richard Smith053f6c62014-05-16 23:01:30 +00006477 // Outside of C++, we don't have a lookup table for the TU, so update
Richard Smitha534a312015-07-21 23:54:07 +00006478 // the identifier instead. (For C++ modules, we don't store decls
6479 // in the serialized identifier table, so we do the lookup in the TU.)
6480 auto *II = Name.getAsIdentifierInfo();
6481 assert(II && "non-identifier name in C?");
Richard Smith053f6c62014-05-16 23:01:30 +00006482 if (II->isOutOfDate())
6483 updateOutOfDateIdentifier(*II);
6484 } else
6485 DC->lookup(Name);
Richard Smith01bdb7a2014-08-28 05:44:07 +00006486 } else if (needsAnonymousDeclarationNumber(cast<NamedDecl>(D))) {
Richard Smith3cb15722015-08-05 22:41:45 +00006487 // Find all declarations of this kind from the relevant context.
6488 for (auto *DCDecl : cast<Decl>(D->getLexicalDeclContext())->redecls()) {
6489 auto *DC = cast<DeclContext>(DCDecl);
6490 SmallVector<Decl*, 8> Decls;
6491 FindExternalLexicalDecls(
6492 DC, [&](Decl::Kind K) { return K == D->getKind(); }, Decls);
6493 }
Richard Smith053f6c62014-05-16 23:01:30 +00006494 }
6495 }
Richard Smith50895422015-01-31 03:04:55 +00006496
6497 if (auto *CTSD = dyn_cast<ClassTemplateSpecializationDecl>(D))
6498 CTSD->getSpecializedTemplate()->LoadLazySpecializations();
6499 if (auto *VTSD = dyn_cast<VarTemplateSpecializationDecl>(D))
6500 VTSD->getSpecializedTemplate()->LoadLazySpecializations();
6501 if (auto *FD = dyn_cast<FunctionDecl>(D)) {
6502 if (auto *Template = FD->getPrimaryTemplate())
6503 Template->LoadLazySpecializations();
6504 }
Richard Smith053f6c62014-05-16 23:01:30 +00006505}
6506
Richard Smithc2bb8182015-03-24 06:36:48 +00006507CXXCtorInitializer **
6508ASTReader::GetExternalCXXCtorInitializers(uint64_t Offset) {
6509 RecordLocation Loc = getLocalBitOffset(Offset);
6510 BitstreamCursor &Cursor = Loc.F->DeclsCursor;
6511 SavedStreamPosition SavedPosition(Cursor);
6512 Cursor.JumpToBit(Loc.Offset);
6513 ReadingKindTracker ReadingKind(Read_Decl, *this);
6514
6515 RecordData Record;
6516 unsigned Code = Cursor.ReadCode();
6517 unsigned RecCode = Cursor.readRecord(Code, Record);
6518 if (RecCode != DECL_CXX_CTOR_INITIALIZERS) {
6519 Error("malformed AST file: missing C++ ctor initializers");
6520 return nullptr;
6521 }
6522
6523 unsigned Idx = 0;
6524 return ReadCXXCtorInitializers(*Loc.F, Record, Idx);
6525}
6526
Guy Benyei11169dd2012-12-18 14:30:41 +00006527CXXBaseSpecifier *ASTReader::GetExternalCXXBaseSpecifiers(uint64_t Offset) {
6528 RecordLocation Loc = getLocalBitOffset(Offset);
Chris Lattner7fb3bef2013-01-20 00:56:42 +00006529 BitstreamCursor &Cursor = Loc.F->DeclsCursor;
Guy Benyei11169dd2012-12-18 14:30:41 +00006530 SavedStreamPosition SavedPosition(Cursor);
6531 Cursor.JumpToBit(Loc.Offset);
6532 ReadingKindTracker ReadingKind(Read_Decl, *this);
6533 RecordData Record;
6534 unsigned Code = Cursor.ReadCode();
Chris Lattner0e6c9402013-01-20 02:38:54 +00006535 unsigned RecCode = Cursor.readRecord(Code, Record);
Guy Benyei11169dd2012-12-18 14:30:41 +00006536 if (RecCode != DECL_CXX_BASE_SPECIFIERS) {
Richard Smithcd45dbc2014-04-19 03:48:30 +00006537 Error("malformed AST file: missing C++ base specifiers");
Craig Toppera13603a2014-05-22 05:54:18 +00006538 return nullptr;
Guy Benyei11169dd2012-12-18 14:30:41 +00006539 }
6540
6541 unsigned Idx = 0;
6542 unsigned NumBases = Record[Idx++];
6543 void *Mem = Context.Allocate(sizeof(CXXBaseSpecifier) * NumBases);
6544 CXXBaseSpecifier *Bases = new (Mem) CXXBaseSpecifier [NumBases];
6545 for (unsigned I = 0; I != NumBases; ++I)
6546 Bases[I] = ReadCXXBaseSpecifier(*Loc.F, Record, Idx);
6547 return Bases;
6548}
6549
David L. Jonesc4808b9e2016-12-15 20:53:26 +00006550serialization::DeclID
Guy Benyei11169dd2012-12-18 14:30:41 +00006551ASTReader::getGlobalDeclID(ModuleFile &F, LocalDeclID LocalID) const {
6552 if (LocalID < NUM_PREDEF_DECL_IDS)
6553 return LocalID;
6554
6555 ContinuousRangeMap<uint32_t, int, 2>::iterator I
6556 = F.DeclRemap.find(LocalID - NUM_PREDEF_DECL_IDS);
6557 assert(I != F.DeclRemap.end() && "Invalid index into decl index remap");
David L. Jonesc4808b9e2016-12-15 20:53:26 +00006558
Guy Benyei11169dd2012-12-18 14:30:41 +00006559 return LocalID + I->second;
6560}
6561
6562bool ASTReader::isDeclIDFromModule(serialization::GlobalDeclID ID,
6563 ModuleFile &M) const {
Richard Smithfe620d22015-03-05 23:24:12 +00006564 // Predefined decls aren't from any module.
6565 if (ID < NUM_PREDEF_DECL_IDS)
6566 return false;
6567
David L. Jonesc4808b9e2016-12-15 20:53:26 +00006568 return ID - NUM_PREDEF_DECL_IDS >= M.BaseDeclID &&
Richard Smithbcda1a92015-07-12 23:51:20 +00006569 ID - NUM_PREDEF_DECL_IDS < M.BaseDeclID + M.LocalNumDecls;
Guy Benyei11169dd2012-12-18 14:30:41 +00006570}
6571
Douglas Gregor9f782892013-01-21 15:25:38 +00006572ModuleFile *ASTReader::getOwningModuleFile(const Decl *D) {
Guy Benyei11169dd2012-12-18 14:30:41 +00006573 if (!D->isFromASTFile())
Craig Toppera13603a2014-05-22 05:54:18 +00006574 return nullptr;
Guy Benyei11169dd2012-12-18 14:30:41 +00006575 GlobalDeclMapType::const_iterator I = GlobalDeclMap.find(D->getGlobalID());
6576 assert(I != GlobalDeclMap.end() && "Corrupted global declaration map");
6577 return I->second;
6578}
6579
6580SourceLocation ASTReader::getSourceLocationForDeclID(GlobalDeclID ID) {
6581 if (ID < NUM_PREDEF_DECL_IDS)
6582 return SourceLocation();
Richard Smithcd45dbc2014-04-19 03:48:30 +00006583
Guy Benyei11169dd2012-12-18 14:30:41 +00006584 unsigned Index = ID - NUM_PREDEF_DECL_IDS;
6585
6586 if (Index > DeclsLoaded.size()) {
6587 Error("declaration ID out-of-range for AST file");
6588 return SourceLocation();
6589 }
Richard Smithcd45dbc2014-04-19 03:48:30 +00006590
Guy Benyei11169dd2012-12-18 14:30:41 +00006591 if (Decl *D = DeclsLoaded[Index])
6592 return D->getLocation();
6593
Richard Smithcb34bd32016-03-27 07:28:06 +00006594 SourceLocation Loc;
6595 DeclCursorForID(ID, Loc);
6596 return Loc;
Guy Benyei11169dd2012-12-18 14:30:41 +00006597}
6598
Richard Smithfe620d22015-03-05 23:24:12 +00006599static Decl *getPredefinedDecl(ASTContext &Context, PredefinedDeclIDs ID) {
6600 switch (ID) {
6601 case PREDEF_DECL_NULL_ID:
6602 return nullptr;
6603
6604 case PREDEF_DECL_TRANSLATION_UNIT_ID:
6605 return Context.getTranslationUnitDecl();
6606
6607 case PREDEF_DECL_OBJC_ID_ID:
6608 return Context.getObjCIdDecl();
6609
6610 case PREDEF_DECL_OBJC_SEL_ID:
6611 return Context.getObjCSelDecl();
6612
6613 case PREDEF_DECL_OBJC_CLASS_ID:
6614 return Context.getObjCClassDecl();
6615
6616 case PREDEF_DECL_OBJC_PROTOCOL_ID:
6617 return Context.getObjCProtocolDecl();
6618
6619 case PREDEF_DECL_INT_128_ID:
6620 return Context.getInt128Decl();
6621
6622 case PREDEF_DECL_UNSIGNED_INT_128_ID:
6623 return Context.getUInt128Decl();
6624
6625 case PREDEF_DECL_OBJC_INSTANCETYPE_ID:
6626 return Context.getObjCInstanceTypeDecl();
6627
6628 case PREDEF_DECL_BUILTIN_VA_LIST_ID:
6629 return Context.getBuiltinVaListDecl();
Richard Smithf19e1272015-03-07 00:04:49 +00006630
Richard Smith9b88a4c2015-07-27 05:40:23 +00006631 case PREDEF_DECL_VA_LIST_TAG:
6632 return Context.getVaListTagDecl();
6633
Charles Davisc7d5c942015-09-17 20:55:33 +00006634 case PREDEF_DECL_BUILTIN_MS_VA_LIST_ID:
6635 return Context.getBuiltinMSVaListDecl();
6636
Richard Smithf19e1272015-03-07 00:04:49 +00006637 case PREDEF_DECL_EXTERN_C_CONTEXT_ID:
6638 return Context.getExternCContextDecl();
David Majnemerd9b1a4f2015-11-04 03:40:30 +00006639
6640 case PREDEF_DECL_MAKE_INTEGER_SEQ_ID:
6641 return Context.getMakeIntegerSeqDecl();
Quentin Colombet043406b2016-02-03 22:41:00 +00006642
6643 case PREDEF_DECL_CF_CONSTANT_STRING_ID:
6644 return Context.getCFConstantStringDecl();
Ben Langmuirf5416742016-02-04 00:55:24 +00006645
6646 case PREDEF_DECL_CF_CONSTANT_STRING_TAG_ID:
6647 return Context.getCFConstantStringTagDecl();
Eric Fiselier6ad68552016-07-01 01:24:09 +00006648
6649 case PREDEF_DECL_TYPE_PACK_ELEMENT_ID:
6650 return Context.getTypePackElementDecl();
Richard Smithfe620d22015-03-05 23:24:12 +00006651 }
Yaron Keren322bdad2015-03-06 07:49:14 +00006652 llvm_unreachable("PredefinedDeclIDs unknown enum value");
Richard Smithfe620d22015-03-05 23:24:12 +00006653}
6654
Richard Smithcd45dbc2014-04-19 03:48:30 +00006655Decl *ASTReader::GetExistingDecl(DeclID ID) {
6656 if (ID < NUM_PREDEF_DECL_IDS) {
Richard Smithfe620d22015-03-05 23:24:12 +00006657 Decl *D = getPredefinedDecl(Context, (PredefinedDeclIDs)ID);
6658 if (D) {
6659 // Track that we have merged the declaration with ID \p ID into the
6660 // pre-existing predefined declaration \p D.
Richard Smith5fc18a92015-07-12 23:43:21 +00006661 auto &Merged = KeyDecls[D->getCanonicalDecl()];
Richard Smithfe620d22015-03-05 23:24:12 +00006662 if (Merged.empty())
6663 Merged.push_back(ID);
Guy Benyei11169dd2012-12-18 14:30:41 +00006664 }
Richard Smithfe620d22015-03-05 23:24:12 +00006665 return D;
Guy Benyei11169dd2012-12-18 14:30:41 +00006666 }
Richard Smithcd45dbc2014-04-19 03:48:30 +00006667
Guy Benyei11169dd2012-12-18 14:30:41 +00006668 unsigned Index = ID - NUM_PREDEF_DECL_IDS;
6669
6670 if (Index >= DeclsLoaded.size()) {
6671 assert(0 && "declaration ID out-of-range for AST file");
6672 Error("declaration ID out-of-range for AST file");
Craig Toppera13603a2014-05-22 05:54:18 +00006673 return nullptr;
Guy Benyei11169dd2012-12-18 14:30:41 +00006674 }
Richard Smithcd45dbc2014-04-19 03:48:30 +00006675
6676 return DeclsLoaded[Index];
6677}
6678
6679Decl *ASTReader::GetDecl(DeclID ID) {
6680 if (ID < NUM_PREDEF_DECL_IDS)
6681 return GetExistingDecl(ID);
6682
6683 unsigned Index = ID - NUM_PREDEF_DECL_IDS;
6684
6685 if (Index >= DeclsLoaded.size()) {
6686 assert(0 && "declaration ID out-of-range for AST file");
6687 Error("declaration ID out-of-range for AST file");
Craig Toppera13603a2014-05-22 05:54:18 +00006688 return nullptr;
Richard Smithcd45dbc2014-04-19 03:48:30 +00006689 }
6690
Guy Benyei11169dd2012-12-18 14:30:41 +00006691 if (!DeclsLoaded[Index]) {
6692 ReadDeclRecord(ID);
6693 if (DeserializationListener)
6694 DeserializationListener->DeclRead(ID, DeclsLoaded[Index]);
6695 }
6696
6697 return DeclsLoaded[Index];
6698}
6699
David L. Jonesc4808b9e2016-12-15 20:53:26 +00006700DeclID ASTReader::mapGlobalIDToModuleFileGlobalID(ModuleFile &M,
Guy Benyei11169dd2012-12-18 14:30:41 +00006701 DeclID GlobalID) {
6702 if (GlobalID < NUM_PREDEF_DECL_IDS)
6703 return GlobalID;
David L. Jonesc4808b9e2016-12-15 20:53:26 +00006704
Guy Benyei11169dd2012-12-18 14:30:41 +00006705 GlobalDeclMapType::const_iterator I = GlobalDeclMap.find(GlobalID);
6706 assert(I != GlobalDeclMap.end() && "Corrupted global declaration map");
6707 ModuleFile *Owner = I->second;
6708
6709 llvm::DenseMap<ModuleFile *, serialization::DeclID>::iterator Pos
6710 = M.GlobalToLocalDeclIDs.find(Owner);
6711 if (Pos == M.GlobalToLocalDeclIDs.end())
6712 return 0;
David L. Jonesc4808b9e2016-12-15 20:53:26 +00006713
Guy Benyei11169dd2012-12-18 14:30:41 +00006714 return GlobalID - Owner->BaseDeclID + Pos->second;
6715}
6716
David L. Jonesc4808b9e2016-12-15 20:53:26 +00006717serialization::DeclID ASTReader::ReadDeclID(ModuleFile &F,
Guy Benyei11169dd2012-12-18 14:30:41 +00006718 const RecordData &Record,
6719 unsigned &Idx) {
6720 if (Idx >= Record.size()) {
6721 Error("Corrupted AST file");
6722 return 0;
6723 }
David L. Jonesc4808b9e2016-12-15 20:53:26 +00006724
Guy Benyei11169dd2012-12-18 14:30:41 +00006725 return getGlobalDeclID(F, Record[Idx++]);
6726}
6727
6728/// \brief Resolve the offset of a statement into a statement.
6729///
6730/// This operation will read a new statement from the external
6731/// source each time it is called, and is meant to be used via a
6732/// LazyOffsetPtr (which is used by Decls for the body of functions, etc).
6733Stmt *ASTReader::GetExternalDeclStmt(uint64_t Offset) {
6734 // Switch case IDs are per Decl.
6735 ClearSwitchCaseIDs();
6736
6737 // Offset here is a global offset across the entire chain.
6738 RecordLocation Loc = getLocalBitOffset(Offset);
6739 Loc.F->DeclsCursor.JumpToBit(Loc.Offset);
6740 return ReadStmtFromStream(*Loc.F);
6741}
6742
Richard Smith3cb15722015-08-05 22:41:45 +00006743void ASTReader::FindExternalLexicalDecls(
6744 const DeclContext *DC, llvm::function_ref<bool(Decl::Kind)> IsKindWeWant,
6745 SmallVectorImpl<Decl *> &Decls) {
Richard Smith82f8fcd2015-08-06 22:07:25 +00006746 bool PredefsVisited[NUM_PREDEF_DECL_IDS] = {};
6747
Richard Smith9ccdd932015-08-06 22:14:12 +00006748 auto Visit = [&] (ModuleFile *M, LexicalContents LexicalDecls) {
Richard Smith82f8fcd2015-08-06 22:07:25 +00006749 assert(LexicalDecls.size() % 2 == 0 && "expected an even number of entries");
6750 for (int I = 0, N = LexicalDecls.size(); I != N; I += 2) {
6751 auto K = (Decl::Kind)+LexicalDecls[I];
6752 if (!IsKindWeWant(K))
6753 continue;
6754
6755 auto ID = (serialization::DeclID)+LexicalDecls[I + 1];
6756
6757 // Don't add predefined declarations to the lexical context more
6758 // than once.
6759 if (ID < NUM_PREDEF_DECL_IDS) {
6760 if (PredefsVisited[ID])
6761 continue;
6762
6763 PredefsVisited[ID] = true;
6764 }
6765
6766 if (Decl *D = GetLocalDecl(*M, ID)) {
Richard Smith2317a3e2015-08-11 21:21:20 +00006767 assert(D->getKind() == K && "wrong kind for lexical decl");
Richard Smith82f8fcd2015-08-06 22:07:25 +00006768 if (!DC->isDeclInLexicalTraversal(D))
6769 Decls.push_back(D);
6770 }
6771 }
6772 };
6773
6774 if (isa<TranslationUnitDecl>(DC)) {
6775 for (auto Lexical : TULexicalDecls)
6776 Visit(Lexical.first, Lexical.second);
6777 } else {
6778 auto I = LexicalDecls.find(DC);
6779 if (I != LexicalDecls.end())
Richard Smith9c9173d2015-08-11 22:00:24 +00006780 Visit(I->second.first, I->second.second);
Richard Smith82f8fcd2015-08-06 22:07:25 +00006781 }
6782
Guy Benyei11169dd2012-12-18 14:30:41 +00006783 ++NumLexicalDeclContextsRead;
Guy Benyei11169dd2012-12-18 14:30:41 +00006784}
6785
6786namespace {
6787
6788class DeclIDComp {
6789 ASTReader &Reader;
6790 ModuleFile &Mod;
6791
6792public:
6793 DeclIDComp(ASTReader &Reader, ModuleFile &M) : Reader(Reader), Mod(M) {}
6794
6795 bool operator()(LocalDeclID L, LocalDeclID R) const {
6796 SourceLocation LHS = getLocation(L);
6797 SourceLocation RHS = getLocation(R);
6798 return Reader.getSourceManager().isBeforeInTranslationUnit(LHS, RHS);
6799 }
6800
6801 bool operator()(SourceLocation LHS, LocalDeclID R) const {
6802 SourceLocation RHS = getLocation(R);
6803 return Reader.getSourceManager().isBeforeInTranslationUnit(LHS, RHS);
6804 }
6805
6806 bool operator()(LocalDeclID L, SourceLocation RHS) const {
6807 SourceLocation LHS = getLocation(L);
6808 return Reader.getSourceManager().isBeforeInTranslationUnit(LHS, RHS);
6809 }
6810
6811 SourceLocation getLocation(LocalDeclID ID) const {
6812 return Reader.getSourceManager().getFileLoc(
6813 Reader.getSourceLocationForDeclID(Reader.getGlobalDeclID(Mod, ID)));
6814 }
6815};
6816
Eugene Zelenkoe95e7d52016-09-07 21:53:17 +00006817} // end anonymous namespace
Guy Benyei11169dd2012-12-18 14:30:41 +00006818
6819void ASTReader::FindFileRegionDecls(FileID File,
6820 unsigned Offset, unsigned Length,
6821 SmallVectorImpl<Decl *> &Decls) {
6822 SourceManager &SM = getSourceManager();
6823
6824 llvm::DenseMap<FileID, FileDeclsInfo>::iterator I = FileDeclIDs.find(File);
6825 if (I == FileDeclIDs.end())
6826 return;
6827
6828 FileDeclsInfo &DInfo = I->second;
6829 if (DInfo.Decls.empty())
6830 return;
6831
6832 SourceLocation
6833 BeginLoc = SM.getLocForStartOfFile(File).getLocWithOffset(Offset);
6834 SourceLocation EndLoc = BeginLoc.getLocWithOffset(Length);
6835
6836 DeclIDComp DIDComp(*this, *DInfo.Mod);
6837 ArrayRef<serialization::LocalDeclID>::iterator
6838 BeginIt = std::lower_bound(DInfo.Decls.begin(), DInfo.Decls.end(),
6839 BeginLoc, DIDComp);
6840 if (BeginIt != DInfo.Decls.begin())
6841 --BeginIt;
6842
6843 // If we are pointing at a top-level decl inside an objc container, we need
6844 // to backtrack until we find it otherwise we will fail to report that the
6845 // region overlaps with an objc container.
6846 while (BeginIt != DInfo.Decls.begin() &&
6847 GetDecl(getGlobalDeclID(*DInfo.Mod, *BeginIt))
6848 ->isTopLevelDeclInObjCContainer())
6849 --BeginIt;
6850
6851 ArrayRef<serialization::LocalDeclID>::iterator
6852 EndIt = std::upper_bound(DInfo.Decls.begin(), DInfo.Decls.end(),
6853 EndLoc, DIDComp);
6854 if (EndIt != DInfo.Decls.end())
6855 ++EndIt;
David L. Jonesc4808b9e2016-12-15 20:53:26 +00006856
Guy Benyei11169dd2012-12-18 14:30:41 +00006857 for (ArrayRef<serialization::LocalDeclID>::iterator
6858 DIt = BeginIt; DIt != EndIt; ++DIt)
6859 Decls.push_back(GetDecl(getGlobalDeclID(*DInfo.Mod, *DIt)));
6860}
6861
Richard Smith9ce12e32013-02-07 03:30:24 +00006862bool
Guy Benyei11169dd2012-12-18 14:30:41 +00006863ASTReader::FindExternalVisibleDeclsByName(const DeclContext *DC,
6864 DeclarationName Name) {
Richard Smithd88a7f12015-09-01 20:35:42 +00006865 assert(DC->hasExternalVisibleStorage() && DC == DC->getPrimaryContext() &&
Guy Benyei11169dd2012-12-18 14:30:41 +00006866 "DeclContext has no visible decls in storage");
6867 if (!Name)
Richard Smith9ce12e32013-02-07 03:30:24 +00006868 return false;
Guy Benyei11169dd2012-12-18 14:30:41 +00006869
Richard Smithd88a7f12015-09-01 20:35:42 +00006870 auto It = Lookups.find(DC);
6871 if (It == Lookups.end())
6872 return false;
6873
Richard Smith8c913ec2014-08-14 02:21:01 +00006874 Deserializing LookupResults(this);
6875
Richard Smithd88a7f12015-09-01 20:35:42 +00006876 // Load the list of declarations.
Guy Benyei11169dd2012-12-18 14:30:41 +00006877 SmallVector<NamedDecl *, 64> Decls;
Richard Smithd88a7f12015-09-01 20:35:42 +00006878 for (DeclID ID : It->second.Table.find(Name)) {
6879 NamedDecl *ND = cast<NamedDecl>(GetDecl(ID));
6880 if (ND->getDeclName() == Name)
6881 Decls.push_back(ND);
6882 }
Richard Smithcd45dbc2014-04-19 03:48:30 +00006883
Guy Benyei11169dd2012-12-18 14:30:41 +00006884 ++NumVisibleDeclContextsRead;
6885 SetExternalVisibleDeclsForName(DC, Name, Decls);
Richard Smith9ce12e32013-02-07 03:30:24 +00006886 return !Decls.empty();
Guy Benyei11169dd2012-12-18 14:30:41 +00006887}
6888
Guy Benyei11169dd2012-12-18 14:30:41 +00006889void ASTReader::completeVisibleDeclsMap(const DeclContext *DC) {
6890 if (!DC->hasExternalVisibleStorage())
6891 return;
Richard Smithd88a7f12015-09-01 20:35:42 +00006892
6893 auto It = Lookups.find(DC);
6894 assert(It != Lookups.end() &&
6895 "have external visible storage but no lookup tables");
6896
Craig Topper79be4cd2013-07-05 04:33:53 +00006897 DeclsMap Decls;
Guy Benyei11169dd2012-12-18 14:30:41 +00006898
Richard Smithd88a7f12015-09-01 20:35:42 +00006899 for (DeclID ID : It->second.Table.findAll()) {
6900 NamedDecl *ND = cast<NamedDecl>(GetDecl(ID));
6901 Decls[ND->getDeclName()].push_back(ND);
Guy Benyei11169dd2012-12-18 14:30:41 +00006902 }
6903
Guy Benyei11169dd2012-12-18 14:30:41 +00006904 ++NumVisibleDeclContextsRead;
6905
Craig Topper79be4cd2013-07-05 04:33:53 +00006906 for (DeclsMap::iterator I = Decls.begin(), E = Decls.end(); I != E; ++I) {
Guy Benyei11169dd2012-12-18 14:30:41 +00006907 SetExternalVisibleDeclsForName(DC, I->first, I->second);
6908 }
6909 const_cast<DeclContext *>(DC)->setHasExternalVisibleStorage(false);
6910}
6911
Richard Smithd88a7f12015-09-01 20:35:42 +00006912const serialization::reader::DeclContextLookupTable *
6913ASTReader::getLoadedLookupTables(DeclContext *Primary) const {
6914 auto I = Lookups.find(Primary);
6915 return I == Lookups.end() ? nullptr : &I->second;
6916}
6917
Guy Benyei11169dd2012-12-18 14:30:41 +00006918/// \brief Under non-PCH compilation the consumer receives the objc methods
6919/// before receiving the implementation, and codegen depends on this.
6920/// We simulate this by deserializing and passing to consumer the methods of the
6921/// implementation before passing the deserialized implementation decl.
6922static void PassObjCImplDeclToConsumer(ObjCImplDecl *ImplD,
6923 ASTConsumer *Consumer) {
6924 assert(ImplD && Consumer);
6925
Aaron Ballmanaff18c02014-03-13 19:03:34 +00006926 for (auto *I : ImplD->methods())
6927 Consumer->HandleInterestingDecl(DeclGroupRef(I));
Guy Benyei11169dd2012-12-18 14:30:41 +00006928
6929 Consumer->HandleInterestingDecl(DeclGroupRef(ImplD));
6930}
6931
6932void ASTReader::PassInterestingDeclsToConsumer() {
6933 assert(Consumer);
Richard Smith04d05b52014-03-23 00:27:18 +00006934
6935 if (PassingDeclsToConsumer)
6936 return;
6937
6938 // Guard variable to avoid recursively redoing the process of passing
6939 // decls to consumer.
6940 SaveAndRestore<bool> GuardPassingDeclsToConsumer(PassingDeclsToConsumer,
6941 true);
6942
Richard Smith9e2341d2015-03-23 03:25:59 +00006943 // Ensure that we've loaded all potentially-interesting declarations
6944 // that need to be eagerly loaded.
6945 for (auto ID : EagerlyDeserializedDecls)
6946 GetDecl(ID);
6947 EagerlyDeserializedDecls.clear();
6948
Guy Benyei11169dd2012-12-18 14:30:41 +00006949 while (!InterestingDecls.empty()) {
6950 Decl *D = InterestingDecls.front();
6951 InterestingDecls.pop_front();
6952
6953 PassInterestingDeclToConsumer(D);
6954 }
6955}
6956
6957void ASTReader::PassInterestingDeclToConsumer(Decl *D) {
6958 if (ObjCImplDecl *ImplD = dyn_cast<ObjCImplDecl>(D))
6959 PassObjCImplDeclToConsumer(ImplD, Consumer);
6960 else
6961 Consumer->HandleInterestingDecl(DeclGroupRef(D));
6962}
6963
6964void ASTReader::StartTranslationUnit(ASTConsumer *Consumer) {
6965 this->Consumer = Consumer;
6966
Richard Smith9e2341d2015-03-23 03:25:59 +00006967 if (Consumer)
6968 PassInterestingDeclsToConsumer();
Richard Smith7f330cd2015-03-18 01:42:29 +00006969
6970 if (DeserializationListener)
6971 DeserializationListener->ReaderInitialized(this);
Guy Benyei11169dd2012-12-18 14:30:41 +00006972}
6973
6974void ASTReader::PrintStats() {
6975 std::fprintf(stderr, "*** AST File Statistics:\n");
6976
6977 unsigned NumTypesLoaded
6978 = TypesLoaded.size() - std::count(TypesLoaded.begin(), TypesLoaded.end(),
6979 QualType());
6980 unsigned NumDeclsLoaded
6981 = DeclsLoaded.size() - std::count(DeclsLoaded.begin(), DeclsLoaded.end(),
Craig Toppera13603a2014-05-22 05:54:18 +00006982 (Decl *)nullptr);
Guy Benyei11169dd2012-12-18 14:30:41 +00006983 unsigned NumIdentifiersLoaded
6984 = IdentifiersLoaded.size() - std::count(IdentifiersLoaded.begin(),
6985 IdentifiersLoaded.end(),
Craig Toppera13603a2014-05-22 05:54:18 +00006986 (IdentifierInfo *)nullptr);
Guy Benyei11169dd2012-12-18 14:30:41 +00006987 unsigned NumMacrosLoaded
6988 = MacrosLoaded.size() - std::count(MacrosLoaded.begin(),
6989 MacrosLoaded.end(),
Craig Toppera13603a2014-05-22 05:54:18 +00006990 (MacroInfo *)nullptr);
Guy Benyei11169dd2012-12-18 14:30:41 +00006991 unsigned NumSelectorsLoaded
6992 = SelectorsLoaded.size() - std::count(SelectorsLoaded.begin(),
6993 SelectorsLoaded.end(),
6994 Selector());
6995
6996 if (unsigned TotalNumSLocEntries = getTotalNumSLocs())
6997 std::fprintf(stderr, " %u/%u source location entries read (%f%%)\n",
6998 NumSLocEntriesRead, TotalNumSLocEntries,
6999 ((float)NumSLocEntriesRead/TotalNumSLocEntries * 100));
7000 if (!TypesLoaded.empty())
7001 std::fprintf(stderr, " %u/%u types read (%f%%)\n",
7002 NumTypesLoaded, (unsigned)TypesLoaded.size(),
7003 ((float)NumTypesLoaded/TypesLoaded.size() * 100));
7004 if (!DeclsLoaded.empty())
7005 std::fprintf(stderr, " %u/%u declarations read (%f%%)\n",
7006 NumDeclsLoaded, (unsigned)DeclsLoaded.size(),
7007 ((float)NumDeclsLoaded/DeclsLoaded.size() * 100));
7008 if (!IdentifiersLoaded.empty())
7009 std::fprintf(stderr, " %u/%u identifiers read (%f%%)\n",
7010 NumIdentifiersLoaded, (unsigned)IdentifiersLoaded.size(),
7011 ((float)NumIdentifiersLoaded/IdentifiersLoaded.size() * 100));
7012 if (!MacrosLoaded.empty())
7013 std::fprintf(stderr, " %u/%u macros read (%f%%)\n",
7014 NumMacrosLoaded, (unsigned)MacrosLoaded.size(),
7015 ((float)NumMacrosLoaded/MacrosLoaded.size() * 100));
7016 if (!SelectorsLoaded.empty())
7017 std::fprintf(stderr, " %u/%u selectors read (%f%%)\n",
7018 NumSelectorsLoaded, (unsigned)SelectorsLoaded.size(),
7019 ((float)NumSelectorsLoaded/SelectorsLoaded.size() * 100));
7020 if (TotalNumStatements)
7021 std::fprintf(stderr, " %u/%u statements read (%f%%)\n",
7022 NumStatementsRead, TotalNumStatements,
7023 ((float)NumStatementsRead/TotalNumStatements * 100));
7024 if (TotalNumMacros)
7025 std::fprintf(stderr, " %u/%u macros read (%f%%)\n",
7026 NumMacrosRead, TotalNumMacros,
7027 ((float)NumMacrosRead/TotalNumMacros * 100));
7028 if (TotalLexicalDeclContexts)
7029 std::fprintf(stderr, " %u/%u lexical declcontexts read (%f%%)\n",
7030 NumLexicalDeclContextsRead, TotalLexicalDeclContexts,
7031 ((float)NumLexicalDeclContextsRead/TotalLexicalDeclContexts
7032 * 100));
7033 if (TotalVisibleDeclContexts)
7034 std::fprintf(stderr, " %u/%u visible declcontexts read (%f%%)\n",
7035 NumVisibleDeclContextsRead, TotalVisibleDeclContexts,
7036 ((float)NumVisibleDeclContextsRead/TotalVisibleDeclContexts
7037 * 100));
7038 if (TotalNumMethodPoolEntries) {
7039 std::fprintf(stderr, " %u/%u method pool entries read (%f%%)\n",
7040 NumMethodPoolEntriesRead, TotalNumMethodPoolEntries,
7041 ((float)NumMethodPoolEntriesRead/TotalNumMethodPoolEntries
7042 * 100));
Guy Benyei11169dd2012-12-18 14:30:41 +00007043 }
Douglas Gregorad2f7a52013-01-28 17:54:36 +00007044 if (NumMethodPoolLookups) {
7045 std::fprintf(stderr, " %u/%u method pool lookups succeeded (%f%%)\n",
7046 NumMethodPoolHits, NumMethodPoolLookups,
7047 ((float)NumMethodPoolHits/NumMethodPoolLookups * 100.0));
7048 }
7049 if (NumMethodPoolTableLookups) {
7050 std::fprintf(stderr, " %u/%u method pool table lookups succeeded (%f%%)\n",
7051 NumMethodPoolTableHits, NumMethodPoolTableLookups,
7052 ((float)NumMethodPoolTableHits/NumMethodPoolTableLookups
7053 * 100.0));
7054 }
7055
Douglas Gregor00a50f72013-01-25 00:38:33 +00007056 if (NumIdentifierLookupHits) {
7057 std::fprintf(stderr,
7058 " %u / %u identifier table lookups succeeded (%f%%)\n",
7059 NumIdentifierLookupHits, NumIdentifierLookups,
7060 (double)NumIdentifierLookupHits*100.0/NumIdentifierLookups);
7061 }
7062
Douglas Gregore060e572013-01-25 01:03:03 +00007063 if (GlobalIndex) {
7064 std::fprintf(stderr, "\n");
7065 GlobalIndex->printStats();
7066 }
David L. Jonesc4808b9e2016-12-15 20:53:26 +00007067
Guy Benyei11169dd2012-12-18 14:30:41 +00007068 std::fprintf(stderr, "\n");
7069 dump();
7070 std::fprintf(stderr, "\n");
7071}
7072
7073template<typename Key, typename ModuleFile, unsigned InitialCapacity>
David L. Jonesc4808b9e2016-12-15 20:53:26 +00007074static void
Guy Benyei11169dd2012-12-18 14:30:41 +00007075dumpModuleIDMap(StringRef Name,
David L. Jonesc4808b9e2016-12-15 20:53:26 +00007076 const ContinuousRangeMap<Key, ModuleFile *,
Guy Benyei11169dd2012-12-18 14:30:41 +00007077 InitialCapacity> &Map) {
7078 if (Map.begin() == Map.end())
7079 return;
David L. Jonesc4808b9e2016-12-15 20:53:26 +00007080
Guy Benyei11169dd2012-12-18 14:30:41 +00007081 typedef ContinuousRangeMap<Key, ModuleFile *, InitialCapacity> MapType;
7082 llvm::errs() << Name << ":\n";
David L. Jonesc4808b9e2016-12-15 20:53:26 +00007083 for (typename MapType::const_iterator I = Map.begin(), IEnd = Map.end();
Guy Benyei11169dd2012-12-18 14:30:41 +00007084 I != IEnd; ++I) {
7085 llvm::errs() << " " << I->first << " -> " << I->second->FileName
7086 << "\n";
7087 }
7088}
7089
Yaron Kerencdae9412016-01-29 19:38:18 +00007090LLVM_DUMP_METHOD void ASTReader::dump() {
Guy Benyei11169dd2012-12-18 14:30:41 +00007091 llvm::errs() << "*** PCH/ModuleFile Remappings:\n";
7092 dumpModuleIDMap("Global bit offset map", GlobalBitOffsetsMap);
7093 dumpModuleIDMap("Global source location entry map", GlobalSLocEntryMap);
7094 dumpModuleIDMap("Global type map", GlobalTypeMap);
7095 dumpModuleIDMap("Global declaration map", GlobalDeclMap);
7096 dumpModuleIDMap("Global identifier map", GlobalIdentifierMap);
7097 dumpModuleIDMap("Global macro map", GlobalMacroMap);
7098 dumpModuleIDMap("Global submodule map", GlobalSubmoduleMap);
7099 dumpModuleIDMap("Global selector map", GlobalSelectorMap);
David L. Jonesc4808b9e2016-12-15 20:53:26 +00007100 dumpModuleIDMap("Global preprocessed entity map",
Guy Benyei11169dd2012-12-18 14:30:41 +00007101 GlobalPreprocessedEntityMap);
David L. Jonesc4808b9e2016-12-15 20:53:26 +00007102
Guy Benyei11169dd2012-12-18 14:30:41 +00007103 llvm::errs() << "\n*** PCH/Modules Loaded:";
David L. Jonesc4808b9e2016-12-15 20:53:26 +00007104 for (ModuleManager::ModuleConstIterator M = ModuleMgr.begin(),
Guy Benyei11169dd2012-12-18 14:30:41 +00007105 MEnd = ModuleMgr.end();
7106 M != MEnd; ++M)
7107 (*M)->dump();
7108}
7109
7110/// Return the amount of memory used by memory buffers, breaking down
7111/// by heap-backed versus mmap'ed memory.
7112void ASTReader::getMemoryBufferSizes(MemoryBufferSizes &sizes) const {
7113 for (ModuleConstIterator I = ModuleMgr.begin(),
7114 E = ModuleMgr.end(); I != E; ++I) {
7115 if (llvm::MemoryBuffer *buf = (*I)->Buffer.get()) {
7116 size_t bytes = buf->getBufferSize();
7117 switch (buf->getBufferKind()) {
7118 case llvm::MemoryBuffer::MemoryBuffer_Malloc:
7119 sizes.malloc_bytes += bytes;
7120 break;
7121 case llvm::MemoryBuffer::MemoryBuffer_MMap:
7122 sizes.mmap_bytes += bytes;
7123 break;
7124 }
7125 }
7126 }
7127}
7128
7129void ASTReader::InitializeSema(Sema &S) {
7130 SemaObj = &S;
7131 S.addExternalSource(this);
7132
7133 // Makes sure any declarations that were deserialized "too early"
7134 // still get added to the identifier's declaration chains.
Ben Langmuir5418f402014-09-10 21:29:41 +00007135 for (uint64_t ID : PreloadedDeclIDs) {
7136 NamedDecl *D = cast<NamedDecl>(GetDecl(ID));
7137 pushExternalDeclIntoScope(D, D->getDeclName());
Guy Benyei11169dd2012-12-18 14:30:41 +00007138 }
Ben Langmuir5418f402014-09-10 21:29:41 +00007139 PreloadedDeclIDs.clear();
Guy Benyei11169dd2012-12-18 14:30:41 +00007140
Richard Smith3d8e97e2013-10-18 06:54:39 +00007141 // FIXME: What happens if these are changed by a module import?
Guy Benyei11169dd2012-12-18 14:30:41 +00007142 if (!FPPragmaOptions.empty()) {
7143 assert(FPPragmaOptions.size() == 1 && "Wrong number of FP_PRAGMA_OPTIONS");
7144 SemaObj->FPFeatures.fp_contract = FPPragmaOptions[0];
7145 }
7146
Yaxun Liu5b746652016-12-18 05:18:55 +00007147 SemaObj->OpenCLFeatures.copy(OpenCLExtensions);
7148 SemaObj->OpenCLTypeExtMap = OpenCLTypeExtMap;
7149 SemaObj->OpenCLDeclExtMap = OpenCLDeclExtMap;
Richard Smith3d8e97e2013-10-18 06:54:39 +00007150
7151 UpdateSema();
7152}
7153
7154void ASTReader::UpdateSema() {
7155 assert(SemaObj && "no Sema to update");
7156
7157 // Load the offsets of the declarations that Sema references.
7158 // They will be lazily deserialized when needed.
7159 if (!SemaDeclRefs.empty()) {
Richard Smith96269c52016-09-29 22:49:46 +00007160 assert(SemaDeclRefs.size() % 3 == 0);
7161 for (unsigned I = 0; I != SemaDeclRefs.size(); I += 3) {
Richard Smith3d8e97e2013-10-18 06:54:39 +00007162 if (!SemaObj->StdNamespace)
7163 SemaObj->StdNamespace = SemaDeclRefs[I];
7164 if (!SemaObj->StdBadAlloc)
7165 SemaObj->StdBadAlloc = SemaDeclRefs[I+1];
Richard Smith96269c52016-09-29 22:49:46 +00007166 if (!SemaObj->StdAlignValT)
7167 SemaObj->StdAlignValT = SemaDeclRefs[I+2];
Richard Smith3d8e97e2013-10-18 06:54:39 +00007168 }
7169 SemaDeclRefs.clear();
7170 }
Dario Domizioli13a0a382014-05-23 12:13:25 +00007171
Nico Weber779355f2016-03-02 23:22:00 +00007172 // Update the state of pragmas. Use the same API as if we had encountered the
7173 // pragma in the source.
Dario Domizioli13a0a382014-05-23 12:13:25 +00007174 if(OptimizeOffPragmaLocation.isValid())
7175 SemaObj->ActOnPragmaOptimize(/* IsOn = */ false, OptimizeOffPragmaLocation);
Nico Weber779355f2016-03-02 23:22:00 +00007176 if (PragmaMSStructState != -1)
7177 SemaObj->ActOnPragmaMSStruct((PragmaMSStructKind)PragmaMSStructState);
Nico Weber42932312016-03-03 00:17:35 +00007178 if (PointersToMembersPragmaLocation.isValid()) {
7179 SemaObj->ActOnPragmaMSPointersToMembers(
7180 (LangOptions::PragmaMSPointersToMembersKind)
7181 PragmaMSPointersToMembersState,
7182 PointersToMembersPragmaLocation);
7183 }
Justin Lebar67a78a62016-10-08 22:15:58 +00007184 SemaObj->ForceCUDAHostDeviceDepth = ForceCUDAHostDeviceDepth;
Guy Benyei11169dd2012-12-18 14:30:41 +00007185}
7186
Richard Smitha8d5b6a2015-07-17 19:51:03 +00007187IdentifierInfo *ASTReader::get(StringRef Name) {
Guy Benyei11169dd2012-12-18 14:30:41 +00007188 // Note that we are loading an identifier.
7189 Deserializing AnIdentifier(this);
Douglas Gregore060e572013-01-25 01:03:03 +00007190
Douglas Gregor7211ac12013-01-25 23:32:03 +00007191 IdentifierLookupVisitor Visitor(Name, /*PriorGeneration=*/0,
Douglas Gregor00a50f72013-01-25 00:38:33 +00007192 NumIdentifierLookups,
7193 NumIdentifierLookupHits);
Richard Smith33e0f7e2015-07-22 02:08:40 +00007194
7195 // We don't need to do identifier table lookups in C++ modules (we preload
7196 // all interesting declarations, and don't need to use the scope for name
7197 // lookups). Perform the lookup in PCH files, though, since we don't build
7198 // a complete initial identifier table if we're carrying on from a PCH.
7199 if (Context.getLangOpts().CPlusPlus) {
7200 for (auto F : ModuleMgr.pch_modules())
Benjamin Kramer9a9efba2015-07-25 12:14:04 +00007201 if (Visitor(*F))
Richard Smith33e0f7e2015-07-22 02:08:40 +00007202 break;
7203 } else {
7204 // If there is a global index, look there first to determine which modules
7205 // provably do not have any results for this identifier.
7206 GlobalModuleIndex::HitSet Hits;
7207 GlobalModuleIndex::HitSet *HitsPtr = nullptr;
7208 if (!loadGlobalIndex()) {
7209 if (GlobalIndex->lookupIdentifier(Name, Hits)) {
7210 HitsPtr = &Hits;
7211 }
7212 }
7213
Benjamin Kramer9a9efba2015-07-25 12:14:04 +00007214 ModuleMgr.visit(Visitor, HitsPtr);
Richard Smith33e0f7e2015-07-22 02:08:40 +00007215 }
7216
Guy Benyei11169dd2012-12-18 14:30:41 +00007217 IdentifierInfo *II = Visitor.getIdentifierInfo();
7218 markIdentifierUpToDate(II);
7219 return II;
7220}
7221
7222namespace clang {
Eugene Zelenkoe95e7d52016-09-07 21:53:17 +00007223
Guy Benyei11169dd2012-12-18 14:30:41 +00007224 /// \brief An identifier-lookup iterator that enumerates all of the
7225 /// identifiers stored within a set of AST files.
7226 class ASTIdentifierIterator : public IdentifierIterator {
7227 /// \brief The AST reader whose identifiers are being enumerated.
7228 const ASTReader &Reader;
7229
7230 /// \brief The current index into the chain of AST files stored in
7231 /// the AST reader.
7232 unsigned Index;
7233
7234 /// \brief The current position within the identifier lookup table
7235 /// of the current AST file.
7236 ASTIdentifierLookupTable::key_iterator Current;
7237
7238 /// \brief The end position within the identifier lookup table of
7239 /// the current AST file.
7240 ASTIdentifierLookupTable::key_iterator End;
7241
Ben Langmuir537c5b52016-05-04 00:53:13 +00007242 /// \brief Whether to skip any modules in the ASTReader.
7243 bool SkipModules;
7244
Guy Benyei11169dd2012-12-18 14:30:41 +00007245 public:
Ben Langmuir537c5b52016-05-04 00:53:13 +00007246 explicit ASTIdentifierIterator(const ASTReader &Reader,
7247 bool SkipModules = false);
Guy Benyei11169dd2012-12-18 14:30:41 +00007248
Craig Topper3e89dfe2014-03-13 02:13:41 +00007249 StringRef Next() override;
Guy Benyei11169dd2012-12-18 14:30:41 +00007250 };
Eugene Zelenkoe95e7d52016-09-07 21:53:17 +00007251
7252} // end namespace clang
Guy Benyei11169dd2012-12-18 14:30:41 +00007253
Ben Langmuir537c5b52016-05-04 00:53:13 +00007254ASTIdentifierIterator::ASTIdentifierIterator(const ASTReader &Reader,
7255 bool SkipModules)
7256 : Reader(Reader), Index(Reader.ModuleMgr.size()), SkipModules(SkipModules) {
Guy Benyei11169dd2012-12-18 14:30:41 +00007257}
7258
7259StringRef ASTIdentifierIterator::Next() {
7260 while (Current == End) {
7261 // If we have exhausted all of our AST files, we're done.
7262 if (Index == 0)
7263 return StringRef();
7264
7265 --Index;
Ben Langmuir537c5b52016-05-04 00:53:13 +00007266 ModuleFile &F = Reader.ModuleMgr[Index];
7267 if (SkipModules && F.isModule())
7268 continue;
7269
7270 ASTIdentifierLookupTable *IdTable =
7271 (ASTIdentifierLookupTable *)F.IdentifierLookupTable;
Guy Benyei11169dd2012-12-18 14:30:41 +00007272 Current = IdTable->key_begin();
7273 End = IdTable->key_end();
7274 }
7275
7276 // We have any identifiers remaining in the current AST file; return
7277 // the next one.
Douglas Gregorbfd73d72013-01-23 18:53:14 +00007278 StringRef Result = *Current;
Guy Benyei11169dd2012-12-18 14:30:41 +00007279 ++Current;
Douglas Gregorbfd73d72013-01-23 18:53:14 +00007280 return Result;
Guy Benyei11169dd2012-12-18 14:30:41 +00007281}
7282
Ben Langmuir537c5b52016-05-04 00:53:13 +00007283namespace {
Eugene Zelenkoe95e7d52016-09-07 21:53:17 +00007284
Ben Langmuir537c5b52016-05-04 00:53:13 +00007285/// A utility for appending two IdentifierIterators.
7286class ChainedIdentifierIterator : public IdentifierIterator {
7287 std::unique_ptr<IdentifierIterator> Current;
7288 std::unique_ptr<IdentifierIterator> Queued;
7289
7290public:
7291 ChainedIdentifierIterator(std::unique_ptr<IdentifierIterator> First,
7292 std::unique_ptr<IdentifierIterator> Second)
7293 : Current(std::move(First)), Queued(std::move(Second)) {}
7294
7295 StringRef Next() override {
7296 if (!Current)
7297 return StringRef();
7298
7299 StringRef result = Current->Next();
7300 if (!result.empty())
7301 return result;
7302
7303 // Try the queued iterator, which may itself be empty.
7304 Current.reset();
7305 std::swap(Current, Queued);
7306 return Next();
7307 }
7308};
Eugene Zelenkoe95e7d52016-09-07 21:53:17 +00007309
Ben Langmuir537c5b52016-05-04 00:53:13 +00007310} // end anonymous namespace.
7311
Argyrios Kyrtzidis9aca3c62013-04-17 22:10:55 +00007312IdentifierIterator *ASTReader::getIdentifiers() {
Ben Langmuir537c5b52016-05-04 00:53:13 +00007313 if (!loadGlobalIndex()) {
7314 std::unique_ptr<IdentifierIterator> ReaderIter(
7315 new ASTIdentifierIterator(*this, /*SkipModules=*/true));
7316 std::unique_ptr<IdentifierIterator> ModulesIter(
7317 GlobalIndex->createIdentifierIterator());
7318 return new ChainedIdentifierIterator(std::move(ReaderIter),
7319 std::move(ModulesIter));
7320 }
Argyrios Kyrtzidis9aca3c62013-04-17 22:10:55 +00007321
Guy Benyei11169dd2012-12-18 14:30:41 +00007322 return new ASTIdentifierIterator(*this);
7323}
7324
Eugene Zelenkoe95e7d52016-09-07 21:53:17 +00007325namespace clang {
7326namespace serialization {
7327
Guy Benyei11169dd2012-12-18 14:30:41 +00007328 class ReadMethodPoolVisitor {
7329 ASTReader &Reader;
7330 Selector Sel;
7331 unsigned PriorGeneration;
Argyrios Kyrtzidisd3da6e02013-04-17 00:08:58 +00007332 unsigned InstanceBits;
7333 unsigned FactoryBits;
Nico Weberff4b35e2014-12-27 22:14:15 +00007334 bool InstanceHasMoreThanOneDecl;
7335 bool FactoryHasMoreThanOneDecl;
Dmitri Gribenkof8579502013-01-12 19:30:44 +00007336 SmallVector<ObjCMethodDecl *, 4> InstanceMethods;
7337 SmallVector<ObjCMethodDecl *, 4> FactoryMethods;
Guy Benyei11169dd2012-12-18 14:30:41 +00007338
7339 public:
Nico Weber2e0c8f72014-12-27 03:58:08 +00007340 ReadMethodPoolVisitor(ASTReader &Reader, Selector Sel,
Guy Benyei11169dd2012-12-18 14:30:41 +00007341 unsigned PriorGeneration)
Nico Weber2e0c8f72014-12-27 03:58:08 +00007342 : Reader(Reader), Sel(Sel), PriorGeneration(PriorGeneration),
Nico Weberff4b35e2014-12-27 22:14:15 +00007343 InstanceBits(0), FactoryBits(0), InstanceHasMoreThanOneDecl(false),
7344 FactoryHasMoreThanOneDecl(false) {}
Nico Weber2e0c8f72014-12-27 03:58:08 +00007345
Benjamin Kramer9a9efba2015-07-25 12:14:04 +00007346 bool operator()(ModuleFile &M) {
Guy Benyei11169dd2012-12-18 14:30:41 +00007347 if (!M.SelectorLookupTable)
7348 return false;
David L. Jonesc4808b9e2016-12-15 20:53:26 +00007349
Guy Benyei11169dd2012-12-18 14:30:41 +00007350 // If we've already searched this module file, skip it now.
Richard Smithbdf2d932015-07-30 03:37:16 +00007351 if (M.Generation <= PriorGeneration)
Guy Benyei11169dd2012-12-18 14:30:41 +00007352 return true;
7353
Richard Smithbdf2d932015-07-30 03:37:16 +00007354 ++Reader.NumMethodPoolTableLookups;
Guy Benyei11169dd2012-12-18 14:30:41 +00007355 ASTSelectorLookupTable *PoolTable
7356 = (ASTSelectorLookupTable*)M.SelectorLookupTable;
Richard Smithbdf2d932015-07-30 03:37:16 +00007357 ASTSelectorLookupTable::iterator Pos = PoolTable->find(Sel);
Guy Benyei11169dd2012-12-18 14:30:41 +00007358 if (Pos == PoolTable->end())
7359 return false;
Douglas Gregorad2f7a52013-01-28 17:54:36 +00007360
Richard Smithbdf2d932015-07-30 03:37:16 +00007361 ++Reader.NumMethodPoolTableHits;
7362 ++Reader.NumSelectorsRead;
Guy Benyei11169dd2012-12-18 14:30:41 +00007363 // FIXME: Not quite happy with the statistics here. We probably should
7364 // disable this tracking when called via LoadSelector.
7365 // Also, should entries without methods count as misses?
Richard Smithbdf2d932015-07-30 03:37:16 +00007366 ++Reader.NumMethodPoolEntriesRead;
Guy Benyei11169dd2012-12-18 14:30:41 +00007367 ASTSelectorLookupTrait::data_type Data = *Pos;
Richard Smithbdf2d932015-07-30 03:37:16 +00007368 if (Reader.DeserializationListener)
7369 Reader.DeserializationListener->SelectorRead(Data.ID, Sel);
Benjamin Kramer9a9efba2015-07-25 12:14:04 +00007370
Richard Smithbdf2d932015-07-30 03:37:16 +00007371 InstanceMethods.append(Data.Instance.begin(), Data.Instance.end());
7372 FactoryMethods.append(Data.Factory.begin(), Data.Factory.end());
7373 InstanceBits = Data.InstanceBits;
7374 FactoryBits = Data.FactoryBits;
7375 InstanceHasMoreThanOneDecl = Data.InstanceHasMoreThanOneDecl;
7376 FactoryHasMoreThanOneDecl = Data.FactoryHasMoreThanOneDecl;
Guy Benyei11169dd2012-12-18 14:30:41 +00007377 return true;
7378 }
David L. Jonesc4808b9e2016-12-15 20:53:26 +00007379
Guy Benyei11169dd2012-12-18 14:30:41 +00007380 /// \brief Retrieve the instance methods found by this visitor.
David L. Jonesc4808b9e2016-12-15 20:53:26 +00007381 ArrayRef<ObjCMethodDecl *> getInstanceMethods() const {
7382 return InstanceMethods;
Guy Benyei11169dd2012-12-18 14:30:41 +00007383 }
7384
7385 /// \brief Retrieve the instance methods found by this visitor.
David L. Jonesc4808b9e2016-12-15 20:53:26 +00007386 ArrayRef<ObjCMethodDecl *> getFactoryMethods() const {
Guy Benyei11169dd2012-12-18 14:30:41 +00007387 return FactoryMethods;
7388 }
Argyrios Kyrtzidisd3da6e02013-04-17 00:08:58 +00007389
7390 unsigned getInstanceBits() const { return InstanceBits; }
7391 unsigned getFactoryBits() const { return FactoryBits; }
Nico Weberff4b35e2014-12-27 22:14:15 +00007392 bool instanceHasMoreThanOneDecl() const {
7393 return InstanceHasMoreThanOneDecl;
7394 }
7395 bool factoryHasMoreThanOneDecl() const { return FactoryHasMoreThanOneDecl; }
Guy Benyei11169dd2012-12-18 14:30:41 +00007396 };
Eugene Zelenkoe95e7d52016-09-07 21:53:17 +00007397
7398} // end namespace serialization
7399} // end namespace clang
Guy Benyei11169dd2012-12-18 14:30:41 +00007400
7401/// \brief Add the given set of methods to the method list.
7402static void addMethodsToPool(Sema &S, ArrayRef<ObjCMethodDecl *> Methods,
7403 ObjCMethodList &List) {
7404 for (unsigned I = 0, N = Methods.size(); I != N; ++I) {
7405 S.addMethodToGlobalList(&List, Methods[I]);
7406 }
7407}
David L. Jonesc4808b9e2016-12-15 20:53:26 +00007408
Guy Benyei11169dd2012-12-18 14:30:41 +00007409void ASTReader::ReadMethodPool(Selector Sel) {
7410 // Get the selector generation and update it to the current generation.
7411 unsigned &Generation = SelectorGeneration[Sel];
7412 unsigned PriorGeneration = Generation;
Richard Smith053f6c62014-05-16 23:01:30 +00007413 Generation = getGeneration();
Manman Rena0f31a02016-04-29 19:04:05 +00007414 SelectorOutOfDate[Sel] = false;
David L. Jonesc4808b9e2016-12-15 20:53:26 +00007415
Guy Benyei11169dd2012-12-18 14:30:41 +00007416 // Search for methods defined with this selector.
Douglas Gregorad2f7a52013-01-28 17:54:36 +00007417 ++NumMethodPoolLookups;
Guy Benyei11169dd2012-12-18 14:30:41 +00007418 ReadMethodPoolVisitor Visitor(*this, Sel, PriorGeneration);
Benjamin Kramer9a9efba2015-07-25 12:14:04 +00007419 ModuleMgr.visit(Visitor);
7420
Guy Benyei11169dd2012-12-18 14:30:41 +00007421 if (Visitor.getInstanceMethods().empty() &&
Douglas Gregorad2f7a52013-01-28 17:54:36 +00007422 Visitor.getFactoryMethods().empty())
Guy Benyei11169dd2012-12-18 14:30:41 +00007423 return;
Douglas Gregorad2f7a52013-01-28 17:54:36 +00007424
7425 ++NumMethodPoolHits;
7426
Guy Benyei11169dd2012-12-18 14:30:41 +00007427 if (!getSema())
7428 return;
David L. Jonesc4808b9e2016-12-15 20:53:26 +00007429
Guy Benyei11169dd2012-12-18 14:30:41 +00007430 Sema &S = *getSema();
7431 Sema::GlobalMethodPool::iterator Pos
7432 = S.MethodPool.insert(std::make_pair(Sel, Sema::GlobalMethods())).first;
Ben Langmuira0c32e92015-01-12 19:27:00 +00007433
Argyrios Kyrtzidisd3da6e02013-04-17 00:08:58 +00007434 Pos->second.first.setBits(Visitor.getInstanceBits());
Nico Weberff4b35e2014-12-27 22:14:15 +00007435 Pos->second.first.setHasMoreThanOneDecl(Visitor.instanceHasMoreThanOneDecl());
Argyrios Kyrtzidisd3da6e02013-04-17 00:08:58 +00007436 Pos->second.second.setBits(Visitor.getFactoryBits());
Nico Weberff4b35e2014-12-27 22:14:15 +00007437 Pos->second.second.setHasMoreThanOneDecl(Visitor.factoryHasMoreThanOneDecl());
Ben Langmuira0c32e92015-01-12 19:27:00 +00007438
7439 // Add methods to the global pool *after* setting hasMoreThanOneDecl, since
7440 // when building a module we keep every method individually and may need to
7441 // update hasMoreThanOneDecl as we add the methods.
7442 addMethodsToPool(S, Visitor.getInstanceMethods(), Pos->second.first);
7443 addMethodsToPool(S, Visitor.getFactoryMethods(), Pos->second.second);
Guy Benyei11169dd2012-12-18 14:30:41 +00007444}
7445
Manman Rena0f31a02016-04-29 19:04:05 +00007446void ASTReader::updateOutOfDateSelector(Selector Sel) {
7447 if (SelectorOutOfDate[Sel])
7448 ReadMethodPool(Sel);
7449}
7450
Guy Benyei11169dd2012-12-18 14:30:41 +00007451void ASTReader::ReadKnownNamespaces(
7452 SmallVectorImpl<NamespaceDecl *> &Namespaces) {
7453 Namespaces.clear();
David L. Jonesc4808b9e2016-12-15 20:53:26 +00007454
Guy Benyei11169dd2012-12-18 14:30:41 +00007455 for (unsigned I = 0, N = KnownNamespaces.size(); I != N; ++I) {
David L. Jonesc4808b9e2016-12-15 20:53:26 +00007456 if (NamespaceDecl *Namespace
Guy Benyei11169dd2012-12-18 14:30:41 +00007457 = dyn_cast_or_null<NamespaceDecl>(GetDecl(KnownNamespaces[I])))
7458 Namespaces.push_back(Namespace);
7459 }
7460}
7461
Nick Lewycky9c7eb1d2013-02-01 08:13:20 +00007462void ASTReader::ReadUndefinedButUsed(
Richard Smithd6a04d72016-03-25 21:49:43 +00007463 llvm::MapVector<NamedDecl *, SourceLocation> &Undefined) {
Nick Lewycky9c7eb1d2013-02-01 08:13:20 +00007464 for (unsigned Idx = 0, N = UndefinedButUsed.size(); Idx != N;) {
7465 NamedDecl *D = cast<NamedDecl>(GetDecl(UndefinedButUsed[Idx++]));
Nick Lewycky8334af82013-01-26 00:35:08 +00007466 SourceLocation Loc =
Nick Lewycky9c7eb1d2013-02-01 08:13:20 +00007467 SourceLocation::getFromRawEncoding(UndefinedButUsed[Idx++]);
Nick Lewycky8334af82013-01-26 00:35:08 +00007468 Undefined.insert(std::make_pair(D, Loc));
7469 }
7470}
Nick Lewycky8334af82013-01-26 00:35:08 +00007471
Ismail Pazarbasie5768d12015-05-18 19:59:11 +00007472void ASTReader::ReadMismatchingDeleteExpressions(llvm::MapVector<
7473 FieldDecl *, llvm::SmallVector<std::pair<SourceLocation, bool>, 4>> &
7474 Exprs) {
7475 for (unsigned Idx = 0, N = DelayedDeleteExprs.size(); Idx != N;) {
7476 FieldDecl *FD = cast<FieldDecl>(GetDecl(DelayedDeleteExprs[Idx++]));
7477 uint64_t Count = DelayedDeleteExprs[Idx++];
7478 for (uint64_t C = 0; C < Count; ++C) {
7479 SourceLocation DeleteLoc =
7480 SourceLocation::getFromRawEncoding(DelayedDeleteExprs[Idx++]);
7481 const bool IsArrayForm = DelayedDeleteExprs[Idx++];
7482 Exprs[FD].push_back(std::make_pair(DeleteLoc, IsArrayForm));
7483 }
7484 }
7485}
7486
Guy Benyei11169dd2012-12-18 14:30:41 +00007487void ASTReader::ReadTentativeDefinitions(
7488 SmallVectorImpl<VarDecl *> &TentativeDefs) {
7489 for (unsigned I = 0, N = TentativeDefinitions.size(); I != N; ++I) {
7490 VarDecl *Var = dyn_cast_or_null<VarDecl>(GetDecl(TentativeDefinitions[I]));
7491 if (Var)
7492 TentativeDefs.push_back(Var);
7493 }
7494 TentativeDefinitions.clear();
7495}
7496
7497void ASTReader::ReadUnusedFileScopedDecls(
7498 SmallVectorImpl<const DeclaratorDecl *> &Decls) {
7499 for (unsigned I = 0, N = UnusedFileScopedDecls.size(); I != N; ++I) {
7500 DeclaratorDecl *D
7501 = dyn_cast_or_null<DeclaratorDecl>(GetDecl(UnusedFileScopedDecls[I]));
7502 if (D)
7503 Decls.push_back(D);
7504 }
7505 UnusedFileScopedDecls.clear();
7506}
7507
7508void ASTReader::ReadDelegatingConstructors(
7509 SmallVectorImpl<CXXConstructorDecl *> &Decls) {
7510 for (unsigned I = 0, N = DelegatingCtorDecls.size(); I != N; ++I) {
7511 CXXConstructorDecl *D
7512 = dyn_cast_or_null<CXXConstructorDecl>(GetDecl(DelegatingCtorDecls[I]));
7513 if (D)
7514 Decls.push_back(D);
7515 }
7516 DelegatingCtorDecls.clear();
7517}
7518
7519void ASTReader::ReadExtVectorDecls(SmallVectorImpl<TypedefNameDecl *> &Decls) {
7520 for (unsigned I = 0, N = ExtVectorDecls.size(); I != N; ++I) {
7521 TypedefNameDecl *D
7522 = dyn_cast_or_null<TypedefNameDecl>(GetDecl(ExtVectorDecls[I]));
7523 if (D)
7524 Decls.push_back(D);
7525 }
7526 ExtVectorDecls.clear();
7527}
7528
Nico Weber72889432014-09-06 01:25:55 +00007529void ASTReader::ReadUnusedLocalTypedefNameCandidates(
7530 llvm::SmallSetVector<const TypedefNameDecl *, 4> &Decls) {
7531 for (unsigned I = 0, N = UnusedLocalTypedefNameCandidates.size(); I != N;
7532 ++I) {
7533 TypedefNameDecl *D = dyn_cast_or_null<TypedefNameDecl>(
7534 GetDecl(UnusedLocalTypedefNameCandidates[I]));
7535 if (D)
7536 Decls.insert(D);
7537 }
7538 UnusedLocalTypedefNameCandidates.clear();
7539}
7540
Guy Benyei11169dd2012-12-18 14:30:41 +00007541void ASTReader::ReadReferencedSelectors(
7542 SmallVectorImpl<std::pair<Selector, SourceLocation> > &Sels) {
7543 if (ReferencedSelectorsData.empty())
7544 return;
David L. Jonesc4808b9e2016-12-15 20:53:26 +00007545
Guy Benyei11169dd2012-12-18 14:30:41 +00007546 // If there are @selector references added them to its pool. This is for
7547 // implementation of -Wselector.
7548 unsigned int DataSize = ReferencedSelectorsData.size()-1;
7549 unsigned I = 0;
7550 while (I < DataSize) {
7551 Selector Sel = DecodeSelector(ReferencedSelectorsData[I++]);
7552 SourceLocation SelLoc
7553 = SourceLocation::getFromRawEncoding(ReferencedSelectorsData[I++]);
7554 Sels.push_back(std::make_pair(Sel, SelLoc));
7555 }
7556 ReferencedSelectorsData.clear();
7557}
7558
7559void ASTReader::ReadWeakUndeclaredIdentifiers(
7560 SmallVectorImpl<std::pair<IdentifierInfo *, WeakInfo> > &WeakIDs) {
7561 if (WeakUndeclaredIdentifiers.empty())
7562 return;
7563
7564 for (unsigned I = 0, N = WeakUndeclaredIdentifiers.size(); I < N; /*none*/) {
David L. Jonesc4808b9e2016-12-15 20:53:26 +00007565 IdentifierInfo *WeakId
Guy Benyei11169dd2012-12-18 14:30:41 +00007566 = DecodeIdentifierInfo(WeakUndeclaredIdentifiers[I++]);
David L. Jonesc4808b9e2016-12-15 20:53:26 +00007567 IdentifierInfo *AliasId
Guy Benyei11169dd2012-12-18 14:30:41 +00007568 = DecodeIdentifierInfo(WeakUndeclaredIdentifiers[I++]);
7569 SourceLocation Loc
7570 = SourceLocation::getFromRawEncoding(WeakUndeclaredIdentifiers[I++]);
7571 bool Used = WeakUndeclaredIdentifiers[I++];
7572 WeakInfo WI(AliasId, Loc);
7573 WI.setUsed(Used);
7574 WeakIDs.push_back(std::make_pair(WeakId, WI));
7575 }
7576 WeakUndeclaredIdentifiers.clear();
7577}
7578
7579void ASTReader::ReadUsedVTables(SmallVectorImpl<ExternalVTableUse> &VTables) {
7580 for (unsigned Idx = 0, N = VTableUses.size(); Idx < N; /* In loop */) {
7581 ExternalVTableUse VT;
7582 VT.Record = dyn_cast_or_null<CXXRecordDecl>(GetDecl(VTableUses[Idx++]));
7583 VT.Location = SourceLocation::getFromRawEncoding(VTableUses[Idx++]);
7584 VT.DefinitionRequired = VTableUses[Idx++];
7585 VTables.push_back(VT);
7586 }
David L. Jonesc4808b9e2016-12-15 20:53:26 +00007587
Guy Benyei11169dd2012-12-18 14:30:41 +00007588 VTableUses.clear();
7589}
7590
7591void ASTReader::ReadPendingInstantiations(
7592 SmallVectorImpl<std::pair<ValueDecl *, SourceLocation> > &Pending) {
7593 for (unsigned Idx = 0, N = PendingInstantiations.size(); Idx < N;) {
7594 ValueDecl *D = cast<ValueDecl>(GetDecl(PendingInstantiations[Idx++]));
7595 SourceLocation Loc
7596 = SourceLocation::getFromRawEncoding(PendingInstantiations[Idx++]);
7597
7598 Pending.push_back(std::make_pair(D, Loc));
David L. Jonesc4808b9e2016-12-15 20:53:26 +00007599 }
Guy Benyei11169dd2012-12-18 14:30:41 +00007600 PendingInstantiations.clear();
7601}
7602
Richard Smithe40f2ba2013-08-07 21:41:30 +00007603void ASTReader::ReadLateParsedTemplates(
Justin Lebar28f09c52016-10-10 16:26:08 +00007604 llvm::MapVector<const FunctionDecl *, std::unique_ptr<LateParsedTemplate>>
7605 &LPTMap) {
Richard Smithe40f2ba2013-08-07 21:41:30 +00007606 for (unsigned Idx = 0, N = LateParsedTemplates.size(); Idx < N;
7607 /* In loop */) {
7608 FunctionDecl *FD = cast<FunctionDecl>(GetDecl(LateParsedTemplates[Idx++]));
7609
Justin Lebar28f09c52016-10-10 16:26:08 +00007610 auto LT = llvm::make_unique<LateParsedTemplate>();
Richard Smithe40f2ba2013-08-07 21:41:30 +00007611 LT->D = GetDecl(LateParsedTemplates[Idx++]);
7612
7613 ModuleFile *F = getOwningModuleFile(LT->D);
7614 assert(F && "No module");
7615
7616 unsigned TokN = LateParsedTemplates[Idx++];
7617 LT->Toks.reserve(TokN);
7618 for (unsigned T = 0; T < TokN; ++T)
7619 LT->Toks.push_back(ReadToken(*F, LateParsedTemplates, Idx));
7620
Justin Lebar28f09c52016-10-10 16:26:08 +00007621 LPTMap.insert(std::make_pair(FD, std::move(LT)));
Richard Smithe40f2ba2013-08-07 21:41:30 +00007622 }
7623
7624 LateParsedTemplates.clear();
7625}
7626
Guy Benyei11169dd2012-12-18 14:30:41 +00007627void ASTReader::LoadSelector(Selector Sel) {
7628 // It would be complicated to avoid reading the methods anyway. So don't.
7629 ReadMethodPool(Sel);
7630}
7631
7632void ASTReader::SetIdentifierInfo(IdentifierID ID, IdentifierInfo *II) {
7633 assert(ID && "Non-zero identifier ID required");
7634 assert(ID <= IdentifiersLoaded.size() && "identifier ID out of range");
7635 IdentifiersLoaded[ID - 1] = II;
7636 if (DeserializationListener)
7637 DeserializationListener->IdentifierRead(ID, II);
7638}
7639
7640/// \brief Set the globally-visible declarations associated with the given
7641/// identifier.
7642///
7643/// If the AST reader is currently in a state where the given declaration IDs
7644/// cannot safely be resolved, they are queued until it is safe to resolve
7645/// them.
7646///
7647/// \param II an IdentifierInfo that refers to one or more globally-visible
7648/// declarations.
7649///
7650/// \param DeclIDs the set of declaration IDs with the name @p II that are
7651/// visible at global scope.
7652///
Douglas Gregor6168bd22013-02-18 15:53:43 +00007653/// \param Decls if non-null, this vector will be populated with the set of
7654/// deserialized declarations. These declarations will not be pushed into
7655/// scope.
Guy Benyei11169dd2012-12-18 14:30:41 +00007656void
7657ASTReader::SetGloballyVisibleDecls(IdentifierInfo *II,
7658 const SmallVectorImpl<uint32_t> &DeclIDs,
Douglas Gregor6168bd22013-02-18 15:53:43 +00007659 SmallVectorImpl<Decl *> *Decls) {
7660 if (NumCurrentElementsDeserializing && !Decls) {
7661 PendingIdentifierInfos[II].append(DeclIDs.begin(), DeclIDs.end());
Guy Benyei11169dd2012-12-18 14:30:41 +00007662 return;
7663 }
7664
7665 for (unsigned I = 0, N = DeclIDs.size(); I != N; ++I) {
Ben Langmuir5418f402014-09-10 21:29:41 +00007666 if (!SemaObj) {
Guy Benyei11169dd2012-12-18 14:30:41 +00007667 // Queue this declaration so that it will be added to the
7668 // translation unit scope and identifier's declaration chain
7669 // once a Sema object is known.
Ben Langmuir5418f402014-09-10 21:29:41 +00007670 PreloadedDeclIDs.push_back(DeclIDs[I]);
7671 continue;
Guy Benyei11169dd2012-12-18 14:30:41 +00007672 }
Ben Langmuir5418f402014-09-10 21:29:41 +00007673
7674 NamedDecl *D = cast<NamedDecl>(GetDecl(DeclIDs[I]));
7675
7676 // If we're simply supposed to record the declarations, do so now.
7677 if (Decls) {
7678 Decls->push_back(D);
7679 continue;
7680 }
7681
7682 // Introduce this declaration into the translation-unit scope
7683 // and add it to the declaration chain for this identifier, so
7684 // that (unqualified) name lookup will find it.
7685 pushExternalDeclIntoScope(D, II);
Guy Benyei11169dd2012-12-18 14:30:41 +00007686 }
7687}
7688
Douglas Gregorc8a992f2013-01-21 16:52:34 +00007689IdentifierInfo *ASTReader::DecodeIdentifierInfo(IdentifierID ID) {
Guy Benyei11169dd2012-12-18 14:30:41 +00007690 if (ID == 0)
Craig Toppera13603a2014-05-22 05:54:18 +00007691 return nullptr;
Guy Benyei11169dd2012-12-18 14:30:41 +00007692
7693 if (IdentifiersLoaded.empty()) {
7694 Error("no identifier table in AST file");
Craig Toppera13603a2014-05-22 05:54:18 +00007695 return nullptr;
Guy Benyei11169dd2012-12-18 14:30:41 +00007696 }
7697
7698 ID -= 1;
7699 if (!IdentifiersLoaded[ID]) {
7700 GlobalIdentifierMapType::iterator I = GlobalIdentifierMap.find(ID + 1);
7701 assert(I != GlobalIdentifierMap.end() && "Corrupted global identifier map");
7702 ModuleFile *M = I->second;
7703 unsigned Index = ID - M->BaseIdentifierID;
7704 const char *Str = M->IdentifierTableData + M->IdentifierOffsets[Index];
7705
7706 // All of the strings in the AST file are preceded by a 16-bit length.
7707 // Extract that 16-bit length to avoid having to execute strlen().
7708 // NOTE: 'StrLenPtr' is an 'unsigned char*' so that we load bytes as
7709 // unsigned integers. This is important to avoid integer overflow when
7710 // we cast them to 'unsigned'.
7711 const unsigned char *StrLenPtr = (const unsigned char*) Str - 2;
7712 unsigned StrLen = (((unsigned) StrLenPtr[0])
7713 | (((unsigned) StrLenPtr[1]) << 8)) - 1;
Richard Smitheb4b58f62016-02-05 01:40:54 +00007714 auto &II = PP.getIdentifierTable().get(StringRef(Str, StrLen));
7715 IdentifiersLoaded[ID] = &II;
7716 markIdentifierFromAST(*this, II);
Guy Benyei11169dd2012-12-18 14:30:41 +00007717 if (DeserializationListener)
Richard Smitheb4b58f62016-02-05 01:40:54 +00007718 DeserializationListener->IdentifierRead(ID + 1, &II);
Guy Benyei11169dd2012-12-18 14:30:41 +00007719 }
7720
7721 return IdentifiersLoaded[ID];
7722}
7723
Douglas Gregorc8a992f2013-01-21 16:52:34 +00007724IdentifierInfo *ASTReader::getLocalIdentifier(ModuleFile &M, unsigned LocalID) {
7725 return DecodeIdentifierInfo(getGlobalIdentifierID(M, LocalID));
Guy Benyei11169dd2012-12-18 14:30:41 +00007726}
7727
7728IdentifierID ASTReader::getGlobalIdentifierID(ModuleFile &M, unsigned LocalID) {
7729 if (LocalID < NUM_PREDEF_IDENT_IDS)
7730 return LocalID;
David L. Jonesc4808b9e2016-12-15 20:53:26 +00007731
Guy Benyei11169dd2012-12-18 14:30:41 +00007732 ContinuousRangeMap<uint32_t, int, 2>::iterator I
7733 = M.IdentifierRemap.find(LocalID - NUM_PREDEF_IDENT_IDS);
David L. Jonesc4808b9e2016-12-15 20:53:26 +00007734 assert(I != M.IdentifierRemap.end()
Guy Benyei11169dd2012-12-18 14:30:41 +00007735 && "Invalid index into identifier index remap");
David L. Jonesc4808b9e2016-12-15 20:53:26 +00007736
Guy Benyei11169dd2012-12-18 14:30:41 +00007737 return LocalID + I->second;
7738}
7739
Argyrios Kyrtzidiseb663da2013-03-22 21:12:57 +00007740MacroInfo *ASTReader::getMacro(MacroID ID) {
Guy Benyei11169dd2012-12-18 14:30:41 +00007741 if (ID == 0)
Craig Toppera13603a2014-05-22 05:54:18 +00007742 return nullptr;
Guy Benyei11169dd2012-12-18 14:30:41 +00007743
7744 if (MacrosLoaded.empty()) {
7745 Error("no macro table in AST file");
Craig Toppera13603a2014-05-22 05:54:18 +00007746 return nullptr;
Guy Benyei11169dd2012-12-18 14:30:41 +00007747 }
7748
7749 ID -= NUM_PREDEF_MACRO_IDS;
7750 if (!MacrosLoaded[ID]) {
7751 GlobalMacroMapType::iterator I
7752 = GlobalMacroMap.find(ID + NUM_PREDEF_MACRO_IDS);
7753 assert(I != GlobalMacroMap.end() && "Corrupted global macro map");
7754 ModuleFile *M = I->second;
7755 unsigned Index = ID - M->BaseMacroID;
Argyrios Kyrtzidiseb663da2013-03-22 21:12:57 +00007756 MacrosLoaded[ID] = ReadMacroRecord(*M, M->MacroOffsets[Index]);
David L. Jonesc4808b9e2016-12-15 20:53:26 +00007757
Argyrios Kyrtzidiseb663da2013-03-22 21:12:57 +00007758 if (DeserializationListener)
7759 DeserializationListener->MacroRead(ID + NUM_PREDEF_MACRO_IDS,
7760 MacrosLoaded[ID]);
Guy Benyei11169dd2012-12-18 14:30:41 +00007761 }
7762
7763 return MacrosLoaded[ID];
7764}
7765
7766MacroID ASTReader::getGlobalMacroID(ModuleFile &M, unsigned LocalID) {
7767 if (LocalID < NUM_PREDEF_MACRO_IDS)
7768 return LocalID;
7769
7770 ContinuousRangeMap<uint32_t, int, 2>::iterator I
7771 = M.MacroRemap.find(LocalID - NUM_PREDEF_MACRO_IDS);
7772 assert(I != M.MacroRemap.end() && "Invalid index into macro index remap");
7773
7774 return LocalID + I->second;
7775}
7776
7777serialization::SubmoduleID
7778ASTReader::getGlobalSubmoduleID(ModuleFile &M, unsigned LocalID) {
7779 if (LocalID < NUM_PREDEF_SUBMODULE_IDS)
7780 return LocalID;
David L. Jonesc4808b9e2016-12-15 20:53:26 +00007781
Guy Benyei11169dd2012-12-18 14:30:41 +00007782 ContinuousRangeMap<uint32_t, int, 2>::iterator I
7783 = M.SubmoduleRemap.find(LocalID - NUM_PREDEF_SUBMODULE_IDS);
David L. Jonesc4808b9e2016-12-15 20:53:26 +00007784 assert(I != M.SubmoduleRemap.end()
Guy Benyei11169dd2012-12-18 14:30:41 +00007785 && "Invalid index into submodule index remap");
David L. Jonesc4808b9e2016-12-15 20:53:26 +00007786
Guy Benyei11169dd2012-12-18 14:30:41 +00007787 return LocalID + I->second;
7788}
7789
7790Module *ASTReader::getSubmodule(SubmoduleID GlobalID) {
7791 if (GlobalID < NUM_PREDEF_SUBMODULE_IDS) {
7792 assert(GlobalID == 0 && "Unhandled global submodule ID");
Craig Toppera13603a2014-05-22 05:54:18 +00007793 return nullptr;
Guy Benyei11169dd2012-12-18 14:30:41 +00007794 }
David L. Jonesc4808b9e2016-12-15 20:53:26 +00007795
Guy Benyei11169dd2012-12-18 14:30:41 +00007796 if (GlobalID > SubmodulesLoaded.size()) {
7797 Error("submodule ID out of range in AST file");
Craig Toppera13603a2014-05-22 05:54:18 +00007798 return nullptr;
Guy Benyei11169dd2012-12-18 14:30:41 +00007799 }
David L. Jonesc4808b9e2016-12-15 20:53:26 +00007800
Guy Benyei11169dd2012-12-18 14:30:41 +00007801 return SubmodulesLoaded[GlobalID - NUM_PREDEF_SUBMODULE_IDS];
7802}
Douglas Gregorc147b0b2013-01-12 01:29:50 +00007803
7804Module *ASTReader::getModule(unsigned ID) {
7805 return getSubmodule(ID);
7806}
7807
Richard Smithd88a7f12015-09-01 20:35:42 +00007808ModuleFile *ASTReader::getLocalModuleFile(ModuleFile &F, unsigned ID) {
7809 if (ID & 1) {
7810 // It's a module, look it up by submodule ID.
7811 auto I = GlobalSubmoduleMap.find(getGlobalSubmoduleID(F, ID >> 1));
7812 return I == GlobalSubmoduleMap.end() ? nullptr : I->second;
7813 } else {
7814 // It's a prefix (preamble, PCH, ...). Look it up by index.
7815 unsigned IndexFromEnd = ID >> 1;
7816 assert(IndexFromEnd && "got reference to unknown module file");
7817 return getModuleManager().pch_modules().end()[-IndexFromEnd];
7818 }
7819}
7820
7821unsigned ASTReader::getModuleFileID(ModuleFile *F) {
7822 if (!F)
7823 return 1;
7824
7825 // For a file representing a module, use the submodule ID of the top-level
7826 // module as the file ID. For any other kind of file, the number of such
7827 // files loaded beforehand will be the same on reload.
7828 // FIXME: Is this true even if we have an explicit module file and a PCH?
7829 if (F->isModule())
7830 return ((F->BaseSubmoduleID + NUM_PREDEF_SUBMODULE_IDS) << 1) | 1;
7831
7832 auto PCHModules = getModuleManager().pch_modules();
7833 auto I = std::find(PCHModules.begin(), PCHModules.end(), F);
7834 assert(I != PCHModules.end() && "emitting reference to unknown file");
7835 return (I - PCHModules.end()) << 1;
7836}
7837
Adrian Prantl15bcf702015-06-30 17:39:43 +00007838llvm::Optional<ExternalASTSource::ASTSourceDescriptor>
7839ASTReader::getSourceDescriptor(unsigned ID) {
7840 if (const Module *M = getSubmodule(ID))
Adrian Prantlc6458d62015-09-19 00:10:32 +00007841 return ExternalASTSource::ASTSourceDescriptor(*M);
Adrian Prantl15bcf702015-06-30 17:39:43 +00007842
7843 // If there is only a single PCH, return it instead.
7844 // Chained PCH are not suported.
7845 if (ModuleMgr.size() == 1) {
7846 ModuleFile &MF = ModuleMgr.getPrimaryModule();
Adrian Prantl3a2d4942016-01-22 23:30:56 +00007847 StringRef ModuleName = llvm::sys::path::filename(MF.OriginalSourceFileName);
Adrian Prantl9bc3c4f2016-04-27 17:06:22 +00007848 StringRef FileName = llvm::sys::path::filename(MF.FileName);
7849 return ASTReader::ASTSourceDescriptor(ModuleName, MF.OriginalDir, FileName,
7850 MF.Signature);
Adrian Prantl15bcf702015-06-30 17:39:43 +00007851 }
7852 return None;
7853}
7854
Guy Benyei11169dd2012-12-18 14:30:41 +00007855Selector ASTReader::getLocalSelector(ModuleFile &M, unsigned LocalID) {
7856 return DecodeSelector(getGlobalSelectorID(M, LocalID));
7857}
7858
7859Selector ASTReader::DecodeSelector(serialization::SelectorID ID) {
7860 if (ID == 0)
7861 return Selector();
7862
7863 if (ID > SelectorsLoaded.size()) {
7864 Error("selector ID out of range in AST file");
7865 return Selector();
7866 }
7867
Craig Toppera13603a2014-05-22 05:54:18 +00007868 if (SelectorsLoaded[ID - 1].getAsOpaquePtr() == nullptr) {
Guy Benyei11169dd2012-12-18 14:30:41 +00007869 // Load this selector from the selector table.
7870 GlobalSelectorMapType::iterator I = GlobalSelectorMap.find(ID);
7871 assert(I != GlobalSelectorMap.end() && "Corrupted global selector map");
7872 ModuleFile &M = *I->second;
7873 ASTSelectorLookupTrait Trait(*this, M);
7874 unsigned Idx = ID - M.BaseSelectorID - NUM_PREDEF_SELECTOR_IDS;
7875 SelectorsLoaded[ID - 1] =
7876 Trait.ReadKey(M.SelectorLookupTableData + M.SelectorOffsets[Idx], 0);
7877 if (DeserializationListener)
7878 DeserializationListener->SelectorRead(ID, SelectorsLoaded[ID - 1]);
7879 }
7880
7881 return SelectorsLoaded[ID - 1];
7882}
7883
7884Selector ASTReader::GetExternalSelector(serialization::SelectorID ID) {
7885 return DecodeSelector(ID);
7886}
7887
7888uint32_t ASTReader::GetNumExternalSelectors() {
7889 // ID 0 (the null selector) is considered an external selector.
7890 return getTotalNumSelectors() + 1;
7891}
7892
7893serialization::SelectorID
7894ASTReader::getGlobalSelectorID(ModuleFile &M, unsigned LocalID) const {
7895 if (LocalID < NUM_PREDEF_SELECTOR_IDS)
7896 return LocalID;
David L. Jonesc4808b9e2016-12-15 20:53:26 +00007897
Guy Benyei11169dd2012-12-18 14:30:41 +00007898 ContinuousRangeMap<uint32_t, int, 2>::iterator I
7899 = M.SelectorRemap.find(LocalID - NUM_PREDEF_SELECTOR_IDS);
David L. Jonesc4808b9e2016-12-15 20:53:26 +00007900 assert(I != M.SelectorRemap.end()
Guy Benyei11169dd2012-12-18 14:30:41 +00007901 && "Invalid index into selector index remap");
David L. Jonesc4808b9e2016-12-15 20:53:26 +00007902
Guy Benyei11169dd2012-12-18 14:30:41 +00007903 return LocalID + I->second;
7904}
7905
7906DeclarationName
David L. Jonesc4808b9e2016-12-15 20:53:26 +00007907ASTReader::ReadDeclarationName(ModuleFile &F,
Guy Benyei11169dd2012-12-18 14:30:41 +00007908 const RecordData &Record, unsigned &Idx) {
7909 DeclarationName::NameKind Kind = (DeclarationName::NameKind)Record[Idx++];
7910 switch (Kind) {
7911 case DeclarationName::Identifier:
Douglas Gregorc8a992f2013-01-21 16:52:34 +00007912 return DeclarationName(GetIdentifierInfo(F, Record, Idx));
Guy Benyei11169dd2012-12-18 14:30:41 +00007913
7914 case DeclarationName::ObjCZeroArgSelector:
7915 case DeclarationName::ObjCOneArgSelector:
7916 case DeclarationName::ObjCMultiArgSelector:
7917 return DeclarationName(ReadSelector(F, Record, Idx));
7918
7919 case DeclarationName::CXXConstructorName:
7920 return Context.DeclarationNames.getCXXConstructorName(
7921 Context.getCanonicalType(readType(F, Record, Idx)));
7922
7923 case DeclarationName::CXXDestructorName:
7924 return Context.DeclarationNames.getCXXDestructorName(
7925 Context.getCanonicalType(readType(F, Record, Idx)));
7926
7927 case DeclarationName::CXXConversionFunctionName:
7928 return Context.DeclarationNames.getCXXConversionFunctionName(
7929 Context.getCanonicalType(readType(F, Record, Idx)));
7930
7931 case DeclarationName::CXXOperatorName:
7932 return Context.DeclarationNames.getCXXOperatorName(
7933 (OverloadedOperatorKind)Record[Idx++]);
7934
7935 case DeclarationName::CXXLiteralOperatorName:
7936 return Context.DeclarationNames.getCXXLiteralOperatorName(
7937 GetIdentifierInfo(F, Record, Idx));
7938
7939 case DeclarationName::CXXUsingDirective:
7940 return DeclarationName::getUsingDirectiveName();
7941 }
7942
7943 llvm_unreachable("Invalid NameKind!");
7944}
7945
7946void ASTReader::ReadDeclarationNameLoc(ModuleFile &F,
7947 DeclarationNameLoc &DNLoc,
7948 DeclarationName Name,
7949 const RecordData &Record, unsigned &Idx) {
7950 switch (Name.getNameKind()) {
7951 case DeclarationName::CXXConstructorName:
7952 case DeclarationName::CXXDestructorName:
7953 case DeclarationName::CXXConversionFunctionName:
7954 DNLoc.NamedType.TInfo = GetTypeSourceInfo(F, Record, Idx);
7955 break;
7956
7957 case DeclarationName::CXXOperatorName:
7958 DNLoc.CXXOperatorName.BeginOpNameLoc
7959 = ReadSourceLocation(F, Record, Idx).getRawEncoding();
7960 DNLoc.CXXOperatorName.EndOpNameLoc
7961 = ReadSourceLocation(F, Record, Idx).getRawEncoding();
7962 break;
7963
7964 case DeclarationName::CXXLiteralOperatorName:
7965 DNLoc.CXXLiteralOperatorName.OpNameLoc
7966 = ReadSourceLocation(F, Record, Idx).getRawEncoding();
7967 break;
7968
7969 case DeclarationName::Identifier:
7970 case DeclarationName::ObjCZeroArgSelector:
7971 case DeclarationName::ObjCOneArgSelector:
7972 case DeclarationName::ObjCMultiArgSelector:
7973 case DeclarationName::CXXUsingDirective:
7974 break;
7975 }
7976}
7977
7978void ASTReader::ReadDeclarationNameInfo(ModuleFile &F,
7979 DeclarationNameInfo &NameInfo,
7980 const RecordData &Record, unsigned &Idx) {
7981 NameInfo.setName(ReadDeclarationName(F, Record, Idx));
7982 NameInfo.setLoc(ReadSourceLocation(F, Record, Idx));
7983 DeclarationNameLoc DNLoc;
7984 ReadDeclarationNameLoc(F, DNLoc, NameInfo.getName(), Record, Idx);
7985 NameInfo.setInfo(DNLoc);
7986}
7987
7988void ASTReader::ReadQualifierInfo(ModuleFile &F, QualifierInfo &Info,
7989 const RecordData &Record, unsigned &Idx) {
7990 Info.QualifierLoc = ReadNestedNameSpecifierLoc(F, Record, Idx);
7991 unsigned NumTPLists = Record[Idx++];
7992 Info.NumTemplParamLists = NumTPLists;
7993 if (NumTPLists) {
7994 Info.TemplParamLists = new (Context) TemplateParameterList*[NumTPLists];
Eugene Zelenkoe95e7d52016-09-07 21:53:17 +00007995 for (unsigned i = 0; i != NumTPLists; ++i)
Guy Benyei11169dd2012-12-18 14:30:41 +00007996 Info.TemplParamLists[i] = ReadTemplateParameterList(F, Record, Idx);
7997 }
7998}
7999
8000TemplateName
David L. Jonesc4808b9e2016-12-15 20:53:26 +00008001ASTReader::ReadTemplateName(ModuleFile &F, const RecordData &Record,
Guy Benyei11169dd2012-12-18 14:30:41 +00008002 unsigned &Idx) {
8003 TemplateName::NameKind Kind = (TemplateName::NameKind)Record[Idx++];
8004 switch (Kind) {
8005 case TemplateName::Template:
8006 return TemplateName(ReadDeclAs<TemplateDecl>(F, Record, Idx));
8007
8008 case TemplateName::OverloadedTemplate: {
8009 unsigned size = Record[Idx++];
8010 UnresolvedSet<8> Decls;
8011 while (size--)
8012 Decls.addDecl(ReadDeclAs<NamedDecl>(F, Record, Idx));
8013
8014 return Context.getOverloadedTemplateName(Decls.begin(), Decls.end());
8015 }
8016
8017 case TemplateName::QualifiedTemplate: {
8018 NestedNameSpecifier *NNS = ReadNestedNameSpecifier(F, Record, Idx);
8019 bool hasTemplKeyword = Record[Idx++];
8020 TemplateDecl *Template = ReadDeclAs<TemplateDecl>(F, Record, Idx);
8021 return Context.getQualifiedTemplateName(NNS, hasTemplKeyword, Template);
8022 }
8023
8024 case TemplateName::DependentTemplate: {
8025 NestedNameSpecifier *NNS = ReadNestedNameSpecifier(F, Record, Idx);
8026 if (Record[Idx++]) // isIdentifier
8027 return Context.getDependentTemplateName(NNS,
David L. Jonesc4808b9e2016-12-15 20:53:26 +00008028 GetIdentifierInfo(F, Record,
Guy Benyei11169dd2012-12-18 14:30:41 +00008029 Idx));
8030 return Context.getDependentTemplateName(NNS,
8031 (OverloadedOperatorKind)Record[Idx++]);
8032 }
8033
8034 case TemplateName::SubstTemplateTemplateParm: {
8035 TemplateTemplateParmDecl *param
8036 = ReadDeclAs<TemplateTemplateParmDecl>(F, Record, Idx);
8037 if (!param) return TemplateName();
8038 TemplateName replacement = ReadTemplateName(F, Record, Idx);
8039 return Context.getSubstTemplateTemplateParm(param, replacement);
8040 }
David L. Jonesc4808b9e2016-12-15 20:53:26 +00008041
Guy Benyei11169dd2012-12-18 14:30:41 +00008042 case TemplateName::SubstTemplateTemplateParmPack: {
David L. Jonesc4808b9e2016-12-15 20:53:26 +00008043 TemplateTemplateParmDecl *Param
Guy Benyei11169dd2012-12-18 14:30:41 +00008044 = ReadDeclAs<TemplateTemplateParmDecl>(F, Record, Idx);
8045 if (!Param)
8046 return TemplateName();
David L. Jonesc4808b9e2016-12-15 20:53:26 +00008047
Guy Benyei11169dd2012-12-18 14:30:41 +00008048 TemplateArgument ArgPack = ReadTemplateArgument(F, Record, Idx);
8049 if (ArgPack.getKind() != TemplateArgument::Pack)
8050 return TemplateName();
David L. Jonesc4808b9e2016-12-15 20:53:26 +00008051
Guy Benyei11169dd2012-12-18 14:30:41 +00008052 return Context.getSubstTemplateTemplateParmPack(Param, ArgPack);
8053 }
8054 }
8055
8056 llvm_unreachable("Unhandled template name kind!");
8057}
8058
Richard Smith2bb3c342015-08-09 01:05:31 +00008059TemplateArgument ASTReader::ReadTemplateArgument(ModuleFile &F,
8060 const RecordData &Record,
8061 unsigned &Idx,
8062 bool Canonicalize) {
8063 if (Canonicalize) {
8064 // The caller wants a canonical template argument. Sometimes the AST only
8065 // wants template arguments in canonical form (particularly as the template
8066 // argument lists of template specializations) so ensure we preserve that
8067 // canonical form across serialization.
8068 TemplateArgument Arg = ReadTemplateArgument(F, Record, Idx, false);
8069 return Context.getCanonicalTemplateArgument(Arg);
8070 }
8071
Guy Benyei11169dd2012-12-18 14:30:41 +00008072 TemplateArgument::ArgKind Kind = (TemplateArgument::ArgKind)Record[Idx++];
8073 switch (Kind) {
8074 case TemplateArgument::Null:
8075 return TemplateArgument();
8076 case TemplateArgument::Type:
8077 return TemplateArgument(readType(F, Record, Idx));
8078 case TemplateArgument::Declaration: {
8079 ValueDecl *D = ReadDeclAs<ValueDecl>(F, Record, Idx);
David Blaikie0f62c8d2014-10-16 04:21:25 +00008080 return TemplateArgument(D, readType(F, Record, Idx));
Guy Benyei11169dd2012-12-18 14:30:41 +00008081 }
8082 case TemplateArgument::NullPtr:
8083 return TemplateArgument(readType(F, Record, Idx), /*isNullPtr*/true);
8084 case TemplateArgument::Integral: {
8085 llvm::APSInt Value = ReadAPSInt(Record, Idx);
8086 QualType T = readType(F, Record, Idx);
8087 return TemplateArgument(Context, Value, T);
8088 }
David L. Jonesc4808b9e2016-12-15 20:53:26 +00008089 case TemplateArgument::Template:
Guy Benyei11169dd2012-12-18 14:30:41 +00008090 return TemplateArgument(ReadTemplateName(F, Record, Idx));
8091 case TemplateArgument::TemplateExpansion: {
8092 TemplateName Name = ReadTemplateName(F, Record, Idx);
David Blaikie05785d12013-02-20 22:23:23 +00008093 Optional<unsigned> NumTemplateExpansions;
Guy Benyei11169dd2012-12-18 14:30:41 +00008094 if (unsigned NumExpansions = Record[Idx++])
8095 NumTemplateExpansions = NumExpansions - 1;
8096 return TemplateArgument(Name, NumTemplateExpansions);
8097 }
8098 case TemplateArgument::Expression:
8099 return TemplateArgument(ReadExpr(F));
8100 case TemplateArgument::Pack: {
8101 unsigned NumArgs = Record[Idx++];
8102 TemplateArgument *Args = new (Context) TemplateArgument[NumArgs];
8103 for (unsigned I = 0; I != NumArgs; ++I)
8104 Args[I] = ReadTemplateArgument(F, Record, Idx);
Benjamin Kramercce63472015-08-05 09:40:22 +00008105 return TemplateArgument(llvm::makeArrayRef(Args, NumArgs));
Guy Benyei11169dd2012-12-18 14:30:41 +00008106 }
8107 }
8108
8109 llvm_unreachable("Unhandled template argument kind!");
8110}
8111
8112TemplateParameterList *
8113ASTReader::ReadTemplateParameterList(ModuleFile &F,
8114 const RecordData &Record, unsigned &Idx) {
8115 SourceLocation TemplateLoc = ReadSourceLocation(F, Record, Idx);
8116 SourceLocation LAngleLoc = ReadSourceLocation(F, Record, Idx);
8117 SourceLocation RAngleLoc = ReadSourceLocation(F, Record, Idx);
8118
8119 unsigned NumParams = Record[Idx++];
8120 SmallVector<NamedDecl *, 16> Params;
8121 Params.reserve(NumParams);
8122 while (NumParams--)
8123 Params.push_back(ReadDeclAs<NamedDecl>(F, Record, Idx));
8124
Hubert Tonge4a0c0e2016-07-30 22:33:34 +00008125 // TODO: Concepts
Guy Benyei11169dd2012-12-18 14:30:41 +00008126 TemplateParameterList* TemplateParams =
8127 TemplateParameterList::Create(Context, TemplateLoc, LAngleLoc,
Hubert Tonge4a0c0e2016-07-30 22:33:34 +00008128 Params, RAngleLoc, nullptr);
Guy Benyei11169dd2012-12-18 14:30:41 +00008129 return TemplateParams;
8130}
8131
8132void
8133ASTReader::
Craig Topper5603df42013-07-05 19:34:19 +00008134ReadTemplateArgumentList(SmallVectorImpl<TemplateArgument> &TemplArgs,
Guy Benyei11169dd2012-12-18 14:30:41 +00008135 ModuleFile &F, const RecordData &Record,
Richard Smith2bb3c342015-08-09 01:05:31 +00008136 unsigned &Idx, bool Canonicalize) {
Guy Benyei11169dd2012-12-18 14:30:41 +00008137 unsigned NumTemplateArgs = Record[Idx++];
8138 TemplArgs.reserve(NumTemplateArgs);
8139 while (NumTemplateArgs--)
Richard Smith2bb3c342015-08-09 01:05:31 +00008140 TemplArgs.push_back(ReadTemplateArgument(F, Record, Idx, Canonicalize));
Guy Benyei11169dd2012-12-18 14:30:41 +00008141}
8142
8143/// \brief Read a UnresolvedSet structure.
Richard Smitha4ba74c2013-08-30 04:46:40 +00008144void ASTReader::ReadUnresolvedSet(ModuleFile &F, LazyASTUnresolvedSet &Set,
Guy Benyei11169dd2012-12-18 14:30:41 +00008145 const RecordData &Record, unsigned &Idx) {
8146 unsigned NumDecls = Record[Idx++];
8147 Set.reserve(Context, NumDecls);
8148 while (NumDecls--) {
Richard Smitha4ba74c2013-08-30 04:46:40 +00008149 DeclID ID = ReadDeclID(F, Record, Idx);
Guy Benyei11169dd2012-12-18 14:30:41 +00008150 AccessSpecifier AS = (AccessSpecifier)Record[Idx++];
Richard Smitha4ba74c2013-08-30 04:46:40 +00008151 Set.addLazyDecl(Context, ID, AS);
Guy Benyei11169dd2012-12-18 14:30:41 +00008152 }
8153}
8154
8155CXXBaseSpecifier
8156ASTReader::ReadCXXBaseSpecifier(ModuleFile &F,
8157 const RecordData &Record, unsigned &Idx) {
8158 bool isVirtual = static_cast<bool>(Record[Idx++]);
8159 bool isBaseOfClass = static_cast<bool>(Record[Idx++]);
8160 AccessSpecifier AS = static_cast<AccessSpecifier>(Record[Idx++]);
8161 bool inheritConstructors = static_cast<bool>(Record[Idx++]);
8162 TypeSourceInfo *TInfo = GetTypeSourceInfo(F, Record, Idx);
8163 SourceRange Range = ReadSourceRange(F, Record, Idx);
8164 SourceLocation EllipsisLoc = ReadSourceLocation(F, Record, Idx);
David L. Jonesc4808b9e2016-12-15 20:53:26 +00008165 CXXBaseSpecifier Result(Range, isVirtual, isBaseOfClass, AS, TInfo,
Guy Benyei11169dd2012-12-18 14:30:41 +00008166 EllipsisLoc);
8167 Result.setInheritConstructors(inheritConstructors);
8168 return Result;
8169}
8170
Richard Smithc2bb8182015-03-24 06:36:48 +00008171CXXCtorInitializer **
Guy Benyei11169dd2012-12-18 14:30:41 +00008172ASTReader::ReadCXXCtorInitializers(ModuleFile &F, const RecordData &Record,
8173 unsigned &Idx) {
Guy Benyei11169dd2012-12-18 14:30:41 +00008174 unsigned NumInitializers = Record[Idx++];
Richard Smithc2bb8182015-03-24 06:36:48 +00008175 assert(NumInitializers && "wrote ctor initializers but have no inits");
8176 auto **CtorInitializers = new (Context) CXXCtorInitializer*[NumInitializers];
8177 for (unsigned i = 0; i != NumInitializers; ++i) {
8178 TypeSourceInfo *TInfo = nullptr;
8179 bool IsBaseVirtual = false;
8180 FieldDecl *Member = nullptr;
8181 IndirectFieldDecl *IndirectMember = nullptr;
Guy Benyei11169dd2012-12-18 14:30:41 +00008182
Richard Smithc2bb8182015-03-24 06:36:48 +00008183 CtorInitializerType Type = (CtorInitializerType)Record[Idx++];
8184 switch (Type) {
8185 case CTOR_INITIALIZER_BASE:
8186 TInfo = GetTypeSourceInfo(F, Record, Idx);
8187 IsBaseVirtual = Record[Idx++];
8188 break;
Guy Benyei11169dd2012-12-18 14:30:41 +00008189
Richard Smithc2bb8182015-03-24 06:36:48 +00008190 case CTOR_INITIALIZER_DELEGATING:
8191 TInfo = GetTypeSourceInfo(F, Record, Idx);
8192 break;
Guy Benyei11169dd2012-12-18 14:30:41 +00008193
Richard Smithc2bb8182015-03-24 06:36:48 +00008194 case CTOR_INITIALIZER_MEMBER:
8195 Member = ReadDeclAs<FieldDecl>(F, Record, Idx);
8196 break;
Guy Benyei11169dd2012-12-18 14:30:41 +00008197
Richard Smithc2bb8182015-03-24 06:36:48 +00008198 case CTOR_INITIALIZER_INDIRECT_MEMBER:
8199 IndirectMember = ReadDeclAs<IndirectFieldDecl>(F, Record, Idx);
8200 break;
Guy Benyei11169dd2012-12-18 14:30:41 +00008201 }
Richard Smithc2bb8182015-03-24 06:36:48 +00008202
8203 SourceLocation MemberOrEllipsisLoc = ReadSourceLocation(F, Record, Idx);
8204 Expr *Init = ReadExpr(F);
8205 SourceLocation LParenLoc = ReadSourceLocation(F, Record, Idx);
8206 SourceLocation RParenLoc = ReadSourceLocation(F, Record, Idx);
Richard Smithc2bb8182015-03-24 06:36:48 +00008207
8208 CXXCtorInitializer *BOMInit;
Richard Smith30e304e2016-12-14 00:03:17 +00008209 if (Type == CTOR_INITIALIZER_BASE)
Richard Smithc2bb8182015-03-24 06:36:48 +00008210 BOMInit = new (Context)
8211 CXXCtorInitializer(Context, TInfo, IsBaseVirtual, LParenLoc, Init,
8212 RParenLoc, MemberOrEllipsisLoc);
Richard Smith30e304e2016-12-14 00:03:17 +00008213 else if (Type == CTOR_INITIALIZER_DELEGATING)
Richard Smithc2bb8182015-03-24 06:36:48 +00008214 BOMInit = new (Context)
8215 CXXCtorInitializer(Context, TInfo, LParenLoc, Init, RParenLoc);
Richard Smith30e304e2016-12-14 00:03:17 +00008216 else if (Member)
8217 BOMInit = new (Context)
8218 CXXCtorInitializer(Context, Member, MemberOrEllipsisLoc, LParenLoc,
8219 Init, RParenLoc);
8220 else
8221 BOMInit = new (Context)
8222 CXXCtorInitializer(Context, IndirectMember, MemberOrEllipsisLoc,
8223 LParenLoc, Init, RParenLoc);
8224
Richard Smith418ed822016-12-14 19:45:03 +00008225 if (/*IsWritten*/Record[Idx++]) {
Richard Smith30e304e2016-12-14 00:03:17 +00008226 unsigned SourceOrder = Record[Idx++];
8227 BOMInit->setSourceOrder(SourceOrder);
Richard Smithc2bb8182015-03-24 06:36:48 +00008228 }
8229
Richard Smithc2bb8182015-03-24 06:36:48 +00008230 CtorInitializers[i] = BOMInit;
Guy Benyei11169dd2012-12-18 14:30:41 +00008231 }
8232
Richard Smithc2bb8182015-03-24 06:36:48 +00008233 return CtorInitializers;
Guy Benyei11169dd2012-12-18 14:30:41 +00008234}
8235
8236NestedNameSpecifier *
8237ASTReader::ReadNestedNameSpecifier(ModuleFile &F,
8238 const RecordData &Record, unsigned &Idx) {
8239 unsigned N = Record[Idx++];
Craig Toppera13603a2014-05-22 05:54:18 +00008240 NestedNameSpecifier *NNS = nullptr, *Prev = nullptr;
Guy Benyei11169dd2012-12-18 14:30:41 +00008241 for (unsigned I = 0; I != N; ++I) {
8242 NestedNameSpecifier::SpecifierKind Kind
8243 = (NestedNameSpecifier::SpecifierKind)Record[Idx++];
8244 switch (Kind) {
8245 case NestedNameSpecifier::Identifier: {
8246 IdentifierInfo *II = GetIdentifierInfo(F, Record, Idx);
8247 NNS = NestedNameSpecifier::Create(Context, Prev, II);
8248 break;
8249 }
8250
8251 case NestedNameSpecifier::Namespace: {
8252 NamespaceDecl *NS = ReadDeclAs<NamespaceDecl>(F, Record, Idx);
8253 NNS = NestedNameSpecifier::Create(Context, Prev, NS);
8254 break;
8255 }
8256
8257 case NestedNameSpecifier::NamespaceAlias: {
8258 NamespaceAliasDecl *Alias =ReadDeclAs<NamespaceAliasDecl>(F, Record, Idx);
8259 NNS = NestedNameSpecifier::Create(Context, Prev, Alias);
8260 break;
8261 }
8262
8263 case NestedNameSpecifier::TypeSpec:
8264 case NestedNameSpecifier::TypeSpecWithTemplate: {
8265 const Type *T = readType(F, Record, Idx).getTypePtrOrNull();
8266 if (!T)
Craig Toppera13603a2014-05-22 05:54:18 +00008267 return nullptr;
8268
Guy Benyei11169dd2012-12-18 14:30:41 +00008269 bool Template = Record[Idx++];
8270 NNS = NestedNameSpecifier::Create(Context, Prev, Template, T);
8271 break;
8272 }
8273
8274 case NestedNameSpecifier::Global: {
8275 NNS = NestedNameSpecifier::GlobalSpecifier(Context);
8276 // No associated value, and there can't be a prefix.
8277 break;
8278 }
Nikola Smiljanic67860242014-09-26 00:28:20 +00008279
8280 case NestedNameSpecifier::Super: {
8281 CXXRecordDecl *RD = ReadDeclAs<CXXRecordDecl>(F, Record, Idx);
8282 NNS = NestedNameSpecifier::SuperSpecifier(Context, RD);
8283 break;
8284 }
Guy Benyei11169dd2012-12-18 14:30:41 +00008285 }
8286 Prev = NNS;
8287 }
8288 return NNS;
8289}
8290
8291NestedNameSpecifierLoc
David L. Jonesc4808b9e2016-12-15 20:53:26 +00008292ASTReader::ReadNestedNameSpecifierLoc(ModuleFile &F, const RecordData &Record,
Guy Benyei11169dd2012-12-18 14:30:41 +00008293 unsigned &Idx) {
8294 unsigned N = Record[Idx++];
8295 NestedNameSpecifierLocBuilder Builder;
8296 for (unsigned I = 0; I != N; ++I) {
8297 NestedNameSpecifier::SpecifierKind Kind
8298 = (NestedNameSpecifier::SpecifierKind)Record[Idx++];
8299 switch (Kind) {
8300 case NestedNameSpecifier::Identifier: {
David L. Jonesc4808b9e2016-12-15 20:53:26 +00008301 IdentifierInfo *II = GetIdentifierInfo(F, Record, Idx);
Guy Benyei11169dd2012-12-18 14:30:41 +00008302 SourceRange Range = ReadSourceRange(F, Record, Idx);
8303 Builder.Extend(Context, II, Range.getBegin(), Range.getEnd());
8304 break;
8305 }
8306
8307 case NestedNameSpecifier::Namespace: {
8308 NamespaceDecl *NS = ReadDeclAs<NamespaceDecl>(F, Record, Idx);
8309 SourceRange Range = ReadSourceRange(F, Record, Idx);
8310 Builder.Extend(Context, NS, Range.getBegin(), Range.getEnd());
8311 break;
8312 }
8313
8314 case NestedNameSpecifier::NamespaceAlias: {
8315 NamespaceAliasDecl *Alias =ReadDeclAs<NamespaceAliasDecl>(F, Record, Idx);
8316 SourceRange Range = ReadSourceRange(F, Record, Idx);
8317 Builder.Extend(Context, Alias, Range.getBegin(), Range.getEnd());
8318 break;
8319 }
8320
8321 case NestedNameSpecifier::TypeSpec:
8322 case NestedNameSpecifier::TypeSpecWithTemplate: {
8323 bool Template = Record[Idx++];
8324 TypeSourceInfo *T = GetTypeSourceInfo(F, Record, Idx);
8325 if (!T)
8326 return NestedNameSpecifierLoc();
8327 SourceLocation ColonColonLoc = ReadSourceLocation(F, Record, Idx);
8328
8329 // FIXME: 'template' keyword location not saved anywhere, so we fake it.
David L. Jonesc4808b9e2016-12-15 20:53:26 +00008330 Builder.Extend(Context,
Guy Benyei11169dd2012-12-18 14:30:41 +00008331 Template? T->getTypeLoc().getBeginLoc() : SourceLocation(),
8332 T->getTypeLoc(), ColonColonLoc);
8333 break;
8334 }
8335
8336 case NestedNameSpecifier::Global: {
8337 SourceLocation ColonColonLoc = ReadSourceLocation(F, Record, Idx);
8338 Builder.MakeGlobal(Context, ColonColonLoc);
8339 break;
8340 }
Nikola Smiljanic67860242014-09-26 00:28:20 +00008341
8342 case NestedNameSpecifier::Super: {
8343 CXXRecordDecl *RD = ReadDeclAs<CXXRecordDecl>(F, Record, Idx);
8344 SourceRange Range = ReadSourceRange(F, Record, Idx);
8345 Builder.MakeSuper(Context, RD, Range.getBegin(), Range.getEnd());
8346 break;
8347 }
Guy Benyei11169dd2012-12-18 14:30:41 +00008348 }
8349 }
Nikola Smiljanic67860242014-09-26 00:28:20 +00008350
Guy Benyei11169dd2012-12-18 14:30:41 +00008351 return Builder.getWithLocInContext(Context);
8352}
8353
8354SourceRange
8355ASTReader::ReadSourceRange(ModuleFile &F, const RecordData &Record,
8356 unsigned &Idx) {
8357 SourceLocation beg = ReadSourceLocation(F, Record, Idx);
8358 SourceLocation end = ReadSourceLocation(F, Record, Idx);
8359 return SourceRange(beg, end);
8360}
8361
8362/// \brief Read an integral value
8363llvm::APInt ASTReader::ReadAPInt(const RecordData &Record, unsigned &Idx) {
8364 unsigned BitWidth = Record[Idx++];
8365 unsigned NumWords = llvm::APInt::getNumWords(BitWidth);
8366 llvm::APInt Result(BitWidth, NumWords, &Record[Idx]);
8367 Idx += NumWords;
8368 return Result;
8369}
8370
8371/// \brief Read a signed integral value
8372llvm::APSInt ASTReader::ReadAPSInt(const RecordData &Record, unsigned &Idx) {
8373 bool isUnsigned = Record[Idx++];
8374 return llvm::APSInt(ReadAPInt(Record, Idx), isUnsigned);
8375}
8376
8377/// \brief Read a floating-point value
Tim Northover178723a2013-01-22 09:46:51 +00008378llvm::APFloat ASTReader::ReadAPFloat(const RecordData &Record,
8379 const llvm::fltSemantics &Sem,
8380 unsigned &Idx) {
8381 return llvm::APFloat(Sem, ReadAPInt(Record, Idx));
Guy Benyei11169dd2012-12-18 14:30:41 +00008382}
8383
8384// \brief Read a string
8385std::string ASTReader::ReadString(const RecordData &Record, unsigned &Idx) {
8386 unsigned Len = Record[Idx++];
8387 std::string Result(Record.data() + Idx, Record.data() + Idx + Len);
8388 Idx += Len;
8389 return Result;
8390}
8391
Richard Smith7ed1bc92014-12-05 22:42:13 +00008392std::string ASTReader::ReadPath(ModuleFile &F, const RecordData &Record,
8393 unsigned &Idx) {
8394 std::string Filename = ReadString(Record, Idx);
8395 ResolveImportedPath(F, Filename);
8396 return Filename;
8397}
8398
David L. Jonesc4808b9e2016-12-15 20:53:26 +00008399VersionTuple ASTReader::ReadVersionTuple(const RecordData &Record,
Guy Benyei11169dd2012-12-18 14:30:41 +00008400 unsigned &Idx) {
8401 unsigned Major = Record[Idx++];
8402 unsigned Minor = Record[Idx++];
8403 unsigned Subminor = Record[Idx++];
8404 if (Minor == 0)
8405 return VersionTuple(Major);
8406 if (Subminor == 0)
8407 return VersionTuple(Major, Minor - 1);
8408 return VersionTuple(Major, Minor - 1, Subminor - 1);
8409}
8410
David L. Jonesc4808b9e2016-12-15 20:53:26 +00008411CXXTemporary *ASTReader::ReadCXXTemporary(ModuleFile &F,
Guy Benyei11169dd2012-12-18 14:30:41 +00008412 const RecordData &Record,
8413 unsigned &Idx) {
8414 CXXDestructorDecl *Decl = ReadDeclAs<CXXDestructorDecl>(F, Record, Idx);
8415 return CXXTemporary::Create(Context, Decl);
8416}
8417
8418DiagnosticBuilder ASTReader::Diag(unsigned DiagID) {
Argyrios Kyrtzidisdc9fdaf2013-05-24 05:44:08 +00008419 return Diag(CurrentImportLoc, DiagID);
Guy Benyei11169dd2012-12-18 14:30:41 +00008420}
8421
8422DiagnosticBuilder ASTReader::Diag(SourceLocation Loc, unsigned DiagID) {
8423 return Diags.Report(Loc, DiagID);
8424}
8425
8426/// \brief Retrieve the identifier table associated with the
8427/// preprocessor.
8428IdentifierTable &ASTReader::getIdentifierTable() {
8429 return PP.getIdentifierTable();
8430}
8431
8432/// \brief Record that the given ID maps to the given switch-case
8433/// statement.
8434void ASTReader::RecordSwitchCaseID(SwitchCase *SC, unsigned ID) {
Craig Toppera13603a2014-05-22 05:54:18 +00008435 assert((*CurrSwitchCaseStmts)[ID] == nullptr &&
Guy Benyei11169dd2012-12-18 14:30:41 +00008436 "Already have a SwitchCase with this ID");
8437 (*CurrSwitchCaseStmts)[ID] = SC;
8438}
8439
8440/// \brief Retrieve the switch-case statement with the given ID.
8441SwitchCase *ASTReader::getSwitchCaseWithID(unsigned ID) {
Craig Toppera13603a2014-05-22 05:54:18 +00008442 assert((*CurrSwitchCaseStmts)[ID] != nullptr && "No SwitchCase with this ID");
Guy Benyei11169dd2012-12-18 14:30:41 +00008443 return (*CurrSwitchCaseStmts)[ID];
8444}
8445
8446void ASTReader::ClearSwitchCaseIDs() {
8447 CurrSwitchCaseStmts->clear();
8448}
8449
8450void ASTReader::ReadComments() {
8451 std::vector<RawComment *> Comments;
Chris Lattner7fb3bef2013-01-20 00:56:42 +00008452 for (SmallVectorImpl<std::pair<BitstreamCursor,
Guy Benyei11169dd2012-12-18 14:30:41 +00008453 serialization::ModuleFile *> >::iterator
8454 I = CommentsCursors.begin(),
8455 E = CommentsCursors.end();
8456 I != E; ++I) {
Dmitri Gribenko9ee0e302014-03-27 15:40:39 +00008457 Comments.clear();
Chris Lattner7fb3bef2013-01-20 00:56:42 +00008458 BitstreamCursor &Cursor = I->first;
Guy Benyei11169dd2012-12-18 14:30:41 +00008459 serialization::ModuleFile &F = *I->second;
8460 SavedStreamPosition SavedPosition(Cursor);
8461
8462 RecordData Record;
8463 while (true) {
Chris Lattner7fb3bef2013-01-20 00:56:42 +00008464 llvm::BitstreamEntry Entry =
8465 Cursor.advanceSkippingSubblocks(BitstreamCursor::AF_DontPopBlockAtEnd);
Dmitri Gribenko9ee0e302014-03-27 15:40:39 +00008466
Chris Lattner7fb3bef2013-01-20 00:56:42 +00008467 switch (Entry.Kind) {
8468 case llvm::BitstreamEntry::SubBlock: // Handled for us already.
8469 case llvm::BitstreamEntry::Error:
8470 Error("malformed block record in AST file");
8471 return;
8472 case llvm::BitstreamEntry::EndBlock:
8473 goto NextCursor;
8474 case llvm::BitstreamEntry::Record:
8475 // The interesting case.
Guy Benyei11169dd2012-12-18 14:30:41 +00008476 break;
Guy Benyei11169dd2012-12-18 14:30:41 +00008477 }
8478
8479 // Read a record.
8480 Record.clear();
Chris Lattner0e6c9402013-01-20 02:38:54 +00008481 switch ((CommentRecordTypes)Cursor.readRecord(Entry.ID, Record)) {
Guy Benyei11169dd2012-12-18 14:30:41 +00008482 case COMMENTS_RAW_COMMENT: {
8483 unsigned Idx = 0;
8484 SourceRange SR = ReadSourceRange(F, Record, Idx);
8485 RawComment::CommentKind Kind =
8486 (RawComment::CommentKind) Record[Idx++];
8487 bool IsTrailingComment = Record[Idx++];
8488 bool IsAlmostTrailingComment = Record[Idx++];
Dmitri Gribenkoa7d16ce2013-04-10 15:35:17 +00008489 Comments.push_back(new (Context) RawComment(
8490 SR, Kind, IsTrailingComment, IsAlmostTrailingComment,
8491 Context.getLangOpts().CommentOpts.ParseAllComments));
Guy Benyei11169dd2012-12-18 14:30:41 +00008492 break;
8493 }
8494 }
8495 }
Dmitri Gribenko9ee0e302014-03-27 15:40:39 +00008496 NextCursor:
Bruno Cardoso Lopesc23af572016-12-19 21:06:06 +00008497 // De-serialized SourceLocations get negative FileIDs for other modules,
8498 // potentially invalidating the original order. Sort it again.
8499 std::sort(Comments.begin(), Comments.end(),
8500 BeforeThanCompare<RawComment>(SourceMgr));
Dmitri Gribenko9ee0e302014-03-27 15:40:39 +00008501 Context.Comments.addDeserializedComments(Comments);
Guy Benyei11169dd2012-12-18 14:30:41 +00008502 }
Guy Benyei11169dd2012-12-18 14:30:41 +00008503}
8504
Richard Smithcd45dbc2014-04-19 03:48:30 +00008505std::string ASTReader::getOwningModuleNameForDiagnostic(const Decl *D) {
8506 // If we know the owning module, use it.
Richard Smith42413142015-05-15 20:05:43 +00008507 if (Module *M = D->getImportedOwningModule())
Richard Smithcd45dbc2014-04-19 03:48:30 +00008508 return M->getFullModuleName();
8509
8510 // Otherwise, use the name of the top-level module the decl is within.
8511 if (ModuleFile *M = getOwningModuleFile(D))
8512 return M->ModuleName;
8513
8514 // Not from a module.
8515 return "";
8516}
8517
Guy Benyei11169dd2012-12-18 14:30:41 +00008518void ASTReader::finishPendingActions() {
Richard Smith851072e2014-05-19 20:59:20 +00008519 while (!PendingIdentifierInfos.empty() ||
8520 !PendingIncompleteDeclChains.empty() || !PendingDeclChains.empty() ||
Richard Smith2b9e3e32013-10-18 06:05:18 +00008521 !PendingMacroIDs.empty() || !PendingDeclContextInfos.empty() ||
Richard Smitha0ce9c42014-07-29 23:23:27 +00008522 !PendingUpdateRecords.empty()) {
Guy Benyei11169dd2012-12-18 14:30:41 +00008523 // If any identifiers with corresponding top-level declarations have
8524 // been loaded, load those declarations now.
Craig Topper79be4cd2013-07-05 04:33:53 +00008525 typedef llvm::DenseMap<IdentifierInfo *, SmallVector<Decl *, 2> >
8526 TopLevelDeclsMap;
8527 TopLevelDeclsMap TopLevelDecls;
8528
Guy Benyei11169dd2012-12-18 14:30:41 +00008529 while (!PendingIdentifierInfos.empty()) {
Douglas Gregor6168bd22013-02-18 15:53:43 +00008530 IdentifierInfo *II = PendingIdentifierInfos.back().first;
Richard Smithf0ae3c2d2014-03-28 17:31:23 +00008531 SmallVector<uint32_t, 4> DeclIDs =
8532 std::move(PendingIdentifierInfos.back().second);
Douglas Gregorcb15f082013-02-19 18:26:28 +00008533 PendingIdentifierInfos.pop_back();
Douglas Gregor6168bd22013-02-18 15:53:43 +00008534
8535 SetGloballyVisibleDecls(II, DeclIDs, &TopLevelDecls[II]);
Guy Benyei11169dd2012-12-18 14:30:41 +00008536 }
Richard Smithf0ae3c2d2014-03-28 17:31:23 +00008537
Richard Smith851072e2014-05-19 20:59:20 +00008538 // For each decl chain that we wanted to complete while deserializing, mark
8539 // it as "still needs to be completed".
8540 for (unsigned I = 0; I != PendingIncompleteDeclChains.size(); ++I) {
8541 markIncompleteDeclChain(PendingIncompleteDeclChains[I]);
8542 }
8543 PendingIncompleteDeclChains.clear();
8544
Guy Benyei11169dd2012-12-18 14:30:41 +00008545 // Load pending declaration chains.
Richard Smithd8a83712015-08-22 01:47:18 +00008546 for (unsigned I = 0; I != PendingDeclChains.size(); ++I)
Richard Smithd61d4ac2015-08-22 20:13:39 +00008547 loadPendingDeclChain(PendingDeclChains[I].first, PendingDeclChains[I].second);
Guy Benyei11169dd2012-12-18 14:30:41 +00008548 PendingDeclChains.clear();
8549
Douglas Gregor6168bd22013-02-18 15:53:43 +00008550 // Make the most recent of the top-level declarations visible.
Craig Topper79be4cd2013-07-05 04:33:53 +00008551 for (TopLevelDeclsMap::iterator TLD = TopLevelDecls.begin(),
8552 TLDEnd = TopLevelDecls.end(); TLD != TLDEnd; ++TLD) {
Douglas Gregor6168bd22013-02-18 15:53:43 +00008553 IdentifierInfo *II = TLD->first;
8554 for (unsigned I = 0, N = TLD->second.size(); I != N; ++I) {
Argyrios Kyrtzidise5edbf92013-04-26 21:33:35 +00008555 pushExternalDeclIntoScope(cast<NamedDecl>(TLD->second[I]), II);
Douglas Gregor6168bd22013-02-18 15:53:43 +00008556 }
8557 }
8558
Guy Benyei11169dd2012-12-18 14:30:41 +00008559 // Load any pending macro definitions.
8560 for (unsigned I = 0; I != PendingMacroIDs.size(); ++I) {
Argyrios Kyrtzidiseb663da2013-03-22 21:12:57 +00008561 IdentifierInfo *II = PendingMacroIDs.begin()[I].first;
8562 SmallVector<PendingMacroInfo, 2> GlobalIDs;
8563 GlobalIDs.swap(PendingMacroIDs.begin()[I].second);
8564 // Initialize the macro history from chained-PCHs ahead of module imports.
Richard Smith49f906a2014-03-01 00:08:04 +00008565 for (unsigned IDIdx = 0, NumIDs = GlobalIDs.size(); IDIdx != NumIDs;
Argyrios Kyrtzidis719736c2013-01-19 03:14:56 +00008566 ++IDIdx) {
Argyrios Kyrtzidiseb663da2013-03-22 21:12:57 +00008567 const PendingMacroInfo &Info = GlobalIDs[IDIdx];
Manman Ren11f2a472016-08-18 17:42:15 +00008568 if (!Info.M->isModule())
Argyrios Kyrtzidiseb663da2013-03-22 21:12:57 +00008569 resolvePendingMacro(II, Info);
8570 }
8571 // Handle module imports.
Richard Smith49f906a2014-03-01 00:08:04 +00008572 for (unsigned IDIdx = 0, NumIDs = GlobalIDs.size(); IDIdx != NumIDs;
Argyrios Kyrtzidiseb663da2013-03-22 21:12:57 +00008573 ++IDIdx) {
8574 const PendingMacroInfo &Info = GlobalIDs[IDIdx];
Manman Ren11f2a472016-08-18 17:42:15 +00008575 if (Info.M->isModule())
Argyrios Kyrtzidiseb663da2013-03-22 21:12:57 +00008576 resolvePendingMacro(II, Info);
Guy Benyei11169dd2012-12-18 14:30:41 +00008577 }
8578 }
8579 PendingMacroIDs.clear();
Argyrios Kyrtzidis83a6e3b2013-02-16 00:48:59 +00008580
8581 // Wire up the DeclContexts for Decls that we delayed setting until
8582 // recursive loading is completed.
8583 while (!PendingDeclContextInfos.empty()) {
8584 PendingDeclContextInfo Info = PendingDeclContextInfos.front();
8585 PendingDeclContextInfos.pop_front();
8586 DeclContext *SemaDC = cast<DeclContext>(GetDecl(Info.SemaDC));
8587 DeclContext *LexicalDC = cast<DeclContext>(GetDecl(Info.LexicalDC));
8588 Info.D->setDeclContextsImpl(SemaDC, LexicalDC, getContext());
8589 }
Richard Smith2b9e3e32013-10-18 06:05:18 +00008590
Richard Smithd1c46742014-04-30 02:24:17 +00008591 // Perform any pending declaration updates.
Richard Smithd6db68c2014-08-07 20:58:41 +00008592 while (!PendingUpdateRecords.empty()) {
Richard Smithd1c46742014-04-30 02:24:17 +00008593 auto Update = PendingUpdateRecords.pop_back_val();
8594 ReadingKindTracker ReadingKind(Read_Decl, *this);
8595 loadDeclUpdateRecords(Update.first, Update.second);
8596 }
Guy Benyei11169dd2012-12-18 14:30:41 +00008597 }
Richard Smith8a639892015-01-24 01:07:20 +00008598
8599 // At this point, all update records for loaded decls are in place, so any
8600 // fake class definitions should have become real.
8601 assert(PendingFakeDefinitionData.empty() &&
8602 "faked up a class definition but never saw the real one");
8603
Guy Benyei11169dd2012-12-18 14:30:41 +00008604 // If we deserialized any C++ or Objective-C class definitions, any
8605 // Objective-C protocol definitions, or any redeclarable templates, make sure
David L. Jonesc4808b9e2016-12-15 20:53:26 +00008606 // that all redeclarations point to the definitions. Note that this can only
Guy Benyei11169dd2012-12-18 14:30:41 +00008607 // happen now, after the redeclaration chains have been fully wired.
Craig Topperc6914d02014-08-25 04:15:02 +00008608 for (Decl *D : PendingDefinitions) {
8609 if (TagDecl *TD = dyn_cast<TagDecl>(D)) {
Richard Smith5b21db82014-04-23 18:20:42 +00008610 if (const TagType *TagT = dyn_cast<TagType>(TD->getTypeForDecl())) {
Guy Benyei11169dd2012-12-18 14:30:41 +00008611 // Make sure that the TagType points at the definition.
8612 const_cast<TagType*>(TagT)->decl = TD;
8613 }
Richard Smith8ce51082015-03-11 01:44:51 +00008614
Craig Topperc6914d02014-08-25 04:15:02 +00008615 if (auto RD = dyn_cast<CXXRecordDecl>(D)) {
Richard Smith8ce51082015-03-11 01:44:51 +00008616 for (auto *R = getMostRecentExistingDecl(RD); R;
8617 R = R->getPreviousDecl()) {
8618 assert((R == D) ==
8619 cast<CXXRecordDecl>(R)->isThisDeclarationADefinition() &&
Richard Smith2c381642014-08-27 23:11:59 +00008620 "declaration thinks it's the definition but it isn't");
Aaron Ballman86c93902014-03-06 23:45:36 +00008621 cast<CXXRecordDecl>(R)->DefinitionData = RD->DefinitionData;
Richard Smith2c381642014-08-27 23:11:59 +00008622 }
Guy Benyei11169dd2012-12-18 14:30:41 +00008623 }
8624
8625 continue;
8626 }
Richard Smith8ce51082015-03-11 01:44:51 +00008627
Craig Topperc6914d02014-08-25 04:15:02 +00008628 if (auto ID = dyn_cast<ObjCInterfaceDecl>(D)) {
Guy Benyei11169dd2012-12-18 14:30:41 +00008629 // Make sure that the ObjCInterfaceType points at the definition.
8630 const_cast<ObjCInterfaceType *>(cast<ObjCInterfaceType>(ID->TypeForDecl))
8631 ->Decl = ID;
Richard Smith8ce51082015-03-11 01:44:51 +00008632
8633 for (auto *R = getMostRecentExistingDecl(ID); R; R = R->getPreviousDecl())
8634 cast<ObjCInterfaceDecl>(R)->Data = ID->Data;
8635
Guy Benyei11169dd2012-12-18 14:30:41 +00008636 continue;
8637 }
Richard Smith8ce51082015-03-11 01:44:51 +00008638
Craig Topperc6914d02014-08-25 04:15:02 +00008639 if (auto PD = dyn_cast<ObjCProtocolDecl>(D)) {
Richard Smith8ce51082015-03-11 01:44:51 +00008640 for (auto *R = getMostRecentExistingDecl(PD); R; R = R->getPreviousDecl())
8641 cast<ObjCProtocolDecl>(R)->Data = PD->Data;
8642
Guy Benyei11169dd2012-12-18 14:30:41 +00008643 continue;
8644 }
Richard Smith8ce51082015-03-11 01:44:51 +00008645
Craig Topperc6914d02014-08-25 04:15:02 +00008646 auto RTD = cast<RedeclarableTemplateDecl>(D)->getCanonicalDecl();
Richard Smith8ce51082015-03-11 01:44:51 +00008647 for (auto *R = getMostRecentExistingDecl(RTD); R; R = R->getPreviousDecl())
8648 cast<RedeclarableTemplateDecl>(R)->Common = RTD->Common;
Guy Benyei11169dd2012-12-18 14:30:41 +00008649 }
8650 PendingDefinitions.clear();
8651
8652 // Load the bodies of any functions or methods we've encountered. We do
8653 // this now (delayed) so that we can be sure that the declaration chains
Richard Smithb9fa9962015-08-21 03:04:33 +00008654 // have been fully wired up (hasBody relies on this).
8655 // FIXME: We shouldn't require complete redeclaration chains here.
Guy Benyei11169dd2012-12-18 14:30:41 +00008656 for (PendingBodiesMap::iterator PB = PendingBodies.begin(),
8657 PBEnd = PendingBodies.end();
8658 PB != PBEnd; ++PB) {
8659 if (FunctionDecl *FD = dyn_cast<FunctionDecl>(PB->first)) {
8660 // FIXME: Check for =delete/=default?
8661 // FIXME: Complain about ODR violations here?
Richard Smith6561f922016-09-12 21:06:40 +00008662 const FunctionDecl *Defn = nullptr;
8663 if (!getContext().getLangOpts().Modules || !FD->hasBody(Defn))
Guy Benyei11169dd2012-12-18 14:30:41 +00008664 FD->setLazyBody(PB->second);
Benjamin Kramera72a70a2016-10-17 13:00:44 +00008665 else
Richard Smith6561f922016-09-12 21:06:40 +00008666 mergeDefinitionVisibility(const_cast<FunctionDecl*>(Defn), FD);
Guy Benyei11169dd2012-12-18 14:30:41 +00008667 continue;
8668 }
8669
8670 ObjCMethodDecl *MD = cast<ObjCMethodDecl>(PB->first);
8671 if (!getContext().getLangOpts().Modules || !MD->hasBody())
8672 MD->setLazyBody(PB->second);
8673 }
8674 PendingBodies.clear();
Richard Smith42413142015-05-15 20:05:43 +00008675
8676 // Do some cleanup.
8677 for (auto *ND : PendingMergedDefinitionsToDeduplicate)
8678 getContext().deduplicateMergedDefinitonsFor(ND);
8679 PendingMergedDefinitionsToDeduplicate.clear();
Richard Smitha0ce9c42014-07-29 23:23:27 +00008680}
8681
8682void ASTReader::diagnoseOdrViolations() {
Richard Smithbb853c72014-08-13 01:23:33 +00008683 if (PendingOdrMergeFailures.empty() && PendingOdrMergeChecks.empty())
8684 return;
8685
Richard Smitha0ce9c42014-07-29 23:23:27 +00008686 // Trigger the import of the full definition of each class that had any
8687 // odr-merging problems, so we can produce better diagnostics for them.
Richard Smithbb853c72014-08-13 01:23:33 +00008688 // These updates may in turn find and diagnose some ODR failures, so take
8689 // ownership of the set first.
8690 auto OdrMergeFailures = std::move(PendingOdrMergeFailures);
8691 PendingOdrMergeFailures.clear();
8692 for (auto &Merge : OdrMergeFailures) {
Richard Smitha0ce9c42014-07-29 23:23:27 +00008693 Merge.first->buildLookup();
8694 Merge.first->decls_begin();
8695 Merge.first->bases_begin();
8696 Merge.first->vbases_begin();
8697 for (auto *RD : Merge.second) {
8698 RD->decls_begin();
8699 RD->bases_begin();
8700 RD->vbases_begin();
8701 }
8702 }
8703
8704 // For each declaration from a merged context, check that the canonical
8705 // definition of that context also contains a declaration of the same
8706 // entity.
8707 //
8708 // Caution: this loop does things that might invalidate iterators into
8709 // PendingOdrMergeChecks. Don't turn this into a range-based for loop!
8710 while (!PendingOdrMergeChecks.empty()) {
8711 NamedDecl *D = PendingOdrMergeChecks.pop_back_val();
8712
8713 // FIXME: Skip over implicit declarations for now. This matters for things
8714 // like implicitly-declared special member functions. This isn't entirely
8715 // correct; we can end up with multiple unmerged declarations of the same
8716 // implicit entity.
8717 if (D->isImplicit())
8718 continue;
8719
8720 DeclContext *CanonDef = D->getDeclContext();
Richard Smitha0ce9c42014-07-29 23:23:27 +00008721
8722 bool Found = false;
8723 const Decl *DCanon = D->getCanonicalDecl();
8724
Richard Smith01bdb7a2014-08-28 05:44:07 +00008725 for (auto RI : D->redecls()) {
8726 if (RI->getLexicalDeclContext() == CanonDef) {
8727 Found = true;
8728 break;
8729 }
8730 }
8731 if (Found)
8732 continue;
8733
Richard Smith0f4e2c42015-08-06 04:23:48 +00008734 // Quick check failed, time to do the slow thing. Note, we can't just
8735 // look up the name of D in CanonDef here, because the member that is
8736 // in CanonDef might not be found by name lookup (it might have been
8737 // replaced by a more recent declaration in the lookup table), and we
8738 // can't necessarily find it in the redeclaration chain because it might
8739 // be merely mergeable, not redeclarable.
Richard Smitha0ce9c42014-07-29 23:23:27 +00008740 llvm::SmallVector<const NamedDecl*, 4> Candidates;
Richard Smith0f4e2c42015-08-06 04:23:48 +00008741 for (auto *CanonMember : CanonDef->decls()) {
8742 if (CanonMember->getCanonicalDecl() == DCanon) {
8743 // This can happen if the declaration is merely mergeable and not
8744 // actually redeclarable (we looked for redeclarations earlier).
8745 //
8746 // FIXME: We should be able to detect this more efficiently, without
8747 // pulling in all of the members of CanonDef.
8748 Found = true;
8749 break;
Richard Smitha0ce9c42014-07-29 23:23:27 +00008750 }
Richard Smith0f4e2c42015-08-06 04:23:48 +00008751 if (auto *ND = dyn_cast<NamedDecl>(CanonMember))
8752 if (ND->getDeclName() == D->getDeclName())
8753 Candidates.push_back(ND);
Richard Smitha0ce9c42014-07-29 23:23:27 +00008754 }
8755
8756 if (!Found) {
Richard Smithd08aeb62014-08-28 01:33:39 +00008757 // The AST doesn't like TagDecls becoming invalid after they've been
8758 // completed. We only really need to mark FieldDecls as invalid here.
8759 if (!isa<TagDecl>(D))
8760 D->setInvalidDecl();
David L. Jonesc4808b9e2016-12-15 20:53:26 +00008761
Richard Smith4ab3dbd2015-02-13 22:43:51 +00008762 // Ensure we don't accidentally recursively enter deserialization while
8763 // we're producing our diagnostic.
8764 Deserializing RecursionGuard(this);
Richard Smitha0ce9c42014-07-29 23:23:27 +00008765
8766 std::string CanonDefModule =
8767 getOwningModuleNameForDiagnostic(cast<Decl>(CanonDef));
8768 Diag(D->getLocation(), diag::err_module_odr_violation_missing_decl)
8769 << D << getOwningModuleNameForDiagnostic(D)
8770 << CanonDef << CanonDefModule.empty() << CanonDefModule;
8771
8772 if (Candidates.empty())
8773 Diag(cast<Decl>(CanonDef)->getLocation(),
8774 diag::note_module_odr_violation_no_possible_decls) << D;
8775 else {
8776 for (unsigned I = 0, N = Candidates.size(); I != N; ++I)
8777 Diag(Candidates[I]->getLocation(),
8778 diag::note_module_odr_violation_possible_decl)
8779 << Candidates[I];
8780 }
8781
8782 DiagnosedOdrMergeFailures.insert(CanonDef);
8783 }
8784 }
Richard Smithcd45dbc2014-04-19 03:48:30 +00008785
Richard Smith4ab3dbd2015-02-13 22:43:51 +00008786 if (OdrMergeFailures.empty())
8787 return;
8788
8789 // Ensure we don't accidentally recursively enter deserialization while
8790 // we're producing our diagnostics.
8791 Deserializing RecursionGuard(this);
8792
Richard Smithcd45dbc2014-04-19 03:48:30 +00008793 // Issue any pending ODR-failure diagnostics.
Richard Smithbb853c72014-08-13 01:23:33 +00008794 for (auto &Merge : OdrMergeFailures) {
Richard Smitha0ce9c42014-07-29 23:23:27 +00008795 // If we've already pointed out a specific problem with this class, don't
8796 // bother issuing a general "something's different" diagnostic.
David Blaikie82e95a32014-11-19 07:49:47 +00008797 if (!DiagnosedOdrMergeFailures.insert(Merge.first).second)
Richard Smithcd45dbc2014-04-19 03:48:30 +00008798 continue;
8799
8800 bool Diagnosed = false;
8801 for (auto *RD : Merge.second) {
8802 // Multiple different declarations got merged together; tell the user
8803 // where they came from.
8804 if (Merge.first != RD) {
8805 // FIXME: Walk the definition, figure out what's different,
8806 // and diagnose that.
8807 if (!Diagnosed) {
8808 std::string Module = getOwningModuleNameForDiagnostic(Merge.first);
8809 Diag(Merge.first->getLocation(),
8810 diag::err_module_odr_violation_different_definitions)
8811 << Merge.first << Module.empty() << Module;
8812 Diagnosed = true;
8813 }
8814
8815 Diag(RD->getLocation(),
8816 diag::note_module_odr_violation_different_definitions)
8817 << getOwningModuleNameForDiagnostic(RD);
8818 }
8819 }
8820
8821 if (!Diagnosed) {
8822 // All definitions are updates to the same declaration. This happens if a
8823 // module instantiates the declaration of a class template specialization
8824 // and two or more other modules instantiate its definition.
8825 //
8826 // FIXME: Indicate which modules had instantiations of this definition.
8827 // FIXME: How can this even happen?
8828 Diag(Merge.first->getLocation(),
8829 diag::err_module_odr_violation_different_instantiations)
8830 << Merge.first;
8831 }
8832 }
Guy Benyei11169dd2012-12-18 14:30:41 +00008833}
8834
Richard Smithce18a182015-07-14 00:26:00 +00008835void ASTReader::StartedDeserializing() {
David L. Jonesc4808b9e2016-12-15 20:53:26 +00008836 if (++NumCurrentElementsDeserializing == 1 && ReadTimer.get())
Richard Smithce18a182015-07-14 00:26:00 +00008837 ReadTimer->startTimer();
8838}
8839
Guy Benyei11169dd2012-12-18 14:30:41 +00008840void ASTReader::FinishedDeserializing() {
8841 assert(NumCurrentElementsDeserializing &&
8842 "FinishedDeserializing not paired with StartedDeserializing");
8843 if (NumCurrentElementsDeserializing == 1) {
8844 // We decrease NumCurrentElementsDeserializing only after pending actions
8845 // are finished, to avoid recursively re-calling finishPendingActions().
8846 finishPendingActions();
8847 }
8848 --NumCurrentElementsDeserializing;
8849
Richard Smitha0ce9c42014-07-29 23:23:27 +00008850 if (NumCurrentElementsDeserializing == 0) {
Richard Smith9e2341d2015-03-23 03:25:59 +00008851 // Propagate exception specification updates along redeclaration chains.
Richard Smith7226f2a2015-03-23 19:54:56 +00008852 while (!PendingExceptionSpecUpdates.empty()) {
8853 auto Updates = std::move(PendingExceptionSpecUpdates);
8854 PendingExceptionSpecUpdates.clear();
8855 for (auto Update : Updates) {
Vassil Vassilev19765fb2016-07-22 21:08:24 +00008856 ProcessingUpdatesRAIIObj ProcessingUpdates(*this);
Richard Smith7226f2a2015-03-23 19:54:56 +00008857 auto *FPT = Update.second->getType()->castAs<FunctionProtoType>();
Richard Smith1d0f1992015-08-19 21:09:32 +00008858 auto ESI = FPT->getExtProtoInfo().ExceptionSpec;
Richard Smithd88a7f12015-09-01 20:35:42 +00008859 if (auto *Listener = Context.getASTMutationListener())
8860 Listener->ResolvedExceptionSpec(cast<FunctionDecl>(Update.second));
Richard Smith1d0f1992015-08-19 21:09:32 +00008861 for (auto *Redecl : Update.second->redecls())
8862 Context.adjustExceptionSpec(cast<FunctionDecl>(Redecl), ESI);
Richard Smith7226f2a2015-03-23 19:54:56 +00008863 }
Richard Smith9e2341d2015-03-23 03:25:59 +00008864 }
8865
Richard Smithce18a182015-07-14 00:26:00 +00008866 if (ReadTimer)
8867 ReadTimer->stopTimer();
8868
Richard Smith0f4e2c42015-08-06 04:23:48 +00008869 diagnoseOdrViolations();
8870
Richard Smith04d05b52014-03-23 00:27:18 +00008871 // We are not in recursive loading, so it's safe to pass the "interesting"
8872 // decls to the consumer.
Richard Smitha0ce9c42014-07-29 23:23:27 +00008873 if (Consumer)
8874 PassInterestingDeclsToConsumer();
Guy Benyei11169dd2012-12-18 14:30:41 +00008875 }
8876}
8877
Argyrios Kyrtzidise5edbf92013-04-26 21:33:35 +00008878void ASTReader::pushExternalDeclIntoScope(NamedDecl *D, DeclarationName Name) {
Richard Smith9e2341d2015-03-23 03:25:59 +00008879 if (IdentifierInfo *II = Name.getAsIdentifierInfo()) {
8880 // Remove any fake results before adding any real ones.
8881 auto It = PendingFakeLookupResults.find(II);
8882 if (It != PendingFakeLookupResults.end()) {
Richard Smitha534a312015-07-21 23:54:07 +00008883 for (auto *ND : It->second)
Richard Smith9e2341d2015-03-23 03:25:59 +00008884 SemaObj->IdResolver.RemoveDecl(ND);
Ben Langmuireb8bd2d2015-04-10 22:25:42 +00008885 // FIXME: this works around module+PCH performance issue.
8886 // Rather than erase the result from the map, which is O(n), just clear
8887 // the vector of NamedDecls.
8888 It->second.clear();
Richard Smith9e2341d2015-03-23 03:25:59 +00008889 }
8890 }
Argyrios Kyrtzidise5edbf92013-04-26 21:33:35 +00008891
8892 if (SemaObj->IdResolver.tryAddTopLevelDecl(D, Name) && SemaObj->TUScope) {
8893 SemaObj->TUScope->AddDecl(D);
8894 } else if (SemaObj->TUScope) {
8895 // Adding the decl to IdResolver may have failed because it was already in
8896 // (even though it was not added in scope). If it is already in, make sure
8897 // it gets in the scope as well.
8898 if (std::find(SemaObj->IdResolver.begin(Name),
8899 SemaObj->IdResolver.end(), D) != SemaObj->IdResolver.end())
8900 SemaObj->TUScope->AddDecl(D);
8901 }
8902}
8903
David Blaikie61137e12017-01-05 18:23:18 +00008904ASTReader::ASTReader(Preprocessor &PP, ASTContext &Context,
8905 const PCHContainerReader &PCHContainerRdr,
8906 ArrayRef<std::shared_ptr<ModuleFileExtension>> Extensions,
8907 StringRef isysroot, bool DisableValidation,
8908 bool AllowASTWithCompilerErrors,
8909 bool AllowConfigurationMismatch, bool ValidateSystemInputs,
8910 bool UseGlobalIndex,
8911 std::unique_ptr<llvm::Timer> ReadTimer)
8912 : Listener(DisableValidation
8913 ? cast<ASTReaderListener>(new SimpleASTReaderListener(PP))
8914 : cast<ASTReaderListener>(new PCHValidator(PP, *this))),
David Blaikie61137e12017-01-05 18:23:18 +00008915 SourceMgr(PP.getSourceManager()), FileMgr(PP.getFileManager()),
David Blaikie9d7c1ba2017-01-05 18:45:43 +00008916 PCHContainerRdr(PCHContainerRdr), Diags(PP.getDiagnostics()), PP(PP),
8917 Context(Context), ModuleMgr(PP.getFileManager(), PCHContainerRdr),
8918 DummyIdResolver(PP), ReadTimer(std::move(ReadTimer)), isysroot(isysroot),
David Blaikie61137e12017-01-05 18:23:18 +00008919 DisableValidation(DisableValidation),
Nico Weber824285e2014-05-08 04:26:47 +00008920 AllowASTWithCompilerErrors(AllowASTWithCompilerErrors),
8921 AllowConfigurationMismatch(AllowConfigurationMismatch),
8922 ValidateSystemInputs(ValidateSystemInputs),
David Blaikie9d7c1ba2017-01-05 18:45:43 +00008923 UseGlobalIndex(UseGlobalIndex), CurrSwitchCaseStmts(&SwitchCaseStmts) {
Guy Benyei11169dd2012-12-18 14:30:41 +00008924 SourceMgr.setExternalSLocEntrySource(this);
Douglas Gregor6623e1f2015-11-03 18:33:07 +00008925
8926 for (const auto &Ext : Extensions) {
8927 auto BlockName = Ext->getExtensionMetadata().BlockName;
8928 auto Known = ModuleFileExtensions.find(BlockName);
8929 if (Known != ModuleFileExtensions.end()) {
8930 Diags.Report(diag::warn_duplicate_module_file_extension)
8931 << BlockName;
8932 continue;
8933 }
8934
8935 ModuleFileExtensions.insert({BlockName, Ext});
8936 }
Guy Benyei11169dd2012-12-18 14:30:41 +00008937}
8938
8939ASTReader::~ASTReader() {
Nico Weber824285e2014-05-08 04:26:47 +00008940 if (OwnsDeserializationListener)
8941 delete DeserializationListener;
Guy Benyei11169dd2012-12-18 14:30:41 +00008942}
Richard Smith10379092016-05-06 23:14:07 +00008943
8944IdentifierResolver &ASTReader::getIdResolver() {
8945 return SemaObj ? SemaObj->IdResolver : DummyIdResolver;
8946}
David L. Jonesbe1557a2016-12-21 00:17:49 +00008947
8948unsigned ASTRecordReader::readRecord(llvm::BitstreamCursor &Cursor,
8949 unsigned AbbrevID) {
8950 Idx = 0;
8951 Record.clear();
8952 return Cursor.readRecord(AbbrevID, Record);
8953}