blob: 452f5410a8cdaa890bca2558c867125885c11670 [file] [log] [blame]
Eugene Zelenkoe95e7d52016-09-07 21:53:17 +00001//===-- ASTReader.cpp - AST File Reader -----------------------------------===//
Guy Benyei11169dd2012-12-18 14:30:41 +00002//
3// The LLVM Compiler Infrastructure
4//
5// This file is distributed under the University of Illinois Open Source
6// License. See LICENSE.TXT for details.
7//
8//===----------------------------------------------------------------------===//
9//
10// This file defines the ASTReader class, which reads AST files.
11//
12//===----------------------------------------------------------------------===//
13
14#include "clang/Serialization/ASTReader.h"
15#include "ASTCommon.h"
16#include "ASTReaderInternals.h"
17#include "clang/AST/ASTConsumer.h"
18#include "clang/AST/ASTContext.h"
Eugene Zelenkoe95e7d52016-09-07 21:53:17 +000019#include "clang/AST/ASTMutationListener.h"
20#include "clang/AST/ASTUnresolvedSet.h"
21#include "clang/AST/Decl.h"
22#include "clang/AST/DeclCXX.h"
23#include "clang/AST/DeclGroup.h"
24#include "clang/AST/DeclObjC.h"
Guy Benyei11169dd2012-12-18 14:30:41 +000025#include "clang/AST/DeclTemplate.h"
26#include "clang/AST/Expr.h"
27#include "clang/AST/ExprCXX.h"
28#include "clang/AST/NestedNameSpecifier.h"
Eugene Zelenkoe95e7d52016-09-07 21:53:17 +000029#include "clang/AST/RawCommentList.h"
Guy Benyei11169dd2012-12-18 14:30:41 +000030#include "clang/AST/Type.h"
31#include "clang/AST/TypeLocVisitor.h"
Eugene Zelenkoe95e7d52016-09-07 21:53:17 +000032#include "clang/AST/UnresolvedSet.h"
33#include "clang/Basic/CommentOptions.h"
Benjamin Kramerf3ca26982014-05-10 16:31:55 +000034#include "clang/Basic/DiagnosticOptions.h"
Eugene Zelenkoe95e7d52016-09-07 21:53:17 +000035#include "clang/Basic/ExceptionSpecificationType.h"
Guy Benyei11169dd2012-12-18 14:30:41 +000036#include "clang/Basic/FileManager.h"
Eugene Zelenkoe95e7d52016-09-07 21:53:17 +000037#include "clang/Basic/FileSystemOptions.h"
38#include "clang/Basic/LangOptions.h"
39#include "clang/Basic/ObjCRuntime.h"
40#include "clang/Basic/OperatorKinds.h"
41#include "clang/Basic/Sanitizers.h"
Guy Benyei11169dd2012-12-18 14:30:41 +000042#include "clang/Basic/SourceManager.h"
43#include "clang/Basic/SourceManagerInternals.h"
Eugene Zelenkoe95e7d52016-09-07 21:53:17 +000044#include "clang/Basic/Specifiers.h"
Guy Benyei11169dd2012-12-18 14:30:41 +000045#include "clang/Basic/TargetInfo.h"
46#include "clang/Basic/TargetOptions.h"
Eugene Zelenkoe95e7d52016-09-07 21:53:17 +000047#include "clang/Basic/TokenKinds.h"
Guy Benyei11169dd2012-12-18 14:30:41 +000048#include "clang/Basic/Version.h"
49#include "clang/Basic/VersionTuple.h"
Eugene Zelenkoe95e7d52016-09-07 21:53:17 +000050#include "clang/Frontend/PCHContainerOperations.h"
Guy Benyei11169dd2012-12-18 14:30:41 +000051#include "clang/Lex/HeaderSearch.h"
52#include "clang/Lex/HeaderSearchOptions.h"
53#include "clang/Lex/MacroInfo.h"
Eugene Zelenkoe95e7d52016-09-07 21:53:17 +000054#include "clang/Lex/ModuleMap.h"
Guy Benyei11169dd2012-12-18 14:30:41 +000055#include "clang/Lex/PreprocessingRecord.h"
56#include "clang/Lex/Preprocessor.h"
57#include "clang/Lex/PreprocessorOptions.h"
58#include "clang/Sema/Scope.h"
59#include "clang/Sema/Sema.h"
Eugene Zelenkoe95e7d52016-09-07 21:53:17 +000060#include "clang/Sema/Weak.h"
Guy Benyei11169dd2012-12-18 14:30:41 +000061#include "clang/Serialization/ASTDeserializationListener.h"
Douglas Gregore060e572013-01-25 01:03:03 +000062#include "clang/Serialization/GlobalModuleIndex.h"
Guy Benyei11169dd2012-12-18 14:30:41 +000063#include "clang/Serialization/ModuleManager.h"
64#include "clang/Serialization/SerializationDiagnostic.h"
Eugene Zelenkoe95e7d52016-09-07 21:53:17 +000065#include "llvm/ADT/APFloat.h"
66#include "llvm/ADT/APInt.h"
67#include "llvm/ADT/APSInt.h"
Argyrios Kyrtzidis5c2a3452013-03-06 18:12:47 +000068#include "llvm/ADT/Hashing.h"
Eugene Zelenkoe95e7d52016-09-07 21:53:17 +000069#include "llvm/ADT/SmallString.h"
Guy Benyei11169dd2012-12-18 14:30:41 +000070#include "llvm/ADT/StringExtras.h"
Eugene Zelenkoe95e7d52016-09-07 21:53:17 +000071#include "llvm/ADT/Triple.h"
Guy Benyei11169dd2012-12-18 14:30:41 +000072#include "llvm/Bitcode/BitstreamReader.h"
Richard Smithaada85c2016-02-06 02:06:43 +000073#include "llvm/Support/Compression.h"
Eugene Zelenkoe95e7d52016-09-07 21:53:17 +000074#include "llvm/Support/Compiler.h"
George Rimarc39f5492017-01-17 15:45:31 +000075#include "llvm/Support/Error.h"
Guy Benyei11169dd2012-12-18 14:30:41 +000076#include "llvm/Support/ErrorHandling.h"
77#include "llvm/Support/FileSystem.h"
78#include "llvm/Support/MemoryBuffer.h"
79#include "llvm/Support/Path.h"
80#include "llvm/Support/SaveAndRestore.h"
Dmitri Gribenkof430da42014-02-12 10:33:14 +000081#include "llvm/Support/raw_ostream.h"
Guy Benyei11169dd2012-12-18 14:30:41 +000082#include <algorithm>
Eugene Zelenkoe95e7d52016-09-07 21:53:17 +000083#include <cassert>
84#include <cstdint>
Chris Lattner91f373e2013-01-20 00:57:52 +000085#include <cstdio>
Eugene Zelenkoe95e7d52016-09-07 21:53:17 +000086#include <cstring>
87#include <ctime>
Guy Benyei11169dd2012-12-18 14:30:41 +000088#include <iterator>
Eugene Zelenkoe95e7d52016-09-07 21:53:17 +000089#include <limits>
90#include <map>
91#include <memory>
92#include <new>
93#include <string>
Rafael Espindola8a8e5542014-06-12 17:19:42 +000094#include <system_error>
Eugene Zelenkoe95e7d52016-09-07 21:53:17 +000095#include <tuple>
96#include <utility>
97#include <vector>
Guy Benyei11169dd2012-12-18 14:30:41 +000098
99using namespace clang;
100using namespace clang::serialization;
101using namespace clang::serialization::reader;
Chris Lattner7fb3bef2013-01-20 00:56:42 +0000102using llvm::BitstreamCursor;
Guy Benyei11169dd2012-12-18 14:30:41 +0000103
Ben Langmuircb69b572014-03-07 06:40:32 +0000104//===----------------------------------------------------------------------===//
105// ChainedASTReaderListener implementation
106//===----------------------------------------------------------------------===//
107
108bool
109ChainedASTReaderListener::ReadFullVersionInformation(StringRef FullVersion) {
110 return First->ReadFullVersionInformation(FullVersion) ||
111 Second->ReadFullVersionInformation(FullVersion);
112}
Eugene Zelenkoe95e7d52016-09-07 21:53:17 +0000113
Ben Langmuir4f5212a2014-04-14 22:12:44 +0000114void ChainedASTReaderListener::ReadModuleName(StringRef ModuleName) {
115 First->ReadModuleName(ModuleName);
116 Second->ReadModuleName(ModuleName);
117}
Eugene Zelenkoe95e7d52016-09-07 21:53:17 +0000118
Ben Langmuir4f5212a2014-04-14 22:12:44 +0000119void ChainedASTReaderListener::ReadModuleMapFile(StringRef ModuleMapPath) {
120 First->ReadModuleMapFile(ModuleMapPath);
121 Second->ReadModuleMapFile(ModuleMapPath);
122}
Eugene Zelenkoe95e7d52016-09-07 21:53:17 +0000123
Richard Smith1e2cf0d2014-10-31 02:28:58 +0000124bool
125ChainedASTReaderListener::ReadLanguageOptions(const LangOptions &LangOpts,
126 bool Complain,
127 bool AllowCompatibleDifferences) {
128 return First->ReadLanguageOptions(LangOpts, Complain,
129 AllowCompatibleDifferences) ||
130 Second->ReadLanguageOptions(LangOpts, Complain,
131 AllowCompatibleDifferences);
Ben Langmuircb69b572014-03-07 06:40:32 +0000132}
Eugene Zelenkoe95e7d52016-09-07 21:53:17 +0000133
Chandler Carruth0d745bc2015-03-14 04:47:43 +0000134bool ChainedASTReaderListener::ReadTargetOptions(
135 const TargetOptions &TargetOpts, bool Complain,
136 bool AllowCompatibleDifferences) {
137 return First->ReadTargetOptions(TargetOpts, Complain,
138 AllowCompatibleDifferences) ||
139 Second->ReadTargetOptions(TargetOpts, Complain,
140 AllowCompatibleDifferences);
Ben Langmuircb69b572014-03-07 06:40:32 +0000141}
Eugene Zelenkoe95e7d52016-09-07 21:53:17 +0000142
Ben Langmuircb69b572014-03-07 06:40:32 +0000143bool ChainedASTReaderListener::ReadDiagnosticOptions(
Ben Langmuirb92de022014-04-29 16:25:26 +0000144 IntrusiveRefCntPtr<DiagnosticOptions> DiagOpts, bool Complain) {
Ben Langmuircb69b572014-03-07 06:40:32 +0000145 return First->ReadDiagnosticOptions(DiagOpts, Complain) ||
146 Second->ReadDiagnosticOptions(DiagOpts, Complain);
147}
Eugene Zelenkoe95e7d52016-09-07 21:53:17 +0000148
Ben Langmuircb69b572014-03-07 06:40:32 +0000149bool
150ChainedASTReaderListener::ReadFileSystemOptions(const FileSystemOptions &FSOpts,
151 bool Complain) {
152 return First->ReadFileSystemOptions(FSOpts, Complain) ||
153 Second->ReadFileSystemOptions(FSOpts, Complain);
154}
155
156bool ChainedASTReaderListener::ReadHeaderSearchOptions(
Argyrios Kyrtzidisbd0b6512015-02-19 20:12:20 +0000157 const HeaderSearchOptions &HSOpts, StringRef SpecificModuleCachePath,
158 bool Complain) {
159 return First->ReadHeaderSearchOptions(HSOpts, SpecificModuleCachePath,
160 Complain) ||
161 Second->ReadHeaderSearchOptions(HSOpts, SpecificModuleCachePath,
162 Complain);
Ben Langmuircb69b572014-03-07 06:40:32 +0000163}
Eugene Zelenkoe95e7d52016-09-07 21:53:17 +0000164
Ben Langmuircb69b572014-03-07 06:40:32 +0000165bool ChainedASTReaderListener::ReadPreprocessorOptions(
166 const PreprocessorOptions &PPOpts, bool Complain,
167 std::string &SuggestedPredefines) {
168 return First->ReadPreprocessorOptions(PPOpts, Complain,
169 SuggestedPredefines) ||
170 Second->ReadPreprocessorOptions(PPOpts, Complain, SuggestedPredefines);
171}
172void ChainedASTReaderListener::ReadCounter(const serialization::ModuleFile &M,
173 unsigned Value) {
174 First->ReadCounter(M, Value);
175 Second->ReadCounter(M, Value);
176}
177bool ChainedASTReaderListener::needsInputFileVisitation() {
178 return First->needsInputFileVisitation() ||
179 Second->needsInputFileVisitation();
180}
181bool ChainedASTReaderListener::needsSystemInputFileVisitation() {
182 return First->needsSystemInputFileVisitation() ||
183 Second->needsSystemInputFileVisitation();
184}
Richard Smith216a3bd2015-08-13 17:57:10 +0000185void ChainedASTReaderListener::visitModuleFile(StringRef Filename,
186 ModuleKind Kind) {
187 First->visitModuleFile(Filename, Kind);
188 Second->visitModuleFile(Filename, Kind);
Argyrios Kyrtzidis6d0753d2014-03-14 03:07:38 +0000189}
Eugene Zelenkoe95e7d52016-09-07 21:53:17 +0000190
Ben Langmuircb69b572014-03-07 06:40:32 +0000191bool ChainedASTReaderListener::visitInputFile(StringRef Filename,
Argyrios Kyrtzidis68ccbe02014-03-14 02:26:31 +0000192 bool isSystem,
Richard Smith216a3bd2015-08-13 17:57:10 +0000193 bool isOverridden,
194 bool isExplicitModule) {
Justin Bognerc65a66d2014-05-22 06:04:59 +0000195 bool Continue = false;
196 if (First->needsInputFileVisitation() &&
197 (!isSystem || First->needsSystemInputFileVisitation()))
Richard Smith216a3bd2015-08-13 17:57:10 +0000198 Continue |= First->visitInputFile(Filename, isSystem, isOverridden,
199 isExplicitModule);
Justin Bognerc65a66d2014-05-22 06:04:59 +0000200 if (Second->needsInputFileVisitation() &&
201 (!isSystem || Second->needsSystemInputFileVisitation()))
Richard Smith216a3bd2015-08-13 17:57:10 +0000202 Continue |= Second->visitInputFile(Filename, isSystem, isOverridden,
203 isExplicitModule);
Justin Bognerc65a66d2014-05-22 06:04:59 +0000204 return Continue;
Ben Langmuircb69b572014-03-07 06:40:32 +0000205}
206
Douglas Gregor6623e1f2015-11-03 18:33:07 +0000207void ChainedASTReaderListener::readModuleFileExtension(
208 const ModuleFileExtensionMetadata &Metadata) {
209 First->readModuleFileExtension(Metadata);
210 Second->readModuleFileExtension(Metadata);
211}
212
Guy Benyei11169dd2012-12-18 14:30:41 +0000213//===----------------------------------------------------------------------===//
214// PCH validator implementation
215//===----------------------------------------------------------------------===//
216
Angel Garcia Gomez637d1e62015-10-20 13:23:58 +0000217ASTReaderListener::~ASTReaderListener() {}
Guy Benyei11169dd2012-12-18 14:30:41 +0000218
219/// \brief Compare the given set of language options against an existing set of
220/// language options.
221///
222/// \param Diags If non-NULL, diagnostics will be emitted via this engine.
Richard Smith1e2cf0d2014-10-31 02:28:58 +0000223/// \param AllowCompatibleDifferences If true, differences between compatible
224/// language options will be permitted.
Guy Benyei11169dd2012-12-18 14:30:41 +0000225///
226/// \returns true if the languagae options mis-match, false otherwise.
227static bool checkLanguageOptions(const LangOptions &LangOpts,
228 const LangOptions &ExistingLangOpts,
Richard Smith1e2cf0d2014-10-31 02:28:58 +0000229 DiagnosticsEngine *Diags,
230 bool AllowCompatibleDifferences = true) {
Guy Benyei11169dd2012-12-18 14:30:41 +0000231#define LANGOPT(Name, Bits, Default, Description) \
232 if (ExistingLangOpts.Name != LangOpts.Name) { \
233 if (Diags) \
234 Diags->Report(diag::err_pch_langopt_mismatch) \
235 << Description << LangOpts.Name << ExistingLangOpts.Name; \
236 return true; \
237 }
238
239#define VALUE_LANGOPT(Name, Bits, Default, Description) \
240 if (ExistingLangOpts.Name != LangOpts.Name) { \
241 if (Diags) \
242 Diags->Report(diag::err_pch_langopt_value_mismatch) \
243 << Description; \
244 return true; \
245 }
246
247#define ENUM_LANGOPT(Name, Type, Bits, Default, Description) \
248 if (ExistingLangOpts.get##Name() != LangOpts.get##Name()) { \
249 if (Diags) \
250 Diags->Report(diag::err_pch_langopt_value_mismatch) \
251 << Description; \
252 return true; \
253 }
254
Richard Smith1e2cf0d2014-10-31 02:28:58 +0000255#define COMPATIBLE_LANGOPT(Name, Bits, Default, Description) \
256 if (!AllowCompatibleDifferences) \
257 LANGOPT(Name, Bits, Default, Description)
258
259#define COMPATIBLE_ENUM_LANGOPT(Name, Bits, Default, Description) \
260 if (!AllowCompatibleDifferences) \
261 ENUM_LANGOPT(Name, Bits, Default, Description)
262
Richard Smitha1ddf5e2016-04-07 20:47:37 +0000263#define COMPATIBLE_VALUE_LANGOPT(Name, Bits, Default, Description) \
264 if (!AllowCompatibleDifferences) \
265 VALUE_LANGOPT(Name, Bits, Default, Description)
266
Guy Benyei11169dd2012-12-18 14:30:41 +0000267#define BENIGN_LANGOPT(Name, Bits, Default, Description)
268#define BENIGN_ENUM_LANGOPT(Name, Type, Bits, Default, Description)
Richard Smitha1ddf5e2016-04-07 20:47:37 +0000269#define BENIGN_VALUE_LANGOPT(Name, Type, Bits, Default, Description)
Guy Benyei11169dd2012-12-18 14:30:41 +0000270#include "clang/Basic/LangOptions.def"
271
Ben Langmuircd98cb72015-06-23 18:20:18 +0000272 if (ExistingLangOpts.ModuleFeatures != LangOpts.ModuleFeatures) {
273 if (Diags)
274 Diags->Report(diag::err_pch_langopt_value_mismatch) << "module features";
275 return true;
276 }
277
Guy Benyei11169dd2012-12-18 14:30:41 +0000278 if (ExistingLangOpts.ObjCRuntime != LangOpts.ObjCRuntime) {
279 if (Diags)
280 Diags->Report(diag::err_pch_langopt_value_mismatch)
281 << "target Objective-C runtime";
282 return true;
283 }
284
Dmitri Gribenkoacf2e782013-02-22 14:21:27 +0000285 if (ExistingLangOpts.CommentOpts.BlockCommandNames !=
286 LangOpts.CommentOpts.BlockCommandNames) {
287 if (Diags)
288 Diags->Report(diag::err_pch_langopt_value_mismatch)
289 << "block command names";
290 return true;
291 }
292
Guy Benyei11169dd2012-12-18 14:30:41 +0000293 return false;
294}
295
296/// \brief Compare the given set of target options against an existing set of
297/// target options.
298///
299/// \param Diags If non-NULL, diagnostics will be emitted via this engine.
300///
301/// \returns true if the target options mis-match, false otherwise.
302static bool checkTargetOptions(const TargetOptions &TargetOpts,
303 const TargetOptions &ExistingTargetOpts,
Chandler Carruth0d745bc2015-03-14 04:47:43 +0000304 DiagnosticsEngine *Diags,
305 bool AllowCompatibleDifferences = true) {
Guy Benyei11169dd2012-12-18 14:30:41 +0000306#define CHECK_TARGET_OPT(Field, Name) \
307 if (TargetOpts.Field != ExistingTargetOpts.Field) { \
308 if (Diags) \
309 Diags->Report(diag::err_pch_targetopt_mismatch) \
310 << Name << TargetOpts.Field << ExistingTargetOpts.Field; \
311 return true; \
312 }
313
Chandler Carruth0d745bc2015-03-14 04:47:43 +0000314 // The triple and ABI must match exactly.
Guy Benyei11169dd2012-12-18 14:30:41 +0000315 CHECK_TARGET_OPT(Triple, "target");
Guy Benyei11169dd2012-12-18 14:30:41 +0000316 CHECK_TARGET_OPT(ABI, "target ABI");
Chandler Carruth0d745bc2015-03-14 04:47:43 +0000317
318 // We can tolerate different CPUs in many cases, notably when one CPU
319 // supports a strict superset of another. When allowing compatible
320 // differences skip this check.
321 if (!AllowCompatibleDifferences)
322 CHECK_TARGET_OPT(CPU, "target CPU");
323
Guy Benyei11169dd2012-12-18 14:30:41 +0000324#undef CHECK_TARGET_OPT
325
326 // Compare feature sets.
327 SmallVector<StringRef, 4> ExistingFeatures(
328 ExistingTargetOpts.FeaturesAsWritten.begin(),
329 ExistingTargetOpts.FeaturesAsWritten.end());
330 SmallVector<StringRef, 4> ReadFeatures(TargetOpts.FeaturesAsWritten.begin(),
331 TargetOpts.FeaturesAsWritten.end());
332 std::sort(ExistingFeatures.begin(), ExistingFeatures.end());
333 std::sort(ReadFeatures.begin(), ReadFeatures.end());
334
Chandler Carruth0d745bc2015-03-14 04:47:43 +0000335 // We compute the set difference in both directions explicitly so that we can
336 // diagnose the differences differently.
337 SmallVector<StringRef, 4> UnmatchedExistingFeatures, UnmatchedReadFeatures;
338 std::set_difference(
339 ExistingFeatures.begin(), ExistingFeatures.end(), ReadFeatures.begin(),
340 ReadFeatures.end(), std::back_inserter(UnmatchedExistingFeatures));
341 std::set_difference(ReadFeatures.begin(), ReadFeatures.end(),
342 ExistingFeatures.begin(), ExistingFeatures.end(),
343 std::back_inserter(UnmatchedReadFeatures));
Guy Benyei11169dd2012-12-18 14:30:41 +0000344
Chandler Carruth0d745bc2015-03-14 04:47:43 +0000345 // If we are allowing compatible differences and the read feature set is
346 // a strict subset of the existing feature set, there is nothing to diagnose.
347 if (AllowCompatibleDifferences && UnmatchedReadFeatures.empty())
348 return false;
Guy Benyei11169dd2012-12-18 14:30:41 +0000349
Chandler Carruth0d745bc2015-03-14 04:47:43 +0000350 if (Diags) {
351 for (StringRef Feature : UnmatchedReadFeatures)
Guy Benyei11169dd2012-12-18 14:30:41 +0000352 Diags->Report(diag::err_pch_targetopt_feature_mismatch)
Chandler Carruth0d745bc2015-03-14 04:47:43 +0000353 << /* is-existing-feature */ false << Feature;
354 for (StringRef Feature : UnmatchedExistingFeatures)
355 Diags->Report(diag::err_pch_targetopt_feature_mismatch)
356 << /* is-existing-feature */ true << Feature;
Guy Benyei11169dd2012-12-18 14:30:41 +0000357 }
358
Chandler Carruth0d745bc2015-03-14 04:47:43 +0000359 return !UnmatchedReadFeatures.empty() || !UnmatchedExistingFeatures.empty();
Guy Benyei11169dd2012-12-18 14:30:41 +0000360}
361
362bool
363PCHValidator::ReadLanguageOptions(const LangOptions &LangOpts,
Richard Smith1e2cf0d2014-10-31 02:28:58 +0000364 bool Complain,
365 bool AllowCompatibleDifferences) {
Guy Benyei11169dd2012-12-18 14:30:41 +0000366 const LangOptions &ExistingLangOpts = PP.getLangOpts();
367 return checkLanguageOptions(LangOpts, ExistingLangOpts,
Richard Smith1e2cf0d2014-10-31 02:28:58 +0000368 Complain ? &Reader.Diags : nullptr,
369 AllowCompatibleDifferences);
Guy Benyei11169dd2012-12-18 14:30:41 +0000370}
371
372bool PCHValidator::ReadTargetOptions(const TargetOptions &TargetOpts,
Chandler Carruth0d745bc2015-03-14 04:47:43 +0000373 bool Complain,
374 bool AllowCompatibleDifferences) {
Guy Benyei11169dd2012-12-18 14:30:41 +0000375 const TargetOptions &ExistingTargetOpts = PP.getTargetInfo().getTargetOpts();
376 return checkTargetOptions(TargetOpts, ExistingTargetOpts,
Chandler Carruth0d745bc2015-03-14 04:47:43 +0000377 Complain ? &Reader.Diags : nullptr,
378 AllowCompatibleDifferences);
Guy Benyei11169dd2012-12-18 14:30:41 +0000379}
380
381namespace {
Eugene Zelenkoe95e7d52016-09-07 21:53:17 +0000382
Guy Benyei11169dd2012-12-18 14:30:41 +0000383 typedef llvm::StringMap<std::pair<StringRef, bool /*IsUndef*/> >
384 MacroDefinitionsMap;
Craig Topper3598eb72013-07-05 04:43:31 +0000385 typedef llvm::DenseMap<DeclarationName, SmallVector<NamedDecl *, 8> >
386 DeclsMap;
Eugene Zelenkoe95e7d52016-09-07 21:53:17 +0000387
388} // end anonymous namespace
Guy Benyei11169dd2012-12-18 14:30:41 +0000389
Ben Langmuirb92de022014-04-29 16:25:26 +0000390static bool checkDiagnosticGroupMappings(DiagnosticsEngine &StoredDiags,
391 DiagnosticsEngine &Diags,
392 bool Complain) {
393 typedef DiagnosticsEngine::Level Level;
394
395 // Check current mappings for new -Werror mappings, and the stored mappings
396 // for cases that were explicitly mapped to *not* be errors that are now
397 // errors because of options like -Werror.
398 DiagnosticsEngine *MappingSources[] = { &Diags, &StoredDiags };
399
400 for (DiagnosticsEngine *MappingSource : MappingSources) {
401 for (auto DiagIDMappingPair : MappingSource->getDiagnosticMappings()) {
402 diag::kind DiagID = DiagIDMappingPair.first;
403 Level CurLevel = Diags.getDiagnosticLevel(DiagID, SourceLocation());
404 if (CurLevel < DiagnosticsEngine::Error)
405 continue; // not significant
406 Level StoredLevel =
407 StoredDiags.getDiagnosticLevel(DiagID, SourceLocation());
408 if (StoredLevel < DiagnosticsEngine::Error) {
409 if (Complain)
410 Diags.Report(diag::err_pch_diagopt_mismatch) << "-Werror=" +
411 Diags.getDiagnosticIDs()->getWarningOptionForDiag(DiagID).str();
412 return true;
413 }
414 }
415 }
416
417 return false;
418}
419
Alp Tokerac4e8e52014-06-22 21:58:33 +0000420static bool isExtHandlingFromDiagsError(DiagnosticsEngine &Diags) {
421 diag::Severity Ext = Diags.getExtensionHandlingBehavior();
422 if (Ext == diag::Severity::Warning && Diags.getWarningsAsErrors())
423 return true;
424 return Ext >= diag::Severity::Error;
Ben Langmuirb92de022014-04-29 16:25:26 +0000425}
426
427static bool checkDiagnosticMappings(DiagnosticsEngine &StoredDiags,
428 DiagnosticsEngine &Diags,
429 bool IsSystem, bool Complain) {
430 // Top-level options
431 if (IsSystem) {
432 if (Diags.getSuppressSystemWarnings())
433 return false;
434 // If -Wsystem-headers was not enabled before, be conservative
435 if (StoredDiags.getSuppressSystemWarnings()) {
436 if (Complain)
437 Diags.Report(diag::err_pch_diagopt_mismatch) << "-Wsystem-headers";
438 return true;
439 }
440 }
441
442 if (Diags.getWarningsAsErrors() && !StoredDiags.getWarningsAsErrors()) {
443 if (Complain)
444 Diags.Report(diag::err_pch_diagopt_mismatch) << "-Werror";
445 return true;
446 }
447
448 if (Diags.getWarningsAsErrors() && Diags.getEnableAllWarnings() &&
449 !StoredDiags.getEnableAllWarnings()) {
450 if (Complain)
451 Diags.Report(diag::err_pch_diagopt_mismatch) << "-Weverything -Werror";
452 return true;
453 }
454
455 if (isExtHandlingFromDiagsError(Diags) &&
456 !isExtHandlingFromDiagsError(StoredDiags)) {
457 if (Complain)
458 Diags.Report(diag::err_pch_diagopt_mismatch) << "-pedantic-errors";
459 return true;
460 }
461
462 return checkDiagnosticGroupMappings(StoredDiags, Diags, Complain);
463}
464
465bool PCHValidator::ReadDiagnosticOptions(
466 IntrusiveRefCntPtr<DiagnosticOptions> DiagOpts, bool Complain) {
467 DiagnosticsEngine &ExistingDiags = PP.getDiagnostics();
468 IntrusiveRefCntPtr<DiagnosticIDs> DiagIDs(ExistingDiags.getDiagnosticIDs());
469 IntrusiveRefCntPtr<DiagnosticsEngine> Diags(
Alp Tokerf994cef2014-07-05 03:08:06 +0000470 new DiagnosticsEngine(DiagIDs, DiagOpts.get()));
Ben Langmuirb92de022014-04-29 16:25:26 +0000471 // This should never fail, because we would have processed these options
472 // before writing them to an ASTFile.
473 ProcessWarningOptions(*Diags, *DiagOpts, /*Report*/false);
474
475 ModuleManager &ModuleMgr = Reader.getModuleManager();
476 assert(ModuleMgr.size() >= 1 && "what ASTFile is this then");
477
478 // If the original import came from a file explicitly generated by the user,
479 // don't check the diagnostic mappings.
480 // FIXME: currently this is approximated by checking whether this is not a
Richard Smithe842a472014-10-22 02:05:46 +0000481 // module import of an implicitly-loaded module file.
Ben Langmuirb92de022014-04-29 16:25:26 +0000482 // Note: ModuleMgr.rbegin() may not be the current module, but it must be in
483 // the transitive closure of its imports, since unrelated modules cannot be
484 // imported until after this module finishes validation.
Duncan P. N. Exon Smith96a06e02017-01-28 22:15:22 +0000485 ModuleFile *TopImport = &*ModuleMgr.rbegin();
Ben Langmuirb92de022014-04-29 16:25:26 +0000486 while (!TopImport->ImportedBy.empty())
487 TopImport = TopImport->ImportedBy[0];
Richard Smithe842a472014-10-22 02:05:46 +0000488 if (TopImport->Kind != MK_ImplicitModule)
Ben Langmuirb92de022014-04-29 16:25:26 +0000489 return false;
490
491 StringRef ModuleName = TopImport->ModuleName;
492 assert(!ModuleName.empty() && "diagnostic options read before module name");
493
494 Module *M = PP.getHeaderSearchInfo().lookupModule(ModuleName);
495 assert(M && "missing module");
496
497 // FIXME: if the diagnostics are incompatible, save a DiagnosticOptions that
498 // contains the union of their flags.
499 return checkDiagnosticMappings(*Diags, ExistingDiags, M->IsSystem, Complain);
500}
501
Guy Benyei11169dd2012-12-18 14:30:41 +0000502/// \brief Collect the macro definitions provided by the given preprocessor
503/// options.
Craig Toppera13603a2014-05-22 05:54:18 +0000504static void
505collectMacroDefinitions(const PreprocessorOptions &PPOpts,
506 MacroDefinitionsMap &Macros,
507 SmallVectorImpl<StringRef> *MacroNames = nullptr) {
Guy Benyei11169dd2012-12-18 14:30:41 +0000508 for (unsigned I = 0, N = PPOpts.Macros.size(); I != N; ++I) {
509 StringRef Macro = PPOpts.Macros[I].first;
510 bool IsUndef = PPOpts.Macros[I].second;
511
512 std::pair<StringRef, StringRef> MacroPair = Macro.split('=');
513 StringRef MacroName = MacroPair.first;
514 StringRef MacroBody = MacroPair.second;
515
516 // For an #undef'd macro, we only care about the name.
517 if (IsUndef) {
518 if (MacroNames && !Macros.count(MacroName))
519 MacroNames->push_back(MacroName);
520
521 Macros[MacroName] = std::make_pair("", true);
522 continue;
523 }
524
525 // For a #define'd macro, figure out the actual definition.
526 if (MacroName.size() == Macro.size())
527 MacroBody = "1";
528 else {
529 // Note: GCC drops anything following an end-of-line character.
530 StringRef::size_type End = MacroBody.find_first_of("\n\r");
531 MacroBody = MacroBody.substr(0, End);
532 }
533
534 if (MacroNames && !Macros.count(MacroName))
535 MacroNames->push_back(MacroName);
536 Macros[MacroName] = std::make_pair(MacroBody, false);
537 }
538}
Argyrios Kyrtzidisbd0b6512015-02-19 20:12:20 +0000539
Guy Benyei11169dd2012-12-18 14:30:41 +0000540/// \brief Check the preprocessor options deserialized from the control block
541/// against the preprocessor options in an existing preprocessor.
542///
543/// \param Diags If non-null, produce diagnostics for any mismatches incurred.
Yaxun Liu43712e02016-09-07 18:40:20 +0000544/// \param Validate If true, validate preprocessor options. If false, allow
545/// macros defined by \p ExistingPPOpts to override those defined by
546/// \p PPOpts in SuggestedPredefines.
Guy Benyei11169dd2012-12-18 14:30:41 +0000547static bool checkPreprocessorOptions(const PreprocessorOptions &PPOpts,
548 const PreprocessorOptions &ExistingPPOpts,
549 DiagnosticsEngine *Diags,
550 FileManager &FileMgr,
Argyrios Kyrtzidisd3afa0c2013-04-26 21:33:40 +0000551 std::string &SuggestedPredefines,
Yaxun Liu43712e02016-09-07 18:40:20 +0000552 const LangOptions &LangOpts,
553 bool Validate = true) {
Guy Benyei11169dd2012-12-18 14:30:41 +0000554 // Check macro definitions.
555 MacroDefinitionsMap ASTFileMacros;
556 collectMacroDefinitions(PPOpts, ASTFileMacros);
557 MacroDefinitionsMap ExistingMacros;
558 SmallVector<StringRef, 4> ExistingMacroNames;
559 collectMacroDefinitions(ExistingPPOpts, ExistingMacros, &ExistingMacroNames);
560
561 for (unsigned I = 0, N = ExistingMacroNames.size(); I != N; ++I) {
562 // Dig out the macro definition in the existing preprocessor options.
563 StringRef MacroName = ExistingMacroNames[I];
564 std::pair<StringRef, bool> Existing = ExistingMacros[MacroName];
565
566 // Check whether we know anything about this macro name or not.
567 llvm::StringMap<std::pair<StringRef, bool /*IsUndef*/> >::iterator Known
568 = ASTFileMacros.find(MacroName);
Yaxun Liu43712e02016-09-07 18:40:20 +0000569 if (!Validate || Known == ASTFileMacros.end()) {
Guy Benyei11169dd2012-12-18 14:30:41 +0000570 // FIXME: Check whether this identifier was referenced anywhere in the
571 // AST file. If so, we should reject the AST file. Unfortunately, this
572 // information isn't in the control block. What shall we do about it?
573
574 if (Existing.second) {
575 SuggestedPredefines += "#undef ";
576 SuggestedPredefines += MacroName.str();
577 SuggestedPredefines += '\n';
578 } else {
579 SuggestedPredefines += "#define ";
580 SuggestedPredefines += MacroName.str();
581 SuggestedPredefines += ' ';
582 SuggestedPredefines += Existing.first.str();
583 SuggestedPredefines += '\n';
584 }
585 continue;
586 }
587
588 // If the macro was defined in one but undef'd in the other, we have a
589 // conflict.
590 if (Existing.second != Known->second.second) {
591 if (Diags) {
592 Diags->Report(diag::err_pch_macro_def_undef)
593 << MacroName << Known->second.second;
594 }
595 return true;
596 }
597
598 // If the macro was #undef'd in both, or if the macro bodies are identical,
599 // it's fine.
600 if (Existing.second || Existing.first == Known->second.first)
601 continue;
602
603 // The macro bodies differ; complain.
604 if (Diags) {
605 Diags->Report(diag::err_pch_macro_def_conflict)
606 << MacroName << Known->second.first << Existing.first;
607 }
608 return true;
609 }
610
611 // Check whether we're using predefines.
Yaxun Liu43712e02016-09-07 18:40:20 +0000612 if (PPOpts.UsePredefines != ExistingPPOpts.UsePredefines && Validate) {
Guy Benyei11169dd2012-12-18 14:30:41 +0000613 if (Diags) {
614 Diags->Report(diag::err_pch_undef) << ExistingPPOpts.UsePredefines;
615 }
616 return true;
617 }
618
Argyrios Kyrtzidisd3afa0c2013-04-26 21:33:40 +0000619 // Detailed record is important since it is used for the module cache hash.
620 if (LangOpts.Modules &&
Yaxun Liu43712e02016-09-07 18:40:20 +0000621 PPOpts.DetailedRecord != ExistingPPOpts.DetailedRecord && Validate) {
Argyrios Kyrtzidisd3afa0c2013-04-26 21:33:40 +0000622 if (Diags) {
623 Diags->Report(diag::err_pch_pp_detailed_record) << PPOpts.DetailedRecord;
624 }
625 return true;
626 }
627
Guy Benyei11169dd2012-12-18 14:30:41 +0000628 // Compute the #include and #include_macros lines we need.
629 for (unsigned I = 0, N = ExistingPPOpts.Includes.size(); I != N; ++I) {
630 StringRef File = ExistingPPOpts.Includes[I];
631 if (File == ExistingPPOpts.ImplicitPCHInclude)
632 continue;
633
634 if (std::find(PPOpts.Includes.begin(), PPOpts.Includes.end(), File)
635 != PPOpts.Includes.end())
636 continue;
637
638 SuggestedPredefines += "#include \"";
Manuel Klimek9af34ae2014-08-12 08:25:57 +0000639 SuggestedPredefines += File;
Guy Benyei11169dd2012-12-18 14:30:41 +0000640 SuggestedPredefines += "\"\n";
641 }
642
643 for (unsigned I = 0, N = ExistingPPOpts.MacroIncludes.size(); I != N; ++I) {
644 StringRef File = ExistingPPOpts.MacroIncludes[I];
645 if (std::find(PPOpts.MacroIncludes.begin(), PPOpts.MacroIncludes.end(),
646 File)
647 != PPOpts.MacroIncludes.end())
648 continue;
649
650 SuggestedPredefines += "#__include_macros \"";
Manuel Klimek9af34ae2014-08-12 08:25:57 +0000651 SuggestedPredefines += File;
Guy Benyei11169dd2012-12-18 14:30:41 +0000652 SuggestedPredefines += "\"\n##\n";
653 }
654
655 return false;
656}
657
658bool PCHValidator::ReadPreprocessorOptions(const PreprocessorOptions &PPOpts,
659 bool Complain,
660 std::string &SuggestedPredefines) {
661 const PreprocessorOptions &ExistingPPOpts = PP.getPreprocessorOpts();
662
663 return checkPreprocessorOptions(PPOpts, ExistingPPOpts,
Craig Toppera13603a2014-05-22 05:54:18 +0000664 Complain? &Reader.Diags : nullptr,
Guy Benyei11169dd2012-12-18 14:30:41 +0000665 PP.getFileManager(),
Argyrios Kyrtzidisd3afa0c2013-04-26 21:33:40 +0000666 SuggestedPredefines,
667 PP.getLangOpts());
Guy Benyei11169dd2012-12-18 14:30:41 +0000668}
669
Yaxun Liu43712e02016-09-07 18:40:20 +0000670bool SimpleASTReaderListener::ReadPreprocessorOptions(
671 const PreprocessorOptions &PPOpts,
672 bool Complain,
673 std::string &SuggestedPredefines) {
674 return checkPreprocessorOptions(PPOpts,
675 PP.getPreprocessorOpts(),
676 nullptr,
677 PP.getFileManager(),
678 SuggestedPredefines,
679 PP.getLangOpts(),
680 false);
681}
682
Argyrios Kyrtzidisbd0b6512015-02-19 20:12:20 +0000683/// Check the header search options deserialized from the control block
684/// against the header search options in an existing preprocessor.
685///
686/// \param Diags If non-null, produce diagnostics for any mismatches incurred.
687static bool checkHeaderSearchOptions(const HeaderSearchOptions &HSOpts,
688 StringRef SpecificModuleCachePath,
689 StringRef ExistingModuleCachePath,
690 DiagnosticsEngine *Diags,
691 const LangOptions &LangOpts) {
692 if (LangOpts.Modules) {
693 if (SpecificModuleCachePath != ExistingModuleCachePath) {
694 if (Diags)
695 Diags->Report(diag::err_pch_modulecache_mismatch)
696 << SpecificModuleCachePath << ExistingModuleCachePath;
697 return true;
698 }
699 }
700
701 return false;
702}
703
704bool PCHValidator::ReadHeaderSearchOptions(const HeaderSearchOptions &HSOpts,
705 StringRef SpecificModuleCachePath,
706 bool Complain) {
707 return checkHeaderSearchOptions(HSOpts, SpecificModuleCachePath,
708 PP.getHeaderSearchInfo().getModuleCachePath(),
709 Complain ? &Reader.Diags : nullptr,
710 PP.getLangOpts());
711}
712
Guy Benyei11169dd2012-12-18 14:30:41 +0000713void PCHValidator::ReadCounter(const ModuleFile &M, unsigned Value) {
714 PP.setCounterValue(Value);
715}
716
717//===----------------------------------------------------------------------===//
718// AST reader implementation
719//===----------------------------------------------------------------------===//
720
Nico Weber824285e2014-05-08 04:26:47 +0000721void ASTReader::setDeserializationListener(ASTDeserializationListener *Listener,
722 bool TakeOwnership) {
Guy Benyei11169dd2012-12-18 14:30:41 +0000723 DeserializationListener = Listener;
Nico Weber824285e2014-05-08 04:26:47 +0000724 OwnsDeserializationListener = TakeOwnership;
Guy Benyei11169dd2012-12-18 14:30:41 +0000725}
726
Guy Benyei11169dd2012-12-18 14:30:41 +0000727unsigned ASTSelectorLookupTrait::ComputeHash(Selector Sel) {
728 return serialization::ComputeHash(Sel);
729}
730
Guy Benyei11169dd2012-12-18 14:30:41 +0000731std::pair<unsigned, unsigned>
732ASTSelectorLookupTrait::ReadKeyDataLength(const unsigned char*& d) {
Justin Bogner57ba0b22014-03-28 22:03:24 +0000733 using namespace llvm::support;
734 unsigned KeyLen = endian::readNext<uint16_t, little, unaligned>(d);
735 unsigned DataLen = endian::readNext<uint16_t, little, unaligned>(d);
Guy Benyei11169dd2012-12-18 14:30:41 +0000736 return std::make_pair(KeyLen, DataLen);
737}
738
David L. Jonesc4808b9e2016-12-15 20:53:26 +0000739ASTSelectorLookupTrait::internal_key_type
Guy Benyei11169dd2012-12-18 14:30:41 +0000740ASTSelectorLookupTrait::ReadKey(const unsigned char* d, unsigned) {
Justin Bogner57ba0b22014-03-28 22:03:24 +0000741 using namespace llvm::support;
Guy Benyei11169dd2012-12-18 14:30:41 +0000742 SelectorTable &SelTable = Reader.getContext().Selectors;
Justin Bogner57ba0b22014-03-28 22:03:24 +0000743 unsigned N = endian::readNext<uint16_t, little, unaligned>(d);
744 IdentifierInfo *FirstII = Reader.getLocalIdentifier(
745 F, endian::readNext<uint32_t, little, unaligned>(d));
Guy Benyei11169dd2012-12-18 14:30:41 +0000746 if (N == 0)
747 return SelTable.getNullarySelector(FirstII);
748 else if (N == 1)
749 return SelTable.getUnarySelector(FirstII);
750
751 SmallVector<IdentifierInfo *, 16> Args;
752 Args.push_back(FirstII);
753 for (unsigned I = 1; I != N; ++I)
Justin Bogner57ba0b22014-03-28 22:03:24 +0000754 Args.push_back(Reader.getLocalIdentifier(
755 F, endian::readNext<uint32_t, little, unaligned>(d)));
Guy Benyei11169dd2012-12-18 14:30:41 +0000756
757 return SelTable.getSelector(N, Args.data());
758}
759
David L. Jonesc4808b9e2016-12-15 20:53:26 +0000760ASTSelectorLookupTrait::data_type
761ASTSelectorLookupTrait::ReadData(Selector, const unsigned char* d,
Guy Benyei11169dd2012-12-18 14:30:41 +0000762 unsigned DataLen) {
Justin Bogner57ba0b22014-03-28 22:03:24 +0000763 using namespace llvm::support;
Guy Benyei11169dd2012-12-18 14:30:41 +0000764
765 data_type Result;
766
Justin Bogner57ba0b22014-03-28 22:03:24 +0000767 Result.ID = Reader.getGlobalSelectorID(
768 F, endian::readNext<uint32_t, little, unaligned>(d));
Nico Weberff4b35e2014-12-27 22:14:15 +0000769 unsigned FullInstanceBits = endian::readNext<uint16_t, little, unaligned>(d);
770 unsigned FullFactoryBits = endian::readNext<uint16_t, little, unaligned>(d);
771 Result.InstanceBits = FullInstanceBits & 0x3;
772 Result.InstanceHasMoreThanOneDecl = (FullInstanceBits >> 2) & 0x1;
773 Result.FactoryBits = FullFactoryBits & 0x3;
774 Result.FactoryHasMoreThanOneDecl = (FullFactoryBits >> 2) & 0x1;
775 unsigned NumInstanceMethods = FullInstanceBits >> 3;
776 unsigned NumFactoryMethods = FullFactoryBits >> 3;
Guy Benyei11169dd2012-12-18 14:30:41 +0000777
778 // Load instance methods
779 for (unsigned I = 0; I != NumInstanceMethods; ++I) {
Justin Bogner57ba0b22014-03-28 22:03:24 +0000780 if (ObjCMethodDecl *Method = Reader.GetLocalDeclAs<ObjCMethodDecl>(
781 F, endian::readNext<uint32_t, little, unaligned>(d)))
Guy Benyei11169dd2012-12-18 14:30:41 +0000782 Result.Instance.push_back(Method);
783 }
784
785 // Load factory methods
786 for (unsigned I = 0; I != NumFactoryMethods; ++I) {
Justin Bogner57ba0b22014-03-28 22:03:24 +0000787 if (ObjCMethodDecl *Method = Reader.GetLocalDeclAs<ObjCMethodDecl>(
788 F, endian::readNext<uint32_t, little, unaligned>(d)))
Guy Benyei11169dd2012-12-18 14:30:41 +0000789 Result.Factory.push_back(Method);
790 }
791
792 return Result;
793}
794
Douglas Gregorbfd73d72013-01-23 18:53:14 +0000795unsigned ASTIdentifierLookupTraitBase::ComputeHash(const internal_key_type& a) {
796 return llvm::HashString(a);
Guy Benyei11169dd2012-12-18 14:30:41 +0000797}
798
799std::pair<unsigned, unsigned>
Douglas Gregorbfd73d72013-01-23 18:53:14 +0000800ASTIdentifierLookupTraitBase::ReadKeyDataLength(const unsigned char*& d) {
Justin Bogner57ba0b22014-03-28 22:03:24 +0000801 using namespace llvm::support;
802 unsigned DataLen = endian::readNext<uint16_t, little, unaligned>(d);
803 unsigned KeyLen = endian::readNext<uint16_t, little, unaligned>(d);
Guy Benyei11169dd2012-12-18 14:30:41 +0000804 return std::make_pair(KeyLen, DataLen);
805}
806
Douglas Gregorbfd73d72013-01-23 18:53:14 +0000807ASTIdentifierLookupTraitBase::internal_key_type
808ASTIdentifierLookupTraitBase::ReadKey(const unsigned char* d, unsigned n) {
Guy Benyei11169dd2012-12-18 14:30:41 +0000809 assert(n >= 2 && d[n-1] == '\0');
Douglas Gregorbfd73d72013-01-23 18:53:14 +0000810 return StringRef((const char*) d, n-1);
Guy Benyei11169dd2012-12-18 14:30:41 +0000811}
812
Douglas Gregordcf25082013-02-11 18:16:18 +0000813/// \brief Whether the given identifier is "interesting".
Richard Smitha534a312015-07-21 23:54:07 +0000814static bool isInterestingIdentifier(ASTReader &Reader, IdentifierInfo &II,
815 bool IsModule) {
Richard Smithcab89802015-07-17 20:19:56 +0000816 return II.hadMacroDefinition() ||
817 II.isPoisoned() ||
Richard Smith9c254182015-07-19 21:41:12 +0000818 (IsModule ? II.hasRevertedBuiltin() : II.getObjCOrBuiltinID()) ||
Douglas Gregordcf25082013-02-11 18:16:18 +0000819 II.hasRevertedTokenIDToIdentifier() ||
Richard Smitha534a312015-07-21 23:54:07 +0000820 (!(IsModule && Reader.getContext().getLangOpts().CPlusPlus) &&
821 II.getFETokenInfo<void>());
Douglas Gregordcf25082013-02-11 18:16:18 +0000822}
823
Richard Smith76c2f2c2015-07-17 20:09:43 +0000824static bool readBit(unsigned &Bits) {
825 bool Value = Bits & 0x1;
826 Bits >>= 1;
827 return Value;
828}
829
Richard Smith79bf9202015-08-24 03:33:22 +0000830IdentID ASTIdentifierLookupTrait::ReadIdentifierID(const unsigned char *d) {
831 using namespace llvm::support;
832 unsigned RawID = endian::readNext<uint32_t, little, unaligned>(d);
833 return Reader.getGlobalIdentifierID(F, RawID >> 1);
834}
835
Richard Smitheb4b58f62016-02-05 01:40:54 +0000836static void markIdentifierFromAST(ASTReader &Reader, IdentifierInfo &II) {
837 if (!II.isFromAST()) {
838 II.setIsFromAST();
839 bool IsModule = Reader.getPreprocessor().getCurrentModule() != nullptr;
840 if (isInterestingIdentifier(Reader, II, IsModule))
841 II.setChangedSinceDeserialization();
842 }
843}
844
Guy Benyei11169dd2012-12-18 14:30:41 +0000845IdentifierInfo *ASTIdentifierLookupTrait::ReadData(const internal_key_type& k,
846 const unsigned char* d,
847 unsigned DataLen) {
Justin Bogner57ba0b22014-03-28 22:03:24 +0000848 using namespace llvm::support;
849 unsigned RawID = endian::readNext<uint32_t, little, unaligned>(d);
Guy Benyei11169dd2012-12-18 14:30:41 +0000850 bool IsInteresting = RawID & 0x01;
851
852 // Wipe out the "is interesting" bit.
853 RawID = RawID >> 1;
854
Richard Smith76c2f2c2015-07-17 20:09:43 +0000855 // Build the IdentifierInfo and link the identifier ID with it.
856 IdentifierInfo *II = KnownII;
857 if (!II) {
858 II = &Reader.getIdentifierTable().getOwn(k);
859 KnownII = II;
860 }
Richard Smitheb4b58f62016-02-05 01:40:54 +0000861 markIdentifierFromAST(Reader, *II);
Richard Smith76c2f2c2015-07-17 20:09:43 +0000862 Reader.markIdentifierUpToDate(II);
863
Guy Benyei11169dd2012-12-18 14:30:41 +0000864 IdentID ID = Reader.getGlobalIdentifierID(F, RawID);
865 if (!IsInteresting) {
Richard Smith76c2f2c2015-07-17 20:09:43 +0000866 // For uninteresting identifiers, there's nothing else to do. Just notify
867 // the reader that we've finished loading this identifier.
Guy Benyei11169dd2012-12-18 14:30:41 +0000868 Reader.SetIdentifierInfo(ID, II);
Guy Benyei11169dd2012-12-18 14:30:41 +0000869 return II;
870 }
871
Justin Bogner57ba0b22014-03-28 22:03:24 +0000872 unsigned ObjCOrBuiltinID = endian::readNext<uint16_t, little, unaligned>(d);
873 unsigned Bits = endian::readNext<uint16_t, little, unaligned>(d);
Richard Smith76c2f2c2015-07-17 20:09:43 +0000874 bool CPlusPlusOperatorKeyword = readBit(Bits);
875 bool HasRevertedTokenIDToIdentifier = readBit(Bits);
Richard Smith9c254182015-07-19 21:41:12 +0000876 bool HasRevertedBuiltin = readBit(Bits);
Richard Smith76c2f2c2015-07-17 20:09:43 +0000877 bool Poisoned = readBit(Bits);
878 bool ExtensionToken = readBit(Bits);
879 bool HadMacroDefinition = readBit(Bits);
Guy Benyei11169dd2012-12-18 14:30:41 +0000880
881 assert(Bits == 0 && "Extra bits in the identifier?");
882 DataLen -= 8;
883
Guy Benyei11169dd2012-12-18 14:30:41 +0000884 // Set or check the various bits in the IdentifierInfo structure.
885 // Token IDs are read-only.
Argyrios Kyrtzidisddee8c92013-02-27 01:13:51 +0000886 if (HasRevertedTokenIDToIdentifier && II->getTokenID() != tok::identifier)
Richard Smith9c254182015-07-19 21:41:12 +0000887 II->revertTokenIDToIdentifier();
888 if (!F.isModule())
889 II->setObjCOrBuiltinID(ObjCOrBuiltinID);
890 else if (HasRevertedBuiltin && II->getBuiltinID()) {
891 II->revertBuiltin();
892 assert((II->hasRevertedBuiltin() ||
893 II->getObjCOrBuiltinID() == ObjCOrBuiltinID) &&
894 "Incorrect ObjC keyword or builtin ID");
895 }
Guy Benyei11169dd2012-12-18 14:30:41 +0000896 assert(II->isExtensionToken() == ExtensionToken &&
897 "Incorrect extension token flag");
898 (void)ExtensionToken;
899 if (Poisoned)
900 II->setIsPoisoned(true);
901 assert(II->isCPlusPlusOperatorKeyword() == CPlusPlusOperatorKeyword &&
902 "Incorrect C++ operator keyword flag");
903 (void)CPlusPlusOperatorKeyword;
904
905 // If this identifier is a macro, deserialize the macro
906 // definition.
Richard Smith76c2f2c2015-07-17 20:09:43 +0000907 if (HadMacroDefinition) {
Justin Bogner57ba0b22014-03-28 22:03:24 +0000908 uint32_t MacroDirectivesOffset =
909 endian::readNext<uint32_t, little, unaligned>(d);
Argyrios Kyrtzidiseb663da2013-03-22 21:12:57 +0000910 DataLen -= 4;
Argyrios Kyrtzidiseb663da2013-03-22 21:12:57 +0000911
Richard Smithd7329392015-04-21 21:46:32 +0000912 Reader.addPendingMacro(II, &F, MacroDirectivesOffset);
Guy Benyei11169dd2012-12-18 14:30:41 +0000913 }
914
915 Reader.SetIdentifierInfo(ID, II);
916
917 // Read all of the declarations visible at global scope with this
918 // name.
919 if (DataLen > 0) {
920 SmallVector<uint32_t, 4> DeclIDs;
921 for (; DataLen > 0; DataLen -= 4)
Justin Bogner57ba0b22014-03-28 22:03:24 +0000922 DeclIDs.push_back(Reader.getGlobalDeclID(
923 F, endian::readNext<uint32_t, little, unaligned>(d)));
Guy Benyei11169dd2012-12-18 14:30:41 +0000924 Reader.SetGloballyVisibleDecls(II, DeclIDs);
925 }
926
927 return II;
928}
929
Richard Smitha06c7e62015-08-26 23:55:49 +0000930DeclarationNameKey::DeclarationNameKey(DeclarationName Name)
931 : Kind(Name.getNameKind()) {
932 switch (Kind) {
Guy Benyei11169dd2012-12-18 14:30:41 +0000933 case DeclarationName::Identifier:
Richard Smitha06c7e62015-08-26 23:55:49 +0000934 Data = (uint64_t)Name.getAsIdentifierInfo();
Guy Benyei11169dd2012-12-18 14:30:41 +0000935 break;
936 case DeclarationName::ObjCZeroArgSelector:
937 case DeclarationName::ObjCOneArgSelector:
938 case DeclarationName::ObjCMultiArgSelector:
Richard Smitha06c7e62015-08-26 23:55:49 +0000939 Data = (uint64_t)Name.getObjCSelector().getAsOpaquePtr();
Guy Benyei11169dd2012-12-18 14:30:41 +0000940 break;
941 case DeclarationName::CXXOperatorName:
Richard Smitha06c7e62015-08-26 23:55:49 +0000942 Data = Name.getCXXOverloadedOperator();
943 break;
944 case DeclarationName::CXXLiteralOperatorName:
945 Data = (uint64_t)Name.getCXXLiteralIdentifier();
946 break;
Richard Smith35845152017-02-07 01:37:30 +0000947 case DeclarationName::CXXDeductionGuideName:
948 Data = (uint64_t)Name.getCXXDeductionGuideTemplate()
949 ->getDeclName().getAsIdentifierInfo();
950 break;
Richard Smitha06c7e62015-08-26 23:55:49 +0000951 case DeclarationName::CXXConstructorName:
952 case DeclarationName::CXXDestructorName:
953 case DeclarationName::CXXConversionFunctionName:
954 case DeclarationName::CXXUsingDirective:
955 Data = 0;
956 break;
957 }
958}
959
960unsigned DeclarationNameKey::getHash() const {
961 llvm::FoldingSetNodeID ID;
962 ID.AddInteger(Kind);
963
964 switch (Kind) {
965 case DeclarationName::Identifier:
966 case DeclarationName::CXXLiteralOperatorName:
Richard Smith35845152017-02-07 01:37:30 +0000967 case DeclarationName::CXXDeductionGuideName:
Richard Smitha06c7e62015-08-26 23:55:49 +0000968 ID.AddString(((IdentifierInfo*)Data)->getName());
969 break;
970 case DeclarationName::ObjCZeroArgSelector:
971 case DeclarationName::ObjCOneArgSelector:
972 case DeclarationName::ObjCMultiArgSelector:
973 ID.AddInteger(serialization::ComputeHash(Selector(Data)));
974 break;
975 case DeclarationName::CXXOperatorName:
976 ID.AddInteger((OverloadedOperatorKind)Data);
Guy Benyei11169dd2012-12-18 14:30:41 +0000977 break;
978 case DeclarationName::CXXConstructorName:
979 case DeclarationName::CXXDestructorName:
980 case DeclarationName::CXXConversionFunctionName:
981 case DeclarationName::CXXUsingDirective:
982 break;
983 }
984
985 return ID.ComputeHash();
986}
987
Richard Smithd88a7f12015-09-01 20:35:42 +0000988ModuleFile *
989ASTDeclContextNameLookupTrait::ReadFileRef(const unsigned char *&d) {
990 using namespace llvm::support;
991 uint32_t ModuleFileID = endian::readNext<uint32_t, little, unaligned>(d);
992 return Reader.getLocalModuleFile(F, ModuleFileID);
993}
994
Guy Benyei11169dd2012-12-18 14:30:41 +0000995std::pair<unsigned, unsigned>
Richard Smitha06c7e62015-08-26 23:55:49 +0000996ASTDeclContextNameLookupTrait::ReadKeyDataLength(const unsigned char *&d) {
Justin Bogner57ba0b22014-03-28 22:03:24 +0000997 using namespace llvm::support;
998 unsigned KeyLen = endian::readNext<uint16_t, little, unaligned>(d);
999 unsigned DataLen = endian::readNext<uint16_t, little, unaligned>(d);
Guy Benyei11169dd2012-12-18 14:30:41 +00001000 return std::make_pair(KeyLen, DataLen);
1001}
1002
Richard Smitha06c7e62015-08-26 23:55:49 +00001003ASTDeclContextNameLookupTrait::internal_key_type
1004ASTDeclContextNameLookupTrait::ReadKey(const unsigned char *d, unsigned) {
Justin Bogner57ba0b22014-03-28 22:03:24 +00001005 using namespace llvm::support;
Guy Benyei11169dd2012-12-18 14:30:41 +00001006
Richard Smitha06c7e62015-08-26 23:55:49 +00001007 auto Kind = (DeclarationName::NameKind)*d++;
1008 uint64_t Data;
1009 switch (Kind) {
Guy Benyei11169dd2012-12-18 14:30:41 +00001010 case DeclarationName::Identifier:
Richard Smith35845152017-02-07 01:37:30 +00001011 case DeclarationName::CXXLiteralOperatorName:
1012 case DeclarationName::CXXDeductionGuideName:
Richard Smitha06c7e62015-08-26 23:55:49 +00001013 Data = (uint64_t)Reader.getLocalIdentifier(
Justin Bogner57ba0b22014-03-28 22:03:24 +00001014 F, endian::readNext<uint32_t, little, unaligned>(d));
Guy Benyei11169dd2012-12-18 14:30:41 +00001015 break;
1016 case DeclarationName::ObjCZeroArgSelector:
1017 case DeclarationName::ObjCOneArgSelector:
1018 case DeclarationName::ObjCMultiArgSelector:
Richard Smitha06c7e62015-08-26 23:55:49 +00001019 Data =
Justin Bogner57ba0b22014-03-28 22:03:24 +00001020 (uint64_t)Reader.getLocalSelector(
1021 F, endian::readNext<uint32_t, little, unaligned>(
1022 d)).getAsOpaquePtr();
Guy Benyei11169dd2012-12-18 14:30:41 +00001023 break;
1024 case DeclarationName::CXXOperatorName:
Richard Smitha06c7e62015-08-26 23:55:49 +00001025 Data = *d++; // OverloadedOperatorKind
Guy Benyei11169dd2012-12-18 14:30:41 +00001026 break;
Guy Benyei11169dd2012-12-18 14:30:41 +00001027 case DeclarationName::CXXConstructorName:
1028 case DeclarationName::CXXDestructorName:
1029 case DeclarationName::CXXConversionFunctionName:
1030 case DeclarationName::CXXUsingDirective:
Richard Smitha06c7e62015-08-26 23:55:49 +00001031 Data = 0;
Guy Benyei11169dd2012-12-18 14:30:41 +00001032 break;
1033 }
1034
Richard Smitha06c7e62015-08-26 23:55:49 +00001035 return DeclarationNameKey(Kind, Data);
Guy Benyei11169dd2012-12-18 14:30:41 +00001036}
1037
Richard Smithd88a7f12015-09-01 20:35:42 +00001038void ASTDeclContextNameLookupTrait::ReadDataInto(internal_key_type,
1039 const unsigned char *d,
1040 unsigned DataLen,
1041 data_type_builder &Val) {
Justin Bogner57ba0b22014-03-28 22:03:24 +00001042 using namespace llvm::support;
Richard Smithd88a7f12015-09-01 20:35:42 +00001043 for (unsigned NumDecls = DataLen / 4; NumDecls; --NumDecls) {
1044 uint32_t LocalID = endian::readNext<uint32_t, little, unaligned>(d);
1045 Val.insert(Reader.getGlobalDeclID(F, LocalID));
1046 }
Guy Benyei11169dd2012-12-18 14:30:41 +00001047}
1048
Richard Smith0f4e2c42015-08-06 04:23:48 +00001049bool ASTReader::ReadLexicalDeclContextStorage(ModuleFile &M,
1050 BitstreamCursor &Cursor,
1051 uint64_t Offset,
1052 DeclContext *DC) {
1053 assert(Offset != 0);
1054
Guy Benyei11169dd2012-12-18 14:30:41 +00001055 SavedStreamPosition SavedPosition(Cursor);
Richard Smith0f4e2c42015-08-06 04:23:48 +00001056 Cursor.JumpToBit(Offset);
Guy Benyei11169dd2012-12-18 14:30:41 +00001057
Richard Smith0f4e2c42015-08-06 04:23:48 +00001058 RecordData Record;
1059 StringRef Blob;
1060 unsigned Code = Cursor.ReadCode();
1061 unsigned RecCode = Cursor.readRecord(Code, Record, &Blob);
1062 if (RecCode != DECL_CONTEXT_LEXICAL) {
1063 Error("Expected lexical block");
1064 return true;
Guy Benyei11169dd2012-12-18 14:30:41 +00001065 }
1066
Richard Smith82f8fcd2015-08-06 22:07:25 +00001067 assert(!isa<TranslationUnitDecl>(DC) &&
1068 "expected a TU_UPDATE_LEXICAL record for TU");
Richard Smith9c9173d2015-08-11 22:00:24 +00001069 // If we are handling a C++ class template instantiation, we can see multiple
1070 // lexical updates for the same record. It's important that we select only one
1071 // of them, so that field numbering works properly. Just pick the first one we
1072 // see.
1073 auto &Lex = LexicalDecls[DC];
1074 if (!Lex.first) {
1075 Lex = std::make_pair(
1076 &M, llvm::makeArrayRef(
1077 reinterpret_cast<const llvm::support::unaligned_uint32_t *>(
1078 Blob.data()),
1079 Blob.size() / 4));
1080 }
Richard Smith0f4e2c42015-08-06 04:23:48 +00001081 DC->setHasExternalLexicalStorage(true);
1082 return false;
1083}
Guy Benyei11169dd2012-12-18 14:30:41 +00001084
Richard Smith0f4e2c42015-08-06 04:23:48 +00001085bool ASTReader::ReadVisibleDeclContextStorage(ModuleFile &M,
1086 BitstreamCursor &Cursor,
1087 uint64_t Offset,
1088 DeclID ID) {
1089 assert(Offset != 0);
1090
1091 SavedStreamPosition SavedPosition(Cursor);
1092 Cursor.JumpToBit(Offset);
1093
1094 RecordData Record;
1095 StringRef Blob;
1096 unsigned Code = Cursor.ReadCode();
1097 unsigned RecCode = Cursor.readRecord(Code, Record, &Blob);
1098 if (RecCode != DECL_CONTEXT_VISIBLE) {
1099 Error("Expected visible lookup table block");
1100 return true;
Guy Benyei11169dd2012-12-18 14:30:41 +00001101 }
1102
Richard Smith0f4e2c42015-08-06 04:23:48 +00001103 // We can't safely determine the primary context yet, so delay attaching the
1104 // lookup table until we're done with recursive deserialization.
Richard Smithd88a7f12015-09-01 20:35:42 +00001105 auto *Data = (const unsigned char*)Blob.data();
1106 PendingVisibleUpdates[ID].push_back(PendingVisibleUpdate{&M, Data});
Guy Benyei11169dd2012-12-18 14:30:41 +00001107 return false;
1108}
1109
1110void ASTReader::Error(StringRef Msg) {
1111 Error(diag::err_fe_pch_malformed, Msg);
Richard Smithfb1e7f72015-08-14 05:02:58 +00001112 if (Context.getLangOpts().Modules && !Diags.isDiagnosticInFlight() &&
1113 !PP.getHeaderSearchInfo().getModuleCachePath().empty()) {
Douglas Gregor940e8052013-05-10 22:15:13 +00001114 Diag(diag::note_module_cache_path)
1115 << PP.getHeaderSearchInfo().getModuleCachePath();
1116 }
Guy Benyei11169dd2012-12-18 14:30:41 +00001117}
1118
1119void ASTReader::Error(unsigned DiagID,
1120 StringRef Arg1, StringRef Arg2) {
1121 if (Diags.isDiagnosticInFlight())
1122 Diags.SetDelayedDiagnostic(DiagID, Arg1, Arg2);
1123 else
1124 Diag(DiagID) << Arg1 << Arg2;
1125}
1126
1127//===----------------------------------------------------------------------===//
1128// Source Manager Deserialization
1129//===----------------------------------------------------------------------===//
1130
1131/// \brief Read the line table in the source manager block.
1132/// \returns true if there was an error.
1133bool ASTReader::ParseLineTable(ModuleFile &F,
Richard Smith7ed1bc92014-12-05 22:42:13 +00001134 const RecordData &Record) {
Guy Benyei11169dd2012-12-18 14:30:41 +00001135 unsigned Idx = 0;
1136 LineTableInfo &LineTable = SourceMgr.getLineTable();
1137
1138 // Parse the file names
1139 std::map<int, int> FileIDs;
Richard Smith63078492015-09-01 07:41:55 +00001140 for (unsigned I = 0; Record[Idx]; ++I) {
Guy Benyei11169dd2012-12-18 14:30:41 +00001141 // Extract the file name
Richard Smith7ed1bc92014-12-05 22:42:13 +00001142 auto Filename = ReadPath(F, Record, Idx);
Guy Benyei11169dd2012-12-18 14:30:41 +00001143 FileIDs[I] = LineTable.getLineTableFilenameID(Filename);
1144 }
Richard Smith63078492015-09-01 07:41:55 +00001145 ++Idx;
Guy Benyei11169dd2012-12-18 14:30:41 +00001146
1147 // Parse the line entries
1148 std::vector<LineEntry> Entries;
1149 while (Idx < Record.size()) {
1150 int FID = Record[Idx++];
1151 assert(FID >= 0 && "Serialized line entries for non-local file.");
1152 // Remap FileID from 1-based old view.
1153 FID += F.SLocEntryBaseID - 1;
1154
1155 // Extract the line entries
1156 unsigned NumEntries = Record[Idx++];
Richard Smith63078492015-09-01 07:41:55 +00001157 assert(NumEntries && "no line entries for file ID");
Guy Benyei11169dd2012-12-18 14:30:41 +00001158 Entries.clear();
1159 Entries.reserve(NumEntries);
1160 for (unsigned I = 0; I != NumEntries; ++I) {
1161 unsigned FileOffset = Record[Idx++];
1162 unsigned LineNo = Record[Idx++];
1163 int FilenameID = FileIDs[Record[Idx++]];
1164 SrcMgr::CharacteristicKind FileKind
1165 = (SrcMgr::CharacteristicKind)Record[Idx++];
1166 unsigned IncludeOffset = Record[Idx++];
1167 Entries.push_back(LineEntry::get(FileOffset, LineNo, FilenameID,
1168 FileKind, IncludeOffset));
1169 }
1170 LineTable.AddEntry(FileID::get(FID), Entries);
1171 }
1172
1173 return false;
1174}
1175
1176/// \brief Read a source manager block
1177bool ASTReader::ReadSourceManagerBlock(ModuleFile &F) {
1178 using namespace SrcMgr;
1179
Chris Lattner7fb3bef2013-01-20 00:56:42 +00001180 BitstreamCursor &SLocEntryCursor = F.SLocEntryCursor;
Guy Benyei11169dd2012-12-18 14:30:41 +00001181
1182 // Set the source-location entry cursor to the current position in
1183 // the stream. This cursor will be used to read the contents of the
1184 // source manager block initially, and then lazily read
1185 // source-location entries as needed.
1186 SLocEntryCursor = F.Stream;
1187
1188 // The stream itself is going to skip over the source manager block.
1189 if (F.Stream.SkipBlock()) {
1190 Error("malformed block record in AST file");
1191 return true;
1192 }
1193
1194 // Enter the source manager block.
1195 if (SLocEntryCursor.EnterSubBlock(SOURCE_MANAGER_BLOCK_ID)) {
1196 Error("malformed source manager block record in AST file");
1197 return true;
1198 }
1199
1200 RecordData Record;
1201 while (true) {
Chris Lattnere7b154b2013-01-19 21:39:22 +00001202 llvm::BitstreamEntry E = SLocEntryCursor.advanceSkippingSubblocks();
David L. Jonesc4808b9e2016-12-15 20:53:26 +00001203
Chris Lattnere7b154b2013-01-19 21:39:22 +00001204 switch (E.Kind) {
1205 case llvm::BitstreamEntry::SubBlock: // Handled for us already.
1206 case llvm::BitstreamEntry::Error:
1207 Error("malformed block record in AST file");
1208 return true;
1209 case llvm::BitstreamEntry::EndBlock:
Guy Benyei11169dd2012-12-18 14:30:41 +00001210 return false;
Chris Lattnere7b154b2013-01-19 21:39:22 +00001211 case llvm::BitstreamEntry::Record:
1212 // The interesting case.
1213 break;
Guy Benyei11169dd2012-12-18 14:30:41 +00001214 }
David L. Jonesc4808b9e2016-12-15 20:53:26 +00001215
Guy Benyei11169dd2012-12-18 14:30:41 +00001216 // Read a record.
Guy Benyei11169dd2012-12-18 14:30:41 +00001217 Record.clear();
Chris Lattner15c3e7d2013-01-21 18:28:26 +00001218 StringRef Blob;
1219 switch (SLocEntryCursor.readRecord(E.ID, Record, &Blob)) {
Guy Benyei11169dd2012-12-18 14:30:41 +00001220 default: // Default behavior: ignore.
1221 break;
1222
1223 case SM_SLOC_FILE_ENTRY:
1224 case SM_SLOC_BUFFER_ENTRY:
1225 case SM_SLOC_EXPANSION_ENTRY:
1226 // Once we hit one of the source location entries, we're done.
1227 return false;
1228 }
1229 }
1230}
1231
1232/// \brief If a header file is not found at the path that we expect it to be
1233/// and the PCH file was moved from its original location, try to resolve the
1234/// file by assuming that header+PCH were moved together and the header is in
1235/// the same place relative to the PCH.
1236static std::string
1237resolveFileRelativeToOriginalDir(const std::string &Filename,
1238 const std::string &OriginalDir,
1239 const std::string &CurrDir) {
1240 assert(OriginalDir != CurrDir &&
1241 "No point trying to resolve the file if the PCH dir didn't change");
1242 using namespace llvm::sys;
1243 SmallString<128> filePath(Filename);
1244 fs::make_absolute(filePath);
1245 assert(path::is_absolute(OriginalDir));
1246 SmallString<128> currPCHPath(CurrDir);
1247
1248 path::const_iterator fileDirI = path::begin(path::parent_path(filePath)),
1249 fileDirE = path::end(path::parent_path(filePath));
1250 path::const_iterator origDirI = path::begin(OriginalDir),
1251 origDirE = path::end(OriginalDir);
1252 // Skip the common path components from filePath and OriginalDir.
1253 while (fileDirI != fileDirE && origDirI != origDirE &&
1254 *fileDirI == *origDirI) {
1255 ++fileDirI;
1256 ++origDirI;
1257 }
1258 for (; origDirI != origDirE; ++origDirI)
1259 path::append(currPCHPath, "..");
1260 path::append(currPCHPath, fileDirI, fileDirE);
1261 path::append(currPCHPath, path::filename(Filename));
1262 return currPCHPath.str();
1263}
1264
1265bool ASTReader::ReadSLocEntry(int ID) {
1266 if (ID == 0)
1267 return false;
1268
1269 if (unsigned(-ID) - 2 >= getTotalNumSLocs() || ID > 0) {
1270 Error("source location entry ID out-of-range for AST file");
1271 return true;
1272 }
1273
Richard Smithaada85c2016-02-06 02:06:43 +00001274 // Local helper to read the (possibly-compressed) buffer data following the
1275 // entry record.
1276 auto ReadBuffer = [this](
1277 BitstreamCursor &SLocEntryCursor,
1278 StringRef Name) -> std::unique_ptr<llvm::MemoryBuffer> {
1279 RecordData Record;
1280 StringRef Blob;
1281 unsigned Code = SLocEntryCursor.ReadCode();
1282 unsigned RecCode = SLocEntryCursor.readRecord(Code, Record, &Blob);
1283
1284 if (RecCode == SM_SLOC_BUFFER_BLOB_COMPRESSED) {
George Rimarc39f5492017-01-17 15:45:31 +00001285 if (!llvm::zlib::isAvailable()) {
1286 Error("zlib is not available");
1287 return nullptr;
1288 }
Richard Smithaada85c2016-02-06 02:06:43 +00001289 SmallString<0> Uncompressed;
George Rimarc39f5492017-01-17 15:45:31 +00001290 if (llvm::Error E =
1291 llvm::zlib::uncompress(Blob, Uncompressed, Record[0])) {
1292 Error("could not decompress embedded file contents: " +
1293 llvm::toString(std::move(E)));
Richard Smithaada85c2016-02-06 02:06:43 +00001294 return nullptr;
1295 }
1296 return llvm::MemoryBuffer::getMemBufferCopy(Uncompressed, Name);
1297 } else if (RecCode == SM_SLOC_BUFFER_BLOB) {
1298 return llvm::MemoryBuffer::getMemBuffer(Blob.drop_back(1), Name, true);
1299 } else {
1300 Error("AST record has invalid code");
1301 return nullptr;
1302 }
1303 };
1304
Guy Benyei11169dd2012-12-18 14:30:41 +00001305 ModuleFile *F = GlobalSLocEntryMap.find(-ID)->second;
1306 F->SLocEntryCursor.JumpToBit(F->SLocEntryOffsets[ID - F->SLocEntryBaseID]);
Chris Lattner7fb3bef2013-01-20 00:56:42 +00001307 BitstreamCursor &SLocEntryCursor = F->SLocEntryCursor;
Guy Benyei11169dd2012-12-18 14:30:41 +00001308 unsigned BaseOffset = F->SLocEntryBaseOffset;
1309
1310 ++NumSLocEntriesRead;
Chris Lattnere7b154b2013-01-19 21:39:22 +00001311 llvm::BitstreamEntry Entry = SLocEntryCursor.advance();
1312 if (Entry.Kind != llvm::BitstreamEntry::Record) {
Guy Benyei11169dd2012-12-18 14:30:41 +00001313 Error("incorrectly-formatted source location entry in AST file");
1314 return true;
1315 }
David L. Jonesc4808b9e2016-12-15 20:53:26 +00001316
Guy Benyei11169dd2012-12-18 14:30:41 +00001317 RecordData Record;
Chris Lattner0e6c9402013-01-20 02:38:54 +00001318 StringRef Blob;
1319 switch (SLocEntryCursor.readRecord(Entry.ID, Record, &Blob)) {
Guy Benyei11169dd2012-12-18 14:30:41 +00001320 default:
1321 Error("incorrectly-formatted source location entry in AST file");
1322 return true;
1323
1324 case SM_SLOC_FILE_ENTRY: {
1325 // We will detect whether a file changed and return 'Failure' for it, but
1326 // we will also try to fail gracefully by setting up the SLocEntry.
1327 unsigned InputID = Record[4];
1328 InputFile IF = getInputFile(*F, InputID);
Argyrios Kyrtzidis61c3d872013-03-01 03:26:04 +00001329 const FileEntry *File = IF.getFile();
1330 bool OverriddenBuffer = IF.isOverridden();
Guy Benyei11169dd2012-12-18 14:30:41 +00001331
Argyrios Kyrtzidis61c3d872013-03-01 03:26:04 +00001332 // Note that we only check if a File was returned. If it was out-of-date
1333 // we have complained but we will continue creating a FileID to recover
1334 // gracefully.
1335 if (!File)
Guy Benyei11169dd2012-12-18 14:30:41 +00001336 return true;
1337
1338 SourceLocation IncludeLoc = ReadSourceLocation(*F, Record[1]);
1339 if (IncludeLoc.isInvalid() && F->Kind != MK_MainFile) {
1340 // This is the module's main file.
1341 IncludeLoc = getImportLocation(F);
1342 }
1343 SrcMgr::CharacteristicKind
1344 FileCharacter = (SrcMgr::CharacteristicKind)Record[2];
1345 FileID FID = SourceMgr.createFileID(File, IncludeLoc, FileCharacter,
1346 ID, BaseOffset + Record[0]);
1347 SrcMgr::FileInfo &FileInfo =
1348 const_cast<SrcMgr::FileInfo&>(SourceMgr.getSLocEntry(FID).getFile());
1349 FileInfo.NumCreatedFIDs = Record[5];
1350 if (Record[3])
1351 FileInfo.setHasLineDirectives();
1352
1353 const DeclID *FirstDecl = F->FileSortedDecls + Record[6];
1354 unsigned NumFileDecls = Record[7];
1355 if (NumFileDecls) {
1356 assert(F->FileSortedDecls && "FILE_SORTED_DECLS not encountered yet ?");
1357 FileDeclIDs[FID] = FileDeclsInfo(F, llvm::makeArrayRef(FirstDecl,
1358 NumFileDecls));
1359 }
Richard Smithaada85c2016-02-06 02:06:43 +00001360
Guy Benyei11169dd2012-12-18 14:30:41 +00001361 const SrcMgr::ContentCache *ContentCache
1362 = SourceMgr.getOrCreateContentCache(File,
1363 /*isSystemFile=*/FileCharacter != SrcMgr::C_User);
1364 if (OverriddenBuffer && !ContentCache->BufferOverridden &&
Richard Smitha8cfffa2015-11-26 02:04:16 +00001365 ContentCache->ContentsEntry == ContentCache->OrigEntry &&
1366 !ContentCache->getRawBuffer()) {
Richard Smithaada85c2016-02-06 02:06:43 +00001367 auto Buffer = ReadBuffer(SLocEntryCursor, File->getName());
1368 if (!Buffer)
Guy Benyei11169dd2012-12-18 14:30:41 +00001369 return true;
David Blaikie49cc3182014-08-27 20:54:45 +00001370 SourceMgr.overrideFileContents(File, std::move(Buffer));
Guy Benyei11169dd2012-12-18 14:30:41 +00001371 }
1372
1373 break;
1374 }
1375
1376 case SM_SLOC_BUFFER_ENTRY: {
Chris Lattner0e6c9402013-01-20 02:38:54 +00001377 const char *Name = Blob.data();
Guy Benyei11169dd2012-12-18 14:30:41 +00001378 unsigned Offset = Record[0];
1379 SrcMgr::CharacteristicKind
1380 FileCharacter = (SrcMgr::CharacteristicKind)Record[2];
1381 SourceLocation IncludeLoc = ReadSourceLocation(*F, Record[1]);
Manman Ren11f2a472016-08-18 17:42:15 +00001382 if (IncludeLoc.isInvalid() && F->isModule()) {
Guy Benyei11169dd2012-12-18 14:30:41 +00001383 IncludeLoc = getImportLocation(F);
1384 }
Guy Benyei11169dd2012-12-18 14:30:41 +00001385
Richard Smithaada85c2016-02-06 02:06:43 +00001386 auto Buffer = ReadBuffer(SLocEntryCursor, Name);
1387 if (!Buffer)
Guy Benyei11169dd2012-12-18 14:30:41 +00001388 return true;
David Blaikie50a5f972014-08-29 07:59:55 +00001389 SourceMgr.createFileID(std::move(Buffer), FileCharacter, ID,
Rafael Espindolad87f8d72014-08-27 20:03:29 +00001390 BaseOffset + Offset, IncludeLoc);
Guy Benyei11169dd2012-12-18 14:30:41 +00001391 break;
1392 }
1393
1394 case SM_SLOC_EXPANSION_ENTRY: {
1395 SourceLocation SpellingLoc = ReadSourceLocation(*F, Record[1]);
1396 SourceMgr.createExpansionLoc(SpellingLoc,
1397 ReadSourceLocation(*F, Record[2]),
1398 ReadSourceLocation(*F, Record[3]),
1399 Record[4],
1400 ID,
1401 BaseOffset + Record[0]);
1402 break;
1403 }
1404 }
1405
1406 return false;
1407}
1408
1409std::pair<SourceLocation, StringRef> ASTReader::getModuleImportLoc(int ID) {
1410 if (ID == 0)
1411 return std::make_pair(SourceLocation(), "");
1412
1413 if (unsigned(-ID) - 2 >= getTotalNumSLocs() || ID > 0) {
1414 Error("source location entry ID out-of-range for AST file");
1415 return std::make_pair(SourceLocation(), "");
1416 }
1417
1418 // Find which module file this entry lands in.
1419 ModuleFile *M = GlobalSLocEntryMap.find(-ID)->second;
Manman Ren11f2a472016-08-18 17:42:15 +00001420 if (!M->isModule())
Guy Benyei11169dd2012-12-18 14:30:41 +00001421 return std::make_pair(SourceLocation(), "");
1422
1423 // FIXME: Can we map this down to a particular submodule? That would be
1424 // ideal.
Ben Langmuirbeee15e2014-04-14 18:00:01 +00001425 return std::make_pair(M->ImportLoc, StringRef(M->ModuleName));
Guy Benyei11169dd2012-12-18 14:30:41 +00001426}
1427
1428/// \brief Find the location where the module F is imported.
1429SourceLocation ASTReader::getImportLocation(ModuleFile *F) {
1430 if (F->ImportLoc.isValid())
1431 return F->ImportLoc;
David L. Jonesc4808b9e2016-12-15 20:53:26 +00001432
Guy Benyei11169dd2012-12-18 14:30:41 +00001433 // Otherwise we have a PCH. It's considered to be "imported" at the first
1434 // location of its includer.
1435 if (F->ImportedBy.empty() || !F->ImportedBy[0]) {
Ben Langmuirbeee15e2014-04-14 18:00:01 +00001436 // Main file is the importer.
Yaron Keren8b563662015-10-03 10:46:20 +00001437 assert(SourceMgr.getMainFileID().isValid() && "missing main file");
Ben Langmuirbeee15e2014-04-14 18:00:01 +00001438 return SourceMgr.getLocForStartOfFile(SourceMgr.getMainFileID());
Guy Benyei11169dd2012-12-18 14:30:41 +00001439 }
Guy Benyei11169dd2012-12-18 14:30:41 +00001440 return F->ImportedBy[0]->FirstLoc;
1441}
1442
1443/// ReadBlockAbbrevs - Enter a subblock of the specified BlockID with the
1444/// specified cursor. Read the abbreviations that are at the top of the block
1445/// and then leave the cursor pointing into the block.
Chris Lattner7fb3bef2013-01-20 00:56:42 +00001446bool ASTReader::ReadBlockAbbrevs(BitstreamCursor &Cursor, unsigned BlockID) {
Richard Smith0516b182015-09-08 19:40:14 +00001447 if (Cursor.EnterSubBlock(BlockID))
1448 return true;
Guy Benyei11169dd2012-12-18 14:30:41 +00001449
1450 while (true) {
1451 uint64_t Offset = Cursor.GetCurrentBitNo();
1452 unsigned Code = Cursor.ReadCode();
1453
1454 // We expect all abbrevs to be at the start of the block.
1455 if (Code != llvm::bitc::DEFINE_ABBREV) {
1456 Cursor.JumpToBit(Offset);
1457 return false;
1458 }
1459 Cursor.ReadAbbrevRecord();
1460 }
1461}
1462
Richard Smithe40f2ba2013-08-07 21:41:30 +00001463Token ASTReader::ReadToken(ModuleFile &F, const RecordDataImpl &Record,
John McCallf413f5e2013-05-03 00:10:13 +00001464 unsigned &Idx) {
1465 Token Tok;
1466 Tok.startToken();
1467 Tok.setLocation(ReadSourceLocation(F, Record, Idx));
1468 Tok.setLength(Record[Idx++]);
1469 if (IdentifierInfo *II = getLocalIdentifier(F, Record[Idx++]))
1470 Tok.setIdentifierInfo(II);
1471 Tok.setKind((tok::TokenKind)Record[Idx++]);
1472 Tok.setFlag((Token::TokenFlags)Record[Idx++]);
1473 return Tok;
1474}
1475
Argyrios Kyrtzidiseb663da2013-03-22 21:12:57 +00001476MacroInfo *ASTReader::ReadMacroRecord(ModuleFile &F, uint64_t Offset) {
Chris Lattner7fb3bef2013-01-20 00:56:42 +00001477 BitstreamCursor &Stream = F.MacroCursor;
Guy Benyei11169dd2012-12-18 14:30:41 +00001478
1479 // Keep track of where we are in the stream, then jump back there
1480 // after reading this macro.
1481 SavedStreamPosition SavedPosition(Stream);
1482
1483 Stream.JumpToBit(Offset);
1484 RecordData Record;
1485 SmallVector<IdentifierInfo*, 16> MacroArgs;
Craig Toppera13603a2014-05-22 05:54:18 +00001486 MacroInfo *Macro = nullptr;
Guy Benyei11169dd2012-12-18 14:30:41 +00001487
Guy Benyei11169dd2012-12-18 14:30:41 +00001488 while (true) {
Chris Lattnerefa77172013-01-20 00:00:22 +00001489 // Advance to the next record, but if we get to the end of the block, don't
1490 // pop it (removing all the abbreviations from the cursor) since we want to
1491 // be able to reseek within the block and read entries.
Chris Lattner7fb3bef2013-01-20 00:56:42 +00001492 unsigned Flags = BitstreamCursor::AF_DontPopBlockAtEnd;
Chris Lattnerefa77172013-01-20 00:00:22 +00001493 llvm::BitstreamEntry Entry = Stream.advanceSkippingSubblocks(Flags);
David L. Jonesc4808b9e2016-12-15 20:53:26 +00001494
Chris Lattnerefa77172013-01-20 00:00:22 +00001495 switch (Entry.Kind) {
1496 case llvm::BitstreamEntry::SubBlock: // Handled for us already.
1497 case llvm::BitstreamEntry::Error:
1498 Error("malformed block record in AST file");
Argyrios Kyrtzidiseb663da2013-03-22 21:12:57 +00001499 return Macro;
Chris Lattnerefa77172013-01-20 00:00:22 +00001500 case llvm::BitstreamEntry::EndBlock:
Argyrios Kyrtzidiseb663da2013-03-22 21:12:57 +00001501 return Macro;
Chris Lattnerefa77172013-01-20 00:00:22 +00001502 case llvm::BitstreamEntry::Record:
1503 // The interesting case.
1504 break;
Guy Benyei11169dd2012-12-18 14:30:41 +00001505 }
1506
1507 // Read a record.
Guy Benyei11169dd2012-12-18 14:30:41 +00001508 Record.clear();
1509 PreprocessorRecordTypes RecType =
Chris Lattner0e6c9402013-01-20 02:38:54 +00001510 (PreprocessorRecordTypes)Stream.readRecord(Entry.ID, Record);
Guy Benyei11169dd2012-12-18 14:30:41 +00001511 switch (RecType) {
Richard Smithd7329392015-04-21 21:46:32 +00001512 case PP_MODULE_MACRO:
Argyrios Kyrtzidiseb663da2013-03-22 21:12:57 +00001513 case PP_MACRO_DIRECTIVE_HISTORY:
1514 return Macro;
1515
Guy Benyei11169dd2012-12-18 14:30:41 +00001516 case PP_MACRO_OBJECT_LIKE:
1517 case PP_MACRO_FUNCTION_LIKE: {
1518 // If we already have a macro, that means that we've hit the end
1519 // of the definition of the macro we were looking for. We're
1520 // done.
1521 if (Macro)
Argyrios Kyrtzidiseb663da2013-03-22 21:12:57 +00001522 return Macro;
Guy Benyei11169dd2012-12-18 14:30:41 +00001523
Argyrios Kyrtzidiseb663da2013-03-22 21:12:57 +00001524 unsigned NextIndex = 1; // Skip identifier ID.
1525 SubmoduleID SubModID = getGlobalSubmoduleID(F, Record[NextIndex++]);
Guy Benyei11169dd2012-12-18 14:30:41 +00001526 SourceLocation Loc = ReadSourceLocation(F, Record, NextIndex);
Argyrios Kyrtzidiseb663da2013-03-22 21:12:57 +00001527 MacroInfo *MI = PP.AllocateDeserializedMacroInfo(Loc, SubModID);
Argyrios Kyrtzidis7572be22013-01-07 19:16:23 +00001528 MI->setDefinitionEndLoc(ReadSourceLocation(F, Record, NextIndex));
Guy Benyei11169dd2012-12-18 14:30:41 +00001529 MI->setIsUsed(Record[NextIndex++]);
Argyrios Kyrtzidis9ef53ce2014-04-09 18:21:23 +00001530 MI->setUsedForHeaderGuard(Record[NextIndex++]);
Guy Benyei11169dd2012-12-18 14:30:41 +00001531
Guy Benyei11169dd2012-12-18 14:30:41 +00001532 if (RecType == PP_MACRO_FUNCTION_LIKE) {
1533 // Decode function-like macro info.
1534 bool isC99VarArgs = Record[NextIndex++];
1535 bool isGNUVarArgs = Record[NextIndex++];
1536 bool hasCommaPasting = Record[NextIndex++];
1537 MacroArgs.clear();
1538 unsigned NumArgs = Record[NextIndex++];
1539 for (unsigned i = 0; i != NumArgs; ++i)
1540 MacroArgs.push_back(getLocalIdentifier(F, Record[NextIndex++]));
1541
1542 // Install function-like macro info.
1543 MI->setIsFunctionLike();
1544 if (isC99VarArgs) MI->setIsC99Varargs();
1545 if (isGNUVarArgs) MI->setIsGNUVarargs();
1546 if (hasCommaPasting) MI->setHasCommaPasting();
Craig Topperd96b3f92015-10-22 04:59:52 +00001547 MI->setArgumentList(MacroArgs, PP.getPreprocessorAllocator());
Guy Benyei11169dd2012-12-18 14:30:41 +00001548 }
1549
Guy Benyei11169dd2012-12-18 14:30:41 +00001550 // Remember that we saw this macro last so that we add the tokens that
1551 // form its body to it.
1552 Macro = MI;
1553
1554 if (NextIndex + 1 == Record.size() && PP.getPreprocessingRecord() &&
1555 Record[NextIndex]) {
1556 // We have a macro definition. Register the association
1557 PreprocessedEntityID
1558 GlobalID = getGlobalPreprocessedEntityID(F, Record[NextIndex]);
1559 PreprocessingRecord &PPRec = *PP.getPreprocessingRecord();
Richard Smith66a81862015-05-04 02:25:31 +00001560 PreprocessingRecord::PPEntityID PPID =
1561 PPRec.getPPEntityID(GlobalID - 1, /*isLoaded=*/true);
1562 MacroDefinitionRecord *PPDef = cast_or_null<MacroDefinitionRecord>(
1563 PPRec.getPreprocessedEntity(PPID));
Argyrios Kyrtzidis832de9f2013-02-22 18:35:59 +00001564 if (PPDef)
1565 PPRec.RegisterMacroDefinition(Macro, PPDef);
Guy Benyei11169dd2012-12-18 14:30:41 +00001566 }
1567
1568 ++NumMacrosRead;
1569 break;
1570 }
1571
1572 case PP_TOKEN: {
1573 // If we see a TOKEN before a PP_MACRO_*, then the file is
1574 // erroneous, just pretend we didn't see this.
Craig Toppera13603a2014-05-22 05:54:18 +00001575 if (!Macro) break;
Guy Benyei11169dd2012-12-18 14:30:41 +00001576
John McCallf413f5e2013-05-03 00:10:13 +00001577 unsigned Idx = 0;
1578 Token Tok = ReadToken(F, Record, Idx);
Guy Benyei11169dd2012-12-18 14:30:41 +00001579 Macro->AddTokenToBody(Tok);
1580 break;
1581 }
1582 }
1583 }
1584}
1585
David L. Jonesc4808b9e2016-12-15 20:53:26 +00001586PreprocessedEntityID
Guy Benyei11169dd2012-12-18 14:30:41 +00001587ASTReader::getGlobalPreprocessedEntityID(ModuleFile &M, unsigned LocalID) const {
David L. Jonesc4808b9e2016-12-15 20:53:26 +00001588 ContinuousRangeMap<uint32_t, int, 2>::const_iterator
Guy Benyei11169dd2012-12-18 14:30:41 +00001589 I = M.PreprocessedEntityRemap.find(LocalID - NUM_PREDEF_PP_ENTITY_IDS);
David L. Jonesc4808b9e2016-12-15 20:53:26 +00001590 assert(I != M.PreprocessedEntityRemap.end()
Guy Benyei11169dd2012-12-18 14:30:41 +00001591 && "Invalid index into preprocessed entity index remap");
David L. Jonesc4808b9e2016-12-15 20:53:26 +00001592
Guy Benyei11169dd2012-12-18 14:30:41 +00001593 return LocalID + I->second;
1594}
1595
Argyrios Kyrtzidis5c2a3452013-03-06 18:12:47 +00001596unsigned HeaderFileInfoTrait::ComputeHash(internal_key_ref ikey) {
1597 return llvm::hash_combine(ikey.Size, ikey.ModTime);
Guy Benyei11169dd2012-12-18 14:30:41 +00001598}
Richard Smith7ed1bc92014-12-05 22:42:13 +00001599
David L. Jonesc4808b9e2016-12-15 20:53:26 +00001600HeaderFileInfoTrait::internal_key_type
Argyrios Kyrtzidis5c2a3452013-03-06 18:12:47 +00001601HeaderFileInfoTrait::GetInternalKey(const FileEntry *FE) {
Richard Smithe75ee0f2015-08-17 07:13:32 +00001602 internal_key_type ikey = {FE->getSize(),
1603 M.HasTimestamps ? FE->getModificationTime() : 0,
1604 FE->getName(), /*Imported*/ false};
Argyrios Kyrtzidis5c2a3452013-03-06 18:12:47 +00001605 return ikey;
1606}
David L. Jonesc4808b9e2016-12-15 20:53:26 +00001607
Argyrios Kyrtzidis5c2a3452013-03-06 18:12:47 +00001608bool HeaderFileInfoTrait::EqualKey(internal_key_ref a, internal_key_ref b) {
Richard Smithe75ee0f2015-08-17 07:13:32 +00001609 if (a.Size != b.Size || (a.ModTime && b.ModTime && a.ModTime != b.ModTime))
Guy Benyei11169dd2012-12-18 14:30:41 +00001610 return false;
1611
Mehdi Amini004b9c72016-10-10 22:52:47 +00001612 if (llvm::sys::path::is_absolute(a.Filename) && a.Filename == b.Filename)
Argyrios Kyrtzidis5c2a3452013-03-06 18:12:47 +00001613 return true;
David L. Jonesc4808b9e2016-12-15 20:53:26 +00001614
Guy Benyei11169dd2012-12-18 14:30:41 +00001615 // Determine whether the actual files are equivalent.
Argyrios Kyrtzidis2a513e82013-03-04 20:33:40 +00001616 FileManager &FileMgr = Reader.getFileManager();
Richard Smith7ed1bc92014-12-05 22:42:13 +00001617 auto GetFile = [&](const internal_key_type &Key) -> const FileEntry* {
1618 if (!Key.Imported)
1619 return FileMgr.getFile(Key.Filename);
1620
1621 std::string Resolved = Key.Filename;
1622 Reader.ResolveImportedPath(M, Resolved);
1623 return FileMgr.getFile(Resolved);
1624 };
1625
1626 const FileEntry *FEA = GetFile(a);
1627 const FileEntry *FEB = GetFile(b);
1628 return FEA && FEA == FEB;
Guy Benyei11169dd2012-12-18 14:30:41 +00001629}
David L. Jonesc4808b9e2016-12-15 20:53:26 +00001630
Guy Benyei11169dd2012-12-18 14:30:41 +00001631std::pair<unsigned, unsigned>
1632HeaderFileInfoTrait::ReadKeyDataLength(const unsigned char*& d) {
Justin Bogner57ba0b22014-03-28 22:03:24 +00001633 using namespace llvm::support;
1634 unsigned KeyLen = (unsigned) endian::readNext<uint16_t, little, unaligned>(d);
Guy Benyei11169dd2012-12-18 14:30:41 +00001635 unsigned DataLen = (unsigned) *d++;
Argyrios Kyrtzidis5c2a3452013-03-06 18:12:47 +00001636 return std::make_pair(KeyLen, DataLen);
Guy Benyei11169dd2012-12-18 14:30:41 +00001637}
Argyrios Kyrtzidis5c2a3452013-03-06 18:12:47 +00001638
1639HeaderFileInfoTrait::internal_key_type
1640HeaderFileInfoTrait::ReadKey(const unsigned char *d, unsigned) {
Justin Bogner57ba0b22014-03-28 22:03:24 +00001641 using namespace llvm::support;
Argyrios Kyrtzidis5c2a3452013-03-06 18:12:47 +00001642 internal_key_type ikey;
Justin Bogner57ba0b22014-03-28 22:03:24 +00001643 ikey.Size = off_t(endian::readNext<uint64_t, little, unaligned>(d));
1644 ikey.ModTime = time_t(endian::readNext<uint64_t, little, unaligned>(d));
Argyrios Kyrtzidis5c2a3452013-03-06 18:12:47 +00001645 ikey.Filename = (const char *)d;
Richard Smith7ed1bc92014-12-05 22:42:13 +00001646 ikey.Imported = true;
Argyrios Kyrtzidis5c2a3452013-03-06 18:12:47 +00001647 return ikey;
1648}
1649
David L. Jonesc4808b9e2016-12-15 20:53:26 +00001650HeaderFileInfoTrait::data_type
Argyrios Kyrtzidisb146baa2013-03-13 21:13:51 +00001651HeaderFileInfoTrait::ReadData(internal_key_ref key, const unsigned char *d,
Guy Benyei11169dd2012-12-18 14:30:41 +00001652 unsigned DataLen) {
1653 const unsigned char *End = d + DataLen;
Justin Bogner57ba0b22014-03-28 22:03:24 +00001654 using namespace llvm::support;
Guy Benyei11169dd2012-12-18 14:30:41 +00001655 HeaderFileInfo HFI;
1656 unsigned Flags = *d++;
Richard Smith386bb072015-08-18 23:42:23 +00001657 // FIXME: Refactor with mergeHeaderFileInfo in HeaderSearch.cpp.
1658 HFI.isImport |= (Flags >> 4) & 0x01;
1659 HFI.isPragmaOnce |= (Flags >> 3) & 0x01;
1660 HFI.DirInfo = (Flags >> 1) & 0x03;
Guy Benyei11169dd2012-12-18 14:30:41 +00001661 HFI.IndexHeaderMapHeader = Flags & 0x01;
Richard Smith386bb072015-08-18 23:42:23 +00001662 // FIXME: Find a better way to handle this. Maybe just store a
1663 // "has been included" flag?
1664 HFI.NumIncludes = std::max(endian::readNext<uint16_t, little, unaligned>(d),
1665 HFI.NumIncludes);
Justin Bogner57ba0b22014-03-28 22:03:24 +00001666 HFI.ControllingMacroID = Reader.getGlobalIdentifierID(
1667 M, endian::readNext<uint32_t, little, unaligned>(d));
1668 if (unsigned FrameworkOffset =
1669 endian::readNext<uint32_t, little, unaligned>(d)) {
David L. Jonesc4808b9e2016-12-15 20:53:26 +00001670 // The framework offset is 1 greater than the actual offset,
Guy Benyei11169dd2012-12-18 14:30:41 +00001671 // since 0 is used as an indicator for "no framework name".
1672 StringRef FrameworkName(FrameworkStrings + FrameworkOffset - 1);
1673 HFI.Framework = HS->getUniqueFrameworkName(FrameworkName);
1674 }
Richard Smith386bb072015-08-18 23:42:23 +00001675
1676 assert((End - d) % 4 == 0 &&
1677 "Wrong data length in HeaderFileInfo deserialization");
1678 while (d != End) {
Justin Bogner57ba0b22014-03-28 22:03:24 +00001679 uint32_t LocalSMID = endian::readNext<uint32_t, little, unaligned>(d);
Richard Smith386bb072015-08-18 23:42:23 +00001680 auto HeaderRole = static_cast<ModuleMap::ModuleHeaderRole>(LocalSMID & 3);
1681 LocalSMID >>= 2;
1682
1683 // This header is part of a module. Associate it with the module to enable
1684 // implicit module import.
1685 SubmoduleID GlobalSMID = Reader.getGlobalSubmoduleID(M, LocalSMID);
1686 Module *Mod = Reader.getSubmodule(GlobalSMID);
1687 FileManager &FileMgr = Reader.getFileManager();
1688 ModuleMap &ModMap =
1689 Reader.getPreprocessor().getHeaderSearchInfo().getModuleMap();
1690
1691 std::string Filename = key.Filename;
1692 if (key.Imported)
1693 Reader.ResolveImportedPath(M, Filename);
1694 // FIXME: This is not always the right filename-as-written, but we're not
1695 // going to use this information to rebuild the module, so it doesn't make
1696 // a lot of difference.
1697 Module::Header H = { key.Filename, FileMgr.getFile(Filename) };
Richard Smithd8879c82015-08-24 21:59:32 +00001698 ModMap.addHeader(Mod, H, HeaderRole, /*Imported*/true);
1699 HFI.isModuleHeader |= !(HeaderRole & ModuleMap::TextualHeader);
Argyrios Kyrtzidisb146baa2013-03-13 21:13:51 +00001700 }
1701
Guy Benyei11169dd2012-12-18 14:30:41 +00001702 // This HeaderFileInfo was externally loaded.
1703 HFI.External = true;
Richard Smithd8879c82015-08-24 21:59:32 +00001704 HFI.IsValid = true;
Guy Benyei11169dd2012-12-18 14:30:41 +00001705 return HFI;
1706}
1707
Richard Smithd7329392015-04-21 21:46:32 +00001708void ASTReader::addPendingMacro(IdentifierInfo *II,
1709 ModuleFile *M,
1710 uint64_t MacroDirectivesOffset) {
Argyrios Kyrtzidiseb663da2013-03-22 21:12:57 +00001711 assert(NumCurrentElementsDeserializing > 0 &&"Missing deserialization guard");
1712 PendingMacroIDs[II].push_back(PendingMacroInfo(M, MacroDirectivesOffset));
Guy Benyei11169dd2012-12-18 14:30:41 +00001713}
1714
1715void ASTReader::ReadDefinedMacros() {
1716 // Note that we are loading defined macros.
1717 Deserializing Macros(this);
1718
Duncan P. N. Exon Smith96a06e02017-01-28 22:15:22 +00001719 for (ModuleFile &I : llvm::reverse(ModuleMgr)) {
1720 BitstreamCursor &MacroCursor = I.MacroCursor;
Guy Benyei11169dd2012-12-18 14:30:41 +00001721
1722 // If there was no preprocessor block, skip this file.
Peter Collingbourne77c89b62016-11-08 04:17:11 +00001723 if (MacroCursor.getBitcodeBytes().empty())
Guy Benyei11169dd2012-12-18 14:30:41 +00001724 continue;
1725
Chris Lattner7fb3bef2013-01-20 00:56:42 +00001726 BitstreamCursor Cursor = MacroCursor;
Duncan P. N. Exon Smith96a06e02017-01-28 22:15:22 +00001727 Cursor.JumpToBit(I.MacroStartOffset);
Guy Benyei11169dd2012-12-18 14:30:41 +00001728
1729 RecordData Record;
1730 while (true) {
Chris Lattnere7b154b2013-01-19 21:39:22 +00001731 llvm::BitstreamEntry E = Cursor.advanceSkippingSubblocks();
David L. Jonesc4808b9e2016-12-15 20:53:26 +00001732
Chris Lattnere7b154b2013-01-19 21:39:22 +00001733 switch (E.Kind) {
1734 case llvm::BitstreamEntry::SubBlock: // Handled for us already.
1735 case llvm::BitstreamEntry::Error:
1736 Error("malformed block record in AST file");
1737 return;
1738 case llvm::BitstreamEntry::EndBlock:
1739 goto NextCursor;
David L. Jonesc4808b9e2016-12-15 20:53:26 +00001740
Chris Lattnere7b154b2013-01-19 21:39:22 +00001741 case llvm::BitstreamEntry::Record:
Chris Lattnere7b154b2013-01-19 21:39:22 +00001742 Record.clear();
Chris Lattner0e6c9402013-01-20 02:38:54 +00001743 switch (Cursor.readRecord(E.ID, Record)) {
Chris Lattnere7b154b2013-01-19 21:39:22 +00001744 default: // Default behavior: ignore.
1745 break;
David L. Jonesc4808b9e2016-12-15 20:53:26 +00001746
Chris Lattnere7b154b2013-01-19 21:39:22 +00001747 case PP_MACRO_OBJECT_LIKE:
Sean Callananf3682a72016-05-14 06:24:14 +00001748 case PP_MACRO_FUNCTION_LIKE: {
Duncan P. N. Exon Smith96a06e02017-01-28 22:15:22 +00001749 IdentifierInfo *II = getLocalIdentifier(I, Record[0]);
Sean Callananf3682a72016-05-14 06:24:14 +00001750 if (II->isOutOfDate())
1751 updateOutOfDateIdentifier(*II);
Chris Lattnere7b154b2013-01-19 21:39:22 +00001752 break;
Sean Callananf3682a72016-05-14 06:24:14 +00001753 }
David L. Jonesc4808b9e2016-12-15 20:53:26 +00001754
Chris Lattnere7b154b2013-01-19 21:39:22 +00001755 case PP_TOKEN:
1756 // Ignore tokens.
1757 break;
Guy Benyei11169dd2012-12-18 14:30:41 +00001758 }
Guy Benyei11169dd2012-12-18 14:30:41 +00001759 break;
1760 }
1761 }
Chris Lattnere7b154b2013-01-19 21:39:22 +00001762 NextCursor: ;
Guy Benyei11169dd2012-12-18 14:30:41 +00001763 }
1764}
1765
1766namespace {
Eugene Zelenkoe95e7d52016-09-07 21:53:17 +00001767
Guy Benyei11169dd2012-12-18 14:30:41 +00001768 /// \brief Visitor class used to look up identifirs in an AST file.
1769 class IdentifierLookupVisitor {
1770 StringRef Name;
Richard Smith3b637412015-07-14 18:42:41 +00001771 unsigned NameHash;
Guy Benyei11169dd2012-12-18 14:30:41 +00001772 unsigned PriorGeneration;
Douglas Gregor00a50f72013-01-25 00:38:33 +00001773 unsigned &NumIdentifierLookups;
1774 unsigned &NumIdentifierLookupHits;
Guy Benyei11169dd2012-12-18 14:30:41 +00001775 IdentifierInfo *Found;
Douglas Gregor00a50f72013-01-25 00:38:33 +00001776
Guy Benyei11169dd2012-12-18 14:30:41 +00001777 public:
Douglas Gregor00a50f72013-01-25 00:38:33 +00001778 IdentifierLookupVisitor(StringRef Name, unsigned PriorGeneration,
1779 unsigned &NumIdentifierLookups,
1780 unsigned &NumIdentifierLookupHits)
Richard Smith3b637412015-07-14 18:42:41 +00001781 : Name(Name), NameHash(ASTIdentifierLookupTrait::ComputeHash(Name)),
1782 PriorGeneration(PriorGeneration),
Douglas Gregor00a50f72013-01-25 00:38:33 +00001783 NumIdentifierLookups(NumIdentifierLookups),
1784 NumIdentifierLookupHits(NumIdentifierLookupHits),
1785 Found()
1786 {
1787 }
Benjamin Kramer9a9efba2015-07-25 12:14:04 +00001788
1789 bool operator()(ModuleFile &M) {
Guy Benyei11169dd2012-12-18 14:30:41 +00001790 // If we've already searched this module file, skip it now.
Richard Smithbdf2d932015-07-30 03:37:16 +00001791 if (M.Generation <= PriorGeneration)
Guy Benyei11169dd2012-12-18 14:30:41 +00001792 return true;
Douglas Gregore060e572013-01-25 01:03:03 +00001793
Guy Benyei11169dd2012-12-18 14:30:41 +00001794 ASTIdentifierLookupTable *IdTable
1795 = (ASTIdentifierLookupTable *)M.IdentifierLookupTable;
1796 if (!IdTable)
1797 return false;
Benjamin Kramer9a9efba2015-07-25 12:14:04 +00001798
1799 ASTIdentifierLookupTrait Trait(IdTable->getInfoObj().getReader(), M,
Richard Smithbdf2d932015-07-30 03:37:16 +00001800 Found);
1801 ++NumIdentifierLookups;
Richard Smith3b637412015-07-14 18:42:41 +00001802 ASTIdentifierLookupTable::iterator Pos =
Richard Smithbdf2d932015-07-30 03:37:16 +00001803 IdTable->find_hashed(Name, NameHash, &Trait);
Guy Benyei11169dd2012-12-18 14:30:41 +00001804 if (Pos == IdTable->end())
1805 return false;
David L. Jonesc4808b9e2016-12-15 20:53:26 +00001806
Guy Benyei11169dd2012-12-18 14:30:41 +00001807 // Dereferencing the iterator has the effect of building the
1808 // IdentifierInfo node and populating it with the various
1809 // declarations it needs.
Richard Smithbdf2d932015-07-30 03:37:16 +00001810 ++NumIdentifierLookupHits;
1811 Found = *Pos;
Guy Benyei11169dd2012-12-18 14:30:41 +00001812 return true;
1813 }
David L. Jonesc4808b9e2016-12-15 20:53:26 +00001814
Guy Benyei11169dd2012-12-18 14:30:41 +00001815 // \brief Retrieve the identifier info found within the module
1816 // files.
1817 IdentifierInfo *getIdentifierInfo() const { return Found; }
1818 };
Eugene Zelenkoe95e7d52016-09-07 21:53:17 +00001819
1820} // end anonymous namespace
Guy Benyei11169dd2012-12-18 14:30:41 +00001821
1822void ASTReader::updateOutOfDateIdentifier(IdentifierInfo &II) {
1823 // Note that we are loading an identifier.
1824 Deserializing AnIdentifier(this);
1825
1826 unsigned PriorGeneration = 0;
1827 if (getContext().getLangOpts().Modules)
1828 PriorGeneration = IdentifierGeneration[&II];
Douglas Gregore060e572013-01-25 01:03:03 +00001829
1830 // If there is a global index, look there first to determine which modules
1831 // provably do not have any results for this identifier.
Douglas Gregor7211ac12013-01-25 23:32:03 +00001832 GlobalModuleIndex::HitSet Hits;
Craig Toppera13603a2014-05-22 05:54:18 +00001833 GlobalModuleIndex::HitSet *HitsPtr = nullptr;
Douglas Gregore060e572013-01-25 01:03:03 +00001834 if (!loadGlobalIndex()) {
Douglas Gregor7211ac12013-01-25 23:32:03 +00001835 if (GlobalIndex->lookupIdentifier(II.getName(), Hits)) {
1836 HitsPtr = &Hits;
Douglas Gregore060e572013-01-25 01:03:03 +00001837 }
1838 }
1839
Douglas Gregor7211ac12013-01-25 23:32:03 +00001840 IdentifierLookupVisitor Visitor(II.getName(), PriorGeneration,
Douglas Gregor00a50f72013-01-25 00:38:33 +00001841 NumIdentifierLookups,
1842 NumIdentifierLookupHits);
Benjamin Kramer9a9efba2015-07-25 12:14:04 +00001843 ModuleMgr.visit(Visitor, HitsPtr);
Guy Benyei11169dd2012-12-18 14:30:41 +00001844 markIdentifierUpToDate(&II);
1845}
1846
1847void ASTReader::markIdentifierUpToDate(IdentifierInfo *II) {
1848 if (!II)
1849 return;
David L. Jonesc4808b9e2016-12-15 20:53:26 +00001850
Guy Benyei11169dd2012-12-18 14:30:41 +00001851 II->setOutOfDate(false);
1852
1853 // Update the generation for this identifier.
1854 if (getContext().getLangOpts().Modules)
Richard Smith053f6c62014-05-16 23:01:30 +00001855 IdentifierGeneration[II] = getGeneration();
Guy Benyei11169dd2012-12-18 14:30:41 +00001856}
1857
Argyrios Kyrtzidiseb663da2013-03-22 21:12:57 +00001858void ASTReader::resolvePendingMacro(IdentifierInfo *II,
1859 const PendingMacroInfo &PMInfo) {
Richard Smithd7329392015-04-21 21:46:32 +00001860 ModuleFile &M = *PMInfo.M;
Argyrios Kyrtzidiseb663da2013-03-22 21:12:57 +00001861
1862 BitstreamCursor &Cursor = M.MacroCursor;
1863 SavedStreamPosition SavedPosition(Cursor);
Richard Smithd7329392015-04-21 21:46:32 +00001864 Cursor.JumpToBit(PMInfo.MacroDirectivesOffset);
Argyrios Kyrtzidiseb663da2013-03-22 21:12:57 +00001865
Richard Smith713369b2015-04-23 20:40:50 +00001866 struct ModuleMacroRecord {
1867 SubmoduleID SubModID;
1868 MacroInfo *MI;
1869 SmallVector<SubmoduleID, 8> Overrides;
1870 };
1871 llvm::SmallVector<ModuleMacroRecord, 8> ModuleMacros;
Argyrios Kyrtzidiseb663da2013-03-22 21:12:57 +00001872
Richard Smithd7329392015-04-21 21:46:32 +00001873 // We expect to see a sequence of PP_MODULE_MACRO records listing exported
1874 // macros, followed by a PP_MACRO_DIRECTIVE_HISTORY record with the complete
1875 // macro histroy.
Argyrios Kyrtzidiseb663da2013-03-22 21:12:57 +00001876 RecordData Record;
Richard Smithd7329392015-04-21 21:46:32 +00001877 while (true) {
1878 llvm::BitstreamEntry Entry =
1879 Cursor.advance(BitstreamCursor::AF_DontPopBlockAtEnd);
1880 if (Entry.Kind != llvm::BitstreamEntry::Record) {
1881 Error("malformed block record in AST file");
1882 return;
1883 }
1884
1885 Record.clear();
Aaron Ballmanc75a1922015-04-22 15:25:05 +00001886 switch ((PreprocessorRecordTypes)Cursor.readRecord(Entry.ID, Record)) {
Richard Smithd7329392015-04-21 21:46:32 +00001887 case PP_MACRO_DIRECTIVE_HISTORY:
1888 break;
1889
1890 case PP_MODULE_MACRO: {
Richard Smith713369b2015-04-23 20:40:50 +00001891 ModuleMacros.push_back(ModuleMacroRecord());
1892 auto &Info = ModuleMacros.back();
Richard Smithe56c8bc2015-04-22 00:26:11 +00001893 Info.SubModID = getGlobalSubmoduleID(M, Record[0]);
1894 Info.MI = getMacro(getGlobalMacroID(M, Record[1]));
Richard Smith713369b2015-04-23 20:40:50 +00001895 for (int I = 2, N = Record.size(); I != N; ++I)
1896 Info.Overrides.push_back(getGlobalSubmoduleID(M, Record[I]));
Richard Smithd7329392015-04-21 21:46:32 +00001897 continue;
1898 }
1899
1900 default:
1901 Error("malformed block record in AST file");
1902 return;
1903 }
1904
1905 // We found the macro directive history; that's the last record
1906 // for this macro.
1907 break;
Argyrios Kyrtzidiseb663da2013-03-22 21:12:57 +00001908 }
1909
Richard Smithd7329392015-04-21 21:46:32 +00001910 // Module macros are listed in reverse dependency order.
Richard Smithe56c8bc2015-04-22 00:26:11 +00001911 {
1912 std::reverse(ModuleMacros.begin(), ModuleMacros.end());
Richard Smithe56c8bc2015-04-22 00:26:11 +00001913 llvm::SmallVector<ModuleMacro*, 8> Overrides;
Richard Smith713369b2015-04-23 20:40:50 +00001914 for (auto &MMR : ModuleMacros) {
Richard Smithe56c8bc2015-04-22 00:26:11 +00001915 Overrides.clear();
Richard Smith713369b2015-04-23 20:40:50 +00001916 for (unsigned ModID : MMR.Overrides) {
Richard Smithb8b2ed62015-04-23 18:18:26 +00001917 Module *Mod = getSubmodule(ModID);
1918 auto *Macro = PP.getModuleMacro(Mod, II);
Richard Smithe56c8bc2015-04-22 00:26:11 +00001919 assert(Macro && "missing definition for overridden macro");
Richard Smith5dbef922015-04-22 02:09:43 +00001920 Overrides.push_back(Macro);
Richard Smithe56c8bc2015-04-22 00:26:11 +00001921 }
1922
1923 bool Inserted = false;
Richard Smith713369b2015-04-23 20:40:50 +00001924 Module *Owner = getSubmodule(MMR.SubModID);
Richard Smith20e883e2015-04-29 23:20:19 +00001925 PP.addModuleMacro(Owner, II, MMR.MI, Overrides, Inserted);
Richard Smithd7329392015-04-21 21:46:32 +00001926 }
1927 }
1928
1929 // Don't read the directive history for a module; we don't have anywhere
1930 // to put it.
Manman Ren11f2a472016-08-18 17:42:15 +00001931 if (M.isModule())
Richard Smithd7329392015-04-21 21:46:32 +00001932 return;
1933
Argyrios Kyrtzidiseb663da2013-03-22 21:12:57 +00001934 // Deserialize the macro directives history in reverse source-order.
Craig Toppera13603a2014-05-22 05:54:18 +00001935 MacroDirective *Latest = nullptr, *Earliest = nullptr;
Argyrios Kyrtzidiseb663da2013-03-22 21:12:57 +00001936 unsigned Idx = 0, N = Record.size();
1937 while (Idx < N) {
Craig Toppera13603a2014-05-22 05:54:18 +00001938 MacroDirective *MD = nullptr;
Argyrios Kyrtzidiseb663da2013-03-22 21:12:57 +00001939 SourceLocation Loc = ReadSourceLocation(M, Record, Idx);
Argyrios Kyrtzidisb6210df2013-03-26 17:17:01 +00001940 MacroDirective::Kind K = (MacroDirective::Kind)Record[Idx++];
1941 switch (K) {
1942 case MacroDirective::MD_Define: {
Richard Smith713369b2015-04-23 20:40:50 +00001943 MacroInfo *MI = getMacro(getGlobalMacroID(M, Record[Idx++]));
Richard Smith3981b172015-04-30 02:16:23 +00001944 MD = PP.AllocateDefMacroDirective(MI, Loc);
Argyrios Kyrtzidisb6210df2013-03-26 17:17:01 +00001945 break;
1946 }
Richard Smithdaa69e02014-07-25 04:40:03 +00001947 case MacroDirective::MD_Undefine: {
Richard Smith3981b172015-04-30 02:16:23 +00001948 MD = PP.AllocateUndefMacroDirective(Loc);
Argyrios Kyrtzidisb6210df2013-03-26 17:17:01 +00001949 break;
Richard Smithdaa69e02014-07-25 04:40:03 +00001950 }
1951 case MacroDirective::MD_Visibility:
Argyrios Kyrtzidisb6210df2013-03-26 17:17:01 +00001952 bool isPublic = Record[Idx++];
1953 MD = PP.AllocateVisibilityMacroDirective(Loc, isPublic);
1954 break;
1955 }
Argyrios Kyrtzidiseb663da2013-03-22 21:12:57 +00001956
1957 if (!Latest)
1958 Latest = MD;
1959 if (Earliest)
1960 Earliest->setPrevious(MD);
1961 Earliest = MD;
1962 }
1963
Richard Smithd6e8c0d2015-05-04 19:58:00 +00001964 if (Latest)
Nico Weberfd870702016-12-09 17:32:52 +00001965 PP.setLoadedMacroDirective(II, Earliest, Latest);
Argyrios Kyrtzidiseb663da2013-03-22 21:12:57 +00001966}
1967
Argyrios Kyrtzidisce9b49e2014-03-14 02:26:27 +00001968ASTReader::InputFileInfo
1969ASTReader::readInputFileInfo(ModuleFile &F, unsigned ID) {
Ben Langmuir198c1682014-03-07 07:27:49 +00001970 // Go find this input file.
1971 BitstreamCursor &Cursor = F.InputFilesCursor;
1972 SavedStreamPosition SavedPosition(Cursor);
1973 Cursor.JumpToBit(F.InputFileOffsets[ID-1]);
1974
1975 unsigned Code = Cursor.ReadCode();
1976 RecordData Record;
1977 StringRef Blob;
1978
1979 unsigned Result = Cursor.readRecord(Code, Record, &Blob);
1980 assert(static_cast<InputFileRecordTypes>(Result) == INPUT_FILE &&
1981 "invalid record type for input file");
1982 (void)Result;
1983
1984 assert(Record[0] == ID && "Bogus stored ID or offset");
Richard Smitha8cfffa2015-11-26 02:04:16 +00001985 InputFileInfo R;
1986 R.StoredSize = static_cast<off_t>(Record[1]);
1987 R.StoredTime = static_cast<time_t>(Record[2]);
1988 R.Overridden = static_cast<bool>(Record[3]);
1989 R.Transient = static_cast<bool>(Record[4]);
1990 R.Filename = Blob;
1991 ResolveImportedPath(F, R.Filename);
Hans Wennborg73945142014-03-14 17:45:06 +00001992 return R;
Ben Langmuir198c1682014-03-07 07:27:49 +00001993}
1994
Manman Renc8c94152016-10-21 23:35:03 +00001995static unsigned moduleKindForDiagnostic(ModuleKind Kind);
Argyrios Kyrtzidis61c3d872013-03-01 03:26:04 +00001996InputFile ASTReader::getInputFile(ModuleFile &F, unsigned ID, bool Complain) {
Guy Benyei11169dd2012-12-18 14:30:41 +00001997 // If this ID is bogus, just return an empty input file.
1998 if (ID == 0 || ID > F.InputFilesLoaded.size())
1999 return InputFile();
2000
2001 // If we've already loaded this input file, return it.
Argyrios Kyrtzidis61c3d872013-03-01 03:26:04 +00002002 if (F.InputFilesLoaded[ID-1].getFile())
Guy Benyei11169dd2012-12-18 14:30:41 +00002003 return F.InputFilesLoaded[ID-1];
2004
Argyrios Kyrtzidis9308f0a2014-01-08 19:13:34 +00002005 if (F.InputFilesLoaded[ID-1].isNotFound())
2006 return InputFile();
2007
Guy Benyei11169dd2012-12-18 14:30:41 +00002008 // Go find this input file.
Chris Lattner7fb3bef2013-01-20 00:56:42 +00002009 BitstreamCursor &Cursor = F.InputFilesCursor;
Guy Benyei11169dd2012-12-18 14:30:41 +00002010 SavedStreamPosition SavedPosition(Cursor);
2011 Cursor.JumpToBit(F.InputFileOffsets[ID-1]);
David L. Jonesc4808b9e2016-12-15 20:53:26 +00002012
Argyrios Kyrtzidisce9b49e2014-03-14 02:26:27 +00002013 InputFileInfo FI = readInputFileInfo(F, ID);
2014 off_t StoredSize = FI.StoredSize;
2015 time_t StoredTime = FI.StoredTime;
2016 bool Overridden = FI.Overridden;
Richard Smitha8cfffa2015-11-26 02:04:16 +00002017 bool Transient = FI.Transient;
Argyrios Kyrtzidisce9b49e2014-03-14 02:26:27 +00002018 StringRef Filename = FI.Filename;
Argyrios Kyrtzidis61c3d872013-03-01 03:26:04 +00002019
Richard Smitha8cfffa2015-11-26 02:04:16 +00002020 const FileEntry *File = FileMgr.getFile(Filename, /*OpenFile=*/false);
Ben Langmuir198c1682014-03-07 07:27:49 +00002021
2022 // If we didn't find the file, resolve it relative to the
2023 // original directory from which this AST file was created.
Craig Toppera13603a2014-05-22 05:54:18 +00002024 if (File == nullptr && !F.OriginalDir.empty() && !CurrentDir.empty() &&
Ben Langmuir198c1682014-03-07 07:27:49 +00002025 F.OriginalDir != CurrentDir) {
2026 std::string Resolved = resolveFileRelativeToOriginalDir(Filename,
2027 F.OriginalDir,
2028 CurrentDir);
2029 if (!Resolved.empty())
2030 File = FileMgr.getFile(Resolved);
2031 }
2032
2033 // For an overridden file, create a virtual file with the stored
2034 // size/timestamp.
Richard Smitha8cfffa2015-11-26 02:04:16 +00002035 if ((Overridden || Transient) && File == nullptr)
Ben Langmuir198c1682014-03-07 07:27:49 +00002036 File = FileMgr.getVirtualFile(Filename, StoredSize, StoredTime);
Ben Langmuir198c1682014-03-07 07:27:49 +00002037
Craig Toppera13603a2014-05-22 05:54:18 +00002038 if (File == nullptr) {
Ben Langmuir198c1682014-03-07 07:27:49 +00002039 if (Complain) {
2040 std::string ErrorStr = "could not find file '";
2041 ErrorStr += Filename;
Richard Smith68142212015-10-13 01:26:26 +00002042 ErrorStr += "' referenced by AST file '";
2043 ErrorStr += F.FileName;
2044 ErrorStr += "'";
Eugene Zelenkoe95e7d52016-09-07 21:53:17 +00002045 Error(ErrorStr);
Guy Benyei11169dd2012-12-18 14:30:41 +00002046 }
Ben Langmuir198c1682014-03-07 07:27:49 +00002047 // Record that we didn't find the file.
2048 F.InputFilesLoaded[ID-1] = InputFile::getNotFound();
2049 return InputFile();
2050 }
Guy Benyei11169dd2012-12-18 14:30:41 +00002051
Ben Langmuir198c1682014-03-07 07:27:49 +00002052 // Check if there was a request to override the contents of the file
2053 // that was part of the precompiled header. Overridding such a file
2054 // can lead to problems when lexing using the source locations from the
2055 // PCH.
2056 SourceManager &SM = getSourceManager();
Richard Smith64daf7b2015-12-01 03:32:49 +00002057 // FIXME: Reject if the overrides are different.
2058 if ((!Overridden && !Transient) && SM.isFileOverridden(File)) {
Ben Langmuir198c1682014-03-07 07:27:49 +00002059 if (Complain)
2060 Error(diag::err_fe_pch_file_overridden, Filename);
2061 // After emitting the diagnostic, recover by disabling the override so
2062 // that the original file will be used.
Richard Smitha8cfffa2015-11-26 02:04:16 +00002063 //
2064 // FIXME: This recovery is just as broken as the original state; there may
2065 // be another precompiled module that's using the overridden contents, or
2066 // we might be half way through parsing it. Instead, we should treat the
2067 // overridden contents as belonging to a separate FileEntry.
Ben Langmuir198c1682014-03-07 07:27:49 +00002068 SM.disableFileContentsOverride(File);
2069 // The FileEntry is a virtual file entry with the size of the contents
2070 // that would override the original contents. Set it to the original's
2071 // size/time.
2072 FileMgr.modifyFileEntry(const_cast<FileEntry*>(File),
2073 StoredSize, StoredTime);
2074 }
Guy Benyei11169dd2012-12-18 14:30:41 +00002075
Ben Langmuir198c1682014-03-07 07:27:49 +00002076 bool IsOutOfDate = false;
2077
2078 // For an overridden file, there is nothing to validate.
Richard Smith96fdab62014-10-28 16:24:08 +00002079 if (!Overridden && //
2080 (StoredSize != File->getSize() ||
Richard Smithe75ee0f2015-08-17 07:13:32 +00002081 (StoredTime && StoredTime != File->getModificationTime() &&
2082 !DisableValidation)
Ben Langmuir198c1682014-03-07 07:27:49 +00002083 )) {
2084 if (Complain) {
2085 // Build a list of the PCH imports that got us here (in reverse).
2086 SmallVector<ModuleFile *, 4> ImportStack(1, &F);
2087 while (ImportStack.back()->ImportedBy.size() > 0)
2088 ImportStack.push_back(ImportStack.back()->ImportedBy[0]);
Ben Langmuire82630d2014-01-17 00:19:09 +00002089
Ben Langmuir198c1682014-03-07 07:27:49 +00002090 // The top-level PCH is stale.
2091 StringRef TopLevelPCHName(ImportStack.back()->FileName);
Manman Renc8c94152016-10-21 23:35:03 +00002092 unsigned DiagnosticKind = moduleKindForDiagnostic(ImportStack.back()->Kind);
2093 if (DiagnosticKind == 0)
2094 Error(diag::err_fe_pch_file_modified, Filename, TopLevelPCHName);
2095 else if (DiagnosticKind == 1)
2096 Error(diag::err_fe_module_file_modified, Filename, TopLevelPCHName);
2097 else
2098 Error(diag::err_fe_ast_file_modified, Filename, TopLevelPCHName);
Ben Langmuire82630d2014-01-17 00:19:09 +00002099
Ben Langmuir198c1682014-03-07 07:27:49 +00002100 // Print the import stack.
2101 if (ImportStack.size() > 1 && !Diags.isDiagnosticInFlight()) {
2102 Diag(diag::note_pch_required_by)
2103 << Filename << ImportStack[0]->FileName;
2104 for (unsigned I = 1; I < ImportStack.size(); ++I)
Ben Langmuire82630d2014-01-17 00:19:09 +00002105 Diag(diag::note_pch_required_by)
Ben Langmuir198c1682014-03-07 07:27:49 +00002106 << ImportStack[I-1]->FileName << ImportStack[I]->FileName;
Douglas Gregor7029ce12013-03-19 00:28:20 +00002107 }
2108
Ben Langmuir198c1682014-03-07 07:27:49 +00002109 if (!Diags.isDiagnosticInFlight())
2110 Diag(diag::note_pch_rebuild_required) << TopLevelPCHName;
Guy Benyei11169dd2012-12-18 14:30:41 +00002111 }
2112
Ben Langmuir198c1682014-03-07 07:27:49 +00002113 IsOutOfDate = true;
Guy Benyei11169dd2012-12-18 14:30:41 +00002114 }
Richard Smitha8cfffa2015-11-26 02:04:16 +00002115 // FIXME: If the file is overridden and we've already opened it,
2116 // issue an error (or split it into a separate FileEntry).
Guy Benyei11169dd2012-12-18 14:30:41 +00002117
Richard Smitha8cfffa2015-11-26 02:04:16 +00002118 InputFile IF = InputFile(File, Overridden || Transient, IsOutOfDate);
Ben Langmuir198c1682014-03-07 07:27:49 +00002119
2120 // Note that we've loaded this input file.
2121 F.InputFilesLoaded[ID-1] = IF;
2122 return IF;
Guy Benyei11169dd2012-12-18 14:30:41 +00002123}
2124
Richard Smith7ed1bc92014-12-05 22:42:13 +00002125/// \brief If we are loading a relocatable PCH or module file, and the filename
2126/// is not an absolute path, add the system or module root to the beginning of
2127/// the file name.
2128void ASTReader::ResolveImportedPath(ModuleFile &M, std::string &Filename) {
2129 // Resolve relative to the base directory, if we have one.
2130 if (!M.BaseDirectory.empty())
2131 return ResolveImportedPath(Filename, M.BaseDirectory);
Guy Benyei11169dd2012-12-18 14:30:41 +00002132}
2133
Richard Smith7ed1bc92014-12-05 22:42:13 +00002134void ASTReader::ResolveImportedPath(std::string &Filename, StringRef Prefix) {
Guy Benyei11169dd2012-12-18 14:30:41 +00002135 if (Filename.empty() || llvm::sys::path::is_absolute(Filename))
2136 return;
2137
Richard Smith7ed1bc92014-12-05 22:42:13 +00002138 SmallString<128> Buffer;
2139 llvm::sys::path::append(Buffer, Prefix, Filename);
2140 Filename.assign(Buffer.begin(), Buffer.end());
Guy Benyei11169dd2012-12-18 14:30:41 +00002141}
2142
Richard Smith0f99d6a2015-08-09 08:48:41 +00002143static bool isDiagnosedResult(ASTReader::ASTReadResult ARR, unsigned Caps) {
2144 switch (ARR) {
2145 case ASTReader::Failure: return true;
2146 case ASTReader::Missing: return !(Caps & ASTReader::ARR_Missing);
2147 case ASTReader::OutOfDate: return !(Caps & ASTReader::ARR_OutOfDate);
2148 case ASTReader::VersionMismatch: return !(Caps & ASTReader::ARR_VersionMismatch);
2149 case ASTReader::ConfigurationMismatch:
2150 return !(Caps & ASTReader::ARR_ConfigurationMismatch);
2151 case ASTReader::HadErrors: return true;
2152 case ASTReader::Success: return false;
2153 }
2154
2155 llvm_unreachable("unknown ASTReadResult");
2156}
2157
Richard Smith0516b182015-09-08 19:40:14 +00002158ASTReader::ASTReadResult ASTReader::ReadOptionsBlock(
2159 BitstreamCursor &Stream, unsigned ClientLoadCapabilities,
2160 bool AllowCompatibleConfigurationMismatch, ASTReaderListener &Listener,
Manman Ren47a44452016-07-26 17:12:17 +00002161 std::string &SuggestedPredefines, bool ValidateDiagnosticOptions) {
Richard Smith0516b182015-09-08 19:40:14 +00002162 if (Stream.EnterSubBlock(OPTIONS_BLOCK_ID))
2163 return Failure;
2164
2165 // Read all of the records in the options block.
2166 RecordData Record;
2167 ASTReadResult Result = Success;
Eugene Zelenkoe95e7d52016-09-07 21:53:17 +00002168 while (true) {
Richard Smith0516b182015-09-08 19:40:14 +00002169 llvm::BitstreamEntry Entry = Stream.advance();
David L. Jonesc4808b9e2016-12-15 20:53:26 +00002170
Richard Smith0516b182015-09-08 19:40:14 +00002171 switch (Entry.Kind) {
2172 case llvm::BitstreamEntry::Error:
2173 case llvm::BitstreamEntry::SubBlock:
2174 return Failure;
2175
2176 case llvm::BitstreamEntry::EndBlock:
2177 return Result;
2178
2179 case llvm::BitstreamEntry::Record:
2180 // The interesting case.
2181 break;
2182 }
2183
2184 // Read and process a record.
2185 Record.clear();
2186 switch ((OptionsRecordTypes)Stream.readRecord(Entry.ID, Record)) {
2187 case LANGUAGE_OPTIONS: {
2188 bool Complain = (ClientLoadCapabilities & ARR_ConfigurationMismatch) == 0;
2189 if (ParseLanguageOptions(Record, Complain, Listener,
2190 AllowCompatibleConfigurationMismatch))
2191 Result = ConfigurationMismatch;
2192 break;
2193 }
2194
2195 case TARGET_OPTIONS: {
2196 bool Complain = (ClientLoadCapabilities & ARR_ConfigurationMismatch) == 0;
2197 if (ParseTargetOptions(Record, Complain, Listener,
2198 AllowCompatibleConfigurationMismatch))
2199 Result = ConfigurationMismatch;
2200 break;
2201 }
2202
2203 case DIAGNOSTIC_OPTIONS: {
2204 bool Complain = (ClientLoadCapabilities & ARR_OutOfDate) == 0;
Manman Ren47a44452016-07-26 17:12:17 +00002205 if (ValidateDiagnosticOptions &&
2206 !AllowCompatibleConfigurationMismatch &&
Richard Smith0516b182015-09-08 19:40:14 +00002207 ParseDiagnosticOptions(Record, Complain, Listener))
2208 return OutOfDate;
2209 break;
2210 }
2211
2212 case FILE_SYSTEM_OPTIONS: {
2213 bool Complain = (ClientLoadCapabilities & ARR_ConfigurationMismatch) == 0;
2214 if (!AllowCompatibleConfigurationMismatch &&
2215 ParseFileSystemOptions(Record, Complain, Listener))
2216 Result = ConfigurationMismatch;
2217 break;
2218 }
2219
2220 case HEADER_SEARCH_OPTIONS: {
2221 bool Complain = (ClientLoadCapabilities & ARR_ConfigurationMismatch) == 0;
2222 if (!AllowCompatibleConfigurationMismatch &&
2223 ParseHeaderSearchOptions(Record, Complain, Listener))
2224 Result = ConfigurationMismatch;
2225 break;
2226 }
2227
2228 case PREPROCESSOR_OPTIONS:
2229 bool Complain = (ClientLoadCapabilities & ARR_ConfigurationMismatch) == 0;
2230 if (!AllowCompatibleConfigurationMismatch &&
2231 ParsePreprocessorOptions(Record, Complain, Listener,
2232 SuggestedPredefines))
2233 Result = ConfigurationMismatch;
2234 break;
2235 }
2236 }
2237}
2238
Guy Benyei11169dd2012-12-18 14:30:41 +00002239ASTReader::ASTReadResult
2240ASTReader::ReadControlBlock(ModuleFile &F,
Dmitri Gribenkof8579502013-01-12 19:30:44 +00002241 SmallVectorImpl<ImportedModule> &Loaded,
Ben Langmuirbeee15e2014-04-14 18:00:01 +00002242 const ModuleFile *ImportedBy,
Guy Benyei11169dd2012-12-18 14:30:41 +00002243 unsigned ClientLoadCapabilities) {
Chris Lattner7fb3bef2013-01-20 00:56:42 +00002244 BitstreamCursor &Stream = F.Stream;
Richard Smith8a308ec2015-11-05 00:54:55 +00002245 ASTReadResult Result = Success;
Guy Benyei11169dd2012-12-18 14:30:41 +00002246
2247 if (Stream.EnterSubBlock(CONTROL_BLOCK_ID)) {
2248 Error("malformed block record in AST file");
2249 return Failure;
2250 }
2251
2252 // Read all of the records and blocks in the control block.
2253 RecordData Record;
Richard Smitha1825302014-10-23 22:18:29 +00002254 unsigned NumInputs = 0;
2255 unsigned NumUserInputs = 0;
Eugene Zelenkoe95e7d52016-09-07 21:53:17 +00002256 while (true) {
Chris Lattnere7b154b2013-01-19 21:39:22 +00002257 llvm::BitstreamEntry Entry = Stream.advance();
David L. Jonesc4808b9e2016-12-15 20:53:26 +00002258
Chris Lattnere7b154b2013-01-19 21:39:22 +00002259 switch (Entry.Kind) {
2260 case llvm::BitstreamEntry::Error:
2261 Error("malformed block record in AST file");
2262 return Failure;
Dmitri Gribenkof430da42014-02-12 10:33:14 +00002263 case llvm::BitstreamEntry::EndBlock: {
2264 // Validate input files.
2265 const HeaderSearchOptions &HSOpts =
2266 PP.getHeaderSearchInfo().getHeaderSearchOpts();
Ben Langmuircb69b572014-03-07 06:40:32 +00002267
Richard Smitha1825302014-10-23 22:18:29 +00002268 // All user input files reside at the index range [0, NumUserInputs), and
Richard Smith0f99d6a2015-08-09 08:48:41 +00002269 // system input files reside at [NumUserInputs, NumInputs). For explicitly
2270 // loaded module files, ignore missing inputs.
Manman Ren11f2a472016-08-18 17:42:15 +00002271 if (!DisableValidation && F.Kind != MK_ExplicitModule &&
2272 F.Kind != MK_PrebuiltModule) {
Guy Benyei11169dd2012-12-18 14:30:41 +00002273 bool Complain = (ClientLoadCapabilities & ARR_OutOfDate) == 0;
Ben Langmuircb69b572014-03-07 06:40:32 +00002274
Dmitri Gribenkof430da42014-02-12 10:33:14 +00002275 // If we are reading a module, we will create a verification timestamp,
2276 // so we verify all input files. Otherwise, verify only user input
2277 // files.
Ben Langmuircb69b572014-03-07 06:40:32 +00002278
2279 unsigned N = NumUserInputs;
2280 if (ValidateSystemInputs ||
Richard Smithe842a472014-10-22 02:05:46 +00002281 (HSOpts.ModulesValidateOncePerBuildSession &&
Ben Langmuiracb803e2014-11-10 22:13:10 +00002282 F.InputFilesValidationTimestamp <= HSOpts.BuildSessionTimestamp &&
Richard Smithe842a472014-10-22 02:05:46 +00002283 F.Kind == MK_ImplicitModule))
Ben Langmuircb69b572014-03-07 06:40:32 +00002284 N = NumInputs;
2285
Ben Langmuir3d4417c2014-02-07 17:31:11 +00002286 for (unsigned I = 0; I < N; ++I) {
Argyrios Kyrtzidis61c3d872013-03-01 03:26:04 +00002287 InputFile IF = getInputFile(F, I+1, Complain);
2288 if (!IF.getFile() || IF.isOutOfDate())
Guy Benyei11169dd2012-12-18 14:30:41 +00002289 return OutOfDate;
Argyrios Kyrtzidis61c3d872013-03-01 03:26:04 +00002290 }
Guy Benyei11169dd2012-12-18 14:30:41 +00002291 }
Ben Langmuircb69b572014-03-07 06:40:32 +00002292
Argyrios Kyrtzidis6d0753d2014-03-14 03:07:38 +00002293 if (Listener)
Richard Smith216a3bd2015-08-13 17:57:10 +00002294 Listener->visitModuleFile(F.FileName, F.Kind);
Argyrios Kyrtzidis6d0753d2014-03-14 03:07:38 +00002295
Ben Langmuircb69b572014-03-07 06:40:32 +00002296 if (Listener && Listener->needsInputFileVisitation()) {
2297 unsigned N = Listener->needsSystemInputFileVisitation() ? NumInputs
2298 : NumUserInputs;
Argyrios Kyrtzidis68ccbe02014-03-14 02:26:31 +00002299 for (unsigned I = 0; I < N; ++I) {
2300 bool IsSystem = I >= NumUserInputs;
2301 InputFileInfo FI = readInputFileInfo(F, I+1);
Richard Smith216a3bd2015-08-13 17:57:10 +00002302 Listener->visitInputFile(FI.Filename, IsSystem, FI.Overridden,
Manman Ren11f2a472016-08-18 17:42:15 +00002303 F.Kind == MK_ExplicitModule ||
2304 F.Kind == MK_PrebuiltModule);
Argyrios Kyrtzidis68ccbe02014-03-14 02:26:31 +00002305 }
Ben Langmuircb69b572014-03-07 06:40:32 +00002306 }
2307
Richard Smith8a308ec2015-11-05 00:54:55 +00002308 return Result;
Dmitri Gribenkof430da42014-02-12 10:33:14 +00002309 }
2310
Chris Lattnere7b154b2013-01-19 21:39:22 +00002311 case llvm::BitstreamEntry::SubBlock:
2312 switch (Entry.ID) {
Guy Benyei11169dd2012-12-18 14:30:41 +00002313 case INPUT_FILES_BLOCK_ID:
2314 F.InputFilesCursor = Stream;
2315 if (Stream.SkipBlock() || // Skip with the main cursor
2316 // Read the abbreviations
2317 ReadBlockAbbrevs(F.InputFilesCursor, INPUT_FILES_BLOCK_ID)) {
2318 Error("malformed block record in AST file");
2319 return Failure;
2320 }
2321 continue;
Richard Smith0516b182015-09-08 19:40:14 +00002322
2323 case OPTIONS_BLOCK_ID:
2324 // If we're reading the first module for this group, check its options
2325 // are compatible with ours. For modules it imports, no further checking
2326 // is required, because we checked them when we built it.
2327 if (Listener && !ImportedBy) {
2328 // Should we allow the configuration of the module file to differ from
2329 // the configuration of the current translation unit in a compatible
2330 // way?
2331 //
2332 // FIXME: Allow this for files explicitly specified with -include-pch.
2333 bool AllowCompatibleConfigurationMismatch =
Manman Ren11f2a472016-08-18 17:42:15 +00002334 F.Kind == MK_ExplicitModule || F.Kind == MK_PrebuiltModule;
Manman Ren47a44452016-07-26 17:12:17 +00002335 const HeaderSearchOptions &HSOpts =
2336 PP.getHeaderSearchInfo().getHeaderSearchOpts();
Richard Smith0516b182015-09-08 19:40:14 +00002337
Richard Smith8a308ec2015-11-05 00:54:55 +00002338 Result = ReadOptionsBlock(Stream, ClientLoadCapabilities,
2339 AllowCompatibleConfigurationMismatch,
Manman Ren47a44452016-07-26 17:12:17 +00002340 *Listener, SuggestedPredefines,
2341 HSOpts.ModulesValidateDiagnosticOptions);
Richard Smith0516b182015-09-08 19:40:14 +00002342 if (Result == Failure) {
2343 Error("malformed block record in AST file");
2344 return Result;
2345 }
2346
Richard Smith8a308ec2015-11-05 00:54:55 +00002347 if (DisableValidation ||
2348 (AllowConfigurationMismatch && Result == ConfigurationMismatch))
2349 Result = Success;
2350
Ben Langmuir9b1e442e2016-02-11 18:54:02 +00002351 // If we can't load the module, exit early since we likely
2352 // will rebuild the module anyway. The stream may be in the
2353 // middle of a block.
2354 if (Result != Success)
Richard Smith0516b182015-09-08 19:40:14 +00002355 return Result;
2356 } else if (Stream.SkipBlock()) {
2357 Error("malformed block record in AST file");
2358 return Failure;
2359 }
2360 continue;
David L. Jonesc4808b9e2016-12-15 20:53:26 +00002361
Guy Benyei11169dd2012-12-18 14:30:41 +00002362 default:
Chris Lattnere7b154b2013-01-19 21:39:22 +00002363 if (Stream.SkipBlock()) {
2364 Error("malformed block record in AST file");
2365 return Failure;
2366 }
2367 continue;
Guy Benyei11169dd2012-12-18 14:30:41 +00002368 }
David L. Jonesc4808b9e2016-12-15 20:53:26 +00002369
Chris Lattnere7b154b2013-01-19 21:39:22 +00002370 case llvm::BitstreamEntry::Record:
2371 // The interesting case.
2372 break;
Guy Benyei11169dd2012-12-18 14:30:41 +00002373 }
2374
2375 // Read and process a record.
2376 Record.clear();
Chris Lattner0e6c9402013-01-20 02:38:54 +00002377 StringRef Blob;
2378 switch ((ControlRecordTypes)Stream.readRecord(Entry.ID, Record, &Blob)) {
Guy Benyei11169dd2012-12-18 14:30:41 +00002379 case METADATA: {
2380 if (Record[0] != VERSION_MAJOR && !DisableValidation) {
2381 if ((ClientLoadCapabilities & ARR_VersionMismatch) == 0)
Dmitri Gribenko2228cd32014-02-11 15:40:09 +00002382 Diag(Record[0] < VERSION_MAJOR? diag::err_pch_version_too_old
2383 : diag::err_pch_version_too_new);
Guy Benyei11169dd2012-12-18 14:30:41 +00002384 return VersionMismatch;
2385 }
2386
Richard Smithe75ee0f2015-08-17 07:13:32 +00002387 bool hasErrors = Record[6];
Guy Benyei11169dd2012-12-18 14:30:41 +00002388 if (hasErrors && !DisableValidation && !AllowASTWithCompilerErrors) {
2389 Diag(diag::err_pch_with_compiler_errors);
2390 return HadErrors;
2391 }
Argyrios Kyrtzidis70ec1c72016-07-13 20:35:26 +00002392 if (hasErrors) {
2393 Diags.ErrorOccurred = true;
2394 Diags.UncompilableErrorOccurred = true;
2395 Diags.UnrecoverableErrorOccurred = true;
2396 }
Guy Benyei11169dd2012-12-18 14:30:41 +00002397
2398 F.RelocatablePCH = Record[4];
Richard Smith7ed1bc92014-12-05 22:42:13 +00002399 // Relative paths in a relocatable PCH are relative to our sysroot.
2400 if (F.RelocatablePCH)
2401 F.BaseDirectory = isysroot.empty() ? "/" : isysroot;
Guy Benyei11169dd2012-12-18 14:30:41 +00002402
Richard Smithe75ee0f2015-08-17 07:13:32 +00002403 F.HasTimestamps = Record[5];
2404
Guy Benyei11169dd2012-12-18 14:30:41 +00002405 const std::string &CurBranch = getClangFullRepositoryVersion();
Chris Lattner0e6c9402013-01-20 02:38:54 +00002406 StringRef ASTBranch = Blob;
Guy Benyei11169dd2012-12-18 14:30:41 +00002407 if (StringRef(CurBranch) != ASTBranch && !DisableValidation) {
2408 if ((ClientLoadCapabilities & ARR_VersionMismatch) == 0)
Dmitri Gribenko2228cd32014-02-11 15:40:09 +00002409 Diag(diag::err_pch_different_branch) << ASTBranch << CurBranch;
Guy Benyei11169dd2012-12-18 14:30:41 +00002410 return VersionMismatch;
2411 }
2412 break;
2413 }
2414
Ben Langmuir487ea142014-10-23 18:05:36 +00002415 case SIGNATURE:
2416 assert((!F.Signature || F.Signature == Record[0]) && "signature changed");
2417 F.Signature = Record[0];
2418 break;
2419
Guy Benyei11169dd2012-12-18 14:30:41 +00002420 case IMPORTS: {
David L. Jonesc4808b9e2016-12-15 20:53:26 +00002421 // Load each of the imported PCH files.
Guy Benyei11169dd2012-12-18 14:30:41 +00002422 unsigned Idx = 0, N = Record.size();
2423 while (Idx < N) {
2424 // Read information about the AST file.
2425 ModuleKind ImportedKind = (ModuleKind)Record[Idx++];
2426 // The import location will be the local one for now; we will adjust
2427 // all import locations of module imports after the global source
Richard Smithb22a1d12016-03-27 20:13:24 +00002428 // location info are setup, in ReadAST.
Guy Benyei11169dd2012-12-18 14:30:41 +00002429 SourceLocation ImportLoc =
Richard Smithb22a1d12016-03-27 20:13:24 +00002430 ReadUntranslatedSourceLocation(Record[Idx++]);
Douglas Gregor7029ce12013-03-19 00:28:20 +00002431 off_t StoredSize = (off_t)Record[Idx++];
2432 time_t StoredModTime = (time_t)Record[Idx++];
Ben Langmuir487ea142014-10-23 18:05:36 +00002433 ASTFileSignature StoredSignature = Record[Idx++];
Richard Smith7ed1bc92014-12-05 22:42:13 +00002434 auto ImportedFile = ReadPath(F, Record, Idx);
Guy Benyei11169dd2012-12-18 14:30:41 +00002435
Richard Smith0f99d6a2015-08-09 08:48:41 +00002436 // If our client can't cope with us being out of date, we can't cope with
2437 // our dependency being missing.
2438 unsigned Capabilities = ClientLoadCapabilities;
2439 if ((ClientLoadCapabilities & ARR_OutOfDate) == 0)
2440 Capabilities &= ~ARR_Missing;
2441
Guy Benyei11169dd2012-12-18 14:30:41 +00002442 // Load the AST file.
Richard Smith0f99d6a2015-08-09 08:48:41 +00002443 auto Result = ReadASTCore(ImportedFile, ImportedKind, ImportLoc, &F,
2444 Loaded, StoredSize, StoredModTime,
2445 StoredSignature, Capabilities);
2446
2447 // If we diagnosed a problem, produce a backtrace.
2448 if (isDiagnosedResult(Result, Capabilities))
2449 Diag(diag::note_module_file_imported_by)
2450 << F.FileName << !F.ModuleName.empty() << F.ModuleName;
2451
2452 switch (Result) {
Guy Benyei11169dd2012-12-18 14:30:41 +00002453 case Failure: return Failure;
2454 // If we have to ignore the dependency, we'll have to ignore this too.
Douglas Gregor2f1806e2013-03-19 00:38:50 +00002455 case Missing:
Guy Benyei11169dd2012-12-18 14:30:41 +00002456 case OutOfDate: return OutOfDate;
2457 case VersionMismatch: return VersionMismatch;
2458 case ConfigurationMismatch: return ConfigurationMismatch;
2459 case HadErrors: return HadErrors;
2460 case Success: break;
2461 }
2462 }
2463 break;
2464 }
2465
Guy Benyei11169dd2012-12-18 14:30:41 +00002466 case ORIGINAL_FILE:
2467 F.OriginalSourceFileID = FileID::get(Record[0]);
Chris Lattner0e6c9402013-01-20 02:38:54 +00002468 F.ActualOriginalSourceFileName = Blob;
Guy Benyei11169dd2012-12-18 14:30:41 +00002469 F.OriginalSourceFileName = F.ActualOriginalSourceFileName;
Richard Smith7ed1bc92014-12-05 22:42:13 +00002470 ResolveImportedPath(F, F.OriginalSourceFileName);
Guy Benyei11169dd2012-12-18 14:30:41 +00002471 break;
2472
2473 case ORIGINAL_FILE_ID:
2474 F.OriginalSourceFileID = FileID::get(Record[0]);
2475 break;
2476
2477 case ORIGINAL_PCH_DIR:
Chris Lattner0e6c9402013-01-20 02:38:54 +00002478 F.OriginalDir = Blob;
Guy Benyei11169dd2012-12-18 14:30:41 +00002479 break;
2480
Ben Langmuirbeee15e2014-04-14 18:00:01 +00002481 case MODULE_NAME:
2482 F.ModuleName = Blob;
Ben Langmuir4f5212a2014-04-14 22:12:44 +00002483 if (Listener)
2484 Listener->ReadModuleName(F.ModuleName);
Ben Langmuirbeee15e2014-04-14 18:00:01 +00002485 break;
2486
Richard Smith223d3f22014-12-06 03:21:08 +00002487 case MODULE_DIRECTORY: {
2488 assert(!F.ModuleName.empty() &&
2489 "MODULE_DIRECTORY found before MODULE_NAME");
2490 // If we've already loaded a module map file covering this module, we may
2491 // have a better path for it (relative to the current build).
2492 Module *M = PP.getHeaderSearchInfo().lookupModule(F.ModuleName);
2493 if (M && M->Directory) {
2494 // If we're implicitly loading a module, the base directory can't
2495 // change between the build and use.
Manman Ren11f2a472016-08-18 17:42:15 +00002496 if (F.Kind != MK_ExplicitModule && F.Kind != MK_PrebuiltModule) {
Richard Smith223d3f22014-12-06 03:21:08 +00002497 const DirectoryEntry *BuildDir =
2498 PP.getFileManager().getDirectory(Blob);
2499 if (!BuildDir || BuildDir != M->Directory) {
2500 if ((ClientLoadCapabilities & ARR_OutOfDate) == 0)
2501 Diag(diag::err_imported_module_relocated)
2502 << F.ModuleName << Blob << M->Directory->getName();
2503 return OutOfDate;
2504 }
2505 }
2506 F.BaseDirectory = M->Directory->getName();
2507 } else {
2508 F.BaseDirectory = Blob;
2509 }
Richard Smith7ed1bc92014-12-05 22:42:13 +00002510 break;
Richard Smith223d3f22014-12-06 03:21:08 +00002511 }
Richard Smith7ed1bc92014-12-05 22:42:13 +00002512
Ben Langmuirbeee15e2014-04-14 18:00:01 +00002513 case MODULE_MAP_FILE:
Ben Langmuir4b8a9e92014-08-12 16:42:33 +00002514 if (ASTReadResult Result =
2515 ReadModuleMapFileBlock(Record, F, ImportedBy, ClientLoadCapabilities))
2516 return Result;
Ben Langmuir264ea152014-11-08 00:06:39 +00002517 break;
2518
Justin Bognerca9c0cc2015-06-21 20:32:36 +00002519 case INPUT_FILE_OFFSETS:
Richard Smitha1825302014-10-23 22:18:29 +00002520 NumInputs = Record[0];
2521 NumUserInputs = Record[1];
Justin Bogner4c183242015-06-21 20:32:40 +00002522 F.InputFileOffsets =
2523 (const llvm::support::unaligned_uint64_t *)Blob.data();
Richard Smitha1825302014-10-23 22:18:29 +00002524 F.InputFilesLoaded.resize(NumInputs);
Argyrios Kyrtzidisa38cb202017-01-30 06:05:58 +00002525 F.NumUserInputFiles = NumUserInputs;
Guy Benyei11169dd2012-12-18 14:30:41 +00002526 break;
2527 }
2528 }
Guy Benyei11169dd2012-12-18 14:30:41 +00002529}
2530
Ben Langmuir2c9af442014-04-10 17:57:43 +00002531ASTReader::ASTReadResult
2532ASTReader::ReadASTBlock(ModuleFile &F, unsigned ClientLoadCapabilities) {
Chris Lattner7fb3bef2013-01-20 00:56:42 +00002533 BitstreamCursor &Stream = F.Stream;
Guy Benyei11169dd2012-12-18 14:30:41 +00002534
2535 if (Stream.EnterSubBlock(AST_BLOCK_ID)) {
2536 Error("malformed block record in AST file");
Ben Langmuir2c9af442014-04-10 17:57:43 +00002537 return Failure;
Guy Benyei11169dd2012-12-18 14:30:41 +00002538 }
2539
2540 // Read all of the records and blocks for the AST file.
2541 RecordData Record;
Eugene Zelenkoe95e7d52016-09-07 21:53:17 +00002542 while (true) {
Chris Lattnere7b154b2013-01-19 21:39:22 +00002543 llvm::BitstreamEntry Entry = Stream.advance();
David L. Jonesc4808b9e2016-12-15 20:53:26 +00002544
Chris Lattnere7b154b2013-01-19 21:39:22 +00002545 switch (Entry.Kind) {
2546 case llvm::BitstreamEntry::Error:
2547 Error("error at end of module block in AST file");
Ben Langmuir2c9af442014-04-10 17:57:43 +00002548 return Failure;
Chris Lattnere7b154b2013-01-19 21:39:22 +00002549 case llvm::BitstreamEntry::EndBlock: {
Richard Smithc0fbba72013-04-03 22:49:41 +00002550 // Outside of C++, we do not store a lookup map for the translation unit.
2551 // Instead, mark it as needing a lookup map to be built if this module
2552 // contains any declarations lexically within it (which it always does!).
2553 // This usually has no cost, since we very rarely need the lookup map for
2554 // the translation unit outside C++.
Guy Benyei11169dd2012-12-18 14:30:41 +00002555 DeclContext *DC = Context.getTranslationUnitDecl();
Richard Smithc0fbba72013-04-03 22:49:41 +00002556 if (DC->hasExternalLexicalStorage() &&
2557 !getContext().getLangOpts().CPlusPlus)
Guy Benyei11169dd2012-12-18 14:30:41 +00002558 DC->setMustBuildLookupTable();
David L. Jonesc4808b9e2016-12-15 20:53:26 +00002559
Ben Langmuir2c9af442014-04-10 17:57:43 +00002560 return Success;
Guy Benyei11169dd2012-12-18 14:30:41 +00002561 }
Chris Lattnere7b154b2013-01-19 21:39:22 +00002562 case llvm::BitstreamEntry::SubBlock:
2563 switch (Entry.ID) {
Guy Benyei11169dd2012-12-18 14:30:41 +00002564 case DECLTYPES_BLOCK_ID:
2565 // We lazily load the decls block, but we want to set up the
2566 // DeclsCursor cursor to point into it. Clone our current bitcode
2567 // cursor to it, enter the block and read the abbrevs in that block.
2568 // With the main cursor, we just skip over it.
2569 F.DeclsCursor = Stream;
2570 if (Stream.SkipBlock() || // Skip with the main cursor.
2571 // Read the abbrevs.
2572 ReadBlockAbbrevs(F.DeclsCursor, DECLTYPES_BLOCK_ID)) {
2573 Error("malformed block record in AST file");
Ben Langmuir2c9af442014-04-10 17:57:43 +00002574 return Failure;
Guy Benyei11169dd2012-12-18 14:30:41 +00002575 }
2576 break;
Richard Smithb9eab6d2014-03-20 19:44:17 +00002577
Guy Benyei11169dd2012-12-18 14:30:41 +00002578 case PREPROCESSOR_BLOCK_ID:
2579 F.MacroCursor = Stream;
2580 if (!PP.getExternalSource())
2581 PP.setExternalSource(this);
David L. Jonesc4808b9e2016-12-15 20:53:26 +00002582
Guy Benyei11169dd2012-12-18 14:30:41 +00002583 if (Stream.SkipBlock() ||
2584 ReadBlockAbbrevs(F.MacroCursor, PREPROCESSOR_BLOCK_ID)) {
2585 Error("malformed block record in AST file");
Ben Langmuir2c9af442014-04-10 17:57:43 +00002586 return Failure;
Guy Benyei11169dd2012-12-18 14:30:41 +00002587 }
2588 F.MacroStartOffset = F.MacroCursor.GetCurrentBitNo();
2589 break;
David L. Jonesc4808b9e2016-12-15 20:53:26 +00002590
Guy Benyei11169dd2012-12-18 14:30:41 +00002591 case PREPROCESSOR_DETAIL_BLOCK_ID:
2592 F.PreprocessorDetailCursor = Stream;
2593 if (Stream.SkipBlock() ||
Chris Lattnere7b154b2013-01-19 21:39:22 +00002594 ReadBlockAbbrevs(F.PreprocessorDetailCursor,
Guy Benyei11169dd2012-12-18 14:30:41 +00002595 PREPROCESSOR_DETAIL_BLOCK_ID)) {
Chris Lattnere7b154b2013-01-19 21:39:22 +00002596 Error("malformed preprocessor detail record in AST file");
Ben Langmuir2c9af442014-04-10 17:57:43 +00002597 return Failure;
Chris Lattnere7b154b2013-01-19 21:39:22 +00002598 }
Guy Benyei11169dd2012-12-18 14:30:41 +00002599 F.PreprocessorDetailStartOffset
Chris Lattnere7b154b2013-01-19 21:39:22 +00002600 = F.PreprocessorDetailCursor.GetCurrentBitNo();
David L. Jonesc4808b9e2016-12-15 20:53:26 +00002601
Guy Benyei11169dd2012-12-18 14:30:41 +00002602 if (!PP.getPreprocessingRecord())
2603 PP.createPreprocessingRecord();
2604 if (!PP.getPreprocessingRecord()->getExternalSource())
2605 PP.getPreprocessingRecord()->SetExternalSource(*this);
2606 break;
David L. Jonesc4808b9e2016-12-15 20:53:26 +00002607
Guy Benyei11169dd2012-12-18 14:30:41 +00002608 case SOURCE_MANAGER_BLOCK_ID:
2609 if (ReadSourceManagerBlock(F))
Ben Langmuir2c9af442014-04-10 17:57:43 +00002610 return Failure;
Guy Benyei11169dd2012-12-18 14:30:41 +00002611 break;
David L. Jonesc4808b9e2016-12-15 20:53:26 +00002612
Guy Benyei11169dd2012-12-18 14:30:41 +00002613 case SUBMODULE_BLOCK_ID:
David Blaikie9ffe5a32017-01-30 05:00:26 +00002614 if (ASTReadResult Result =
2615 ReadSubmoduleBlock(F, ClientLoadCapabilities))
Ben Langmuir2c9af442014-04-10 17:57:43 +00002616 return Result;
Guy Benyei11169dd2012-12-18 14:30:41 +00002617 break;
David L. Jonesc4808b9e2016-12-15 20:53:26 +00002618
Guy Benyei11169dd2012-12-18 14:30:41 +00002619 case COMMENTS_BLOCK_ID: {
Chris Lattner7fb3bef2013-01-20 00:56:42 +00002620 BitstreamCursor C = Stream;
Guy Benyei11169dd2012-12-18 14:30:41 +00002621 if (Stream.SkipBlock() ||
2622 ReadBlockAbbrevs(C, COMMENTS_BLOCK_ID)) {
2623 Error("malformed comments block in AST file");
Ben Langmuir2c9af442014-04-10 17:57:43 +00002624 return Failure;
Guy Benyei11169dd2012-12-18 14:30:41 +00002625 }
2626 CommentsCursors.push_back(std::make_pair(C, &F));
2627 break;
2628 }
David L. Jonesc4808b9e2016-12-15 20:53:26 +00002629
Guy Benyei11169dd2012-12-18 14:30:41 +00002630 default:
Chris Lattnere7b154b2013-01-19 21:39:22 +00002631 if (Stream.SkipBlock()) {
2632 Error("malformed block record in AST file");
Ben Langmuir2c9af442014-04-10 17:57:43 +00002633 return Failure;
Chris Lattnere7b154b2013-01-19 21:39:22 +00002634 }
2635 break;
Guy Benyei11169dd2012-12-18 14:30:41 +00002636 }
2637 continue;
David L. Jonesc4808b9e2016-12-15 20:53:26 +00002638
Chris Lattnere7b154b2013-01-19 21:39:22 +00002639 case llvm::BitstreamEntry::Record:
2640 // The interesting case.
2641 break;
Guy Benyei11169dd2012-12-18 14:30:41 +00002642 }
2643
2644 // Read and process a record.
2645 Record.clear();
Chris Lattner0e6c9402013-01-20 02:38:54 +00002646 StringRef Blob;
2647 switch ((ASTRecordTypes)Stream.readRecord(Entry.ID, Record, &Blob)) {
Guy Benyei11169dd2012-12-18 14:30:41 +00002648 default: // Default behavior: ignore.
2649 break;
2650
2651 case TYPE_OFFSET: {
2652 if (F.LocalNumTypes != 0) {
2653 Error("duplicate TYPE_OFFSET record in AST file");
Ben Langmuir2c9af442014-04-10 17:57:43 +00002654 return Failure;
Guy Benyei11169dd2012-12-18 14:30:41 +00002655 }
Chris Lattner0e6c9402013-01-20 02:38:54 +00002656 F.TypeOffsets = (const uint32_t *)Blob.data();
Guy Benyei11169dd2012-12-18 14:30:41 +00002657 F.LocalNumTypes = Record[0];
2658 unsigned LocalBaseTypeIndex = Record[1];
2659 F.BaseTypeIndex = getTotalNumTypes();
David L. Jonesc4808b9e2016-12-15 20:53:26 +00002660
Guy Benyei11169dd2012-12-18 14:30:41 +00002661 if (F.LocalNumTypes > 0) {
2662 // Introduce the global -> local mapping for types within this module.
2663 GlobalTypeMap.insert(std::make_pair(getTotalNumTypes(), &F));
David L. Jonesc4808b9e2016-12-15 20:53:26 +00002664
Guy Benyei11169dd2012-12-18 14:30:41 +00002665 // Introduce the local -> global mapping for types within this module.
2666 F.TypeRemap.insertOrReplace(
David L. Jonesc4808b9e2016-12-15 20:53:26 +00002667 std::make_pair(LocalBaseTypeIndex,
Guy Benyei11169dd2012-12-18 14:30:41 +00002668 F.BaseTypeIndex - LocalBaseTypeIndex));
Ben Langmuir52ca6782014-10-20 16:27:32 +00002669
2670 TypesLoaded.resize(TypesLoaded.size() + F.LocalNumTypes);
Guy Benyei11169dd2012-12-18 14:30:41 +00002671 }
2672 break;
2673 }
David L. Jonesc4808b9e2016-12-15 20:53:26 +00002674
Guy Benyei11169dd2012-12-18 14:30:41 +00002675 case DECL_OFFSET: {
2676 if (F.LocalNumDecls != 0) {
2677 Error("duplicate DECL_OFFSET record in AST file");
Ben Langmuir2c9af442014-04-10 17:57:43 +00002678 return Failure;
Guy Benyei11169dd2012-12-18 14:30:41 +00002679 }
Chris Lattner0e6c9402013-01-20 02:38:54 +00002680 F.DeclOffsets = (const DeclOffset *)Blob.data();
Guy Benyei11169dd2012-12-18 14:30:41 +00002681 F.LocalNumDecls = Record[0];
2682 unsigned LocalBaseDeclID = Record[1];
2683 F.BaseDeclID = getTotalNumDecls();
David L. Jonesc4808b9e2016-12-15 20:53:26 +00002684
Guy Benyei11169dd2012-12-18 14:30:41 +00002685 if (F.LocalNumDecls > 0) {
David L. Jonesc4808b9e2016-12-15 20:53:26 +00002686 // Introduce the global -> local mapping for declarations within this
Guy Benyei11169dd2012-12-18 14:30:41 +00002687 // module.
2688 GlobalDeclMap.insert(
2689 std::make_pair(getTotalNumDecls() + NUM_PREDEF_DECL_IDS, &F));
David L. Jonesc4808b9e2016-12-15 20:53:26 +00002690
Guy Benyei11169dd2012-12-18 14:30:41 +00002691 // Introduce the local -> global mapping for declarations within this
2692 // module.
2693 F.DeclRemap.insertOrReplace(
2694 std::make_pair(LocalBaseDeclID, F.BaseDeclID - LocalBaseDeclID));
David L. Jonesc4808b9e2016-12-15 20:53:26 +00002695
Guy Benyei11169dd2012-12-18 14:30:41 +00002696 // Introduce the global -> local mapping for declarations within this
2697 // module.
2698 F.GlobalToLocalDeclIDs[&F] = LocalBaseDeclID;
Ben Langmuirfe971d92014-08-16 04:54:18 +00002699
Ben Langmuir52ca6782014-10-20 16:27:32 +00002700 DeclsLoaded.resize(DeclsLoaded.size() + F.LocalNumDecls);
2701 }
Guy Benyei11169dd2012-12-18 14:30:41 +00002702 break;
2703 }
David L. Jonesc4808b9e2016-12-15 20:53:26 +00002704
Guy Benyei11169dd2012-12-18 14:30:41 +00002705 case TU_UPDATE_LEXICAL: {
2706 DeclContext *TU = Context.getTranslationUnitDecl();
Richard Smith82f8fcd2015-08-06 22:07:25 +00002707 LexicalContents Contents(
2708 reinterpret_cast<const llvm::support::unaligned_uint32_t *>(
2709 Blob.data()),
2710 static_cast<unsigned int>(Blob.size() / 4));
2711 TULexicalDecls.push_back(std::make_pair(&F, Contents));
Guy Benyei11169dd2012-12-18 14:30:41 +00002712 TU->setHasExternalLexicalStorage(true);
2713 break;
2714 }
2715
2716 case UPDATE_VISIBLE: {
2717 unsigned Idx = 0;
2718 serialization::DeclID ID = ReadDeclID(F, Record, Idx);
Richard Smith0f4e2c42015-08-06 04:23:48 +00002719 auto *Data = (const unsigned char*)Blob.data();
Richard Smithd88a7f12015-09-01 20:35:42 +00002720 PendingVisibleUpdates[ID].push_back(PendingVisibleUpdate{&F, Data});
Richard Smith0f4e2c42015-08-06 04:23:48 +00002721 // If we've already loaded the decl, perform the updates when we finish
2722 // loading this block.
2723 if (Decl *D = GetExistingDecl(ID))
2724 PendingUpdateRecords.push_back(std::make_pair(ID, D));
Guy Benyei11169dd2012-12-18 14:30:41 +00002725 break;
2726 }
2727
2728 case IDENTIFIER_TABLE:
Chris Lattner0e6c9402013-01-20 02:38:54 +00002729 F.IdentifierTableData = Blob.data();
Guy Benyei11169dd2012-12-18 14:30:41 +00002730 if (Record[0]) {
Justin Bognerda4e6502014-04-14 16:34:29 +00002731 F.IdentifierLookupTable = ASTIdentifierLookupTable::Create(
2732 (const unsigned char *)F.IdentifierTableData + Record[0],
2733 (const unsigned char *)F.IdentifierTableData + sizeof(uint32_t),
2734 (const unsigned char *)F.IdentifierTableData,
2735 ASTIdentifierLookupTrait(*this, F));
David L. Jonesc4808b9e2016-12-15 20:53:26 +00002736
Guy Benyei11169dd2012-12-18 14:30:41 +00002737 PP.getIdentifierTable().setExternalIdentifierLookup(this);
2738 }
2739 break;
2740
2741 case IDENTIFIER_OFFSET: {
2742 if (F.LocalNumIdentifiers != 0) {
2743 Error("duplicate IDENTIFIER_OFFSET record in AST file");
Ben Langmuir2c9af442014-04-10 17:57:43 +00002744 return Failure;
Guy Benyei11169dd2012-12-18 14:30:41 +00002745 }
Chris Lattner0e6c9402013-01-20 02:38:54 +00002746 F.IdentifierOffsets = (const uint32_t *)Blob.data();
Guy Benyei11169dd2012-12-18 14:30:41 +00002747 F.LocalNumIdentifiers = Record[0];
2748 unsigned LocalBaseIdentifierID = Record[1];
2749 F.BaseIdentifierID = getTotalNumIdentifiers();
David L. Jonesc4808b9e2016-12-15 20:53:26 +00002750
Guy Benyei11169dd2012-12-18 14:30:41 +00002751 if (F.LocalNumIdentifiers > 0) {
2752 // Introduce the global -> local mapping for identifiers within this
2753 // module.
David L. Jonesc4808b9e2016-12-15 20:53:26 +00002754 GlobalIdentifierMap.insert(std::make_pair(getTotalNumIdentifiers() + 1,
Guy Benyei11169dd2012-12-18 14:30:41 +00002755 &F));
David L. Jonesc4808b9e2016-12-15 20:53:26 +00002756
Guy Benyei11169dd2012-12-18 14:30:41 +00002757 // Introduce the local -> global mapping for identifiers within this
2758 // module.
2759 F.IdentifierRemap.insertOrReplace(
2760 std::make_pair(LocalBaseIdentifierID,
2761 F.BaseIdentifierID - LocalBaseIdentifierID));
Ben Langmuirfe971d92014-08-16 04:54:18 +00002762
Ben Langmuir52ca6782014-10-20 16:27:32 +00002763 IdentifiersLoaded.resize(IdentifiersLoaded.size()
2764 + F.LocalNumIdentifiers);
2765 }
Guy Benyei11169dd2012-12-18 14:30:41 +00002766 break;
2767 }
2768
Richard Smith33e0f7e2015-07-22 02:08:40 +00002769 case INTERESTING_IDENTIFIERS:
2770 F.PreloadIdentifierOffsets.assign(Record.begin(), Record.end());
2771 break;
2772
Ben Langmuir332aafe2014-01-31 01:06:56 +00002773 case EAGERLY_DESERIALIZED_DECLS:
Richard Smith9e2341d2015-03-23 03:25:59 +00002774 // FIXME: Skip reading this record if our ASTConsumer doesn't care
2775 // about "interesting" decls (for instance, if we're building a module).
Guy Benyei11169dd2012-12-18 14:30:41 +00002776 for (unsigned I = 0, N = Record.size(); I != N; ++I)
Ben Langmuir332aafe2014-01-31 01:06:56 +00002777 EagerlyDeserializedDecls.push_back(getGlobalDeclID(F, Record[I]));
Guy Benyei11169dd2012-12-18 14:30:41 +00002778 break;
2779
David Blaikie9ffe5a32017-01-30 05:00:26 +00002780 case MODULAR_CODEGEN_DECLS:
2781 // FIXME: Skip reading this record if our ASTConsumer doesn't care about
2782 // them (ie: if we're not codegenerating this module).
2783 if (F.Kind == MK_MainFile)
2784 for (unsigned I = 0, N = Record.size(); I != N; ++I)
2785 EagerlyDeserializedDecls.push_back(getGlobalDeclID(F, Record[I]));
2786 break;
2787
Guy Benyei11169dd2012-12-18 14:30:41 +00002788 case SPECIAL_TYPES:
Douglas Gregor44180f82013-02-01 23:45:03 +00002789 if (SpecialTypes.empty()) {
2790 for (unsigned I = 0, N = Record.size(); I != N; ++I)
2791 SpecialTypes.push_back(getGlobalTypeID(F, Record[I]));
2792 break;
2793 }
2794
2795 if (SpecialTypes.size() != Record.size()) {
2796 Error("invalid special-types record");
Ben Langmuir2c9af442014-04-10 17:57:43 +00002797 return Failure;
Douglas Gregor44180f82013-02-01 23:45:03 +00002798 }
2799
2800 for (unsigned I = 0, N = Record.size(); I != N; ++I) {
2801 serialization::TypeID ID = getGlobalTypeID(F, Record[I]);
2802 if (!SpecialTypes[I])
2803 SpecialTypes[I] = ID;
2804 // FIXME: If ID && SpecialTypes[I] != ID, do we need a separate
2805 // merge step?
2806 }
Guy Benyei11169dd2012-12-18 14:30:41 +00002807 break;
2808
2809 case STATISTICS:
2810 TotalNumStatements += Record[0];
2811 TotalNumMacros += Record[1];
2812 TotalLexicalDeclContexts += Record[2];
2813 TotalVisibleDeclContexts += Record[3];
2814 break;
2815
2816 case UNUSED_FILESCOPED_DECLS:
2817 for (unsigned I = 0, N = Record.size(); I != N; ++I)
2818 UnusedFileScopedDecls.push_back(getGlobalDeclID(F, Record[I]));
2819 break;
2820
2821 case DELEGATING_CTORS:
2822 for (unsigned I = 0, N = Record.size(); I != N; ++I)
2823 DelegatingCtorDecls.push_back(getGlobalDeclID(F, Record[I]));
2824 break;
2825
2826 case WEAK_UNDECLARED_IDENTIFIERS:
2827 if (Record.size() % 4 != 0) {
2828 Error("invalid weak identifiers record");
Ben Langmuir2c9af442014-04-10 17:57:43 +00002829 return Failure;
Guy Benyei11169dd2012-12-18 14:30:41 +00002830 }
David L. Jonesc4808b9e2016-12-15 20:53:26 +00002831
2832 // FIXME: Ignore weak undeclared identifiers from non-original PCH
Guy Benyei11169dd2012-12-18 14:30:41 +00002833 // files. This isn't the way to do it :)
2834 WeakUndeclaredIdentifiers.clear();
David L. Jonesc4808b9e2016-12-15 20:53:26 +00002835
Guy Benyei11169dd2012-12-18 14:30:41 +00002836 // Translate the weak, undeclared identifiers into global IDs.
2837 for (unsigned I = 0, N = Record.size(); I < N; /* in loop */) {
2838 WeakUndeclaredIdentifiers.push_back(
2839 getGlobalIdentifierID(F, Record[I++]));
2840 WeakUndeclaredIdentifiers.push_back(
2841 getGlobalIdentifierID(F, Record[I++]));
2842 WeakUndeclaredIdentifiers.push_back(
2843 ReadSourceLocation(F, Record, I).getRawEncoding());
2844 WeakUndeclaredIdentifiers.push_back(Record[I++]);
2845 }
2846 break;
2847
Guy Benyei11169dd2012-12-18 14:30:41 +00002848 case SELECTOR_OFFSETS: {
Chris Lattner0e6c9402013-01-20 02:38:54 +00002849 F.SelectorOffsets = (const uint32_t *)Blob.data();
Guy Benyei11169dd2012-12-18 14:30:41 +00002850 F.LocalNumSelectors = Record[0];
2851 unsigned LocalBaseSelectorID = Record[1];
2852 F.BaseSelectorID = getTotalNumSelectors();
David L. Jonesc4808b9e2016-12-15 20:53:26 +00002853
Guy Benyei11169dd2012-12-18 14:30:41 +00002854 if (F.LocalNumSelectors > 0) {
David L. Jonesc4808b9e2016-12-15 20:53:26 +00002855 // Introduce the global -> local mapping for selectors within this
Guy Benyei11169dd2012-12-18 14:30:41 +00002856 // module.
2857 GlobalSelectorMap.insert(std::make_pair(getTotalNumSelectors()+1, &F));
David L. Jonesc4808b9e2016-12-15 20:53:26 +00002858
2859 // Introduce the local -> global mapping for selectors within this
Guy Benyei11169dd2012-12-18 14:30:41 +00002860 // module.
2861 F.SelectorRemap.insertOrReplace(
2862 std::make_pair(LocalBaseSelectorID,
2863 F.BaseSelectorID - LocalBaseSelectorID));
Ben Langmuir52ca6782014-10-20 16:27:32 +00002864
2865 SelectorsLoaded.resize(SelectorsLoaded.size() + F.LocalNumSelectors);
Guy Benyei11169dd2012-12-18 14:30:41 +00002866 }
2867 break;
2868 }
David L. Jonesc4808b9e2016-12-15 20:53:26 +00002869
Guy Benyei11169dd2012-12-18 14:30:41 +00002870 case METHOD_POOL:
Chris Lattner0e6c9402013-01-20 02:38:54 +00002871 F.SelectorLookupTableData = (const unsigned char *)Blob.data();
Guy Benyei11169dd2012-12-18 14:30:41 +00002872 if (Record[0])
2873 F.SelectorLookupTable
2874 = ASTSelectorLookupTable::Create(
2875 F.SelectorLookupTableData + Record[0],
2876 F.SelectorLookupTableData,
2877 ASTSelectorLookupTrait(*this, F));
2878 TotalNumMethodPoolEntries += Record[1];
2879 break;
2880
2881 case REFERENCED_SELECTOR_POOL:
2882 if (!Record.empty()) {
2883 for (unsigned Idx = 0, N = Record.size() - 1; Idx < N; /* in loop */) {
David L. Jonesc4808b9e2016-12-15 20:53:26 +00002884 ReferencedSelectorsData.push_back(getGlobalSelectorID(F,
Guy Benyei11169dd2012-12-18 14:30:41 +00002885 Record[Idx++]));
2886 ReferencedSelectorsData.push_back(ReadSourceLocation(F, Record, Idx).
2887 getRawEncoding());
2888 }
2889 }
2890 break;
2891
2892 case PP_COUNTER_VALUE:
2893 if (!Record.empty() && Listener)
2894 Listener->ReadCounter(F, Record[0]);
2895 break;
David L. Jonesc4808b9e2016-12-15 20:53:26 +00002896
Guy Benyei11169dd2012-12-18 14:30:41 +00002897 case FILE_SORTED_DECLS:
Chris Lattner0e6c9402013-01-20 02:38:54 +00002898 F.FileSortedDecls = (const DeclID *)Blob.data();
Guy Benyei11169dd2012-12-18 14:30:41 +00002899 F.NumFileSortedDecls = Record[0];
2900 break;
2901
2902 case SOURCE_LOCATION_OFFSETS: {
Chris Lattner0e6c9402013-01-20 02:38:54 +00002903 F.SLocEntryOffsets = (const uint32_t *)Blob.data();
Guy Benyei11169dd2012-12-18 14:30:41 +00002904 F.LocalNumSLocEntries = Record[0];
2905 unsigned SLocSpaceSize = Record[1];
Benjamin Kramer867ea1d2014-03-02 13:01:17 +00002906 std::tie(F.SLocEntryBaseID, F.SLocEntryBaseOffset) =
Ben Langmuir52ca6782014-10-20 16:27:32 +00002907 SourceMgr.AllocateLoadedSLocEntries(F.LocalNumSLocEntries,
Guy Benyei11169dd2012-12-18 14:30:41 +00002908 SLocSpaceSize);
Richard Smith78d81ec2015-08-12 22:25:24 +00002909 if (!F.SLocEntryBaseID) {
2910 Error("ran out of source locations");
2911 break;
2912 }
Guy Benyei11169dd2012-12-18 14:30:41 +00002913 // Make our entry in the range map. BaseID is negative and growing, so
2914 // we invert it. Because we invert it, though, we need the other end of
2915 // the range.
2916 unsigned RangeStart =
2917 unsigned(-F.SLocEntryBaseID) - F.LocalNumSLocEntries + 1;
2918 GlobalSLocEntryMap.insert(std::make_pair(RangeStart, &F));
2919 F.FirstLoc = SourceLocation::getFromRawEncoding(F.SLocEntryBaseOffset);
2920
2921 // SLocEntryBaseOffset is lower than MaxLoadedOffset and decreasing.
2922 assert((F.SLocEntryBaseOffset & (1U << 31U)) == 0);
2923 GlobalSLocOffsetMap.insert(
2924 std::make_pair(SourceManager::MaxLoadedOffset - F.SLocEntryBaseOffset
2925 - SLocSpaceSize,&F));
2926
2927 // Initialize the remapping table.
2928 // Invalid stays invalid.
Richard Smithb9eab6d2014-03-20 19:44:17 +00002929 F.SLocRemap.insertOrReplace(std::make_pair(0U, 0));
Guy Benyei11169dd2012-12-18 14:30:41 +00002930 // This module. Base was 2 when being compiled.
Richard Smithb9eab6d2014-03-20 19:44:17 +00002931 F.SLocRemap.insertOrReplace(std::make_pair(2U,
Guy Benyei11169dd2012-12-18 14:30:41 +00002932 static_cast<int>(F.SLocEntryBaseOffset - 2)));
David L. Jonesc4808b9e2016-12-15 20:53:26 +00002933
Guy Benyei11169dd2012-12-18 14:30:41 +00002934 TotalNumSLocEntries += F.LocalNumSLocEntries;
2935 break;
2936 }
2937
2938 case MODULE_OFFSET_MAP: {
2939 // Additional remapping information.
Chris Lattner0e6c9402013-01-20 02:38:54 +00002940 const unsigned char *Data = (const unsigned char*)Blob.data();
2941 const unsigned char *DataEnd = Data + Blob.size();
Richard Smithb9eab6d2014-03-20 19:44:17 +00002942
2943 // If we see this entry before SOURCE_LOCATION_OFFSETS, add placeholders.
2944 if (F.SLocRemap.find(0) == F.SLocRemap.end()) {
2945 F.SLocRemap.insert(std::make_pair(0U, 0));
2946 F.SLocRemap.insert(std::make_pair(2U, 1));
2947 }
2948
Guy Benyei11169dd2012-12-18 14:30:41 +00002949 // Continuous range maps we may be updating in our module.
Ben Langmuir785180e2014-10-20 16:27:30 +00002950 typedef ContinuousRangeMap<uint32_t, int, 2>::Builder
2951 RemapBuilder;
2952 RemapBuilder SLocRemap(F.SLocRemap);
2953 RemapBuilder IdentifierRemap(F.IdentifierRemap);
2954 RemapBuilder MacroRemap(F.MacroRemap);
2955 RemapBuilder PreprocessedEntityRemap(F.PreprocessedEntityRemap);
2956 RemapBuilder SubmoduleRemap(F.SubmoduleRemap);
2957 RemapBuilder SelectorRemap(F.SelectorRemap);
2958 RemapBuilder DeclRemap(F.DeclRemap);
2959 RemapBuilder TypeRemap(F.TypeRemap);
Guy Benyei11169dd2012-12-18 14:30:41 +00002960
Richard Smithd8879c82015-08-24 21:59:32 +00002961 while (Data < DataEnd) {
Justin Bogner57ba0b22014-03-28 22:03:24 +00002962 using namespace llvm::support;
2963 uint16_t Len = endian::readNext<uint16_t, little, unaligned>(Data);
Guy Benyei11169dd2012-12-18 14:30:41 +00002964 StringRef Name = StringRef((const char*)Data, Len);
2965 Data += Len;
2966 ModuleFile *OM = ModuleMgr.lookup(Name);
2967 if (!OM) {
Bruno Cardoso Lopes15300652017-02-07 21:55:02 +00002968 std::string Msg =
2969 "SourceLocation remap refers to unknown module, cannot find ";
2970 Msg.append(Name);
2971 Error(Msg);
Ben Langmuir2c9af442014-04-10 17:57:43 +00002972 return Failure;
Guy Benyei11169dd2012-12-18 14:30:41 +00002973 }
2974
Justin Bogner57ba0b22014-03-28 22:03:24 +00002975 uint32_t SLocOffset =
2976 endian::readNext<uint32_t, little, unaligned>(Data);
2977 uint32_t IdentifierIDOffset =
2978 endian::readNext<uint32_t, little, unaligned>(Data);
2979 uint32_t MacroIDOffset =
2980 endian::readNext<uint32_t, little, unaligned>(Data);
2981 uint32_t PreprocessedEntityIDOffset =
2982 endian::readNext<uint32_t, little, unaligned>(Data);
2983 uint32_t SubmoduleIDOffset =
2984 endian::readNext<uint32_t, little, unaligned>(Data);
2985 uint32_t SelectorIDOffset =
2986 endian::readNext<uint32_t, little, unaligned>(Data);
2987 uint32_t DeclIDOffset =
2988 endian::readNext<uint32_t, little, unaligned>(Data);
2989 uint32_t TypeIndexOffset =
2990 endian::readNext<uint32_t, little, unaligned>(Data);
2991
Ben Langmuir785180e2014-10-20 16:27:30 +00002992 uint32_t None = std::numeric_limits<uint32_t>::max();
2993
2994 auto mapOffset = [&](uint32_t Offset, uint32_t BaseOffset,
2995 RemapBuilder &Remap) {
2996 if (Offset != None)
2997 Remap.insert(std::make_pair(Offset,
2998 static_cast<int>(BaseOffset - Offset)));
2999 };
3000 mapOffset(SLocOffset, OM->SLocEntryBaseOffset, SLocRemap);
3001 mapOffset(IdentifierIDOffset, OM->BaseIdentifierID, IdentifierRemap);
3002 mapOffset(MacroIDOffset, OM->BaseMacroID, MacroRemap);
3003 mapOffset(PreprocessedEntityIDOffset, OM->BasePreprocessedEntityID,
3004 PreprocessedEntityRemap);
3005 mapOffset(SubmoduleIDOffset, OM->BaseSubmoduleID, SubmoduleRemap);
3006 mapOffset(SelectorIDOffset, OM->BaseSelectorID, SelectorRemap);
3007 mapOffset(DeclIDOffset, OM->BaseDeclID, DeclRemap);
3008 mapOffset(TypeIndexOffset, OM->BaseTypeIndex, TypeRemap);
Guy Benyei11169dd2012-12-18 14:30:41 +00003009
3010 // Global -> local mappings.
3011 F.GlobalToLocalDeclIDs[OM] = DeclIDOffset;
3012 }
3013 break;
3014 }
3015
3016 case SOURCE_MANAGER_LINE_TABLE:
3017 if (ParseLineTable(F, Record))
Ben Langmuir2c9af442014-04-10 17:57:43 +00003018 return Failure;
Guy Benyei11169dd2012-12-18 14:30:41 +00003019 break;
3020
3021 case SOURCE_LOCATION_PRELOADS: {
3022 // Need to transform from the local view (1-based IDs) to the global view,
3023 // which is based off F.SLocEntryBaseID.
3024 if (!F.PreloadSLocEntries.empty()) {
3025 Error("Multiple SOURCE_LOCATION_PRELOADS records in AST file");
Ben Langmuir2c9af442014-04-10 17:57:43 +00003026 return Failure;
Guy Benyei11169dd2012-12-18 14:30:41 +00003027 }
David L. Jonesc4808b9e2016-12-15 20:53:26 +00003028
Guy Benyei11169dd2012-12-18 14:30:41 +00003029 F.PreloadSLocEntries.swap(Record);
3030 break;
3031 }
3032
3033 case EXT_VECTOR_DECLS:
3034 for (unsigned I = 0, N = Record.size(); I != N; ++I)
3035 ExtVectorDecls.push_back(getGlobalDeclID(F, Record[I]));
3036 break;
3037
3038 case VTABLE_USES:
3039 if (Record.size() % 3 != 0) {
3040 Error("Invalid VTABLE_USES record");
Ben Langmuir2c9af442014-04-10 17:57:43 +00003041 return Failure;
Guy Benyei11169dd2012-12-18 14:30:41 +00003042 }
David L. Jonesc4808b9e2016-12-15 20:53:26 +00003043
Guy Benyei11169dd2012-12-18 14:30:41 +00003044 // Later tables overwrite earlier ones.
3045 // FIXME: Modules will have some trouble with this. This is clearly not
3046 // the right way to do this.
3047 VTableUses.clear();
David L. Jonesc4808b9e2016-12-15 20:53:26 +00003048
Guy Benyei11169dd2012-12-18 14:30:41 +00003049 for (unsigned Idx = 0, N = Record.size(); Idx != N; /* In loop */) {
3050 VTableUses.push_back(getGlobalDeclID(F, Record[Idx++]));
3051 VTableUses.push_back(
3052 ReadSourceLocation(F, Record, Idx).getRawEncoding());
3053 VTableUses.push_back(Record[Idx++]);
3054 }
3055 break;
3056
Guy Benyei11169dd2012-12-18 14:30:41 +00003057 case PENDING_IMPLICIT_INSTANTIATIONS:
3058 if (PendingInstantiations.size() % 2 != 0) {
3059 Error("Invalid existing PendingInstantiations");
Ben Langmuir2c9af442014-04-10 17:57:43 +00003060 return Failure;
Guy Benyei11169dd2012-12-18 14:30:41 +00003061 }
3062
3063 if (Record.size() % 2 != 0) {
3064 Error("Invalid PENDING_IMPLICIT_INSTANTIATIONS block");
Ben Langmuir2c9af442014-04-10 17:57:43 +00003065 return Failure;
Guy Benyei11169dd2012-12-18 14:30:41 +00003066 }
3067
3068 for (unsigned I = 0, N = Record.size(); I != N; /* in loop */) {
3069 PendingInstantiations.push_back(getGlobalDeclID(F, Record[I++]));
3070 PendingInstantiations.push_back(
3071 ReadSourceLocation(F, Record, I).getRawEncoding());
3072 }
3073 break;
3074
3075 case SEMA_DECL_REFS:
Richard Smith96269c52016-09-29 22:49:46 +00003076 if (Record.size() != 3) {
Richard Smith3d8e97e2013-10-18 06:54:39 +00003077 Error("Invalid SEMA_DECL_REFS block");
Ben Langmuir2c9af442014-04-10 17:57:43 +00003078 return Failure;
Richard Smith3d8e97e2013-10-18 06:54:39 +00003079 }
Guy Benyei11169dd2012-12-18 14:30:41 +00003080 for (unsigned I = 0, N = Record.size(); I != N; ++I)
3081 SemaDeclRefs.push_back(getGlobalDeclID(F, Record[I]));
3082 break;
3083
3084 case PPD_ENTITIES_OFFSETS: {
Chris Lattner0e6c9402013-01-20 02:38:54 +00003085 F.PreprocessedEntityOffsets = (const PPEntityOffset *)Blob.data();
3086 assert(Blob.size() % sizeof(PPEntityOffset) == 0);
3087 F.NumPreprocessedEntities = Blob.size() / sizeof(PPEntityOffset);
Guy Benyei11169dd2012-12-18 14:30:41 +00003088
3089 unsigned LocalBasePreprocessedEntityID = Record[0];
David L. Jonesc4808b9e2016-12-15 20:53:26 +00003090
Guy Benyei11169dd2012-12-18 14:30:41 +00003091 unsigned StartingID;
3092 if (!PP.getPreprocessingRecord())
3093 PP.createPreprocessingRecord();
3094 if (!PP.getPreprocessingRecord()->getExternalSource())
3095 PP.getPreprocessingRecord()->SetExternalSource(*this);
David L. Jonesc4808b9e2016-12-15 20:53:26 +00003096 StartingID
Guy Benyei11169dd2012-12-18 14:30:41 +00003097 = PP.getPreprocessingRecord()
Ben Langmuir52ca6782014-10-20 16:27:32 +00003098 ->allocateLoadedEntities(F.NumPreprocessedEntities);
Guy Benyei11169dd2012-12-18 14:30:41 +00003099 F.BasePreprocessedEntityID = StartingID;
3100
3101 if (F.NumPreprocessedEntities > 0) {
3102 // Introduce the global -> local mapping for preprocessed entities in
3103 // this module.
3104 GlobalPreprocessedEntityMap.insert(std::make_pair(StartingID, &F));
David L. Jonesc4808b9e2016-12-15 20:53:26 +00003105
Guy Benyei11169dd2012-12-18 14:30:41 +00003106 // Introduce the local -> global mapping for preprocessed entities in
3107 // this module.
3108 F.PreprocessedEntityRemap.insertOrReplace(
3109 std::make_pair(LocalBasePreprocessedEntityID,
3110 F.BasePreprocessedEntityID - LocalBasePreprocessedEntityID));
3111 }
3112
3113 break;
3114 }
David L. Jonesc4808b9e2016-12-15 20:53:26 +00003115
Guy Benyei11169dd2012-12-18 14:30:41 +00003116 case DECL_UPDATE_OFFSETS: {
3117 if (Record.size() % 2 != 0) {
3118 Error("invalid DECL_UPDATE_OFFSETS block in AST file");
Ben Langmuir2c9af442014-04-10 17:57:43 +00003119 return Failure;
Guy Benyei11169dd2012-12-18 14:30:41 +00003120 }
Richard Smithcd45dbc2014-04-19 03:48:30 +00003121 for (unsigned I = 0, N = Record.size(); I != N; I += 2) {
3122 GlobalDeclID ID = getGlobalDeclID(F, Record[I]);
3123 DeclUpdateOffsets[ID].push_back(std::make_pair(&F, Record[I + 1]));
3124
3125 // If we've already loaded the decl, perform the updates when we finish
3126 // loading this block.
3127 if (Decl *D = GetExistingDecl(ID))
3128 PendingUpdateRecords.push_back(std::make_pair(ID, D));
3129 }
Guy Benyei11169dd2012-12-18 14:30:41 +00003130 break;
3131 }
3132
Guy Benyei11169dd2012-12-18 14:30:41 +00003133 case OBJC_CATEGORIES_MAP: {
3134 if (F.LocalNumObjCCategoriesInMap != 0) {
3135 Error("duplicate OBJC_CATEGORIES_MAP record in AST file");
Ben Langmuir2c9af442014-04-10 17:57:43 +00003136 return Failure;
Guy Benyei11169dd2012-12-18 14:30:41 +00003137 }
David L. Jonesc4808b9e2016-12-15 20:53:26 +00003138
Guy Benyei11169dd2012-12-18 14:30:41 +00003139 F.LocalNumObjCCategoriesInMap = Record[0];
Chris Lattner0e6c9402013-01-20 02:38:54 +00003140 F.ObjCCategoriesMap = (const ObjCCategoriesInfo *)Blob.data();
Guy Benyei11169dd2012-12-18 14:30:41 +00003141 break;
3142 }
David L. Jonesc4808b9e2016-12-15 20:53:26 +00003143
Guy Benyei11169dd2012-12-18 14:30:41 +00003144 case OBJC_CATEGORIES:
3145 F.ObjCCategories.swap(Record);
3146 break;
Richard Smithc2bb8182015-03-24 06:36:48 +00003147
Guy Benyei11169dd2012-12-18 14:30:41 +00003148 case DIAG_PRAGMA_MAPPINGS:
3149 if (F.PragmaDiagMappings.empty())
3150 F.PragmaDiagMappings.swap(Record);
3151 else
3152 F.PragmaDiagMappings.insert(F.PragmaDiagMappings.end(),
3153 Record.begin(), Record.end());
3154 break;
David L. Jonesc4808b9e2016-12-15 20:53:26 +00003155
Guy Benyei11169dd2012-12-18 14:30:41 +00003156 case CUDA_SPECIAL_DECL_REFS:
3157 // Later tables overwrite earlier ones.
3158 // FIXME: Modules will have trouble with this.
3159 CUDASpecialDeclRefs.clear();
3160 for (unsigned I = 0, N = Record.size(); I != N; ++I)
3161 CUDASpecialDeclRefs.push_back(getGlobalDeclID(F, Record[I]));
3162 break;
3163
3164 case HEADER_SEARCH_TABLE: {
Chris Lattner0e6c9402013-01-20 02:38:54 +00003165 F.HeaderFileInfoTableData = Blob.data();
Guy Benyei11169dd2012-12-18 14:30:41 +00003166 F.LocalNumHeaderFileInfos = Record[1];
Guy Benyei11169dd2012-12-18 14:30:41 +00003167 if (Record[0]) {
3168 F.HeaderFileInfoTable
3169 = HeaderFileInfoLookupTable::Create(
3170 (const unsigned char *)F.HeaderFileInfoTableData + Record[0],
3171 (const unsigned char *)F.HeaderFileInfoTableData,
David L. Jonesc4808b9e2016-12-15 20:53:26 +00003172 HeaderFileInfoTrait(*this, F,
Guy Benyei11169dd2012-12-18 14:30:41 +00003173 &PP.getHeaderSearchInfo(),
Chris Lattner0e6c9402013-01-20 02:38:54 +00003174 Blob.data() + Record[2]));
David L. Jonesc4808b9e2016-12-15 20:53:26 +00003175
Guy Benyei11169dd2012-12-18 14:30:41 +00003176 PP.getHeaderSearchInfo().SetExternalSource(this);
3177 if (!PP.getHeaderSearchInfo().getExternalLookup())
3178 PP.getHeaderSearchInfo().SetExternalLookup(this);
3179 }
3180 break;
3181 }
David L. Jonesc4808b9e2016-12-15 20:53:26 +00003182
Guy Benyei11169dd2012-12-18 14:30:41 +00003183 case FP_PRAGMA_OPTIONS:
3184 // Later tables overwrite earlier ones.
3185 FPPragmaOptions.swap(Record);
3186 break;
3187
3188 case OPENCL_EXTENSIONS:
Yaxun Liu5b746652016-12-18 05:18:55 +00003189 for (unsigned I = 0, E = Record.size(); I != E; ) {
3190 auto Name = ReadString(Record, I);
3191 auto &Opt = OpenCLExtensions.OptMap[Name];
Yaxun Liucc2741c2016-12-18 06:35:06 +00003192 Opt.Supported = Record[I++] != 0;
3193 Opt.Enabled = Record[I++] != 0;
Yaxun Liu5b746652016-12-18 05:18:55 +00003194 Opt.Avail = Record[I++];
3195 Opt.Core = Record[I++];
3196 }
3197 break;
3198
3199 case OPENCL_EXTENSION_TYPES:
3200 for (unsigned I = 0, E = Record.size(); I != E;) {
3201 auto TypeID = static_cast<::TypeID>(Record[I++]);
3202 auto *Type = GetType(TypeID).getTypePtr();
3203 auto NumExt = static_cast<unsigned>(Record[I++]);
3204 for (unsigned II = 0; II != NumExt; ++II) {
3205 auto Ext = ReadString(Record, I);
3206 OpenCLTypeExtMap[Type].insert(Ext);
3207 }
3208 }
3209 break;
3210
3211 case OPENCL_EXTENSION_DECLS:
3212 for (unsigned I = 0, E = Record.size(); I != E;) {
3213 auto DeclID = static_cast<::DeclID>(Record[I++]);
3214 auto *Decl = GetDecl(DeclID);
3215 auto NumExt = static_cast<unsigned>(Record[I++]);
3216 for (unsigned II = 0; II != NumExt; ++II) {
3217 auto Ext = ReadString(Record, I);
3218 OpenCLDeclExtMap[Decl].insert(Ext);
3219 }
3220 }
Guy Benyei11169dd2012-12-18 14:30:41 +00003221 break;
3222
3223 case TENTATIVE_DEFINITIONS:
3224 for (unsigned I = 0, N = Record.size(); I != N; ++I)
3225 TentativeDefinitions.push_back(getGlobalDeclID(F, Record[I]));
3226 break;
David L. Jonesc4808b9e2016-12-15 20:53:26 +00003227
Guy Benyei11169dd2012-12-18 14:30:41 +00003228 case KNOWN_NAMESPACES:
3229 for (unsigned I = 0, N = Record.size(); I != N; ++I)
3230 KnownNamespaces.push_back(getGlobalDeclID(F, Record[I]));
3231 break;
Nick Lewycky8334af82013-01-26 00:35:08 +00003232
Nick Lewycky9c7eb1d2013-02-01 08:13:20 +00003233 case UNDEFINED_BUT_USED:
3234 if (UndefinedButUsed.size() % 2 != 0) {
3235 Error("Invalid existing UndefinedButUsed");
Ben Langmuir2c9af442014-04-10 17:57:43 +00003236 return Failure;
Nick Lewycky8334af82013-01-26 00:35:08 +00003237 }
3238
3239 if (Record.size() % 2 != 0) {
Nick Lewycky9c7eb1d2013-02-01 08:13:20 +00003240 Error("invalid undefined-but-used record");
Ben Langmuir2c9af442014-04-10 17:57:43 +00003241 return Failure;
Nick Lewycky8334af82013-01-26 00:35:08 +00003242 }
3243 for (unsigned I = 0, N = Record.size(); I != N; /* in loop */) {
Nick Lewycky9c7eb1d2013-02-01 08:13:20 +00003244 UndefinedButUsed.push_back(getGlobalDeclID(F, Record[I++]));
3245 UndefinedButUsed.push_back(
Nick Lewycky8334af82013-01-26 00:35:08 +00003246 ReadSourceLocation(F, Record, I).getRawEncoding());
3247 }
3248 break;
Ismail Pazarbasie5768d12015-05-18 19:59:11 +00003249 case DELETE_EXPRS_TO_ANALYZE:
3250 for (unsigned I = 0, N = Record.size(); I != N;) {
3251 DelayedDeleteExprs.push_back(getGlobalDeclID(F, Record[I++]));
3252 const uint64_t Count = Record[I++];
3253 DelayedDeleteExprs.push_back(Count);
3254 for (uint64_t C = 0; C < Count; ++C) {
3255 DelayedDeleteExprs.push_back(ReadSourceLocation(F, Record, I).getRawEncoding());
3256 bool IsArrayForm = Record[I++] == 1;
3257 DelayedDeleteExprs.push_back(IsArrayForm);
3258 }
3259 }
3260 break;
Nick Lewycky8334af82013-01-26 00:35:08 +00003261
Guy Benyei11169dd2012-12-18 14:30:41 +00003262 case IMPORTED_MODULES: {
Manman Ren11f2a472016-08-18 17:42:15 +00003263 if (!F.isModule()) {
Guy Benyei11169dd2012-12-18 14:30:41 +00003264 // If we aren't loading a module (which has its own exports), make
3265 // all of the imported modules visible.
3266 // FIXME: Deal with macros-only imports.
Richard Smith56be7542014-03-21 00:33:59 +00003267 for (unsigned I = 0, N = Record.size(); I != N; /**/) {
3268 unsigned GlobalID = getGlobalSubmoduleID(F, Record[I++]);
3269 SourceLocation Loc = ReadSourceLocation(F, Record, I);
Graydon Hoare9c982442017-01-18 20:36:59 +00003270 if (GlobalID) {
Aaron Ballman4f45b712014-03-21 15:22:56 +00003271 ImportedModules.push_back(ImportedSubmodule(GlobalID, Loc));
Graydon Hoare9c982442017-01-18 20:36:59 +00003272 if (DeserializationListener)
3273 DeserializationListener->ModuleImportRead(GlobalID, Loc);
3274 }
Guy Benyei11169dd2012-12-18 14:30:41 +00003275 }
3276 }
3277 break;
3278 }
3279
Guy Benyei11169dd2012-12-18 14:30:41 +00003280 case MACRO_OFFSET: {
3281 if (F.LocalNumMacros != 0) {
3282 Error("duplicate MACRO_OFFSET record in AST file");
Ben Langmuir2c9af442014-04-10 17:57:43 +00003283 return Failure;
Guy Benyei11169dd2012-12-18 14:30:41 +00003284 }
Chris Lattner0e6c9402013-01-20 02:38:54 +00003285 F.MacroOffsets = (const uint32_t *)Blob.data();
Guy Benyei11169dd2012-12-18 14:30:41 +00003286 F.LocalNumMacros = Record[0];
3287 unsigned LocalBaseMacroID = Record[1];
3288 F.BaseMacroID = getTotalNumMacros();
3289
3290 if (F.LocalNumMacros > 0) {
3291 // Introduce the global -> local mapping for macros within this module.
3292 GlobalMacroMap.insert(std::make_pair(getTotalNumMacros() + 1, &F));
3293
3294 // Introduce the local -> global mapping for macros within this module.
3295 F.MacroRemap.insertOrReplace(
3296 std::make_pair(LocalBaseMacroID,
3297 F.BaseMacroID - LocalBaseMacroID));
Ben Langmuir52ca6782014-10-20 16:27:32 +00003298
3299 MacrosLoaded.resize(MacrosLoaded.size() + F.LocalNumMacros);
Guy Benyei11169dd2012-12-18 14:30:41 +00003300 }
3301 break;
3302 }
3303
Richard Smithe40f2ba2013-08-07 21:41:30 +00003304 case LATE_PARSED_TEMPLATE: {
3305 LateParsedTemplates.append(Record.begin(), Record.end());
3306 break;
3307 }
Dario Domizioli13a0a382014-05-23 12:13:25 +00003308
3309 case OPTIMIZE_PRAGMA_OPTIONS:
3310 if (Record.size() != 1) {
3311 Error("invalid pragma optimize record");
3312 return Failure;
3313 }
3314 OptimizeOffPragmaLocation = ReadSourceLocation(F, Record[0]);
3315 break;
Nico Weber72889432014-09-06 01:25:55 +00003316
Nico Weber779355f2016-03-02 23:22:00 +00003317 case MSSTRUCT_PRAGMA_OPTIONS:
3318 if (Record.size() != 1) {
3319 Error("invalid pragma ms_struct record");
3320 return Failure;
3321 }
3322 PragmaMSStructState = Record[0];
3323 break;
3324
Nico Weber42932312016-03-03 00:17:35 +00003325 case POINTERS_TO_MEMBERS_PRAGMA_OPTIONS:
3326 if (Record.size() != 2) {
3327 Error("invalid pragma ms_struct record");
3328 return Failure;
3329 }
3330 PragmaMSPointersToMembersState = Record[0];
3331 PointersToMembersPragmaLocation = ReadSourceLocation(F, Record[1]);
3332 break;
3333
Nico Weber72889432014-09-06 01:25:55 +00003334 case UNUSED_LOCAL_TYPEDEF_NAME_CANDIDATES:
3335 for (unsigned I = 0, N = Record.size(); I != N; ++I)
3336 UnusedLocalTypedefNameCandidates.push_back(
3337 getGlobalDeclID(F, Record[I]));
3338 break;
Justin Lebar67a78a62016-10-08 22:15:58 +00003339
3340 case CUDA_PRAGMA_FORCE_HOST_DEVICE_DEPTH:
3341 if (Record.size() != 1) {
3342 Error("invalid cuda pragma options record");
3343 return Failure;
3344 }
3345 ForceCUDAHostDeviceDepth = Record[0];
3346 break;
Guy Benyei11169dd2012-12-18 14:30:41 +00003347 }
3348 }
Guy Benyei11169dd2012-12-18 14:30:41 +00003349}
3350
Ben Langmuir4b8a9e92014-08-12 16:42:33 +00003351ASTReader::ASTReadResult
3352ASTReader::ReadModuleMapFileBlock(RecordData &Record, ModuleFile &F,
3353 const ModuleFile *ImportedBy,
3354 unsigned ClientLoadCapabilities) {
3355 unsigned Idx = 0;
Richard Smith7ed1bc92014-12-05 22:42:13 +00003356 F.ModuleMapPath = ReadPath(F, Record, Idx);
Ben Langmuir4b8a9e92014-08-12 16:42:33 +00003357
Manman Ren11f2a472016-08-18 17:42:15 +00003358 if (F.Kind == MK_ExplicitModule || F.Kind == MK_PrebuiltModule) {
Richard Smithe842a472014-10-22 02:05:46 +00003359 // For an explicitly-loaded module, we don't care whether the original
3360 // module map file exists or matches.
3361 return Success;
3362 }
3363
Ben Langmuir4b8a9e92014-08-12 16:42:33 +00003364 // Try to resolve ModuleName in the current header search context and
3365 // verify that it is found in the same module map file as we saved. If the
3366 // top-level AST file is a main file, skip this check because there is no
3367 // usable header search context.
3368 assert(!F.ModuleName.empty() &&
Richard Smithe842a472014-10-22 02:05:46 +00003369 "MODULE_NAME should come before MODULE_MAP_FILE");
Duncan P. N. Exon Smith96a06e02017-01-28 22:15:22 +00003370 if (F.Kind == MK_ImplicitModule && ModuleMgr.begin()->Kind != MK_MainFile) {
Richard Smithe842a472014-10-22 02:05:46 +00003371 // An implicitly-loaded module file should have its module listed in some
3372 // module map file that we've already loaded.
Ben Langmuir4b8a9e92014-08-12 16:42:33 +00003373 Module *M = PP.getHeaderSearchInfo().lookupModule(F.ModuleName);
Richard Smithe842a472014-10-22 02:05:46 +00003374 auto &Map = PP.getHeaderSearchInfo().getModuleMap();
3375 const FileEntry *ModMap = M ? Map.getModuleMapFileForUniquing(M) : nullptr;
3376 if (!ModMap) {
Ben Langmuir4b8a9e92014-08-12 16:42:33 +00003377 assert(ImportedBy && "top-level import should be verified");
Richard Smith0f99d6a2015-08-09 08:48:41 +00003378 if ((ClientLoadCapabilities & ARR_OutOfDate) == 0) {
3379 if (auto *ASTFE = M ? M->getASTFile() : nullptr)
3380 // This module was defined by an imported (explicit) module.
3381 Diag(diag::err_module_file_conflict) << F.ModuleName << F.FileName
3382 << ASTFE->getName();
3383 else
3384 // This module was built with a different module map.
3385 Diag(diag::err_imported_module_not_found)
3386 << F.ModuleName << F.FileName << ImportedBy->FileName
3387 << F.ModuleMapPath;
3388 }
3389 return OutOfDate;
Ben Langmuir4b8a9e92014-08-12 16:42:33 +00003390 }
3391
Richard Smithe842a472014-10-22 02:05:46 +00003392 assert(M->Name == F.ModuleName && "found module with different name");
3393
Ben Langmuir4b8a9e92014-08-12 16:42:33 +00003394 // Check the primary module map file.
Ben Langmuir4b8a9e92014-08-12 16:42:33 +00003395 const FileEntry *StoredModMap = FileMgr.getFile(F.ModuleMapPath);
Ben Langmuir4b8a9e92014-08-12 16:42:33 +00003396 if (StoredModMap == nullptr || StoredModMap != ModMap) {
3397 assert(ModMap && "found module is missing module map file");
Ben Langmuir4b8a9e92014-08-12 16:42:33 +00003398 assert(ImportedBy && "top-level import should be verified");
3399 if ((ClientLoadCapabilities & ARR_OutOfDate) == 0)
3400 Diag(diag::err_imported_module_modmap_changed)
3401 << F.ModuleName << ImportedBy->FileName
3402 << ModMap->getName() << F.ModuleMapPath;
3403 return OutOfDate;
3404 }
3405
3406 llvm::SmallPtrSet<const FileEntry *, 1> AdditionalStoredMaps;
3407 for (unsigned I = 0, N = Record[Idx++]; I < N; ++I) {
3408 // FIXME: we should use input files rather than storing names.
Richard Smith7ed1bc92014-12-05 22:42:13 +00003409 std::string Filename = ReadPath(F, Record, Idx);
Ben Langmuir4b8a9e92014-08-12 16:42:33 +00003410 const FileEntry *F =
3411 FileMgr.getFile(Filename, false, false);
3412 if (F == nullptr) {
3413 if ((ClientLoadCapabilities & ARR_OutOfDate) == 0)
3414 Error("could not find file '" + Filename +"' referenced by AST file");
3415 return OutOfDate;
3416 }
3417 AdditionalStoredMaps.insert(F);
3418 }
3419
3420 // Check any additional module map files (e.g. module.private.modulemap)
3421 // that are not in the pcm.
3422 if (auto *AdditionalModuleMaps = Map.getAdditionalModuleMapFiles(M)) {
3423 for (const FileEntry *ModMap : *AdditionalModuleMaps) {
3424 // Remove files that match
3425 // Note: SmallPtrSet::erase is really remove
3426 if (!AdditionalStoredMaps.erase(ModMap)) {
3427 if ((ClientLoadCapabilities & ARR_OutOfDate) == 0)
3428 Diag(diag::err_module_different_modmap)
3429 << F.ModuleName << /*new*/0 << ModMap->getName();
3430 return OutOfDate;
3431 }
3432 }
3433 }
3434
3435 // Check any additional module map files that are in the pcm, but not
3436 // found in header search. Cases that match are already removed.
3437 for (const FileEntry *ModMap : AdditionalStoredMaps) {
3438 if ((ClientLoadCapabilities & ARR_OutOfDate) == 0)
3439 Diag(diag::err_module_different_modmap)
3440 << F.ModuleName << /*not new*/1 << ModMap->getName();
3441 return OutOfDate;
3442 }
3443 }
3444
3445 if (Listener)
3446 Listener->ReadModuleMapFile(F.ModuleMapPath);
3447 return Success;
3448}
3449
3450
Douglas Gregorc1489562013-02-12 23:36:21 +00003451/// \brief Move the given method to the back of the global list of methods.
3452static void moveMethodToBackOfGlobalList(Sema &S, ObjCMethodDecl *Method) {
3453 // Find the entry for this selector in the method pool.
3454 Sema::GlobalMethodPool::iterator Known
3455 = S.MethodPool.find(Method->getSelector());
3456 if (Known == S.MethodPool.end())
3457 return;
3458
3459 // Retrieve the appropriate method list.
3460 ObjCMethodList &Start = Method->isInstanceMethod()? Known->second.first
3461 : Known->second.second;
3462 bool Found = false;
Argyrios Kyrtzidisd3da6e02013-04-17 00:08:58 +00003463 for (ObjCMethodList *List = &Start; List; List = List->getNext()) {
Douglas Gregorc1489562013-02-12 23:36:21 +00003464 if (!Found) {
Nico Weber2e0c8f72014-12-27 03:58:08 +00003465 if (List->getMethod() == Method) {
Douglas Gregorc1489562013-02-12 23:36:21 +00003466 Found = true;
3467 } else {
3468 // Keep searching.
3469 continue;
3470 }
3471 }
3472
Argyrios Kyrtzidisd3da6e02013-04-17 00:08:58 +00003473 if (List->getNext())
Nico Weber2e0c8f72014-12-27 03:58:08 +00003474 List->setMethod(List->getNext()->getMethod());
Douglas Gregorc1489562013-02-12 23:36:21 +00003475 else
Nico Weber2e0c8f72014-12-27 03:58:08 +00003476 List->setMethod(Method);
Douglas Gregorc1489562013-02-12 23:36:21 +00003477 }
3478}
3479
Richard Smithde711422015-04-23 21:20:19 +00003480void ASTReader::makeNamesVisible(const HiddenNames &Names, Module *Owner) {
Richard Smith10434f32015-05-02 02:08:26 +00003481 assert(Owner->NameVisibility != Module::Hidden && "nothing to make visible?");
Richard Smith20e883e2015-04-29 23:20:19 +00003482 for (Decl *D : Names) {
Richard Smith49f906a2014-03-01 00:08:04 +00003483 bool wasHidden = D->Hidden;
3484 D->Hidden = false;
Guy Benyei11169dd2012-12-18 14:30:41 +00003485
Richard Smith49f906a2014-03-01 00:08:04 +00003486 if (wasHidden && SemaObj) {
3487 if (ObjCMethodDecl *Method = dyn_cast<ObjCMethodDecl>(D)) {
3488 moveMethodToBackOfGlobalList(*SemaObj, Method);
Douglas Gregorc1489562013-02-12 23:36:21 +00003489 }
Guy Benyei11169dd2012-12-18 14:30:41 +00003490 }
3491 }
3492}
3493
Richard Smith49f906a2014-03-01 00:08:04 +00003494void ASTReader::makeModuleVisible(Module *Mod,
Argyrios Kyrtzidis125df052013-02-01 16:36:12 +00003495 Module::NameVisibilityKind NameVisibility,
Richard Smitha7e2cc62015-05-01 01:53:09 +00003496 SourceLocation ImportLoc) {
Guy Benyei11169dd2012-12-18 14:30:41 +00003497 llvm::SmallPtrSet<Module *, 4> Visited;
Dmitri Gribenkof8579502013-01-12 19:30:44 +00003498 SmallVector<Module *, 4> Stack;
Robert Wilhelm25284cc2013-08-23 16:11:15 +00003499 Stack.push_back(Mod);
Guy Benyei11169dd2012-12-18 14:30:41 +00003500 while (!Stack.empty()) {
Robert Wilhelm25284cc2013-08-23 16:11:15 +00003501 Mod = Stack.pop_back_val();
Guy Benyei11169dd2012-12-18 14:30:41 +00003502
3503 if (NameVisibility <= Mod->NameVisibility) {
Robert Wilhelm25284cc2013-08-23 16:11:15 +00003504 // This module already has this level of visibility (or greater), so
Guy Benyei11169dd2012-12-18 14:30:41 +00003505 // there is nothing more to do.
3506 continue;
3507 }
Richard Smith49f906a2014-03-01 00:08:04 +00003508
Guy Benyei11169dd2012-12-18 14:30:41 +00003509 if (!Mod->isAvailable()) {
3510 // Modules that aren't available cannot be made visible.
3511 continue;
3512 }
3513
3514 // Update the module's name visibility.
3515 Mod->NameVisibility = NameVisibility;
Richard Smith49f906a2014-03-01 00:08:04 +00003516
Guy Benyei11169dd2012-12-18 14:30:41 +00003517 // If we've already deserialized any names from this module,
3518 // mark them as visible.
3519 HiddenNamesMapType::iterator Hidden = HiddenNamesMap.find(Mod);
3520 if (Hidden != HiddenNamesMap.end()) {
Richard Smith57721ac2014-07-21 04:10:40 +00003521 auto HiddenNames = std::move(*Hidden);
Guy Benyei11169dd2012-12-18 14:30:41 +00003522 HiddenNamesMap.erase(Hidden);
Richard Smithde711422015-04-23 21:20:19 +00003523 makeNamesVisible(HiddenNames.second, HiddenNames.first);
Richard Smith57721ac2014-07-21 04:10:40 +00003524 assert(HiddenNamesMap.find(Mod) == HiddenNamesMap.end() &&
3525 "making names visible added hidden names");
Guy Benyei11169dd2012-12-18 14:30:41 +00003526 }
Dmitri Gribenkoe9bcf5b2013-11-04 21:51:33 +00003527
Guy Benyei11169dd2012-12-18 14:30:41 +00003528 // Push any exported modules onto the stack to be marked as visible.
Argyrios Kyrtzidis8739f7b2013-02-19 19:34:40 +00003529 SmallVector<Module *, 16> Exports;
3530 Mod->getExportedModules(Exports);
3531 for (SmallVectorImpl<Module *>::iterator
3532 I = Exports.begin(), E = Exports.end(); I != E; ++I) {
3533 Module *Exported = *I;
David Blaikie82e95a32014-11-19 07:49:47 +00003534 if (Visited.insert(Exported).second)
Argyrios Kyrtzidis8739f7b2013-02-19 19:34:40 +00003535 Stack.push_back(Exported);
Guy Benyei11169dd2012-12-18 14:30:41 +00003536 }
3537 }
3538}
3539
Richard Smith6561f922016-09-12 21:06:40 +00003540/// We've merged the definition \p MergedDef into the existing definition
3541/// \p Def. Ensure that \p Def is made visible whenever \p MergedDef is made
3542/// visible.
3543void ASTReader::mergeDefinitionVisibility(NamedDecl *Def,
3544 NamedDecl *MergedDef) {
Benjamin Kramera72a70a2016-10-17 13:00:44 +00003545 // FIXME: This doesn't correctly handle the case where MergedDef is visible
3546 // in modules other than its owning module. We should instead give the
3547 // ASTContext a list of merged definitions for Def.
Richard Smith6561f922016-09-12 21:06:40 +00003548 if (Def->isHidden()) {
3549 // If MergedDef is visible or becomes visible, make the definition visible.
Benjamin Kramera72a70a2016-10-17 13:00:44 +00003550 if (!MergedDef->isHidden())
3551 Def->Hidden = false;
3552 else if (getContext().getLangOpts().ModulesLocalVisibility) {
3553 getContext().mergeDefinitionIntoModule(
3554 Def, MergedDef->getImportedOwningModule(),
3555 /*NotifyListeners*/ false);
3556 PendingMergedDefinitionsToDeduplicate.insert(Def);
3557 } else {
3558 auto SubmoduleID = MergedDef->getOwningModuleID();
3559 assert(SubmoduleID && "hidden definition in no module");
3560 HiddenNamesMap[getSubmodule(SubmoduleID)].push_back(Def);
3561 }
Richard Smith6561f922016-09-12 21:06:40 +00003562 }
3563}
3564
Douglas Gregore060e572013-01-25 01:03:03 +00003565bool ASTReader::loadGlobalIndex() {
3566 if (GlobalIndex)
3567 return false;
3568
3569 if (TriedLoadingGlobalIndex || !UseGlobalIndex ||
3570 !Context.getLangOpts().Modules)
3571 return true;
David L. Jonesc4808b9e2016-12-15 20:53:26 +00003572
Douglas Gregore060e572013-01-25 01:03:03 +00003573 // Try to load the global index.
3574 TriedLoadingGlobalIndex = true;
3575 StringRef ModuleCachePath
3576 = getPreprocessor().getHeaderSearchInfo().getModuleCachePath();
3577 std::pair<GlobalModuleIndex *, GlobalModuleIndex::ErrorCode> Result
Douglas Gregor7029ce12013-03-19 00:28:20 +00003578 = GlobalModuleIndex::readIndex(ModuleCachePath);
Douglas Gregore060e572013-01-25 01:03:03 +00003579 if (!Result.first)
3580 return true;
3581
3582 GlobalIndex.reset(Result.first);
Douglas Gregor7211ac12013-01-25 23:32:03 +00003583 ModuleMgr.setGlobalIndex(GlobalIndex.get());
Douglas Gregore060e572013-01-25 01:03:03 +00003584 return false;
3585}
3586
3587bool ASTReader::isGlobalIndexUnavailable() const {
3588 return Context.getLangOpts().Modules && UseGlobalIndex &&
3589 !hasGlobalIndex() && TriedLoadingGlobalIndex;
3590}
3591
Dmitri Gribenkof430da42014-02-12 10:33:14 +00003592static void updateModuleTimestamp(ModuleFile &MF) {
3593 // Overwrite the timestamp file contents so that file's mtime changes.
3594 std::string TimestampFilename = MF.getTimestampFilename();
Rafael Espindoladae941a2014-08-25 18:17:04 +00003595 std::error_code EC;
3596 llvm::raw_fd_ostream OS(TimestampFilename, EC, llvm::sys::fs::F_Text);
3597 if (EC)
Dmitri Gribenkof430da42014-02-12 10:33:14 +00003598 return;
3599 OS << "Timestamp file\n";
3600}
3601
Douglas Gregor6623e1f2015-11-03 18:33:07 +00003602/// \brief Given a cursor at the start of an AST file, scan ahead and drop the
3603/// cursor into the start of the given block ID, returning false on success and
3604/// true on failure.
3605static bool SkipCursorToBlock(BitstreamCursor &Cursor, unsigned BlockID) {
Eugene Zelenkoe95e7d52016-09-07 21:53:17 +00003606 while (true) {
Douglas Gregor6623e1f2015-11-03 18:33:07 +00003607 llvm::BitstreamEntry Entry = Cursor.advance();
3608 switch (Entry.Kind) {
3609 case llvm::BitstreamEntry::Error:
3610 case llvm::BitstreamEntry::EndBlock:
3611 return true;
3612
3613 case llvm::BitstreamEntry::Record:
3614 // Ignore top-level records.
3615 Cursor.skipRecord(Entry.ID);
3616 break;
3617
3618 case llvm::BitstreamEntry::SubBlock:
3619 if (Entry.ID == BlockID) {
3620 if (Cursor.EnterSubBlock(BlockID))
3621 return true;
3622 // Found it!
3623 return false;
3624 }
3625
3626 if (Cursor.SkipBlock())
3627 return true;
3628 }
3629 }
3630}
3631
Benjamin Kramer0772c422016-02-13 13:42:54 +00003632ASTReader::ASTReadResult ASTReader::ReadAST(StringRef FileName,
Guy Benyei11169dd2012-12-18 14:30:41 +00003633 ModuleKind Type,
3634 SourceLocation ImportLoc,
Graydon Hoaree7196af2016-12-09 21:45:49 +00003635 unsigned ClientLoadCapabilities,
3636 SmallVectorImpl<ImportedSubmodule> *Imported) {
Argyrios Kyrtzidisdc9fdaf2013-05-24 05:44:08 +00003637 llvm::SaveAndRestore<SourceLocation>
3638 SetCurImportLocRAII(CurrentImportLoc, ImportLoc);
3639
Richard Smithd1c46742014-04-30 02:24:17 +00003640 // Defer any pending actions until we get to the end of reading the AST file.
3641 Deserializing AnASTFile(this);
3642
Guy Benyei11169dd2012-12-18 14:30:41 +00003643 // Bump the generation number.
Richard Smith053f6c62014-05-16 23:01:30 +00003644 unsigned PreviousGeneration = incrementGeneration(Context);
Guy Benyei11169dd2012-12-18 14:30:41 +00003645
3646 unsigned NumModules = ModuleMgr.size();
Dmitri Gribenkof8579502013-01-12 19:30:44 +00003647 SmallVector<ImportedModule, 4> Loaded;
Guy Benyei11169dd2012-12-18 14:30:41 +00003648 switch(ASTReadResult ReadResult = ReadASTCore(FileName, Type, ImportLoc,
Craig Toppera13603a2014-05-22 05:54:18 +00003649 /*ImportedBy=*/nullptr, Loaded,
Ben Langmuir487ea142014-10-23 18:05:36 +00003650 0, 0, 0,
Guy Benyei11169dd2012-12-18 14:30:41 +00003651 ClientLoadCapabilities)) {
3652 case Failure:
Douglas Gregor7029ce12013-03-19 00:28:20 +00003653 case Missing:
Guy Benyei11169dd2012-12-18 14:30:41 +00003654 case OutOfDate:
3655 case VersionMismatch:
3656 case ConfigurationMismatch:
Ben Langmuir9801b252014-06-20 00:24:56 +00003657 case HadErrors: {
3658 llvm::SmallPtrSet<ModuleFile *, 4> LoadedSet;
3659 for (const ImportedModule &IM : Loaded)
3660 LoadedSet.insert(IM.Mod);
3661
Duncan P. N. Exon Smith8e6bc1972017-01-28 23:02:12 +00003662 ModuleMgr.removeModules(ModuleMgr.begin() + NumModules, LoadedSet,
Douglas Gregor7029ce12013-03-19 00:28:20 +00003663 Context.getLangOpts().Modules
Duncan P. N. Exon Smith8e6bc1972017-01-28 23:02:12 +00003664 ? &PP.getHeaderSearchInfo().getModuleMap()
3665 : nullptr);
Douglas Gregore060e572013-01-25 01:03:03 +00003666
3667 // If we find that any modules are unusable, the global index is going
3668 // to be out-of-date. Just remove it.
3669 GlobalIndex.reset();
Craig Toppera13603a2014-05-22 05:54:18 +00003670 ModuleMgr.setGlobalIndex(nullptr);
Guy Benyei11169dd2012-12-18 14:30:41 +00003671 return ReadResult;
Ben Langmuir9801b252014-06-20 00:24:56 +00003672 }
Guy Benyei11169dd2012-12-18 14:30:41 +00003673 case Success:
3674 break;
3675 }
3676
3677 // Here comes stuff that we only do once the entire chain is loaded.
3678
3679 // Load the AST blocks of all of the modules that we loaded.
Dmitri Gribenkof8579502013-01-12 19:30:44 +00003680 for (SmallVectorImpl<ImportedModule>::iterator M = Loaded.begin(),
3681 MEnd = Loaded.end();
Guy Benyei11169dd2012-12-18 14:30:41 +00003682 M != MEnd; ++M) {
3683 ModuleFile &F = *M->Mod;
3684
3685 // Read the AST block.
Ben Langmuir2c9af442014-04-10 17:57:43 +00003686 if (ASTReadResult Result = ReadASTBlock(F, ClientLoadCapabilities))
3687 return Result;
Guy Benyei11169dd2012-12-18 14:30:41 +00003688
Douglas Gregor6623e1f2015-11-03 18:33:07 +00003689 // Read the extension blocks.
3690 while (!SkipCursorToBlock(F.Stream, EXTENSION_BLOCK_ID)) {
3691 if (ASTReadResult Result = ReadExtensionBlock(F))
3692 return Result;
3693 }
3694
David L. Jonesc4808b9e2016-12-15 20:53:26 +00003695 // Once read, set the ModuleFile bit base offset and update the size in
Guy Benyei11169dd2012-12-18 14:30:41 +00003696 // bits of all files we've seen.
3697 F.GlobalBitOffset = TotalModulesSizeInBits;
3698 TotalModulesSizeInBits += F.SizeInBits;
3699 GlobalBitOffsetsMap.insert(std::make_pair(F.GlobalBitOffset, &F));
David L. Jonesc4808b9e2016-12-15 20:53:26 +00003700
Guy Benyei11169dd2012-12-18 14:30:41 +00003701 // Preload SLocEntries.
3702 for (unsigned I = 0, N = F.PreloadSLocEntries.size(); I != N; ++I) {
3703 int Index = int(F.PreloadSLocEntries[I] - 1) + F.SLocEntryBaseID;
3704 // Load it through the SourceManager and don't call ReadSLocEntry()
3705 // directly because the entry may have already been loaded in which case
3706 // calling ReadSLocEntry() directly would trigger an assertion in
3707 // SourceManager.
3708 SourceMgr.getLoadedSLocEntryByID(Index);
3709 }
Richard Smith33e0f7e2015-07-22 02:08:40 +00003710
3711 // Preload all the pending interesting identifiers by marking them out of
3712 // date.
3713 for (auto Offset : F.PreloadIdentifierOffsets) {
3714 const unsigned char *Data = reinterpret_cast<const unsigned char *>(
3715 F.IdentifierTableData + Offset);
3716
3717 ASTIdentifierLookupTrait Trait(*this, F);
3718 auto KeyDataLen = Trait.ReadKeyDataLength(Data);
3719 auto Key = Trait.ReadKey(Data, KeyDataLen.first);
Richard Smith79bf9202015-08-24 03:33:22 +00003720 auto &II = PP.getIdentifierTable().getOwn(Key);
3721 II.setOutOfDate(true);
3722
3723 // Mark this identifier as being from an AST file so that we can track
3724 // whether we need to serialize it.
Richard Smitheb4b58f62016-02-05 01:40:54 +00003725 markIdentifierFromAST(*this, II);
Richard Smith79bf9202015-08-24 03:33:22 +00003726
3727 // Associate the ID with the identifier so that the writer can reuse it.
3728 auto ID = Trait.ReadIdentifierID(Data + KeyDataLen.first);
3729 SetIdentifierInfo(ID, &II);
Richard Smith33e0f7e2015-07-22 02:08:40 +00003730 }
Guy Benyei11169dd2012-12-18 14:30:41 +00003731 }
3732
Douglas Gregor603cd862013-03-22 18:50:14 +00003733 // Setup the import locations and notify the module manager that we've
3734 // committed to these module files.
Dmitri Gribenkof8579502013-01-12 19:30:44 +00003735 for (SmallVectorImpl<ImportedModule>::iterator M = Loaded.begin(),
3736 MEnd = Loaded.end();
Guy Benyei11169dd2012-12-18 14:30:41 +00003737 M != MEnd; ++M) {
3738 ModuleFile &F = *M->Mod;
Douglas Gregor603cd862013-03-22 18:50:14 +00003739
3740 ModuleMgr.moduleFileAccepted(&F);
3741
3742 // Set the import location.
Argyrios Kyrtzidis71c1af82013-02-01 16:36:14 +00003743 F.DirectImportLoc = ImportLoc;
Richard Smithb22a1d12016-03-27 20:13:24 +00003744 // FIXME: We assume that locations from PCH / preamble do not need
3745 // any translation.
Guy Benyei11169dd2012-12-18 14:30:41 +00003746 if (!M->ImportedBy)
3747 F.ImportLoc = M->ImportLoc;
3748 else
Richard Smithb22a1d12016-03-27 20:13:24 +00003749 F.ImportLoc = TranslateSourceLocation(*M->ImportedBy, M->ImportLoc);
Guy Benyei11169dd2012-12-18 14:30:41 +00003750 }
3751
Richard Smith33e0f7e2015-07-22 02:08:40 +00003752 if (!Context.getLangOpts().CPlusPlus ||
Manman Ren11f2a472016-08-18 17:42:15 +00003753 (Type != MK_ImplicitModule && Type != MK_ExplicitModule &&
3754 Type != MK_PrebuiltModule)) {
Richard Smith33e0f7e2015-07-22 02:08:40 +00003755 // Mark all of the identifiers in the identifier table as being out of date,
3756 // so that various accessors know to check the loaded modules when the
3757 // identifier is used.
3758 //
3759 // For C++ modules, we don't need information on many identifiers (just
3760 // those that provide macros or are poisoned), so we mark all of
3761 // the interesting ones via PreloadIdentifierOffsets.
3762 for (IdentifierTable::iterator Id = PP.getIdentifierTable().begin(),
3763 IdEnd = PP.getIdentifierTable().end();
3764 Id != IdEnd; ++Id)
3765 Id->second->setOutOfDate(true);
3766 }
Manman Rena0f31a02016-04-29 19:04:05 +00003767 // Mark selectors as out of date.
3768 for (auto Sel : SelectorGeneration)
3769 SelectorOutOfDate[Sel.first] = true;
David L. Jonesc4808b9e2016-12-15 20:53:26 +00003770
Guy Benyei11169dd2012-12-18 14:30:41 +00003771 // Resolve any unresolved module exports.
Douglas Gregorfb912652013-03-20 21:10:35 +00003772 for (unsigned I = 0, N = UnresolvedModuleRefs.size(); I != N; ++I) {
3773 UnresolvedModuleRef &Unresolved = UnresolvedModuleRefs[I];
Guy Benyei11169dd2012-12-18 14:30:41 +00003774 SubmoduleID GlobalID = getGlobalSubmoduleID(*Unresolved.File,Unresolved.ID);
3775 Module *ResolvedMod = getSubmodule(GlobalID);
Douglas Gregorfb912652013-03-20 21:10:35 +00003776
3777 switch (Unresolved.Kind) {
3778 case UnresolvedModuleRef::Conflict:
3779 if (ResolvedMod) {
3780 Module::Conflict Conflict;
3781 Conflict.Other = ResolvedMod;
3782 Conflict.Message = Unresolved.String.str();
3783 Unresolved.Mod->Conflicts.push_back(Conflict);
3784 }
3785 continue;
3786
3787 case UnresolvedModuleRef::Import:
Guy Benyei11169dd2012-12-18 14:30:41 +00003788 if (ResolvedMod)
Richard Smith38477db2015-05-02 00:45:56 +00003789 Unresolved.Mod->Imports.insert(ResolvedMod);
Guy Benyei11169dd2012-12-18 14:30:41 +00003790 continue;
Guy Benyei11169dd2012-12-18 14:30:41 +00003791
Douglas Gregorfb912652013-03-20 21:10:35 +00003792 case UnresolvedModuleRef::Export:
3793 if (ResolvedMod || Unresolved.IsWildcard)
3794 Unresolved.Mod->Exports.push_back(
3795 Module::ExportDecl(ResolvedMod, Unresolved.IsWildcard));
3796 continue;
3797 }
Guy Benyei11169dd2012-12-18 14:30:41 +00003798 }
Douglas Gregorfb912652013-03-20 21:10:35 +00003799 UnresolvedModuleRefs.clear();
Daniel Jasperba7f2f72013-09-24 09:14:14 +00003800
Graydon Hoaree7196af2016-12-09 21:45:49 +00003801 if (Imported)
3802 Imported->append(ImportedModules.begin(),
3803 ImportedModules.end());
3804
Daniel Jasperba7f2f72013-09-24 09:14:14 +00003805 // FIXME: How do we load the 'use'd modules? They may not be submodules.
3806 // Might be unnecessary as use declarations are only used to build the
3807 // module itself.
David L. Jonesc4808b9e2016-12-15 20:53:26 +00003808
Guy Benyei11169dd2012-12-18 14:30:41 +00003809 InitializeContext();
3810
Richard Smith3d8e97e2013-10-18 06:54:39 +00003811 if (SemaObj)
3812 UpdateSema();
3813
Guy Benyei11169dd2012-12-18 14:30:41 +00003814 if (DeserializationListener)
3815 DeserializationListener->ReaderInitialized(this);
3816
3817 ModuleFile &PrimaryModule = ModuleMgr.getPrimaryModule();
Yaron Keren8b563662015-10-03 10:46:20 +00003818 if (PrimaryModule.OriginalSourceFileID.isValid()) {
David L. Jonesc4808b9e2016-12-15 20:53:26 +00003819 PrimaryModule.OriginalSourceFileID
Guy Benyei11169dd2012-12-18 14:30:41 +00003820 = FileID::get(PrimaryModule.SLocEntryBaseID
3821 + PrimaryModule.OriginalSourceFileID.getOpaqueValue() - 1);
3822
3823 // If this AST file is a precompiled preamble, then set the
3824 // preamble file ID of the source manager to the file source file
3825 // from which the preamble was built.
3826 if (Type == MK_Preamble) {
3827 SourceMgr.setPreambleFileID(PrimaryModule.OriginalSourceFileID);
3828 } else if (Type == MK_MainFile) {
3829 SourceMgr.setMainFileID(PrimaryModule.OriginalSourceFileID);
3830 }
3831 }
David L. Jonesc4808b9e2016-12-15 20:53:26 +00003832
Guy Benyei11169dd2012-12-18 14:30:41 +00003833 // For any Objective-C class definitions we have already loaded, make sure
3834 // that we load any additional categories.
3835 for (unsigned I = 0, N = ObjCClassesLoaded.size(); I != N; ++I) {
David L. Jonesc4808b9e2016-12-15 20:53:26 +00003836 loadObjCCategories(ObjCClassesLoaded[I]->getGlobalID(),
Guy Benyei11169dd2012-12-18 14:30:41 +00003837 ObjCClassesLoaded[I],
3838 PreviousGeneration);
3839 }
Douglas Gregore060e572013-01-25 01:03:03 +00003840
Dmitri Gribenkof430da42014-02-12 10:33:14 +00003841 if (PP.getHeaderSearchInfo()
3842 .getHeaderSearchOpts()
3843 .ModulesValidateOncePerBuildSession) {
3844 // Now we are certain that the module and all modules it depends on are
3845 // up to date. Create or update timestamp files for modules that are
3846 // located in the module cache (not for PCH files that could be anywhere
3847 // in the filesystem).
3848 for (unsigned I = 0, N = Loaded.size(); I != N; ++I) {
3849 ImportedModule &M = Loaded[I];
Richard Smithe842a472014-10-22 02:05:46 +00003850 if (M.Mod->Kind == MK_ImplicitModule) {
Dmitri Gribenkof430da42014-02-12 10:33:14 +00003851 updateModuleTimestamp(*M.Mod);
3852 }
3853 }
3854 }
3855
Guy Benyei11169dd2012-12-18 14:30:41 +00003856 return Success;
3857}
3858
Peter Collingbourne77c89b62016-11-08 04:17:11 +00003859static ASTFileSignature readASTFileSignature(StringRef PCH);
Ben Langmuir487ea142014-10-23 18:05:36 +00003860
Ben Langmuir70a1b812015-03-24 04:43:52 +00003861/// \brief Whether \p Stream starts with the AST/PCH file magic number 'CPCH'.
3862static bool startsWithASTFileMagic(BitstreamCursor &Stream) {
Peter Collingbourne028eb5a2016-11-02 00:08:19 +00003863 return Stream.canSkipToPos(4) &&
3864 Stream.Read(8) == 'C' &&
Ben Langmuir70a1b812015-03-24 04:43:52 +00003865 Stream.Read(8) == 'P' &&
3866 Stream.Read(8) == 'C' &&
3867 Stream.Read(8) == 'H';
3868}
3869
Richard Smith0f99d6a2015-08-09 08:48:41 +00003870static unsigned moduleKindForDiagnostic(ModuleKind Kind) {
3871 switch (Kind) {
3872 case MK_PCH:
3873 return 0; // PCH
3874 case MK_ImplicitModule:
3875 case MK_ExplicitModule:
Manman Ren11f2a472016-08-18 17:42:15 +00003876 case MK_PrebuiltModule:
Richard Smith0f99d6a2015-08-09 08:48:41 +00003877 return 1; // module
3878 case MK_MainFile:
3879 case MK_Preamble:
3880 return 2; // main source file
3881 }
3882 llvm_unreachable("unknown module kind");
3883}
3884
Guy Benyei11169dd2012-12-18 14:30:41 +00003885ASTReader::ASTReadResult
3886ASTReader::ReadASTCore(StringRef FileName,
3887 ModuleKind Type,
3888 SourceLocation ImportLoc,
3889 ModuleFile *ImportedBy,
Dmitri Gribenkof8579502013-01-12 19:30:44 +00003890 SmallVectorImpl<ImportedModule> &Loaded,
Douglas Gregor7029ce12013-03-19 00:28:20 +00003891 off_t ExpectedSize, time_t ExpectedModTime,
Ben Langmuir487ea142014-10-23 18:05:36 +00003892 ASTFileSignature ExpectedSignature,
Guy Benyei11169dd2012-12-18 14:30:41 +00003893 unsigned ClientLoadCapabilities) {
3894 ModuleFile *M;
Guy Benyei11169dd2012-12-18 14:30:41 +00003895 std::string ErrorStr;
Douglas Gregor7029ce12013-03-19 00:28:20 +00003896 ModuleManager::AddModuleResult AddResult
3897 = ModuleMgr.addModule(FileName, Type, ImportLoc, ImportedBy,
Richard Smith053f6c62014-05-16 23:01:30 +00003898 getGeneration(), ExpectedSize, ExpectedModTime,
Ben Langmuir487ea142014-10-23 18:05:36 +00003899 ExpectedSignature, readASTFileSignature,
Douglas Gregor7029ce12013-03-19 00:28:20 +00003900 M, ErrorStr);
Guy Benyei11169dd2012-12-18 14:30:41 +00003901
Douglas Gregor7029ce12013-03-19 00:28:20 +00003902 switch (AddResult) {
3903 case ModuleManager::AlreadyLoaded:
3904 return Success;
3905
3906 case ModuleManager::NewlyLoaded:
3907 // Load module file below.
3908 break;
3909
3910 case ModuleManager::Missing:
Richard Smithe842a472014-10-22 02:05:46 +00003911 // The module file was missing; if the client can handle that, return
Douglas Gregor7029ce12013-03-19 00:28:20 +00003912 // it.
3913 if (ClientLoadCapabilities & ARR_Missing)
3914 return Missing;
3915
3916 // Otherwise, return an error.
Richard Smith0f99d6a2015-08-09 08:48:41 +00003917 Diag(diag::err_module_file_not_found) << moduleKindForDiagnostic(Type)
Adrian Prantlb3b5a732016-08-29 20:46:59 +00003918 << FileName << !ErrorStr.empty()
Richard Smith0f99d6a2015-08-09 08:48:41 +00003919 << ErrorStr;
Douglas Gregor7029ce12013-03-19 00:28:20 +00003920 return Failure;
3921
3922 case ModuleManager::OutOfDate:
3923 // We couldn't load the module file because it is out-of-date. If the
3924 // client can handle out-of-date, return it.
3925 if (ClientLoadCapabilities & ARR_OutOfDate)
3926 return OutOfDate;
3927
3928 // Otherwise, return an error.
Richard Smith0f99d6a2015-08-09 08:48:41 +00003929 Diag(diag::err_module_file_out_of_date) << moduleKindForDiagnostic(Type)
Adrian Prantl9a06a882016-08-29 20:46:56 +00003930 << FileName << !ErrorStr.empty()
Richard Smith0f99d6a2015-08-09 08:48:41 +00003931 << ErrorStr;
Guy Benyei11169dd2012-12-18 14:30:41 +00003932 return Failure;
3933 }
3934
Douglas Gregor7029ce12013-03-19 00:28:20 +00003935 assert(M && "Missing module file");
Guy Benyei11169dd2012-12-18 14:30:41 +00003936
3937 // FIXME: This seems rather a hack. Should CurrentDir be part of the
3938 // module?
3939 if (FileName != "-") {
3940 CurrentDir = llvm::sys::path::parent_path(FileName);
3941 if (CurrentDir.empty()) CurrentDir = ".";
3942 }
3943
3944 ModuleFile &F = *M;
Chris Lattner7fb3bef2013-01-20 00:56:42 +00003945 BitstreamCursor &Stream = F.Stream;
Peter Collingbourne77c89b62016-11-08 04:17:11 +00003946 Stream = BitstreamCursor(PCHContainerRdr.ExtractPCH(*F.Buffer));
Adrian Prantlcbc368c2015-02-25 02:44:04 +00003947 F.SizeInBits = F.Buffer->getBufferSize() * 8;
David L. Jonesc4808b9e2016-12-15 20:53:26 +00003948
Guy Benyei11169dd2012-12-18 14:30:41 +00003949 // Sniff for the signature.
Ben Langmuir70a1b812015-03-24 04:43:52 +00003950 if (!startsWithASTFileMagic(Stream)) {
Richard Smith0f99d6a2015-08-09 08:48:41 +00003951 Diag(diag::err_module_file_invalid) << moduleKindForDiagnostic(Type)
3952 << FileName;
Guy Benyei11169dd2012-12-18 14:30:41 +00003953 return Failure;
3954 }
3955
3956 // This is used for compatibility with older PCH formats.
3957 bool HaveReadControlBlock = false;
Eugene Zelenkoe95e7d52016-09-07 21:53:17 +00003958 while (true) {
Chris Lattnerefa77172013-01-20 00:00:22 +00003959 llvm::BitstreamEntry Entry = Stream.advance();
David L. Jonesc4808b9e2016-12-15 20:53:26 +00003960
Chris Lattnerefa77172013-01-20 00:00:22 +00003961 switch (Entry.Kind) {
3962 case llvm::BitstreamEntry::Error:
Chris Lattnerefa77172013-01-20 00:00:22 +00003963 case llvm::BitstreamEntry::Record:
Douglas Gregor6623e1f2015-11-03 18:33:07 +00003964 case llvm::BitstreamEntry::EndBlock:
Guy Benyei11169dd2012-12-18 14:30:41 +00003965 Error("invalid record at top-level of AST file");
3966 return Failure;
David L. Jonesc4808b9e2016-12-15 20:53:26 +00003967
Chris Lattnerefa77172013-01-20 00:00:22 +00003968 case llvm::BitstreamEntry::SubBlock:
3969 break;
Guy Benyei11169dd2012-12-18 14:30:41 +00003970 }
3971
Chris Lattnerefa77172013-01-20 00:00:22 +00003972 switch (Entry.ID) {
Guy Benyei11169dd2012-12-18 14:30:41 +00003973 case CONTROL_BLOCK_ID:
3974 HaveReadControlBlock = true;
Ben Langmuirbeee15e2014-04-14 18:00:01 +00003975 switch (ReadControlBlock(F, Loaded, ImportedBy, ClientLoadCapabilities)) {
Guy Benyei11169dd2012-12-18 14:30:41 +00003976 case Success:
Richard Smith0f99d6a2015-08-09 08:48:41 +00003977 // Check that we didn't try to load a non-module AST file as a module.
3978 //
3979 // FIXME: Should we also perform the converse check? Loading a module as
3980 // a PCH file sort of works, but it's a bit wonky.
Manman Ren11f2a472016-08-18 17:42:15 +00003981 if ((Type == MK_ImplicitModule || Type == MK_ExplicitModule ||
3982 Type == MK_PrebuiltModule) &&
Richard Smith0f99d6a2015-08-09 08:48:41 +00003983 F.ModuleName.empty()) {
3984 auto Result = (Type == MK_ImplicitModule) ? OutOfDate : Failure;
3985 if (Result != OutOfDate ||
3986 (ClientLoadCapabilities & ARR_OutOfDate) == 0)
3987 Diag(diag::err_module_file_not_module) << FileName;
3988 return Result;
3989 }
Guy Benyei11169dd2012-12-18 14:30:41 +00003990 break;
3991
3992 case Failure: return Failure;
Douglas Gregor7029ce12013-03-19 00:28:20 +00003993 case Missing: return Missing;
Guy Benyei11169dd2012-12-18 14:30:41 +00003994 case OutOfDate: return OutOfDate;
3995 case VersionMismatch: return VersionMismatch;
3996 case ConfigurationMismatch: return ConfigurationMismatch;
3997 case HadErrors: return HadErrors;
3998 }
3999 break;
Richard Smithf8c32552015-09-02 17:45:54 +00004000
Guy Benyei11169dd2012-12-18 14:30:41 +00004001 case AST_BLOCK_ID:
4002 if (!HaveReadControlBlock) {
4003 if ((ClientLoadCapabilities & ARR_VersionMismatch) == 0)
Dmitri Gribenko2228cd32014-02-11 15:40:09 +00004004 Diag(diag::err_pch_version_too_old);
Guy Benyei11169dd2012-12-18 14:30:41 +00004005 return VersionMismatch;
4006 }
4007
4008 // Record that we've loaded this module.
4009 Loaded.push_back(ImportedModule(M, ImportedBy, ImportLoc));
4010 return Success;
4011
4012 default:
4013 if (Stream.SkipBlock()) {
4014 Error("malformed block record in AST file");
4015 return Failure;
4016 }
4017 break;
4018 }
4019 }
Douglas Gregor6623e1f2015-11-03 18:33:07 +00004020
4021 return Success;
4022}
4023
4024/// Parse a record and blob containing module file extension metadata.
4025static bool parseModuleFileExtensionMetadata(
4026 const SmallVectorImpl<uint64_t> &Record,
4027 StringRef Blob,
4028 ModuleFileExtensionMetadata &Metadata) {
4029 if (Record.size() < 4) return true;
4030
4031 Metadata.MajorVersion = Record[0];
4032 Metadata.MinorVersion = Record[1];
4033
4034 unsigned BlockNameLen = Record[2];
4035 unsigned UserInfoLen = Record[3];
4036
4037 if (BlockNameLen + UserInfoLen > Blob.size()) return true;
4038
4039 Metadata.BlockName = std::string(Blob.data(), Blob.data() + BlockNameLen);
4040 Metadata.UserInfo = std::string(Blob.data() + BlockNameLen,
4041 Blob.data() + BlockNameLen + UserInfoLen);
4042 return false;
4043}
4044
4045ASTReader::ASTReadResult ASTReader::ReadExtensionBlock(ModuleFile &F) {
4046 BitstreamCursor &Stream = F.Stream;
4047
4048 RecordData Record;
4049 while (true) {
4050 llvm::BitstreamEntry Entry = Stream.advance();
4051 switch (Entry.Kind) {
4052 case llvm::BitstreamEntry::SubBlock:
4053 if (Stream.SkipBlock())
4054 return Failure;
4055
4056 continue;
4057
4058 case llvm::BitstreamEntry::EndBlock:
4059 return Success;
4060
4061 case llvm::BitstreamEntry::Error:
4062 return HadErrors;
4063
4064 case llvm::BitstreamEntry::Record:
4065 break;
4066 }
4067
4068 Record.clear();
4069 StringRef Blob;
4070 unsigned RecCode = Stream.readRecord(Entry.ID, Record, &Blob);
4071 switch (RecCode) {
4072 case EXTENSION_METADATA: {
4073 ModuleFileExtensionMetadata Metadata;
4074 if (parseModuleFileExtensionMetadata(Record, Blob, Metadata))
4075 return Failure;
4076
4077 // Find a module file extension with this block name.
4078 auto Known = ModuleFileExtensions.find(Metadata.BlockName);
4079 if (Known == ModuleFileExtensions.end()) break;
4080
4081 // Form a reader.
4082 if (auto Reader = Known->second->createExtensionReader(Metadata, *this,
4083 F, Stream)) {
4084 F.ExtensionReaders.push_back(std::move(Reader));
4085 }
4086
4087 break;
4088 }
4089 }
4090 }
4091
4092 return Success;
Guy Benyei11169dd2012-12-18 14:30:41 +00004093}
4094
Richard Smitha7e2cc62015-05-01 01:53:09 +00004095void ASTReader::InitializeContext() {
Guy Benyei11169dd2012-12-18 14:30:41 +00004096 // If there's a listener, notify them that we "read" the translation unit.
4097 if (DeserializationListener)
David L. Jonesc4808b9e2016-12-15 20:53:26 +00004098 DeserializationListener->DeclRead(PREDEF_DECL_TRANSLATION_UNIT_ID,
Guy Benyei11169dd2012-12-18 14:30:41 +00004099 Context.getTranslationUnitDecl());
4100
Guy Benyei11169dd2012-12-18 14:30:41 +00004101 // FIXME: Find a better way to deal with collisions between these
4102 // built-in types. Right now, we just ignore the problem.
David L. Jonesc4808b9e2016-12-15 20:53:26 +00004103
Guy Benyei11169dd2012-12-18 14:30:41 +00004104 // Load the special types.
4105 if (SpecialTypes.size() >= NumSpecialTypeIDs) {
4106 if (unsigned String = SpecialTypes[SPECIAL_TYPE_CF_CONSTANT_STRING]) {
4107 if (!Context.CFConstantStringTypeDecl)
4108 Context.setCFConstantStringType(GetType(String));
4109 }
David L. Jonesc4808b9e2016-12-15 20:53:26 +00004110
Guy Benyei11169dd2012-12-18 14:30:41 +00004111 if (unsigned File = SpecialTypes[SPECIAL_TYPE_FILE]) {
4112 QualType FileType = GetType(File);
4113 if (FileType.isNull()) {
4114 Error("FILE type is NULL");
4115 return;
4116 }
David L. Jonesc4808b9e2016-12-15 20:53:26 +00004117
Guy Benyei11169dd2012-12-18 14:30:41 +00004118 if (!Context.FILEDecl) {
4119 if (const TypedefType *Typedef = FileType->getAs<TypedefType>())
4120 Context.setFILEDecl(Typedef->getDecl());
4121 else {
4122 const TagType *Tag = FileType->getAs<TagType>();
4123 if (!Tag) {
4124 Error("Invalid FILE type in AST file");
4125 return;
4126 }
4127 Context.setFILEDecl(Tag->getDecl());
4128 }
4129 }
4130 }
David L. Jonesc4808b9e2016-12-15 20:53:26 +00004131
Guy Benyei11169dd2012-12-18 14:30:41 +00004132 if (unsigned Jmp_buf = SpecialTypes[SPECIAL_TYPE_JMP_BUF]) {
4133 QualType Jmp_bufType = GetType(Jmp_buf);
4134 if (Jmp_bufType.isNull()) {
4135 Error("jmp_buf type is NULL");
4136 return;
4137 }
David L. Jonesc4808b9e2016-12-15 20:53:26 +00004138
Guy Benyei11169dd2012-12-18 14:30:41 +00004139 if (!Context.jmp_bufDecl) {
4140 if (const TypedefType *Typedef = Jmp_bufType->getAs<TypedefType>())
4141 Context.setjmp_bufDecl(Typedef->getDecl());
4142 else {
4143 const TagType *Tag = Jmp_bufType->getAs<TagType>();
4144 if (!Tag) {
4145 Error("Invalid jmp_buf type in AST file");
4146 return;
4147 }
4148 Context.setjmp_bufDecl(Tag->getDecl());
4149 }
4150 }
4151 }
David L. Jonesc4808b9e2016-12-15 20:53:26 +00004152
Guy Benyei11169dd2012-12-18 14:30:41 +00004153 if (unsigned Sigjmp_buf = SpecialTypes[SPECIAL_TYPE_SIGJMP_BUF]) {
4154 QualType Sigjmp_bufType = GetType(Sigjmp_buf);
4155 if (Sigjmp_bufType.isNull()) {
4156 Error("sigjmp_buf type is NULL");
4157 return;
4158 }
David L. Jonesc4808b9e2016-12-15 20:53:26 +00004159
Guy Benyei11169dd2012-12-18 14:30:41 +00004160 if (!Context.sigjmp_bufDecl) {
4161 if (const TypedefType *Typedef = Sigjmp_bufType->getAs<TypedefType>())
4162 Context.setsigjmp_bufDecl(Typedef->getDecl());
4163 else {
4164 const TagType *Tag = Sigjmp_bufType->getAs<TagType>();
4165 assert(Tag && "Invalid sigjmp_buf type in AST file");
4166 Context.setsigjmp_bufDecl(Tag->getDecl());
4167 }
4168 }
4169 }
4170
4171 if (unsigned ObjCIdRedef
4172 = SpecialTypes[SPECIAL_TYPE_OBJC_ID_REDEFINITION]) {
4173 if (Context.ObjCIdRedefinitionType.isNull())
4174 Context.ObjCIdRedefinitionType = GetType(ObjCIdRedef);
4175 }
4176
4177 if (unsigned ObjCClassRedef
4178 = SpecialTypes[SPECIAL_TYPE_OBJC_CLASS_REDEFINITION]) {
4179 if (Context.ObjCClassRedefinitionType.isNull())
4180 Context.ObjCClassRedefinitionType = GetType(ObjCClassRedef);
4181 }
4182
4183 if (unsigned ObjCSelRedef
4184 = SpecialTypes[SPECIAL_TYPE_OBJC_SEL_REDEFINITION]) {
4185 if (Context.ObjCSelRedefinitionType.isNull())
4186 Context.ObjCSelRedefinitionType = GetType(ObjCSelRedef);
4187 }
4188
4189 if (unsigned Ucontext_t = SpecialTypes[SPECIAL_TYPE_UCONTEXT_T]) {
4190 QualType Ucontext_tType = GetType(Ucontext_t);
4191 if (Ucontext_tType.isNull()) {
4192 Error("ucontext_t type is NULL");
4193 return;
4194 }
4195
4196 if (!Context.ucontext_tDecl) {
4197 if (const TypedefType *Typedef = Ucontext_tType->getAs<TypedefType>())
4198 Context.setucontext_tDecl(Typedef->getDecl());
4199 else {
4200 const TagType *Tag = Ucontext_tType->getAs<TagType>();
4201 assert(Tag && "Invalid ucontext_t type in AST file");
4202 Context.setucontext_tDecl(Tag->getDecl());
4203 }
4204 }
4205 }
4206 }
David L. Jonesc4808b9e2016-12-15 20:53:26 +00004207
Guy Benyei11169dd2012-12-18 14:30:41 +00004208 ReadPragmaDiagnosticMappings(Context.getDiagnostics());
4209
4210 // If there were any CUDA special declarations, deserialize them.
4211 if (!CUDASpecialDeclRefs.empty()) {
4212 assert(CUDASpecialDeclRefs.size() == 1 && "More decl refs than expected!");
4213 Context.setcudaConfigureCallDecl(
4214 cast<FunctionDecl>(GetDecl(CUDASpecialDeclRefs[0])));
4215 }
Richard Smith56be7542014-03-21 00:33:59 +00004216
Guy Benyei11169dd2012-12-18 14:30:41 +00004217 // Re-export any modules that were imported by a non-module AST file.
Richard Smitha7e2cc62015-05-01 01:53:09 +00004218 // FIXME: This does not make macro-only imports visible again.
Richard Smith56be7542014-03-21 00:33:59 +00004219 for (auto &Import : ImportedModules) {
Richard Smitha7e2cc62015-05-01 01:53:09 +00004220 if (Module *Imported = getSubmodule(Import.ID)) {
Argyrios Kyrtzidis125df052013-02-01 16:36:12 +00004221 makeModuleVisible(Imported, Module::AllVisible,
Richard Smitha7e2cc62015-05-01 01:53:09 +00004222 /*ImportLoc=*/Import.ImportLoc);
Ben Langmuir6d25fdc2016-02-11 17:04:42 +00004223 if (Import.ImportLoc.isValid())
4224 PP.makeModuleVisible(Imported, Import.ImportLoc);
4225 // FIXME: should we tell Sema to make the module visible too?
Richard Smitha7e2cc62015-05-01 01:53:09 +00004226 }
Guy Benyei11169dd2012-12-18 14:30:41 +00004227 }
4228 ImportedModules.clear();
4229}
4230
4231void ASTReader::finalizeForWriting() {
Richard Smithde711422015-04-23 21:20:19 +00004232 // Nothing to do for now.
Guy Benyei11169dd2012-12-18 14:30:41 +00004233}
4234
Peter Collingbourne77c89b62016-11-08 04:17:11 +00004235/// \brief Reads and return the signature record from \p PCH's control block, or
4236/// else returns 0.
4237static ASTFileSignature readASTFileSignature(StringRef PCH) {
4238 BitstreamCursor Stream(PCH);
Ben Langmuir70a1b812015-03-24 04:43:52 +00004239 if (!startsWithASTFileMagic(Stream))
Ben Langmuir487ea142014-10-23 18:05:36 +00004240 return 0;
Ben Langmuir487ea142014-10-23 18:05:36 +00004241
4242 // Scan for the CONTROL_BLOCK_ID block.
4243 if (SkipCursorToBlock(Stream, CONTROL_BLOCK_ID))
4244 return 0;
4245
4246 // Scan for SIGNATURE inside the control block.
4247 ASTReader::RecordData Record;
Eugene Zelenkoe95e7d52016-09-07 21:53:17 +00004248 while (true) {
Ben Langmuir487ea142014-10-23 18:05:36 +00004249 llvm::BitstreamEntry Entry = Stream.advanceSkippingSubblocks();
Simon Pilgrim0b33f112016-11-16 16:11:08 +00004250 if (Entry.Kind != llvm::BitstreamEntry::Record)
Ben Langmuir487ea142014-10-23 18:05:36 +00004251 return 0;
4252
4253 Record.clear();
4254 StringRef Blob;
4255 if (SIGNATURE == Stream.readRecord(Entry.ID, Record, &Blob))
4256 return Record[0];
4257 }
4258}
4259
Guy Benyei11169dd2012-12-18 14:30:41 +00004260/// \brief Retrieve the name of the original source file name
4261/// directly from the AST file, without actually loading the AST
4262/// file.
Adrian Prantlbb165fb2015-06-20 18:53:08 +00004263std::string ASTReader::getOriginalSourceFile(
4264 const std::string &ASTFileName, FileManager &FileMgr,
Adrian Prantlfb2398d2015-07-17 01:19:54 +00004265 const PCHContainerReader &PCHContainerRdr, DiagnosticsEngine &Diags) {
Guy Benyei11169dd2012-12-18 14:30:41 +00004266 // Open the AST file.
Benjamin Kramera8857962014-10-26 22:44:13 +00004267 auto Buffer = FileMgr.getBufferForFile(ASTFileName);
Guy Benyei11169dd2012-12-18 14:30:41 +00004268 if (!Buffer) {
Benjamin Kramera8857962014-10-26 22:44:13 +00004269 Diags.Report(diag::err_fe_unable_to_read_pch_file)
4270 << ASTFileName << Buffer.getError().message();
Guy Benyei11169dd2012-12-18 14:30:41 +00004271 return std::string();
4272 }
4273
4274 // Initialize the stream
Peter Collingbourne77c89b62016-11-08 04:17:11 +00004275 BitstreamCursor Stream(PCHContainerRdr.ExtractPCH(**Buffer));
Guy Benyei11169dd2012-12-18 14:30:41 +00004276
4277 // Sniff for the signature.
Ben Langmuir70a1b812015-03-24 04:43:52 +00004278 if (!startsWithASTFileMagic(Stream)) {
Guy Benyei11169dd2012-12-18 14:30:41 +00004279 Diags.Report(diag::err_fe_not_a_pch_file) << ASTFileName;
4280 return std::string();
4281 }
David L. Jonesc4808b9e2016-12-15 20:53:26 +00004282
Chris Lattnere7b154b2013-01-19 21:39:22 +00004283 // Scan for the CONTROL_BLOCK_ID block.
Argyrios Kyrtzidisc4cd2c42013-05-06 19:23:40 +00004284 if (SkipCursorToBlock(Stream, CONTROL_BLOCK_ID)) {
Chris Lattner7fb3bef2013-01-20 00:56:42 +00004285 Diags.Report(diag::err_fe_pch_malformed_block) << ASTFileName;
4286 return std::string();
Chris Lattnere7b154b2013-01-19 21:39:22 +00004287 }
Guy Benyei11169dd2012-12-18 14:30:41 +00004288
Chris Lattner7fb3bef2013-01-20 00:56:42 +00004289 // Scan for ORIGINAL_FILE inside the control block.
4290 RecordData Record;
Eugene Zelenkoe95e7d52016-09-07 21:53:17 +00004291 while (true) {
Chris Lattner7fb3bef2013-01-20 00:56:42 +00004292 llvm::BitstreamEntry Entry = Stream.advanceSkippingSubblocks();
Chris Lattnere7b154b2013-01-19 21:39:22 +00004293 if (Entry.Kind == llvm::BitstreamEntry::EndBlock)
4294 return std::string();
David L. Jonesc4808b9e2016-12-15 20:53:26 +00004295
Chris Lattnere7b154b2013-01-19 21:39:22 +00004296 if (Entry.Kind != llvm::BitstreamEntry::Record) {
4297 Diags.Report(diag::err_fe_pch_malformed_block) << ASTFileName;
4298 return std::string();
Guy Benyei11169dd2012-12-18 14:30:41 +00004299 }
David L. Jonesc4808b9e2016-12-15 20:53:26 +00004300
Guy Benyei11169dd2012-12-18 14:30:41 +00004301 Record.clear();
Chris Lattner0e6c9402013-01-20 02:38:54 +00004302 StringRef Blob;
4303 if (Stream.readRecord(Entry.ID, Record, &Blob) == ORIGINAL_FILE)
4304 return Blob.str();
Guy Benyei11169dd2012-12-18 14:30:41 +00004305 }
Guy Benyei11169dd2012-12-18 14:30:41 +00004306}
4307
4308namespace {
Eugene Zelenkoe95e7d52016-09-07 21:53:17 +00004309
Guy Benyei11169dd2012-12-18 14:30:41 +00004310 class SimplePCHValidator : public ASTReaderListener {
4311 const LangOptions &ExistingLangOpts;
4312 const TargetOptions &ExistingTargetOpts;
4313 const PreprocessorOptions &ExistingPPOpts;
Argyrios Kyrtzidisbd0b6512015-02-19 20:12:20 +00004314 std::string ExistingModuleCachePath;
Guy Benyei11169dd2012-12-18 14:30:41 +00004315 FileManager &FileMgr;
Argyrios Kyrtzidisbd0b6512015-02-19 20:12:20 +00004316
Guy Benyei11169dd2012-12-18 14:30:41 +00004317 public:
4318 SimplePCHValidator(const LangOptions &ExistingLangOpts,
4319 const TargetOptions &ExistingTargetOpts,
4320 const PreprocessorOptions &ExistingPPOpts,
Argyrios Kyrtzidisbd0b6512015-02-19 20:12:20 +00004321 StringRef ExistingModuleCachePath,
Guy Benyei11169dd2012-12-18 14:30:41 +00004322 FileManager &FileMgr)
4323 : ExistingLangOpts(ExistingLangOpts),
4324 ExistingTargetOpts(ExistingTargetOpts),
4325 ExistingPPOpts(ExistingPPOpts),
Argyrios Kyrtzidisbd0b6512015-02-19 20:12:20 +00004326 ExistingModuleCachePath(ExistingModuleCachePath),
Guy Benyei11169dd2012-12-18 14:30:41 +00004327 FileMgr(FileMgr)
4328 {
4329 }
4330
Richard Smith1e2cf0d2014-10-31 02:28:58 +00004331 bool ReadLanguageOptions(const LangOptions &LangOpts, bool Complain,
4332 bool AllowCompatibleDifferences) override {
4333 return checkLanguageOptions(ExistingLangOpts, LangOpts, nullptr,
4334 AllowCompatibleDifferences);
Guy Benyei11169dd2012-12-18 14:30:41 +00004335 }
Eugene Zelenkoe95e7d52016-09-07 21:53:17 +00004336
Chandler Carruth0d745bc2015-03-14 04:47:43 +00004337 bool ReadTargetOptions(const TargetOptions &TargetOpts, bool Complain,
4338 bool AllowCompatibleDifferences) override {
4339 return checkTargetOptions(ExistingTargetOpts, TargetOpts, nullptr,
4340 AllowCompatibleDifferences);
Guy Benyei11169dd2012-12-18 14:30:41 +00004341 }
Eugene Zelenkoe95e7d52016-09-07 21:53:17 +00004342
Argyrios Kyrtzidisbd0b6512015-02-19 20:12:20 +00004343 bool ReadHeaderSearchOptions(const HeaderSearchOptions &HSOpts,
4344 StringRef SpecificModuleCachePath,
4345 bool Complain) override {
4346 return checkHeaderSearchOptions(HSOpts, SpecificModuleCachePath,
4347 ExistingModuleCachePath,
4348 nullptr, ExistingLangOpts);
4349 }
Eugene Zelenkoe95e7d52016-09-07 21:53:17 +00004350
Craig Topper3e89dfe2014-03-13 02:13:41 +00004351 bool ReadPreprocessorOptions(const PreprocessorOptions &PPOpts,
4352 bool Complain,
4353 std::string &SuggestedPredefines) override {
Craig Toppera13603a2014-05-22 05:54:18 +00004354 return checkPreprocessorOptions(ExistingPPOpts, PPOpts, nullptr, FileMgr,
Argyrios Kyrtzidisd3afa0c2013-04-26 21:33:40 +00004355 SuggestedPredefines, ExistingLangOpts);
Guy Benyei11169dd2012-12-18 14:30:41 +00004356 }
4357 };
Eugene Zelenkoe95e7d52016-09-07 21:53:17 +00004358
4359} // end anonymous namespace
Guy Benyei11169dd2012-12-18 14:30:41 +00004360
Adrian Prantlbb165fb2015-06-20 18:53:08 +00004361bool ASTReader::readASTFileControlBlock(
4362 StringRef Filename, FileManager &FileMgr,
Adrian Prantlfb2398d2015-07-17 01:19:54 +00004363 const PCHContainerReader &PCHContainerRdr,
Douglas Gregor6623e1f2015-11-03 18:33:07 +00004364 bool FindModuleFileExtensions,
Manman Ren47a44452016-07-26 17:12:17 +00004365 ASTReaderListener &Listener, bool ValidateDiagnosticOptions) {
Guy Benyei11169dd2012-12-18 14:30:41 +00004366 // Open the AST file.
Richard Smith7f330cd2015-03-18 01:42:29 +00004367 // FIXME: This allows use of the VFS; we do not allow use of the
4368 // VFS when actually loading a module.
Benjamin Kramera8857962014-10-26 22:44:13 +00004369 auto Buffer = FileMgr.getBufferForFile(Filename);
Guy Benyei11169dd2012-12-18 14:30:41 +00004370 if (!Buffer) {
4371 return true;
4372 }
4373
4374 // Initialize the stream
Peter Collingbourne77c89b62016-11-08 04:17:11 +00004375 BitstreamCursor Stream(PCHContainerRdr.ExtractPCH(**Buffer));
Guy Benyei11169dd2012-12-18 14:30:41 +00004376
4377 // Sniff for the signature.
Ben Langmuir70a1b812015-03-24 04:43:52 +00004378 if (!startsWithASTFileMagic(Stream))
Guy Benyei11169dd2012-12-18 14:30:41 +00004379 return true;
Guy Benyei11169dd2012-12-18 14:30:41 +00004380
Chris Lattner7fb3bef2013-01-20 00:56:42 +00004381 // Scan for the CONTROL_BLOCK_ID block.
Argyrios Kyrtzidisc4cd2c42013-05-06 19:23:40 +00004382 if (SkipCursorToBlock(Stream, CONTROL_BLOCK_ID))
Chris Lattner7fb3bef2013-01-20 00:56:42 +00004383 return true;
Argyrios Kyrtzidisc4cd2c42013-05-06 19:23:40 +00004384
4385 bool NeedsInputFiles = Listener.needsInputFileVisitation();
Ben Langmuircb69b572014-03-07 06:40:32 +00004386 bool NeedsSystemInputFiles = Listener.needsSystemInputFileVisitation();
Richard Smithd4b230b2014-10-27 23:01:16 +00004387 bool NeedsImports = Listener.needsImportVisitation();
Argyrios Kyrtzidisc4cd2c42013-05-06 19:23:40 +00004388 BitstreamCursor InputFilesCursor;
Argyrios Kyrtzidisc4cd2c42013-05-06 19:23:40 +00004389
Guy Benyei11169dd2012-12-18 14:30:41 +00004390 RecordData Record;
Richard Smith7ed1bc92014-12-05 22:42:13 +00004391 std::string ModuleDir;
Douglas Gregor6623e1f2015-11-03 18:33:07 +00004392 bool DoneWithControlBlock = false;
4393 while (!DoneWithControlBlock) {
Richard Smith0516b182015-09-08 19:40:14 +00004394 llvm::BitstreamEntry Entry = Stream.advance();
4395
4396 switch (Entry.Kind) {
4397 case llvm::BitstreamEntry::SubBlock: {
4398 switch (Entry.ID) {
4399 case OPTIONS_BLOCK_ID: {
4400 std::string IgnoredSuggestedPredefines;
4401 if (ReadOptionsBlock(Stream, ARR_ConfigurationMismatch | ARR_OutOfDate,
4402 /*AllowCompatibleConfigurationMismatch*/ false,
Manman Ren47a44452016-07-26 17:12:17 +00004403 Listener, IgnoredSuggestedPredefines,
4404 ValidateDiagnosticOptions) != Success)
Richard Smith0516b182015-09-08 19:40:14 +00004405 return true;
4406 break;
4407 }
4408
4409 case INPUT_FILES_BLOCK_ID:
4410 InputFilesCursor = Stream;
4411 if (Stream.SkipBlock() ||
4412 (NeedsInputFiles &&
4413 ReadBlockAbbrevs(InputFilesCursor, INPUT_FILES_BLOCK_ID)))
4414 return true;
4415 break;
4416
4417 default:
4418 if (Stream.SkipBlock())
4419 return true;
4420 break;
4421 }
4422
4423 continue;
4424 }
4425
4426 case llvm::BitstreamEntry::EndBlock:
Douglas Gregor6623e1f2015-11-03 18:33:07 +00004427 DoneWithControlBlock = true;
4428 break;
Richard Smith0516b182015-09-08 19:40:14 +00004429
4430 case llvm::BitstreamEntry::Error:
Chris Lattner7fb3bef2013-01-20 00:56:42 +00004431 return true;
Richard Smith0516b182015-09-08 19:40:14 +00004432
4433 case llvm::BitstreamEntry::Record:
4434 break;
4435 }
4436
Douglas Gregor6623e1f2015-11-03 18:33:07 +00004437 if (DoneWithControlBlock) break;
4438
Guy Benyei11169dd2012-12-18 14:30:41 +00004439 Record.clear();
Chris Lattner0e6c9402013-01-20 02:38:54 +00004440 StringRef Blob;
4441 unsigned RecCode = Stream.readRecord(Entry.ID, Record, &Blob);
Chris Lattner7fb3bef2013-01-20 00:56:42 +00004442 switch ((ControlRecordTypes)RecCode) {
4443 case METADATA: {
4444 if (Record[0] != VERSION_MAJOR)
4445 return true;
Guy Benyei11169dd2012-12-18 14:30:41 +00004446
Douglas Gregorbf7fc9c2013-03-27 16:47:18 +00004447 if (Listener.ReadFullVersionInformation(Blob))
Chris Lattner7fb3bef2013-01-20 00:56:42 +00004448 return true;
David L. Jonesc4808b9e2016-12-15 20:53:26 +00004449
Chris Lattner7fb3bef2013-01-20 00:56:42 +00004450 break;
4451 }
Ben Langmuir4f5212a2014-04-14 22:12:44 +00004452 case MODULE_NAME:
4453 Listener.ReadModuleName(Blob);
4454 break;
Richard Smith7ed1bc92014-12-05 22:42:13 +00004455 case MODULE_DIRECTORY:
4456 ModuleDir = Blob;
4457 break;
Ben Langmuir4b8a9e92014-08-12 16:42:33 +00004458 case MODULE_MAP_FILE: {
4459 unsigned Idx = 0;
Richard Smith7ed1bc92014-12-05 22:42:13 +00004460 auto Path = ReadString(Record, Idx);
4461 ResolveImportedPath(Path, ModuleDir);
4462 Listener.ReadModuleMapFile(Path);
Ben Langmuir4f5212a2014-04-14 22:12:44 +00004463 break;
Ben Langmuir4b8a9e92014-08-12 16:42:33 +00004464 }
Argyrios Kyrtzidisc4cd2c42013-05-06 19:23:40 +00004465 case INPUT_FILE_OFFSETS: {
4466 if (!NeedsInputFiles)
4467 break;
4468
4469 unsigned NumInputFiles = Record[0];
4470 unsigned NumUserFiles = Record[1];
Richard Smithec216502015-02-13 19:48:37 +00004471 const uint64_t *InputFileOffs = (const uint64_t *)Blob.data();
Argyrios Kyrtzidisc4cd2c42013-05-06 19:23:40 +00004472 for (unsigned I = 0; I != NumInputFiles; ++I) {
4473 // Go find this input file.
4474 bool isSystemFile = I >= NumUserFiles;
Ben Langmuircb69b572014-03-07 06:40:32 +00004475
4476 if (isSystemFile && !NeedsSystemInputFiles)
4477 break; // the rest are system input files
4478
Argyrios Kyrtzidisc4cd2c42013-05-06 19:23:40 +00004479 BitstreamCursor &Cursor = InputFilesCursor;
4480 SavedStreamPosition SavedPosition(Cursor);
4481 Cursor.JumpToBit(InputFileOffs[I]);
4482
4483 unsigned Code = Cursor.ReadCode();
4484 RecordData Record;
4485 StringRef Blob;
4486 bool shouldContinue = false;
4487 switch ((InputFileRecordTypes)Cursor.readRecord(Code, Record, &Blob)) {
4488 case INPUT_FILE:
Argyrios Kyrtzidis68ccbe02014-03-14 02:26:31 +00004489 bool Overridden = static_cast<bool>(Record[3]);
Richard Smith7ed1bc92014-12-05 22:42:13 +00004490 std::string Filename = Blob;
4491 ResolveImportedPath(Filename, ModuleDir);
Richard Smith216a3bd2015-08-13 17:57:10 +00004492 shouldContinue = Listener.visitInputFile(
4493 Filename, isSystemFile, Overridden, /*IsExplicitModule*/false);
Argyrios Kyrtzidisc4cd2c42013-05-06 19:23:40 +00004494 break;
4495 }
4496 if (!shouldContinue)
4497 break;
4498 }
4499 break;
4500 }
4501
Richard Smithd4b230b2014-10-27 23:01:16 +00004502 case IMPORTS: {
4503 if (!NeedsImports)
4504 break;
4505
4506 unsigned Idx = 0, N = Record.size();
4507 while (Idx < N) {
4508 // Read information about the AST file.
Richard Smith79c98cc2014-10-27 23:25:15 +00004509 Idx += 5; // ImportLoc, Size, ModTime, Signature
Richard Smith7ed1bc92014-12-05 22:42:13 +00004510 std::string Filename = ReadString(Record, Idx);
4511 ResolveImportedPath(Filename, ModuleDir);
4512 Listener.visitImport(Filename);
Richard Smithd4b230b2014-10-27 23:01:16 +00004513 }
4514 break;
4515 }
4516
Chris Lattner7fb3bef2013-01-20 00:56:42 +00004517 default:
4518 // No other validation to perform.
4519 break;
Guy Benyei11169dd2012-12-18 14:30:41 +00004520 }
4521 }
Douglas Gregor6623e1f2015-11-03 18:33:07 +00004522
4523 // Look for module file extension blocks, if requested.
4524 if (FindModuleFileExtensions) {
4525 while (!SkipCursorToBlock(Stream, EXTENSION_BLOCK_ID)) {
4526 bool DoneWithExtensionBlock = false;
4527 while (!DoneWithExtensionBlock) {
4528 llvm::BitstreamEntry Entry = Stream.advance();
4529
4530 switch (Entry.Kind) {
4531 case llvm::BitstreamEntry::SubBlock:
4532 if (Stream.SkipBlock())
4533 return true;
4534
4535 continue;
4536
4537 case llvm::BitstreamEntry::EndBlock:
4538 DoneWithExtensionBlock = true;
4539 continue;
4540
4541 case llvm::BitstreamEntry::Error:
4542 return true;
4543
4544 case llvm::BitstreamEntry::Record:
4545 break;
4546 }
4547
4548 Record.clear();
4549 StringRef Blob;
4550 unsigned RecCode = Stream.readRecord(Entry.ID, Record, &Blob);
4551 switch (RecCode) {
4552 case EXTENSION_METADATA: {
4553 ModuleFileExtensionMetadata Metadata;
4554 if (parseModuleFileExtensionMetadata(Record, Blob, Metadata))
4555 return true;
4556
4557 Listener.readModuleFileExtension(Metadata);
4558 break;
4559 }
4560 }
4561 }
4562 }
4563 }
4564
4565 return false;
Guy Benyei11169dd2012-12-18 14:30:41 +00004566}
4567
Adrian Prantlbb165fb2015-06-20 18:53:08 +00004568bool ASTReader::isAcceptableASTFile(
4569 StringRef Filename, FileManager &FileMgr,
Adrian Prantlfb2398d2015-07-17 01:19:54 +00004570 const PCHContainerReader &PCHContainerRdr, const LangOptions &LangOpts,
Adrian Prantlbb165fb2015-06-20 18:53:08 +00004571 const TargetOptions &TargetOpts, const PreprocessorOptions &PPOpts,
4572 std::string ExistingModuleCachePath) {
Argyrios Kyrtzidisbd0b6512015-02-19 20:12:20 +00004573 SimplePCHValidator validator(LangOpts, TargetOpts, PPOpts,
4574 ExistingModuleCachePath, FileMgr);
Adrian Prantlfb2398d2015-07-17 01:19:54 +00004575 return !readASTFileControlBlock(Filename, FileMgr, PCHContainerRdr,
Douglas Gregor6623e1f2015-11-03 18:33:07 +00004576 /*FindModuleFileExtensions=*/false,
Manman Ren47a44452016-07-26 17:12:17 +00004577 validator,
4578 /*ValidateDiagnosticOptions=*/true);
Guy Benyei11169dd2012-12-18 14:30:41 +00004579}
4580
Ben Langmuir2c9af442014-04-10 17:57:43 +00004581ASTReader::ASTReadResult
4582ASTReader::ReadSubmoduleBlock(ModuleFile &F, unsigned ClientLoadCapabilities) {
Guy Benyei11169dd2012-12-18 14:30:41 +00004583 // Enter the submodule block.
4584 if (F.Stream.EnterSubBlock(SUBMODULE_BLOCK_ID)) {
4585 Error("malformed submodule block record in AST file");
Ben Langmuir2c9af442014-04-10 17:57:43 +00004586 return Failure;
Guy Benyei11169dd2012-12-18 14:30:41 +00004587 }
4588
4589 ModuleMap &ModMap = PP.getHeaderSearchInfo().getModuleMap();
4590 bool First = true;
Craig Toppera13603a2014-05-22 05:54:18 +00004591 Module *CurrentModule = nullptr;
Guy Benyei11169dd2012-12-18 14:30:41 +00004592 RecordData Record;
4593 while (true) {
Chris Lattner7fb3bef2013-01-20 00:56:42 +00004594 llvm::BitstreamEntry Entry = F.Stream.advanceSkippingSubblocks();
David L. Jonesc4808b9e2016-12-15 20:53:26 +00004595
Chris Lattner7fb3bef2013-01-20 00:56:42 +00004596 switch (Entry.Kind) {
4597 case llvm::BitstreamEntry::SubBlock: // Handled for us already.
4598 case llvm::BitstreamEntry::Error:
4599 Error("malformed block record in AST file");
Ben Langmuir2c9af442014-04-10 17:57:43 +00004600 return Failure;
Chris Lattner7fb3bef2013-01-20 00:56:42 +00004601 case llvm::BitstreamEntry::EndBlock:
Ben Langmuir2c9af442014-04-10 17:57:43 +00004602 return Success;
Chris Lattner7fb3bef2013-01-20 00:56:42 +00004603 case llvm::BitstreamEntry::Record:
4604 // The interesting case.
4605 break;
Guy Benyei11169dd2012-12-18 14:30:41 +00004606 }
Chris Lattner7fb3bef2013-01-20 00:56:42 +00004607
Guy Benyei11169dd2012-12-18 14:30:41 +00004608 // Read a record.
Chris Lattner0e6c9402013-01-20 02:38:54 +00004609 StringRef Blob;
Guy Benyei11169dd2012-12-18 14:30:41 +00004610 Record.clear();
Richard Smith03478d92014-10-23 22:12:14 +00004611 auto Kind = F.Stream.readRecord(Entry.ID, Record, &Blob);
4612
4613 if ((Kind == SUBMODULE_METADATA) != First) {
4614 Error("submodule metadata record should be at beginning of block");
4615 return Failure;
4616 }
4617 First = false;
4618
4619 // Submodule information is only valid if we have a current module.
4620 // FIXME: Should we error on these cases?
4621 if (!CurrentModule && Kind != SUBMODULE_METADATA &&
4622 Kind != SUBMODULE_DEFINITION)
4623 continue;
4624
4625 switch (Kind) {
Guy Benyei11169dd2012-12-18 14:30:41 +00004626 default: // Default behavior: ignore.
4627 break;
Guy Benyei11169dd2012-12-18 14:30:41 +00004628
Richard Smith03478d92014-10-23 22:12:14 +00004629 case SUBMODULE_DEFINITION: {
Douglas Gregor8d932422013-03-20 03:59:18 +00004630 if (Record.size() < 8) {
Guy Benyei11169dd2012-12-18 14:30:41 +00004631 Error("malformed module definition");
Ben Langmuir2c9af442014-04-10 17:57:43 +00004632 return Failure;
Guy Benyei11169dd2012-12-18 14:30:41 +00004633 }
Richard Smith03478d92014-10-23 22:12:14 +00004634
Chris Lattner0e6c9402013-01-20 02:38:54 +00004635 StringRef Name = Blob;
Richard Smith9bca2982014-03-08 00:03:56 +00004636 unsigned Idx = 0;
4637 SubmoduleID GlobalID = getGlobalSubmoduleID(F, Record[Idx++]);
4638 SubmoduleID Parent = getGlobalSubmoduleID(F, Record[Idx++]);
4639 bool IsFramework = Record[Idx++];
4640 bool IsExplicit = Record[Idx++];
4641 bool IsSystem = Record[Idx++];
4642 bool IsExternC = Record[Idx++];
4643 bool InferSubmodules = Record[Idx++];
4644 bool InferExplicitSubmodules = Record[Idx++];
4645 bool InferExportWildcard = Record[Idx++];
4646 bool ConfigMacrosExhaustive = Record[Idx++];
David Blaikie9ffe5a32017-01-30 05:00:26 +00004647 bool WithCodegen = Record[Idx++];
Douglas Gregor8d932422013-03-20 03:59:18 +00004648
Ben Langmuirbeee15e2014-04-14 18:00:01 +00004649 Module *ParentModule = nullptr;
Ben Langmuir9d6448b2014-08-09 00:57:23 +00004650 if (Parent)
Guy Benyei11169dd2012-12-18 14:30:41 +00004651 ParentModule = getSubmodule(Parent);
Ben Langmuirbeee15e2014-04-14 18:00:01 +00004652
Guy Benyei11169dd2012-12-18 14:30:41 +00004653 // Retrieve this (sub)module from the module map, creating it if
4654 // necessary.
David Blaikie9ffe5a32017-01-30 05:00:26 +00004655 CurrentModule =
4656 ModMap.findOrCreateModule(Name, ParentModule, IsFramework, IsExplicit)
4657 .first;
Ben Langmuir9d6448b2014-08-09 00:57:23 +00004658
4659 // FIXME: set the definition loc for CurrentModule, or call
4660 // ModMap.setInferredModuleAllowedBy()
4661
Guy Benyei11169dd2012-12-18 14:30:41 +00004662 SubmoduleID GlobalIndex = GlobalID - NUM_PREDEF_SUBMODULE_IDS;
4663 if (GlobalIndex >= SubmodulesLoaded.size() ||
4664 SubmodulesLoaded[GlobalIndex]) {
4665 Error("too many submodules");
Ben Langmuir2c9af442014-04-10 17:57:43 +00004666 return Failure;
Guy Benyei11169dd2012-12-18 14:30:41 +00004667 }
Douglas Gregor8a114ab2013-02-06 22:40:31 +00004668
Douglas Gregor7029ce12013-03-19 00:28:20 +00004669 if (!ParentModule) {
4670 if (const FileEntry *CurFile = CurrentModule->getASTFile()) {
4671 if (CurFile != F.File) {
4672 if (!Diags.isDiagnosticInFlight()) {
4673 Diag(diag::err_module_file_conflict)
4674 << CurrentModule->getTopLevelModuleName()
4675 << CurFile->getName()
4676 << F.File->getName();
4677 }
Ben Langmuir2c9af442014-04-10 17:57:43 +00004678 return Failure;
Douglas Gregor8a114ab2013-02-06 22:40:31 +00004679 }
Douglas Gregor8a114ab2013-02-06 22:40:31 +00004680 }
Douglas Gregor7029ce12013-03-19 00:28:20 +00004681
4682 CurrentModule->setASTFile(F.File);
Douglas Gregor8a114ab2013-02-06 22:40:31 +00004683 }
Ben Langmuirbeee15e2014-04-14 18:00:01 +00004684
Adrian Prantl15bcf702015-06-30 17:39:43 +00004685 CurrentModule->Signature = F.Signature;
Guy Benyei11169dd2012-12-18 14:30:41 +00004686 CurrentModule->IsFromModuleFile = true;
4687 CurrentModule->IsSystem = IsSystem || CurrentModule->IsSystem;
Richard Smith9bca2982014-03-08 00:03:56 +00004688 CurrentModule->IsExternC = IsExternC;
Guy Benyei11169dd2012-12-18 14:30:41 +00004689 CurrentModule->InferSubmodules = InferSubmodules;
4690 CurrentModule->InferExplicitSubmodules = InferExplicitSubmodules;
4691 CurrentModule->InferExportWildcard = InferExportWildcard;
Douglas Gregor8d932422013-03-20 03:59:18 +00004692 CurrentModule->ConfigMacrosExhaustive = ConfigMacrosExhaustive;
David Blaikie9ffe5a32017-01-30 05:00:26 +00004693 CurrentModule->WithCodegen = WithCodegen;
Guy Benyei11169dd2012-12-18 14:30:41 +00004694 if (DeserializationListener)
4695 DeserializationListener->ModuleRead(GlobalID, CurrentModule);
David L. Jonesc4808b9e2016-12-15 20:53:26 +00004696
Guy Benyei11169dd2012-12-18 14:30:41 +00004697 SubmodulesLoaded[GlobalIndex] = CurrentModule;
Douglas Gregor6ddfca92013-01-14 17:21:00 +00004698
Richard Smith8a3e39a2016-03-28 21:31:09 +00004699 // Clear out data that will be replaced by what is in the module file.
Douglas Gregor6ddfca92013-01-14 17:21:00 +00004700 CurrentModule->LinkLibraries.clear();
Douglas Gregor8d932422013-03-20 03:59:18 +00004701 CurrentModule->ConfigMacros.clear();
Douglas Gregorfb912652013-03-20 21:10:35 +00004702 CurrentModule->UnresolvedConflicts.clear();
4703 CurrentModule->Conflicts.clear();
Richard Smith8a3e39a2016-03-28 21:31:09 +00004704
4705 // The module is available unless it's missing a requirement; relevant
4706 // requirements will be (re-)added by SUBMODULE_REQUIRES records.
4707 // Missing headers that were present when the module was built do not
4708 // make it unavailable -- if we got this far, this must be an explicitly
4709 // imported module file.
4710 CurrentModule->Requirements.clear();
4711 CurrentModule->MissingHeaders.clear();
4712 CurrentModule->IsMissingRequirement =
4713 ParentModule && ParentModule->IsMissingRequirement;
4714 CurrentModule->IsAvailable = !CurrentModule->IsMissingRequirement;
Guy Benyei11169dd2012-12-18 14:30:41 +00004715 break;
4716 }
Richard Smith8a3e39a2016-03-28 21:31:09 +00004717
Guy Benyei11169dd2012-12-18 14:30:41 +00004718 case SUBMODULE_UMBRELLA_HEADER: {
Richard Smith2b63d152015-05-16 02:28:53 +00004719 std::string Filename = Blob;
4720 ResolveImportedPath(F, Filename);
4721 if (auto *Umbrella = PP.getFileManager().getFile(Filename)) {
Guy Benyei11169dd2012-12-18 14:30:41 +00004722 if (!CurrentModule->getUmbrellaHeader())
Richard Smith2b63d152015-05-16 02:28:53 +00004723 ModMap.setUmbrellaHeader(CurrentModule, Umbrella, Blob);
4724 else if (CurrentModule->getUmbrellaHeader().Entry != Umbrella) {
Ben Langmuirbc35fbe2015-02-20 21:46:39 +00004725 // This can be a spurious difference caused by changing the VFS to
4726 // point to a different copy of the file, and it is too late to
4727 // to rebuild safely.
4728 // FIXME: If we wrote the virtual paths instead of the 'real' paths,
4729 // after input file validation only real problems would remain and we
4730 // could just error. For now, assume it's okay.
4731 break;
Guy Benyei11169dd2012-12-18 14:30:41 +00004732 }
4733 }
4734 break;
4735 }
David L. Jonesc4808b9e2016-12-15 20:53:26 +00004736
Richard Smith202210b2014-10-24 20:23:01 +00004737 case SUBMODULE_HEADER:
4738 case SUBMODULE_EXCLUDED_HEADER:
4739 case SUBMODULE_PRIVATE_HEADER:
4740 // We lazily associate headers with their modules via the HeaderInfo table.
Argyrios Kyrtzidisb146baa2013-03-13 21:13:51 +00004741 // FIXME: Re-evaluate this section; maybe only store InputFile IDs instead
4742 // of complete filenames or remove it entirely.
Richard Smith202210b2014-10-24 20:23:01 +00004743 break;
Guy Benyei11169dd2012-12-18 14:30:41 +00004744
Richard Smith202210b2014-10-24 20:23:01 +00004745 case SUBMODULE_TEXTUAL_HEADER:
4746 case SUBMODULE_PRIVATE_TEXTUAL_HEADER:
4747 // FIXME: Textual headers are not marked in the HeaderInfo table. Load
4748 // them here.
4749 break;
Lawrence Crowlb53e5482013-06-20 21:14:14 +00004750
Guy Benyei11169dd2012-12-18 14:30:41 +00004751 case SUBMODULE_TOPHEADER: {
Argyrios Kyrtzidis3c5305c2013-03-13 21:13:43 +00004752 CurrentModule->addTopHeaderFilename(Blob);
Guy Benyei11169dd2012-12-18 14:30:41 +00004753 break;
4754 }
4755
4756 case SUBMODULE_UMBRELLA_DIR: {
Richard Smith2b63d152015-05-16 02:28:53 +00004757 std::string Dirname = Blob;
4758 ResolveImportedPath(F, Dirname);
4759 if (auto *Umbrella = PP.getFileManager().getDirectory(Dirname)) {
Guy Benyei11169dd2012-12-18 14:30:41 +00004760 if (!CurrentModule->getUmbrellaDir())
Richard Smith2b63d152015-05-16 02:28:53 +00004761 ModMap.setUmbrellaDir(CurrentModule, Umbrella, Blob);
4762 else if (CurrentModule->getUmbrellaDir().Entry != Umbrella) {
Ben Langmuir2c9af442014-04-10 17:57:43 +00004763 if ((ClientLoadCapabilities & ARR_OutOfDate) == 0)
4764 Error("mismatched umbrella directories in submodule");
4765 return OutOfDate;
Guy Benyei11169dd2012-12-18 14:30:41 +00004766 }
4767 }
4768 break;
4769 }
David L. Jonesc4808b9e2016-12-15 20:53:26 +00004770
Guy Benyei11169dd2012-12-18 14:30:41 +00004771 case SUBMODULE_METADATA: {
Guy Benyei11169dd2012-12-18 14:30:41 +00004772 F.BaseSubmoduleID = getTotalNumSubmodules();
4773 F.LocalNumSubmodules = Record[0];
4774 unsigned LocalBaseSubmoduleID = Record[1];
4775 if (F.LocalNumSubmodules > 0) {
David L. Jonesc4808b9e2016-12-15 20:53:26 +00004776 // Introduce the global -> local mapping for submodules within this
Guy Benyei11169dd2012-12-18 14:30:41 +00004777 // module.
4778 GlobalSubmoduleMap.insert(std::make_pair(getTotalNumSubmodules()+1,&F));
David L. Jonesc4808b9e2016-12-15 20:53:26 +00004779
4780 // Introduce the local -> global mapping for submodules within this
Guy Benyei11169dd2012-12-18 14:30:41 +00004781 // module.
4782 F.SubmoduleRemap.insertOrReplace(
4783 std::make_pair(LocalBaseSubmoduleID,
4784 F.BaseSubmoduleID - LocalBaseSubmoduleID));
Ben Langmuirfe971d92014-08-16 04:54:18 +00004785
Ben Langmuir52ca6782014-10-20 16:27:32 +00004786 SubmodulesLoaded.resize(SubmodulesLoaded.size() + F.LocalNumSubmodules);
4787 }
Guy Benyei11169dd2012-12-18 14:30:41 +00004788 break;
4789 }
David L. Jonesc4808b9e2016-12-15 20:53:26 +00004790
Guy Benyei11169dd2012-12-18 14:30:41 +00004791 case SUBMODULE_IMPORTS: {
Guy Benyei11169dd2012-12-18 14:30:41 +00004792 for (unsigned Idx = 0; Idx != Record.size(); ++Idx) {
Douglas Gregorfb912652013-03-20 21:10:35 +00004793 UnresolvedModuleRef Unresolved;
Guy Benyei11169dd2012-12-18 14:30:41 +00004794 Unresolved.File = &F;
4795 Unresolved.Mod = CurrentModule;
4796 Unresolved.ID = Record[Idx];
Douglas Gregorfb912652013-03-20 21:10:35 +00004797 Unresolved.Kind = UnresolvedModuleRef::Import;
Guy Benyei11169dd2012-12-18 14:30:41 +00004798 Unresolved.IsWildcard = false;
Douglas Gregorfb912652013-03-20 21:10:35 +00004799 UnresolvedModuleRefs.push_back(Unresolved);
Guy Benyei11169dd2012-12-18 14:30:41 +00004800 }
4801 break;
4802 }
4803
4804 case SUBMODULE_EXPORTS: {
Guy Benyei11169dd2012-12-18 14:30:41 +00004805 for (unsigned Idx = 0; Idx + 1 < Record.size(); Idx += 2) {
Douglas Gregorfb912652013-03-20 21:10:35 +00004806 UnresolvedModuleRef Unresolved;
Guy Benyei11169dd2012-12-18 14:30:41 +00004807 Unresolved.File = &F;
4808 Unresolved.Mod = CurrentModule;
4809 Unresolved.ID = Record[Idx];
Douglas Gregorfb912652013-03-20 21:10:35 +00004810 Unresolved.Kind = UnresolvedModuleRef::Export;
Guy Benyei11169dd2012-12-18 14:30:41 +00004811 Unresolved.IsWildcard = Record[Idx + 1];
Douglas Gregorfb912652013-03-20 21:10:35 +00004812 UnresolvedModuleRefs.push_back(Unresolved);
Guy Benyei11169dd2012-12-18 14:30:41 +00004813 }
David L. Jonesc4808b9e2016-12-15 20:53:26 +00004814
4815 // Once we've loaded the set of exports, there's no reason to keep
Guy Benyei11169dd2012-12-18 14:30:41 +00004816 // the parsed, unresolved exports around.
4817 CurrentModule->UnresolvedExports.clear();
4818 break;
4819 }
4820 case SUBMODULE_REQUIRES: {
Richard Smitha3feee22013-10-28 22:18:19 +00004821 CurrentModule->addRequirement(Blob, Record[0], Context.getLangOpts(),
Guy Benyei11169dd2012-12-18 14:30:41 +00004822 Context.getTargetInfo());
4823 break;
4824 }
Douglas Gregor6ddfca92013-01-14 17:21:00 +00004825
4826 case SUBMODULE_LINK_LIBRARY:
Douglas Gregor6ddfca92013-01-14 17:21:00 +00004827 CurrentModule->LinkLibraries.push_back(
Chris Lattner0e6c9402013-01-20 02:38:54 +00004828 Module::LinkLibrary(Blob, Record[0]));
Douglas Gregor6ddfca92013-01-14 17:21:00 +00004829 break;
Douglas Gregor35b13ec2013-03-20 00:22:05 +00004830
4831 case SUBMODULE_CONFIG_MACRO:
Douglas Gregor35b13ec2013-03-20 00:22:05 +00004832 CurrentModule->ConfigMacros.push_back(Blob.str());
4833 break;
Douglas Gregorfb912652013-03-20 21:10:35 +00004834
4835 case SUBMODULE_CONFLICT: {
Douglas Gregorfb912652013-03-20 21:10:35 +00004836 UnresolvedModuleRef Unresolved;
4837 Unresolved.File = &F;
4838 Unresolved.Mod = CurrentModule;
4839 Unresolved.ID = Record[0];
4840 Unresolved.Kind = UnresolvedModuleRef::Conflict;
4841 Unresolved.IsWildcard = false;
4842 Unresolved.String = Blob;
4843 UnresolvedModuleRefs.push_back(Unresolved);
4844 break;
4845 }
Richard Smithdc1f0422016-07-20 19:10:16 +00004846
4847 case SUBMODULE_INITIALIZERS:
4848 SmallVector<uint32_t, 16> Inits;
4849 for (auto &ID : Record)
4850 Inits.push_back(getGlobalDeclID(F, ID));
4851 Context.addLazyModuleInitializers(CurrentModule, Inits);
4852 break;
Guy Benyei11169dd2012-12-18 14:30:41 +00004853 }
4854 }
4855}
4856
4857/// \brief Parse the record that corresponds to a LangOptions data
4858/// structure.
4859///
4860/// This routine parses the language options from the AST file and then gives
4861/// them to the AST listener if one is set.
4862///
4863/// \returns true if the listener deems the file unacceptable, false otherwise.
4864bool ASTReader::ParseLanguageOptions(const RecordData &Record,
4865 bool Complain,
Richard Smith1e2cf0d2014-10-31 02:28:58 +00004866 ASTReaderListener &Listener,
4867 bool AllowCompatibleDifferences) {
Guy Benyei11169dd2012-12-18 14:30:41 +00004868 LangOptions LangOpts;
4869 unsigned Idx = 0;
4870#define LANGOPT(Name, Bits, Default, Description) \
4871 LangOpts.Name = Record[Idx++];
4872#define ENUM_LANGOPT(Name, Type, Bits, Default, Description) \
4873 LangOpts.set##Name(static_cast<LangOptions::Type>(Record[Idx++]));
4874#include "clang/Basic/LangOptions.def"
Alexey Samsonovedf99a92014-11-07 22:29:38 +00004875#define SANITIZER(NAME, ID) \
4876 LangOpts.Sanitize.set(SanitizerKind::ID, Record[Idx++]);
Will Dietzf54319c2013-01-18 11:30:38 +00004877#include "clang/Basic/Sanitizers.def"
Guy Benyei11169dd2012-12-18 14:30:41 +00004878
Ben Langmuircd98cb72015-06-23 18:20:18 +00004879 for (unsigned N = Record[Idx++]; N; --N)
4880 LangOpts.ModuleFeatures.push_back(ReadString(Record, Idx));
4881
Guy Benyei11169dd2012-12-18 14:30:41 +00004882 ObjCRuntime::Kind runtimeKind = (ObjCRuntime::Kind) Record[Idx++];
4883 VersionTuple runtimeVersion = ReadVersionTuple(Record, Idx);
4884 LangOpts.ObjCRuntime = ObjCRuntime(runtimeKind, runtimeVersion);
Dmitri Gribenkoacf2e782013-02-22 14:21:27 +00004885
Ben Langmuird4a667a2015-06-23 18:20:23 +00004886 LangOpts.CurrentModule = ReadString(Record, Idx);
Dmitri Gribenkoacf2e782013-02-22 14:21:27 +00004887
4888 // Comment options.
4889 for (unsigned N = Record[Idx++]; N; --N) {
4890 LangOpts.CommentOpts.BlockCommandNames.push_back(
4891 ReadString(Record, Idx));
4892 }
Dmitri Gribenkoa7d16ce2013-04-10 15:35:17 +00004893 LangOpts.CommentOpts.ParseAllComments = Record[Idx++];
Dmitri Gribenkoacf2e782013-02-22 14:21:27 +00004894
Samuel Antaoee8fb302016-01-06 13:42:12 +00004895 // OpenMP offloading options.
4896 for (unsigned N = Record[Idx++]; N; --N) {
4897 LangOpts.OMPTargetTriples.push_back(llvm::Triple(ReadString(Record, Idx)));
4898 }
4899
4900 LangOpts.OMPHostIRFile = ReadString(Record, Idx);
4901
Richard Smith1e2cf0d2014-10-31 02:28:58 +00004902 return Listener.ReadLanguageOptions(LangOpts, Complain,
4903 AllowCompatibleDifferences);
Guy Benyei11169dd2012-12-18 14:30:41 +00004904}
4905
Chandler Carruth0d745bc2015-03-14 04:47:43 +00004906bool ASTReader::ParseTargetOptions(const RecordData &Record, bool Complain,
4907 ASTReaderListener &Listener,
4908 bool AllowCompatibleDifferences) {
Guy Benyei11169dd2012-12-18 14:30:41 +00004909 unsigned Idx = 0;
4910 TargetOptions TargetOpts;
4911 TargetOpts.Triple = ReadString(Record, Idx);
4912 TargetOpts.CPU = ReadString(Record, Idx);
4913 TargetOpts.ABI = ReadString(Record, Idx);
Guy Benyei11169dd2012-12-18 14:30:41 +00004914 for (unsigned N = Record[Idx++]; N; --N) {
4915 TargetOpts.FeaturesAsWritten.push_back(ReadString(Record, Idx));
4916 }
4917 for (unsigned N = Record[Idx++]; N; --N) {
4918 TargetOpts.Features.push_back(ReadString(Record, Idx));
4919 }
4920
Chandler Carruth0d745bc2015-03-14 04:47:43 +00004921 return Listener.ReadTargetOptions(TargetOpts, Complain,
4922 AllowCompatibleDifferences);
Guy Benyei11169dd2012-12-18 14:30:41 +00004923}
4924
4925bool ASTReader::ParseDiagnosticOptions(const RecordData &Record, bool Complain,
4926 ASTReaderListener &Listener) {
Ben Langmuirb92de022014-04-29 16:25:26 +00004927 IntrusiveRefCntPtr<DiagnosticOptions> DiagOpts(new DiagnosticOptions);
Guy Benyei11169dd2012-12-18 14:30:41 +00004928 unsigned Idx = 0;
Ben Langmuirb92de022014-04-29 16:25:26 +00004929#define DIAGOPT(Name, Bits, Default) DiagOpts->Name = Record[Idx++];
Guy Benyei11169dd2012-12-18 14:30:41 +00004930#define ENUM_DIAGOPT(Name, Type, Bits, Default) \
Ben Langmuirb92de022014-04-29 16:25:26 +00004931 DiagOpts->set##Name(static_cast<Type>(Record[Idx++]));
Guy Benyei11169dd2012-12-18 14:30:41 +00004932#include "clang/Basic/DiagnosticOptions.def"
4933
Richard Smith3be1cb22014-08-07 00:24:21 +00004934 for (unsigned N = Record[Idx++]; N; --N)
Ben Langmuirb92de022014-04-29 16:25:26 +00004935 DiagOpts->Warnings.push_back(ReadString(Record, Idx));
Richard Smith3be1cb22014-08-07 00:24:21 +00004936 for (unsigned N = Record[Idx++]; N; --N)
4937 DiagOpts->Remarks.push_back(ReadString(Record, Idx));
Guy Benyei11169dd2012-12-18 14:30:41 +00004938
4939 return Listener.ReadDiagnosticOptions(DiagOpts, Complain);
4940}
4941
4942bool ASTReader::ParseFileSystemOptions(const RecordData &Record, bool Complain,
4943 ASTReaderListener &Listener) {
4944 FileSystemOptions FSOpts;
4945 unsigned Idx = 0;
4946 FSOpts.WorkingDir = ReadString(Record, Idx);
4947 return Listener.ReadFileSystemOptions(FSOpts, Complain);
4948}
4949
4950bool ASTReader::ParseHeaderSearchOptions(const RecordData &Record,
4951 bool Complain,
4952 ASTReaderListener &Listener) {
4953 HeaderSearchOptions HSOpts;
4954 unsigned Idx = 0;
4955 HSOpts.Sysroot = ReadString(Record, Idx);
4956
4957 // Include entries.
4958 for (unsigned N = Record[Idx++]; N; --N) {
4959 std::string Path = ReadString(Record, Idx);
4960 frontend::IncludeDirGroup Group
4961 = static_cast<frontend::IncludeDirGroup>(Record[Idx++]);
Guy Benyei11169dd2012-12-18 14:30:41 +00004962 bool IsFramework = Record[Idx++];
4963 bool IgnoreSysRoot = Record[Idx++];
Benjamin Kramer3204b152015-05-29 19:42:19 +00004964 HSOpts.UserEntries.emplace_back(std::move(Path), Group, IsFramework,
4965 IgnoreSysRoot);
Guy Benyei11169dd2012-12-18 14:30:41 +00004966 }
4967
4968 // System header prefixes.
4969 for (unsigned N = Record[Idx++]; N; --N) {
4970 std::string Prefix = ReadString(Record, Idx);
4971 bool IsSystemHeader = Record[Idx++];
Benjamin Kramer3204b152015-05-29 19:42:19 +00004972 HSOpts.SystemHeaderPrefixes.emplace_back(std::move(Prefix), IsSystemHeader);
Guy Benyei11169dd2012-12-18 14:30:41 +00004973 }
4974
4975 HSOpts.ResourceDir = ReadString(Record, Idx);
4976 HSOpts.ModuleCachePath = ReadString(Record, Idx);
Argyrios Kyrtzidis1594c152014-03-03 08:12:05 +00004977 HSOpts.ModuleUserBuildPath = ReadString(Record, Idx);
Guy Benyei11169dd2012-12-18 14:30:41 +00004978 HSOpts.DisableModuleHash = Record[Idx++];
4979 HSOpts.UseBuiltinIncludes = Record[Idx++];
4980 HSOpts.UseStandardSystemIncludes = Record[Idx++];
4981 HSOpts.UseStandardCXXIncludes = Record[Idx++];
4982 HSOpts.UseLibcxx = Record[Idx++];
Argyrios Kyrtzidisbd0b6512015-02-19 20:12:20 +00004983 std::string SpecificModuleCachePath = ReadString(Record, Idx);
Guy Benyei11169dd2012-12-18 14:30:41 +00004984
Argyrios Kyrtzidisbd0b6512015-02-19 20:12:20 +00004985 return Listener.ReadHeaderSearchOptions(HSOpts, SpecificModuleCachePath,
4986 Complain);
Guy Benyei11169dd2012-12-18 14:30:41 +00004987}
4988
4989bool ASTReader::ParsePreprocessorOptions(const RecordData &Record,
4990 bool Complain,
4991 ASTReaderListener &Listener,
4992 std::string &SuggestedPredefines) {
4993 PreprocessorOptions PPOpts;
4994 unsigned Idx = 0;
4995
4996 // Macro definitions/undefs
4997 for (unsigned N = Record[Idx++]; N; --N) {
4998 std::string Macro = ReadString(Record, Idx);
4999 bool IsUndef = Record[Idx++];
5000 PPOpts.Macros.push_back(std::make_pair(Macro, IsUndef));
5001 }
5002
5003 // Includes
5004 for (unsigned N = Record[Idx++]; N; --N) {
5005 PPOpts.Includes.push_back(ReadString(Record, Idx));
5006 }
5007
5008 // Macro Includes
5009 for (unsigned N = Record[Idx++]; N; --N) {
5010 PPOpts.MacroIncludes.push_back(ReadString(Record, Idx));
5011 }
5012
5013 PPOpts.UsePredefines = Record[Idx++];
Argyrios Kyrtzidisd3afa0c2013-04-26 21:33:40 +00005014 PPOpts.DetailedRecord = Record[Idx++];
Guy Benyei11169dd2012-12-18 14:30:41 +00005015 PPOpts.ImplicitPCHInclude = ReadString(Record, Idx);
5016 PPOpts.ImplicitPTHInclude = ReadString(Record, Idx);
5017 PPOpts.ObjCXXARCStandardLibrary =
5018 static_cast<ObjCXXARCStandardLibraryKind>(Record[Idx++]);
5019 SuggestedPredefines.clear();
5020 return Listener.ReadPreprocessorOptions(PPOpts, Complain,
5021 SuggestedPredefines);
5022}
5023
5024std::pair<ModuleFile *, unsigned>
5025ASTReader::getModulePreprocessedEntity(unsigned GlobalIndex) {
5026 GlobalPreprocessedEntityMapType::iterator
5027 I = GlobalPreprocessedEntityMap.find(GlobalIndex);
David L. Jonesc4808b9e2016-12-15 20:53:26 +00005028 assert(I != GlobalPreprocessedEntityMap.end() &&
Guy Benyei11169dd2012-12-18 14:30:41 +00005029 "Corrupted global preprocessed entity map");
5030 ModuleFile *M = I->second;
5031 unsigned LocalIndex = GlobalIndex - M->BasePreprocessedEntityID;
5032 return std::make_pair(M, LocalIndex);
5033}
5034
Benjamin Kramerb4ef6682015-02-06 17:25:10 +00005035llvm::iterator_range<PreprocessingRecord::iterator>
Guy Benyei11169dd2012-12-18 14:30:41 +00005036ASTReader::getModulePreprocessedEntities(ModuleFile &Mod) const {
5037 if (PreprocessingRecord *PPRec = PP.getPreprocessingRecord())
5038 return PPRec->getIteratorsForLoadedRange(Mod.BasePreprocessedEntityID,
5039 Mod.NumPreprocessedEntities);
5040
Benjamin Kramerb4ef6682015-02-06 17:25:10 +00005041 return llvm::make_range(PreprocessingRecord::iterator(),
5042 PreprocessingRecord::iterator());
Guy Benyei11169dd2012-12-18 14:30:41 +00005043}
5044
Benjamin Kramerb4ef6682015-02-06 17:25:10 +00005045llvm::iterator_range<ASTReader::ModuleDeclIterator>
Guy Benyei11169dd2012-12-18 14:30:41 +00005046ASTReader::getModuleFileLevelDecls(ModuleFile &Mod) {
Benjamin Kramerb4ef6682015-02-06 17:25:10 +00005047 return llvm::make_range(
5048 ModuleDeclIterator(this, &Mod, Mod.FileSortedDecls),
5049 ModuleDeclIterator(this, &Mod,
5050 Mod.FileSortedDecls + Mod.NumFileSortedDecls));
Guy Benyei11169dd2012-12-18 14:30:41 +00005051}
5052
5053PreprocessedEntity *ASTReader::ReadPreprocessedEntity(unsigned Index) {
5054 PreprocessedEntityID PPID = Index+1;
5055 std::pair<ModuleFile *, unsigned> PPInfo = getModulePreprocessedEntity(Index);
5056 ModuleFile &M = *PPInfo.first;
5057 unsigned LocalIndex = PPInfo.second;
5058 const PPEntityOffset &PPOffs = M.PreprocessedEntityOffsets[LocalIndex];
5059
Guy Benyei11169dd2012-12-18 14:30:41 +00005060 if (!PP.getPreprocessingRecord()) {
5061 Error("no preprocessing record");
Craig Toppera13603a2014-05-22 05:54:18 +00005062 return nullptr;
Guy Benyei11169dd2012-12-18 14:30:41 +00005063 }
David L. Jonesc4808b9e2016-12-15 20:53:26 +00005064
5065 SavedStreamPosition SavedPosition(M.PreprocessorDetailCursor);
Chris Lattner7fb3bef2013-01-20 00:56:42 +00005066 M.PreprocessorDetailCursor.JumpToBit(PPOffs.BitOffset);
5067
5068 llvm::BitstreamEntry Entry =
5069 M.PreprocessorDetailCursor.advance(BitstreamCursor::AF_DontPopBlockAtEnd);
5070 if (Entry.Kind != llvm::BitstreamEntry::Record)
Craig Toppera13603a2014-05-22 05:54:18 +00005071 return nullptr;
Chris Lattner7fb3bef2013-01-20 00:56:42 +00005072
Guy Benyei11169dd2012-12-18 14:30:41 +00005073 // Read the record.
Richard Smithcb34bd32016-03-27 07:28:06 +00005074 SourceRange Range(TranslateSourceLocation(M, PPOffs.getBegin()),
5075 TranslateSourceLocation(M, PPOffs.getEnd()));
Guy Benyei11169dd2012-12-18 14:30:41 +00005076 PreprocessingRecord &PPRec = *PP.getPreprocessingRecord();
Chris Lattner0e6c9402013-01-20 02:38:54 +00005077 StringRef Blob;
Guy Benyei11169dd2012-12-18 14:30:41 +00005078 RecordData Record;
5079 PreprocessorDetailRecordTypes RecType =
Chris Lattner0e6c9402013-01-20 02:38:54 +00005080 (PreprocessorDetailRecordTypes)M.PreprocessorDetailCursor.readRecord(
5081 Entry.ID, Record, &Blob);
Guy Benyei11169dd2012-12-18 14:30:41 +00005082 switch (RecType) {
5083 case PPD_MACRO_EXPANSION: {
5084 bool isBuiltin = Record[0];
Craig Toppera13603a2014-05-22 05:54:18 +00005085 IdentifierInfo *Name = nullptr;
Richard Smith66a81862015-05-04 02:25:31 +00005086 MacroDefinitionRecord *Def = nullptr;
Guy Benyei11169dd2012-12-18 14:30:41 +00005087 if (isBuiltin)
5088 Name = getLocalIdentifier(M, Record[1]);
5089 else {
Richard Smith66a81862015-05-04 02:25:31 +00005090 PreprocessedEntityID GlobalID =
5091 getGlobalPreprocessedEntityID(M, Record[1]);
5092 Def = cast<MacroDefinitionRecord>(
5093 PPRec.getLoadedPreprocessedEntity(GlobalID - 1));
Guy Benyei11169dd2012-12-18 14:30:41 +00005094 }
5095
5096 MacroExpansion *ME;
5097 if (isBuiltin)
5098 ME = new (PPRec) MacroExpansion(Name, Range);
5099 else
5100 ME = new (PPRec) MacroExpansion(Def, Range);
5101
5102 return ME;
5103 }
David L. Jonesc4808b9e2016-12-15 20:53:26 +00005104
Guy Benyei11169dd2012-12-18 14:30:41 +00005105 case PPD_MACRO_DEFINITION: {
5106 // Decode the identifier info and then check again; if the macro is
5107 // still defined and associated with the identifier,
5108 IdentifierInfo *II = getLocalIdentifier(M, Record[0]);
Richard Smith66a81862015-05-04 02:25:31 +00005109 MacroDefinitionRecord *MD = new (PPRec) MacroDefinitionRecord(II, Range);
Guy Benyei11169dd2012-12-18 14:30:41 +00005110
5111 if (DeserializationListener)
5112 DeserializationListener->MacroDefinitionRead(PPID, MD);
5113
5114 return MD;
5115 }
David L. Jonesc4808b9e2016-12-15 20:53:26 +00005116
Guy Benyei11169dd2012-12-18 14:30:41 +00005117 case PPD_INCLUSION_DIRECTIVE: {
Chris Lattner0e6c9402013-01-20 02:38:54 +00005118 const char *FullFileNameStart = Blob.data() + Record[0];
5119 StringRef FullFileName(FullFileNameStart, Blob.size() - Record[0]);
Craig Toppera13603a2014-05-22 05:54:18 +00005120 const FileEntry *File = nullptr;
Guy Benyei11169dd2012-12-18 14:30:41 +00005121 if (!FullFileName.empty())
5122 File = PP.getFileManager().getFile(FullFileName);
David L. Jonesc4808b9e2016-12-15 20:53:26 +00005123
Guy Benyei11169dd2012-12-18 14:30:41 +00005124 // FIXME: Stable encoding
5125 InclusionDirective::InclusionKind Kind
5126 = static_cast<InclusionDirective::InclusionKind>(Record[2]);
5127 InclusionDirective *ID
5128 = new (PPRec) InclusionDirective(PPRec, Kind,
Chris Lattner0e6c9402013-01-20 02:38:54 +00005129 StringRef(Blob.data(), Record[0]),
Guy Benyei11169dd2012-12-18 14:30:41 +00005130 Record[1], Record[3],
5131 File,
5132 Range);
5133 return ID;
5134 }
5135 }
5136
5137 llvm_unreachable("Invalid PreprocessorDetailRecordTypes");
5138}
5139
5140/// \brief \arg SLocMapI points at a chunk of a module that contains no
5141/// preprocessed entities or the entities it contains are not the ones we are
5142/// looking for. Find the next module that contains entities and return the ID
5143/// of the first entry.
5144PreprocessedEntityID ASTReader::findNextPreprocessedEntity(
5145 GlobalSLocOffsetMapType::const_iterator SLocMapI) const {
5146 ++SLocMapI;
5147 for (GlobalSLocOffsetMapType::const_iterator
5148 EndI = GlobalSLocOffsetMap.end(); SLocMapI != EndI; ++SLocMapI) {
5149 ModuleFile &M = *SLocMapI->second;
5150 if (M.NumPreprocessedEntities)
5151 return M.BasePreprocessedEntityID;
5152 }
5153
5154 return getTotalNumPreprocessedEntities();
5155}
5156
5157namespace {
5158
Guy Benyei11169dd2012-12-18 14:30:41 +00005159struct PPEntityComp {
5160 const ASTReader &Reader;
5161 ModuleFile &M;
5162
5163 PPEntityComp(const ASTReader &Reader, ModuleFile &M) : Reader(Reader), M(M) { }
5164
5165 bool operator()(const PPEntityOffset &L, const PPEntityOffset &R) const {
5166 SourceLocation LHS = getLoc(L);
5167 SourceLocation RHS = getLoc(R);
5168 return Reader.getSourceManager().isBeforeInTranslationUnit(LHS, RHS);
5169 }
5170
5171 bool operator()(const PPEntityOffset &L, SourceLocation RHS) const {
5172 SourceLocation LHS = getLoc(L);
5173 return Reader.getSourceManager().isBeforeInTranslationUnit(LHS, RHS);
5174 }
5175
5176 bool operator()(SourceLocation LHS, const PPEntityOffset &R) const {
5177 SourceLocation RHS = getLoc(R);
5178 return Reader.getSourceManager().isBeforeInTranslationUnit(LHS, RHS);
5179 }
5180
5181 SourceLocation getLoc(const PPEntityOffset &PPE) const {
Richard Smithb22a1d12016-03-27 20:13:24 +00005182 return Reader.TranslateSourceLocation(M, PPE.getBegin());
Guy Benyei11169dd2012-12-18 14:30:41 +00005183 }
5184};
5185
Eugene Zelenkoe95e7d52016-09-07 21:53:17 +00005186} // end anonymous namespace
Guy Benyei11169dd2012-12-18 14:30:41 +00005187
Alp Toker2e9ce4c2014-05-16 18:59:21 +00005188PreprocessedEntityID ASTReader::findPreprocessedEntity(SourceLocation Loc,
5189 bool EndsAfter) const {
5190 if (SourceMgr.isLocalSourceLocation(Loc))
Guy Benyei11169dd2012-12-18 14:30:41 +00005191 return getTotalNumPreprocessedEntities();
5192
Alp Toker2e9ce4c2014-05-16 18:59:21 +00005193 GlobalSLocOffsetMapType::const_iterator SLocMapI = GlobalSLocOffsetMap.find(
5194 SourceManager::MaxLoadedOffset - Loc.getOffset() - 1);
Guy Benyei11169dd2012-12-18 14:30:41 +00005195 assert(SLocMapI != GlobalSLocOffsetMap.end() &&
5196 "Corrupted global sloc offset map");
5197
5198 if (SLocMapI->second->NumPreprocessedEntities == 0)
5199 return findNextPreprocessedEntity(SLocMapI);
5200
5201 ModuleFile &M = *SLocMapI->second;
5202 typedef const PPEntityOffset *pp_iterator;
5203 pp_iterator pp_begin = M.PreprocessedEntityOffsets;
5204 pp_iterator pp_end = pp_begin + M.NumPreprocessedEntities;
5205
5206 size_t Count = M.NumPreprocessedEntities;
5207 size_t Half;
5208 pp_iterator First = pp_begin;
5209 pp_iterator PPI;
5210
Alp Toker2e9ce4c2014-05-16 18:59:21 +00005211 if (EndsAfter) {
5212 PPI = std::upper_bound(pp_begin, pp_end, Loc,
Richard Smithb22a1d12016-03-27 20:13:24 +00005213 PPEntityComp(*this, M));
Alp Toker2e9ce4c2014-05-16 18:59:21 +00005214 } else {
5215 // Do a binary search manually instead of using std::lower_bound because
5216 // The end locations of entities may be unordered (when a macro expansion
5217 // is inside another macro argument), but for this case it is not important
5218 // whether we get the first macro expansion or its containing macro.
5219 while (Count > 0) {
5220 Half = Count / 2;
5221 PPI = First;
5222 std::advance(PPI, Half);
Richard Smithb22a1d12016-03-27 20:13:24 +00005223 if (SourceMgr.isBeforeInTranslationUnit(
5224 TranslateSourceLocation(M, PPI->getEnd()), Loc)) {
Alp Toker2e9ce4c2014-05-16 18:59:21 +00005225 First = PPI;
5226 ++First;
5227 Count = Count - Half - 1;
5228 } else
5229 Count = Half;
5230 }
Guy Benyei11169dd2012-12-18 14:30:41 +00005231 }
5232
5233 if (PPI == pp_end)
5234 return findNextPreprocessedEntity(SLocMapI);
5235
5236 return M.BasePreprocessedEntityID + (PPI - pp_begin);
5237}
5238
Guy Benyei11169dd2012-12-18 14:30:41 +00005239/// \brief Returns a pair of [Begin, End) indices of preallocated
5240/// preprocessed entities that \arg Range encompasses.
5241std::pair<unsigned, unsigned>
5242 ASTReader::findPreprocessedEntitiesInRange(SourceRange Range) {
5243 if (Range.isInvalid())
5244 return std::make_pair(0,0);
5245 assert(!SourceMgr.isBeforeInTranslationUnit(Range.getEnd(),Range.getBegin()));
5246
Alp Toker2e9ce4c2014-05-16 18:59:21 +00005247 PreprocessedEntityID BeginID =
5248 findPreprocessedEntity(Range.getBegin(), false);
5249 PreprocessedEntityID EndID = findPreprocessedEntity(Range.getEnd(), true);
Guy Benyei11169dd2012-12-18 14:30:41 +00005250 return std::make_pair(BeginID, EndID);
5251}
5252
5253/// \brief Optionally returns true or false if the preallocated preprocessed
5254/// entity with index \arg Index came from file \arg FID.
David Blaikie05785d12013-02-20 22:23:23 +00005255Optional<bool> ASTReader::isPreprocessedEntityInFileID(unsigned Index,
Guy Benyei11169dd2012-12-18 14:30:41 +00005256 FileID FID) {
5257 if (FID.isInvalid())
5258 return false;
5259
5260 std::pair<ModuleFile *, unsigned> PPInfo = getModulePreprocessedEntity(Index);
5261 ModuleFile &M = *PPInfo.first;
5262 unsigned LocalIndex = PPInfo.second;
5263 const PPEntityOffset &PPOffs = M.PreprocessedEntityOffsets[LocalIndex];
David L. Jonesc4808b9e2016-12-15 20:53:26 +00005264
Richard Smithcb34bd32016-03-27 07:28:06 +00005265 SourceLocation Loc = TranslateSourceLocation(M, PPOffs.getBegin());
Guy Benyei11169dd2012-12-18 14:30:41 +00005266 if (Loc.isInvalid())
5267 return false;
David L. Jonesc4808b9e2016-12-15 20:53:26 +00005268
Guy Benyei11169dd2012-12-18 14:30:41 +00005269 if (SourceMgr.isInFileID(SourceMgr.getFileLoc(Loc), FID))
5270 return true;
5271 else
5272 return false;
5273}
5274
5275namespace {
Eugene Zelenkoe95e7d52016-09-07 21:53:17 +00005276
Guy Benyei11169dd2012-12-18 14:30:41 +00005277 /// \brief Visitor used to search for information about a header file.
5278 class HeaderFileInfoVisitor {
Guy Benyei11169dd2012-12-18 14:30:41 +00005279 const FileEntry *FE;
David L. Jonesc4808b9e2016-12-15 20:53:26 +00005280
David Blaikie05785d12013-02-20 22:23:23 +00005281 Optional<HeaderFileInfo> HFI;
David L. Jonesc4808b9e2016-12-15 20:53:26 +00005282
Guy Benyei11169dd2012-12-18 14:30:41 +00005283 public:
Argyrios Kyrtzidis61a38962013-03-06 18:12:44 +00005284 explicit HeaderFileInfoVisitor(const FileEntry *FE)
5285 : FE(FE) { }
Benjamin Kramer9a9efba2015-07-25 12:14:04 +00005286
5287 bool operator()(ModuleFile &M) {
Guy Benyei11169dd2012-12-18 14:30:41 +00005288 HeaderFileInfoLookupTable *Table
5289 = static_cast<HeaderFileInfoLookupTable *>(M.HeaderFileInfoTable);
5290 if (!Table)
5291 return false;
5292
5293 // Look in the on-disk hash table for an entry for this file name.
Richard Smithbdf2d932015-07-30 03:37:16 +00005294 HeaderFileInfoLookupTable::iterator Pos = Table->find(FE);
Guy Benyei11169dd2012-12-18 14:30:41 +00005295 if (Pos == Table->end())
5296 return false;
5297
Richard Smithbdf2d932015-07-30 03:37:16 +00005298 HFI = *Pos;
Guy Benyei11169dd2012-12-18 14:30:41 +00005299 return true;
5300 }
David L. Jonesc4808b9e2016-12-15 20:53:26 +00005301
David Blaikie05785d12013-02-20 22:23:23 +00005302 Optional<HeaderFileInfo> getHeaderFileInfo() const { return HFI; }
Guy Benyei11169dd2012-12-18 14:30:41 +00005303 };
Eugene Zelenkoe95e7d52016-09-07 21:53:17 +00005304
5305} // end anonymous namespace
Guy Benyei11169dd2012-12-18 14:30:41 +00005306
5307HeaderFileInfo ASTReader::GetHeaderFileInfo(const FileEntry *FE) {
Argyrios Kyrtzidis61a38962013-03-06 18:12:44 +00005308 HeaderFileInfoVisitor Visitor(FE);
Benjamin Kramer9a9efba2015-07-25 12:14:04 +00005309 ModuleMgr.visit(Visitor);
Argyrios Kyrtzidis1054bbf2013-05-08 23:46:55 +00005310 if (Optional<HeaderFileInfo> HFI = Visitor.getHeaderFileInfo())
Guy Benyei11169dd2012-12-18 14:30:41 +00005311 return *HFI;
David L. Jonesc4808b9e2016-12-15 20:53:26 +00005312
Guy Benyei11169dd2012-12-18 14:30:41 +00005313 return HeaderFileInfo();
5314}
5315
5316void ASTReader::ReadPragmaDiagnosticMappings(DiagnosticsEngine &Diag) {
Richard Smithd230de22017-01-26 01:01:01 +00005317 using DiagState = DiagnosticsEngine::DiagState;
5318 SmallVector<DiagState *, 32> DiagStates;
5319
Duncan P. N. Exon Smith96a06e02017-01-28 22:15:22 +00005320 for (ModuleFile &F : ModuleMgr) {
Guy Benyei11169dd2012-12-18 14:30:41 +00005321 unsigned Idx = 0;
Richard Smithd230de22017-01-26 01:01:01 +00005322 auto &Record = F.PragmaDiagMappings;
5323 if (Record.empty())
5324 continue;
David L. Jonesc4808b9e2016-12-15 20:53:26 +00005325
Richard Smithd230de22017-01-26 01:01:01 +00005326 DiagStates.clear();
5327
5328 auto ReadDiagState =
5329 [&](const DiagState &BasedOn, SourceLocation Loc,
5330 bool IncludeNonPragmaStates) -> DiagnosticsEngine::DiagState * {
5331 unsigned BackrefID = Record[Idx++];
5332 if (BackrefID != 0)
5333 return DiagStates[BackrefID - 1];
5334
Guy Benyei11169dd2012-12-18 14:30:41 +00005335 // A new DiagState was created here.
Richard Smithd230de22017-01-26 01:01:01 +00005336 Diag.DiagStates.push_back(BasedOn);
5337 DiagState *NewState = &Diag.DiagStates.back();
Guy Benyei11169dd2012-12-18 14:30:41 +00005338 DiagStates.push_back(NewState);
Richard Smithd230de22017-01-26 01:01:01 +00005339 while (Idx + 1 < Record.size() && Record[Idx] != unsigned(-1)) {
5340 unsigned DiagID = Record[Idx++];
5341 diag::Severity Map = (diag::Severity)Record[Idx++];
Alp Tokerc726c362014-06-10 09:31:37 +00005342 DiagnosticMapping Mapping = Diag.makeUserMapping(Map, Loc);
Richard Smithd230de22017-01-26 01:01:01 +00005343 if (Mapping.isPragma() || IncludeNonPragmaStates)
5344 NewState->setMapping(DiagID, Mapping);
5345 }
5346 assert(Idx != Record.size() && Record[Idx] == unsigned(-1) &&
5347 "Invalid data, didn't find '-1' marking end of diag/map pairs");
5348 ++Idx;
5349 return NewState;
5350 };
5351
5352 auto *FirstState = ReadDiagState(
5353 F.isModule() ? DiagState() : *Diag.DiagStatesByLoc.CurDiagState,
5354 SourceLocation(), F.isModule());
5355 SourceLocation CurStateLoc =
5356 ReadSourceLocation(F, F.PragmaDiagMappings[Idx++]);
5357 auto *CurState = ReadDiagState(*FirstState, CurStateLoc, false);
5358
5359 if (!F.isModule()) {
5360 Diag.DiagStatesByLoc.CurDiagState = CurState;
5361 Diag.DiagStatesByLoc.CurDiagStateLoc = CurStateLoc;
5362
5363 // Preserve the property that the imaginary root file describes the
5364 // current state.
5365 auto &T = Diag.DiagStatesByLoc.Files[FileID()].StateTransitions;
5366 if (T.empty())
5367 T.push_back({CurState, 0});
5368 else
5369 T[0].State = CurState;
5370 }
5371
5372 while (Idx < Record.size()) {
5373 SourceLocation Loc = ReadSourceLocation(F, Record[Idx++]);
5374 auto IDAndOffset = SourceMgr.getDecomposedLoc(Loc);
5375 assert(IDAndOffset.second == 0 && "not a start location for a FileID");
5376 unsigned Transitions = Record[Idx++];
5377
5378 // Note that we don't need to set up Parent/ParentOffset here, because
5379 // we won't be changing the diagnostic state within imported FileIDs
5380 // (other than perhaps appending to the main source file, which has no
5381 // parent).
5382 auto &F = Diag.DiagStatesByLoc.Files[IDAndOffset.first];
5383 F.StateTransitions.reserve(F.StateTransitions.size() + Transitions);
5384 for (unsigned I = 0; I != Transitions; ++I) {
5385 unsigned Offset = Record[Idx++];
5386 auto *State =
5387 ReadDiagState(*FirstState, Loc.getLocWithOffset(Offset), false);
5388 F.StateTransitions.push_back({State, Offset});
Guy Benyei11169dd2012-12-18 14:30:41 +00005389 }
5390 }
Richard Smithd230de22017-01-26 01:01:01 +00005391
5392 // Don't try to read these mappings again.
5393 Record.clear();
Guy Benyei11169dd2012-12-18 14:30:41 +00005394 }
5395}
5396
5397/// \brief Get the correct cursor and offset for loading a type.
5398ASTReader::RecordLocation ASTReader::TypeCursorForIndex(unsigned Index) {
5399 GlobalTypeMapType::iterator I = GlobalTypeMap.find(Index);
5400 assert(I != GlobalTypeMap.end() && "Corrupted global type map");
5401 ModuleFile *M = I->second;
5402 return RecordLocation(M, M->TypeOffsets[Index - M->BaseTypeIndex]);
5403}
5404
5405/// \brief Read and return the type with the given index..
5406///
5407/// The index is the type ID, shifted and minus the number of predefs. This
5408/// routine actually reads the record corresponding to the type at the given
5409/// location. It is a helper routine for GetType, which deals with reading type
5410/// IDs.
5411QualType ASTReader::readTypeRecord(unsigned Index) {
5412 RecordLocation Loc = TypeCursorForIndex(Index);
Chris Lattner7fb3bef2013-01-20 00:56:42 +00005413 BitstreamCursor &DeclsCursor = Loc.F->DeclsCursor;
Guy Benyei11169dd2012-12-18 14:30:41 +00005414
5415 // Keep track of where we are in the stream, then jump back there
5416 // after reading this type.
5417 SavedStreamPosition SavedPosition(DeclsCursor);
5418
5419 ReadingKindTracker ReadingKind(Read_Type, *this);
5420
5421 // Note that we are loading a type record.
5422 Deserializing AType(this);
5423
5424 unsigned Idx = 0;
5425 DeclsCursor.JumpToBit(Loc.Offset);
5426 RecordData Record;
5427 unsigned Code = DeclsCursor.ReadCode();
Chris Lattner0e6c9402013-01-20 02:38:54 +00005428 switch ((TypeCode)DeclsCursor.readRecord(Code, Record)) {
Guy Benyei11169dd2012-12-18 14:30:41 +00005429 case TYPE_EXT_QUAL: {
5430 if (Record.size() != 2) {
5431 Error("Incorrect encoding of extended qualifier type");
5432 return QualType();
5433 }
5434 QualType Base = readType(*Loc.F, Record, Idx);
5435 Qualifiers Quals = Qualifiers::fromOpaqueValue(Record[Idx++]);
5436 return Context.getQualifiedType(Base, Quals);
5437 }
5438
5439 case TYPE_COMPLEX: {
5440 if (Record.size() != 1) {
5441 Error("Incorrect encoding of complex type");
5442 return QualType();
5443 }
5444 QualType ElemType = readType(*Loc.F, Record, Idx);
5445 return Context.getComplexType(ElemType);
5446 }
5447
5448 case TYPE_POINTER: {
5449 if (Record.size() != 1) {
5450 Error("Incorrect encoding of pointer type");
5451 return QualType();
5452 }
5453 QualType PointeeType = readType(*Loc.F, Record, Idx);
5454 return Context.getPointerType(PointeeType);
5455 }
5456
Reid Kleckner8a365022013-06-24 17:51:48 +00005457 case TYPE_DECAYED: {
5458 if (Record.size() != 1) {
5459 Error("Incorrect encoding of decayed type");
5460 return QualType();
5461 }
5462 QualType OriginalType = readType(*Loc.F, Record, Idx);
5463 QualType DT = Context.getAdjustedParameterType(OriginalType);
5464 if (!isa<DecayedType>(DT))
5465 Error("Decayed type does not decay");
5466 return DT;
5467 }
5468
Reid Kleckner0503a872013-12-05 01:23:43 +00005469 case TYPE_ADJUSTED: {
5470 if (Record.size() != 2) {
5471 Error("Incorrect encoding of adjusted type");
5472 return QualType();
5473 }
5474 QualType OriginalTy = readType(*Loc.F, Record, Idx);
5475 QualType AdjustedTy = readType(*Loc.F, Record, Idx);
5476 return Context.getAdjustedType(OriginalTy, AdjustedTy);
5477 }
5478
Guy Benyei11169dd2012-12-18 14:30:41 +00005479 case TYPE_BLOCK_POINTER: {
5480 if (Record.size() != 1) {
5481 Error("Incorrect encoding of block pointer type");
5482 return QualType();
5483 }
5484 QualType PointeeType = readType(*Loc.F, Record, Idx);
5485 return Context.getBlockPointerType(PointeeType);
5486 }
5487
5488 case TYPE_LVALUE_REFERENCE: {
5489 if (Record.size() != 2) {
5490 Error("Incorrect encoding of lvalue reference type");
5491 return QualType();
5492 }
5493 QualType PointeeType = readType(*Loc.F, Record, Idx);
5494 return Context.getLValueReferenceType(PointeeType, Record[1]);
5495 }
5496
5497 case TYPE_RVALUE_REFERENCE: {
5498 if (Record.size() != 1) {
5499 Error("Incorrect encoding of rvalue reference type");
5500 return QualType();
5501 }
5502 QualType PointeeType = readType(*Loc.F, Record, Idx);
5503 return Context.getRValueReferenceType(PointeeType);
5504 }
5505
5506 case TYPE_MEMBER_POINTER: {
5507 if (Record.size() != 2) {
5508 Error("Incorrect encoding of member pointer type");
5509 return QualType();
5510 }
5511 QualType PointeeType = readType(*Loc.F, Record, Idx);
5512 QualType ClassType = readType(*Loc.F, Record, Idx);
5513 if (PointeeType.isNull() || ClassType.isNull())
5514 return QualType();
David L. Jonesc4808b9e2016-12-15 20:53:26 +00005515
Guy Benyei11169dd2012-12-18 14:30:41 +00005516 return Context.getMemberPointerType(PointeeType, ClassType.getTypePtr());
5517 }
5518
5519 case TYPE_CONSTANT_ARRAY: {
5520 QualType ElementType = readType(*Loc.F, Record, Idx);
5521 ArrayType::ArraySizeModifier ASM = (ArrayType::ArraySizeModifier)Record[1];
5522 unsigned IndexTypeQuals = Record[2];
5523 unsigned Idx = 3;
5524 llvm::APInt Size = ReadAPInt(Record, Idx);
5525 return Context.getConstantArrayType(ElementType, Size,
5526 ASM, IndexTypeQuals);
5527 }
5528
5529 case TYPE_INCOMPLETE_ARRAY: {
5530 QualType ElementType = readType(*Loc.F, Record, Idx);
5531 ArrayType::ArraySizeModifier ASM = (ArrayType::ArraySizeModifier)Record[1];
5532 unsigned IndexTypeQuals = Record[2];
5533 return Context.getIncompleteArrayType(ElementType, ASM, IndexTypeQuals);
5534 }
5535
5536 case TYPE_VARIABLE_ARRAY: {
5537 QualType ElementType = readType(*Loc.F, Record, Idx);
5538 ArrayType::ArraySizeModifier ASM = (ArrayType::ArraySizeModifier)Record[1];
5539 unsigned IndexTypeQuals = Record[2];
5540 SourceLocation LBLoc = ReadSourceLocation(*Loc.F, Record[3]);
5541 SourceLocation RBLoc = ReadSourceLocation(*Loc.F, Record[4]);
5542 return Context.getVariableArrayType(ElementType, ReadExpr(*Loc.F),
5543 ASM, IndexTypeQuals,
5544 SourceRange(LBLoc, RBLoc));
5545 }
5546
5547 case TYPE_VECTOR: {
5548 if (Record.size() != 3) {
5549 Error("incorrect encoding of vector type in AST file");
5550 return QualType();
5551 }
5552
5553 QualType ElementType = readType(*Loc.F, Record, Idx);
5554 unsigned NumElements = Record[1];
5555 unsigned VecKind = Record[2];
5556 return Context.getVectorType(ElementType, NumElements,
5557 (VectorType::VectorKind)VecKind);
5558 }
5559
5560 case TYPE_EXT_VECTOR: {
5561 if (Record.size() != 3) {
5562 Error("incorrect encoding of extended vector type in AST file");
5563 return QualType();
5564 }
5565
5566 QualType ElementType = readType(*Loc.F, Record, Idx);
5567 unsigned NumElements = Record[1];
5568 return Context.getExtVectorType(ElementType, NumElements);
5569 }
5570
5571 case TYPE_FUNCTION_NO_PROTO: {
5572 if (Record.size() != 6) {
5573 Error("incorrect encoding of no-proto function type");
5574 return QualType();
5575 }
5576 QualType ResultType = readType(*Loc.F, Record, Idx);
5577 FunctionType::ExtInfo Info(Record[1], Record[2], Record[3],
5578 (CallingConv)Record[4], Record[5]);
5579 return Context.getFunctionNoProtoType(ResultType, Info);
5580 }
5581
5582 case TYPE_FUNCTION_PROTO: {
5583 QualType ResultType = readType(*Loc.F, Record, Idx);
5584
5585 FunctionProtoType::ExtProtoInfo EPI;
5586 EPI.ExtInfo = FunctionType::ExtInfo(/*noreturn*/ Record[1],
5587 /*hasregparm*/ Record[2],
5588 /*regparm*/ Record[3],
5589 static_cast<CallingConv>(Record[4]),
5590 /*produces*/ Record[5]);
5591
5592 unsigned Idx = 6;
Guy Benyei11169dd2012-12-18 14:30:41 +00005593
5594 EPI.Variadic = Record[Idx++];
5595 EPI.HasTrailingReturn = Record[Idx++];
5596 EPI.TypeQuals = Record[Idx++];
5597 EPI.RefQualifier = static_cast<RefQualifierKind>(Record[Idx++]);
Richard Smith564417a2014-03-20 21:47:22 +00005598 SmallVector<QualType, 8> ExceptionStorage;
Richard Smith8acb4282014-07-31 21:57:55 +00005599 readExceptionSpec(*Loc.F, ExceptionStorage, EPI.ExceptionSpec, Record, Idx);
Richard Smith01b2cb42014-07-26 06:37:51 +00005600
5601 unsigned NumParams = Record[Idx++];
5602 SmallVector<QualType, 16> ParamTypes;
5603 for (unsigned I = 0; I != NumParams; ++I)
5604 ParamTypes.push_back(readType(*Loc.F, Record, Idx));
5605
John McCall18afab72016-03-01 00:49:02 +00005606 SmallVector<FunctionProtoType::ExtParameterInfo, 4> ExtParameterInfos;
5607 if (Idx != Record.size()) {
5608 for (unsigned I = 0; I != NumParams; ++I)
5609 ExtParameterInfos.push_back(
5610 FunctionProtoType::ExtParameterInfo
5611 ::getFromOpaqueValue(Record[Idx++]));
5612 EPI.ExtParameterInfos = ExtParameterInfos.data();
5613 }
5614
5615 assert(Idx == Record.size());
5616
Jordan Rose5c382722013-03-08 21:51:21 +00005617 return Context.getFunctionType(ResultType, ParamTypes, EPI);
Guy Benyei11169dd2012-12-18 14:30:41 +00005618 }
5619
5620 case TYPE_UNRESOLVED_USING: {
5621 unsigned Idx = 0;
5622 return Context.getTypeDeclType(
5623 ReadDeclAs<UnresolvedUsingTypenameDecl>(*Loc.F, Record, Idx));
5624 }
David L. Jonesc4808b9e2016-12-15 20:53:26 +00005625
Guy Benyei11169dd2012-12-18 14:30:41 +00005626 case TYPE_TYPEDEF: {
5627 if (Record.size() != 2) {
5628 Error("incorrect encoding of typedef type");
5629 return QualType();
5630 }
5631 unsigned Idx = 0;
5632 TypedefNameDecl *Decl = ReadDeclAs<TypedefNameDecl>(*Loc.F, Record, Idx);
5633 QualType Canonical = readType(*Loc.F, Record, Idx);
5634 if (!Canonical.isNull())
5635 Canonical = Context.getCanonicalType(Canonical);
5636 return Context.getTypedefType(Decl, Canonical);
5637 }
5638
5639 case TYPE_TYPEOF_EXPR:
5640 return Context.getTypeOfExprType(ReadExpr(*Loc.F));
5641
5642 case TYPE_TYPEOF: {
5643 if (Record.size() != 1) {
5644 Error("incorrect encoding of typeof(type) in AST file");
5645 return QualType();
5646 }
5647 QualType UnderlyingType = readType(*Loc.F, Record, Idx);
5648 return Context.getTypeOfType(UnderlyingType);
5649 }
5650
5651 case TYPE_DECLTYPE: {
5652 QualType UnderlyingType = readType(*Loc.F, Record, Idx);
5653 return Context.getDecltypeType(ReadExpr(*Loc.F), UnderlyingType);
5654 }
5655
5656 case TYPE_UNARY_TRANSFORM: {
5657 QualType BaseType = readType(*Loc.F, Record, Idx);
5658 QualType UnderlyingType = readType(*Loc.F, Record, Idx);
5659 UnaryTransformType::UTTKind UKind = (UnaryTransformType::UTTKind)Record[2];
5660 return Context.getUnaryTransformType(BaseType, UnderlyingType, UKind);
5661 }
5662
Richard Smith74aeef52013-04-26 16:15:35 +00005663 case TYPE_AUTO: {
5664 QualType Deduced = readType(*Loc.F, Record, Idx);
Richard Smithe301ba22015-11-11 02:02:15 +00005665 AutoTypeKeyword Keyword = (AutoTypeKeyword)Record[Idx++];
Richard Smith27d807c2013-04-30 13:56:41 +00005666 bool IsDependent = Deduced.isNull() ? Record[Idx++] : false;
Richard Smithe301ba22015-11-11 02:02:15 +00005667 return Context.getAutoType(Deduced, Keyword, IsDependent);
Richard Smith74aeef52013-04-26 16:15:35 +00005668 }
Guy Benyei11169dd2012-12-18 14:30:41 +00005669
Richard Smith600b5262017-01-26 20:40:47 +00005670 case TYPE_DEDUCED_TEMPLATE_SPECIALIZATION: {
5671 TemplateName Name = ReadTemplateName(*Loc.F, Record, Idx);
5672 QualType Deduced = readType(*Loc.F, Record, Idx);
5673 bool IsDependent = Deduced.isNull() ? Record[Idx++] : false;
5674 return Context.getDeducedTemplateSpecializationType(Name, Deduced,
5675 IsDependent);
5676 }
5677
Guy Benyei11169dd2012-12-18 14:30:41 +00005678 case TYPE_RECORD: {
5679 if (Record.size() != 2) {
5680 Error("incorrect encoding of record type");
5681 return QualType();
5682 }
5683 unsigned Idx = 0;
5684 bool IsDependent = Record[Idx++];
5685 RecordDecl *RD = ReadDeclAs<RecordDecl>(*Loc.F, Record, Idx);
5686 RD = cast_or_null<RecordDecl>(RD->getCanonicalDecl());
5687 QualType T = Context.getRecordType(RD);
5688 const_cast<Type*>(T.getTypePtr())->setDependent(IsDependent);
5689 return T;
5690 }
5691
5692 case TYPE_ENUM: {
5693 if (Record.size() != 2) {
5694 Error("incorrect encoding of enum type");
5695 return QualType();
5696 }
5697 unsigned Idx = 0;
5698 bool IsDependent = Record[Idx++];
5699 QualType T
5700 = Context.getEnumType(ReadDeclAs<EnumDecl>(*Loc.F, Record, Idx));
5701 const_cast<Type*>(T.getTypePtr())->setDependent(IsDependent);
5702 return T;
5703 }
5704
5705 case TYPE_ATTRIBUTED: {
5706 if (Record.size() != 3) {
5707 Error("incorrect encoding of attributed type");
5708 return QualType();
5709 }
5710 QualType modifiedType = readType(*Loc.F, Record, Idx);
5711 QualType equivalentType = readType(*Loc.F, Record, Idx);
5712 AttributedType::Kind kind = static_cast<AttributedType::Kind>(Record[2]);
5713 return Context.getAttributedType(kind, modifiedType, equivalentType);
5714 }
5715
5716 case TYPE_PAREN: {
5717 if (Record.size() != 1) {
5718 Error("incorrect encoding of paren type");
5719 return QualType();
5720 }
5721 QualType InnerType = readType(*Loc.F, Record, Idx);
5722 return Context.getParenType(InnerType);
5723 }
5724
5725 case TYPE_PACK_EXPANSION: {
5726 if (Record.size() != 2) {
5727 Error("incorrect encoding of pack expansion type");
5728 return QualType();
5729 }
5730 QualType Pattern = readType(*Loc.F, Record, Idx);
5731 if (Pattern.isNull())
5732 return QualType();
David Blaikie05785d12013-02-20 22:23:23 +00005733 Optional<unsigned> NumExpansions;
Guy Benyei11169dd2012-12-18 14:30:41 +00005734 if (Record[1])
5735 NumExpansions = Record[1] - 1;
5736 return Context.getPackExpansionType(Pattern, NumExpansions);
5737 }
5738
5739 case TYPE_ELABORATED: {
5740 unsigned Idx = 0;
5741 ElaboratedTypeKeyword Keyword = (ElaboratedTypeKeyword)Record[Idx++];
5742 NestedNameSpecifier *NNS = ReadNestedNameSpecifier(*Loc.F, Record, Idx);
5743 QualType NamedType = readType(*Loc.F, Record, Idx);
5744 return Context.getElaboratedType(Keyword, NNS, NamedType);
5745 }
5746
5747 case TYPE_OBJC_INTERFACE: {
5748 unsigned Idx = 0;
5749 ObjCInterfaceDecl *ItfD
5750 = ReadDeclAs<ObjCInterfaceDecl>(*Loc.F, Record, Idx);
5751 return Context.getObjCInterfaceType(ItfD->getCanonicalDecl());
5752 }
5753
Manman Rene6be26c2016-09-13 17:25:08 +00005754 case TYPE_OBJC_TYPE_PARAM: {
5755 unsigned Idx = 0;
5756 ObjCTypeParamDecl *Decl
5757 = ReadDeclAs<ObjCTypeParamDecl>(*Loc.F, Record, Idx);
5758 unsigned NumProtos = Record[Idx++];
5759 SmallVector<ObjCProtocolDecl*, 4> Protos;
5760 for (unsigned I = 0; I != NumProtos; ++I)
5761 Protos.push_back(ReadDeclAs<ObjCProtocolDecl>(*Loc.F, Record, Idx));
5762 return Context.getObjCTypeParamType(Decl, Protos);
5763 }
Guy Benyei11169dd2012-12-18 14:30:41 +00005764 case TYPE_OBJC_OBJECT: {
5765 unsigned Idx = 0;
5766 QualType Base = readType(*Loc.F, Record, Idx);
Douglas Gregore9d95f12015-07-07 03:57:35 +00005767 unsigned NumTypeArgs = Record[Idx++];
5768 SmallVector<QualType, 4> TypeArgs;
5769 for (unsigned I = 0; I != NumTypeArgs; ++I)
5770 TypeArgs.push_back(readType(*Loc.F, Record, Idx));
Guy Benyei11169dd2012-12-18 14:30:41 +00005771 unsigned NumProtos = Record[Idx++];
5772 SmallVector<ObjCProtocolDecl*, 4> Protos;
5773 for (unsigned I = 0; I != NumProtos; ++I)
5774 Protos.push_back(ReadDeclAs<ObjCProtocolDecl>(*Loc.F, Record, Idx));
Douglas Gregorab209d82015-07-07 03:58:42 +00005775 bool IsKindOf = Record[Idx++];
5776 return Context.getObjCObjectType(Base, TypeArgs, Protos, IsKindOf);
Guy Benyei11169dd2012-12-18 14:30:41 +00005777 }
5778
5779 case TYPE_OBJC_OBJECT_POINTER: {
5780 unsigned Idx = 0;
5781 QualType Pointee = readType(*Loc.F, Record, Idx);
5782 return Context.getObjCObjectPointerType(Pointee);
5783 }
5784
5785 case TYPE_SUBST_TEMPLATE_TYPE_PARM: {
5786 unsigned Idx = 0;
5787 QualType Parm = readType(*Loc.F, Record, Idx);
5788 QualType Replacement = readType(*Loc.F, Record, Idx);
Stephan Tolksdorfe96f8b32014-03-15 10:23:27 +00005789 return Context.getSubstTemplateTypeParmType(
5790 cast<TemplateTypeParmType>(Parm),
5791 Context.getCanonicalType(Replacement));
Guy Benyei11169dd2012-12-18 14:30:41 +00005792 }
5793
5794 case TYPE_SUBST_TEMPLATE_TYPE_PARM_PACK: {
5795 unsigned Idx = 0;
5796 QualType Parm = readType(*Loc.F, Record, Idx);
5797 TemplateArgument ArgPack = ReadTemplateArgument(*Loc.F, Record, Idx);
5798 return Context.getSubstTemplateTypeParmPackType(
5799 cast<TemplateTypeParmType>(Parm),
5800 ArgPack);
5801 }
5802
5803 case TYPE_INJECTED_CLASS_NAME: {
5804 CXXRecordDecl *D = ReadDeclAs<CXXRecordDecl>(*Loc.F, Record, Idx);
5805 QualType TST = readType(*Loc.F, Record, Idx); // probably derivable
5806 // FIXME: ASTContext::getInjectedClassNameType is not currently suitable
5807 // for AST reading, too much interdependencies.
Richard Smith6377f8f2014-10-21 21:15:18 +00005808 const Type *T = nullptr;
5809 for (auto *DI = D; DI; DI = DI->getPreviousDecl()) {
5810 if (const Type *Existing = DI->getTypeForDecl()) {
5811 T = Existing;
5812 break;
5813 }
5814 }
5815 if (!T) {
Richard Smithf17fdbd2014-04-24 02:25:27 +00005816 T = new (Context, TypeAlignment) InjectedClassNameType(D, TST);
Richard Smith6377f8f2014-10-21 21:15:18 +00005817 for (auto *DI = D; DI; DI = DI->getPreviousDecl())
5818 DI->setTypeForDecl(T);
5819 }
Richard Smithf17fdbd2014-04-24 02:25:27 +00005820 return QualType(T, 0);
Guy Benyei11169dd2012-12-18 14:30:41 +00005821 }
5822
5823 case TYPE_TEMPLATE_TYPE_PARM: {
5824 unsigned Idx = 0;
5825 unsigned Depth = Record[Idx++];
5826 unsigned Index = Record[Idx++];
5827 bool Pack = Record[Idx++];
5828 TemplateTypeParmDecl *D
5829 = ReadDeclAs<TemplateTypeParmDecl>(*Loc.F, Record, Idx);
5830 return Context.getTemplateTypeParmType(Depth, Index, Pack, D);
5831 }
5832
5833 case TYPE_DEPENDENT_NAME: {
5834 unsigned Idx = 0;
5835 ElaboratedTypeKeyword Keyword = (ElaboratedTypeKeyword)Record[Idx++];
5836 NestedNameSpecifier *NNS = ReadNestedNameSpecifier(*Loc.F, Record, Idx);
Richard Smithbdf2d932015-07-30 03:37:16 +00005837 const IdentifierInfo *Name = GetIdentifierInfo(*Loc.F, Record, Idx);
Guy Benyei11169dd2012-12-18 14:30:41 +00005838 QualType Canon = readType(*Loc.F, Record, Idx);
5839 if (!Canon.isNull())
5840 Canon = Context.getCanonicalType(Canon);
5841 return Context.getDependentNameType(Keyword, NNS, Name, Canon);
5842 }
5843
5844 case TYPE_DEPENDENT_TEMPLATE_SPECIALIZATION: {
5845 unsigned Idx = 0;
5846 ElaboratedTypeKeyword Keyword = (ElaboratedTypeKeyword)Record[Idx++];
5847 NestedNameSpecifier *NNS = ReadNestedNameSpecifier(*Loc.F, Record, Idx);
Richard Smithbdf2d932015-07-30 03:37:16 +00005848 const IdentifierInfo *Name = GetIdentifierInfo(*Loc.F, Record, Idx);
Guy Benyei11169dd2012-12-18 14:30:41 +00005849 unsigned NumArgs = Record[Idx++];
5850 SmallVector<TemplateArgument, 8> Args;
5851 Args.reserve(NumArgs);
5852 while (NumArgs--)
5853 Args.push_back(ReadTemplateArgument(*Loc.F, Record, Idx));
5854 return Context.getDependentTemplateSpecializationType(Keyword, NNS, Name,
David Majnemer6fbeee32016-07-07 04:43:07 +00005855 Args);
Guy Benyei11169dd2012-12-18 14:30:41 +00005856 }
5857
5858 case TYPE_DEPENDENT_SIZED_ARRAY: {
5859 unsigned Idx = 0;
5860
5861 // ArrayType
5862 QualType ElementType = readType(*Loc.F, Record, Idx);
5863 ArrayType::ArraySizeModifier ASM
5864 = (ArrayType::ArraySizeModifier)Record[Idx++];
5865 unsigned IndexTypeQuals = Record[Idx++];
5866
5867 // DependentSizedArrayType
5868 Expr *NumElts = ReadExpr(*Loc.F);
5869 SourceRange Brackets = ReadSourceRange(*Loc.F, Record, Idx);
5870
5871 return Context.getDependentSizedArrayType(ElementType, NumElts, ASM,
5872 IndexTypeQuals, Brackets);
5873 }
5874
5875 case TYPE_TEMPLATE_SPECIALIZATION: {
5876 unsigned Idx = 0;
5877 bool IsDependent = Record[Idx++];
5878 TemplateName Name = ReadTemplateName(*Loc.F, Record, Idx);
5879 SmallVector<TemplateArgument, 8> Args;
5880 ReadTemplateArgumentList(Args, *Loc.F, Record, Idx);
5881 QualType Underlying = readType(*Loc.F, Record, Idx);
5882 QualType T;
5883 if (Underlying.isNull())
David Majnemer6fbeee32016-07-07 04:43:07 +00005884 T = Context.getCanonicalTemplateSpecializationType(Name, Args);
Guy Benyei11169dd2012-12-18 14:30:41 +00005885 else
David Majnemer6fbeee32016-07-07 04:43:07 +00005886 T = Context.getTemplateSpecializationType(Name, Args, Underlying);
Guy Benyei11169dd2012-12-18 14:30:41 +00005887 const_cast<Type*>(T.getTypePtr())->setDependent(IsDependent);
5888 return T;
5889 }
5890
5891 case TYPE_ATOMIC: {
5892 if (Record.size() != 1) {
5893 Error("Incorrect encoding of atomic type");
5894 return QualType();
5895 }
5896 QualType ValueType = readType(*Loc.F, Record, Idx);
5897 return Context.getAtomicType(ValueType);
5898 }
Xiuli Pan9c14e282016-01-09 12:53:17 +00005899
Joey Goulye3c85de2016-12-01 11:30:49 +00005900 case TYPE_PIPE: {
5901 if (Record.size() != 2) {
Xiuli Pan9c14e282016-01-09 12:53:17 +00005902 Error("Incorrect encoding of pipe type");
5903 return QualType();
5904 }
5905
5906 // Reading the pipe element type.
5907 QualType ElementType = readType(*Loc.F, Record, Idx);
Joey Goulye3c85de2016-12-01 11:30:49 +00005908 unsigned ReadOnly = Record[1];
5909 return Context.getPipeType(ElementType, ReadOnly);
Joey Gouly5788b782016-11-18 14:10:54 +00005910 }
5911
Guy Benyei11169dd2012-12-18 14:30:41 +00005912 }
5913 llvm_unreachable("Invalid TypeCode!");
5914}
5915
Richard Smith564417a2014-03-20 21:47:22 +00005916void ASTReader::readExceptionSpec(ModuleFile &ModuleFile,
5917 SmallVectorImpl<QualType> &Exceptions,
Richard Smith8acb4282014-07-31 21:57:55 +00005918 FunctionProtoType::ExceptionSpecInfo &ESI,
Richard Smith564417a2014-03-20 21:47:22 +00005919 const RecordData &Record, unsigned &Idx) {
5920 ExceptionSpecificationType EST =
5921 static_cast<ExceptionSpecificationType>(Record[Idx++]);
Richard Smith8acb4282014-07-31 21:57:55 +00005922 ESI.Type = EST;
Richard Smith564417a2014-03-20 21:47:22 +00005923 if (EST == EST_Dynamic) {
Richard Smith8acb4282014-07-31 21:57:55 +00005924 for (unsigned I = 0, N = Record[Idx++]; I != N; ++I)
Richard Smith564417a2014-03-20 21:47:22 +00005925 Exceptions.push_back(readType(ModuleFile, Record, Idx));
Richard Smith8acb4282014-07-31 21:57:55 +00005926 ESI.Exceptions = Exceptions;
Richard Smith564417a2014-03-20 21:47:22 +00005927 } else if (EST == EST_ComputedNoexcept) {
Richard Smith8acb4282014-07-31 21:57:55 +00005928 ESI.NoexceptExpr = ReadExpr(ModuleFile);
Richard Smith564417a2014-03-20 21:47:22 +00005929 } else if (EST == EST_Uninstantiated) {
Richard Smith8acb4282014-07-31 21:57:55 +00005930 ESI.SourceDecl = ReadDeclAs<FunctionDecl>(ModuleFile, Record, Idx);
5931 ESI.SourceTemplate = ReadDeclAs<FunctionDecl>(ModuleFile, Record, Idx);
Richard Smith564417a2014-03-20 21:47:22 +00005932 } else if (EST == EST_Unevaluated) {
Richard Smith8acb4282014-07-31 21:57:55 +00005933 ESI.SourceDecl = ReadDeclAs<FunctionDecl>(ModuleFile, Record, Idx);
Richard Smith564417a2014-03-20 21:47:22 +00005934 }
5935}
5936
Guy Benyei11169dd2012-12-18 14:30:41 +00005937class clang::TypeLocReader : public TypeLocVisitor<TypeLocReader> {
David L. Jonesbe1557a2016-12-21 00:17:49 +00005938 ModuleFile *F;
5939 ASTReader *Reader;
5940 const ASTReader::RecordData &Record;
Guy Benyei11169dd2012-12-18 14:30:41 +00005941 unsigned &Idx;
5942
David L. Jonesc4808b9e2016-12-15 20:53:26 +00005943 SourceLocation ReadSourceLocation() {
David L. Jonesbe1557a2016-12-21 00:17:49 +00005944 return Reader->ReadSourceLocation(*F, Record, Idx);
5945 }
5946
5947 TypeSourceInfo *GetTypeSourceInfo() {
5948 return Reader->GetTypeSourceInfo(*F, Record, Idx);
5949 }
5950
5951 NestedNameSpecifierLoc ReadNestedNameSpecifierLoc() {
5952 return Reader->ReadNestedNameSpecifierLoc(*F, Record, Idx);
Guy Benyei11169dd2012-12-18 14:30:41 +00005953 }
5954
Guy Benyei11169dd2012-12-18 14:30:41 +00005955public:
David L. Jonesbe1557a2016-12-21 00:17:49 +00005956 TypeLocReader(ModuleFile &F, ASTReader &Reader,
Guy Benyei11169dd2012-12-18 14:30:41 +00005957 const ASTReader::RecordData &Record, unsigned &Idx)
David L. Jonesbe1557a2016-12-21 00:17:49 +00005958 : F(&F), Reader(&Reader), Record(Record), Idx(Idx) {}
Guy Benyei11169dd2012-12-18 14:30:41 +00005959
5960 // We want compile-time assurance that we've enumerated all of
5961 // these, so unfortunately we have to declare them first, then
5962 // define them out-of-line.
5963#define ABSTRACT_TYPELOC(CLASS, PARENT)
5964#define TYPELOC(CLASS, PARENT) \
5965 void Visit##CLASS##TypeLoc(CLASS##TypeLoc TyLoc);
5966#include "clang/AST/TypeLocNodes.def"
5967
5968 void VisitFunctionTypeLoc(FunctionTypeLoc);
5969 void VisitArrayTypeLoc(ArrayTypeLoc);
5970};
5971
5972void TypeLocReader::VisitQualifiedTypeLoc(QualifiedTypeLoc TL) {
5973 // nothing to do
5974}
Eugene Zelenkoe95e7d52016-09-07 21:53:17 +00005975
Guy Benyei11169dd2012-12-18 14:30:41 +00005976void TypeLocReader::VisitBuiltinTypeLoc(BuiltinTypeLoc TL) {
David L. Jonesc4808b9e2016-12-15 20:53:26 +00005977 TL.setBuiltinLoc(ReadSourceLocation());
Guy Benyei11169dd2012-12-18 14:30:41 +00005978 if (TL.needsExtraLocalData()) {
David L. Jonesbe1557a2016-12-21 00:17:49 +00005979 TL.setWrittenTypeSpec(static_cast<DeclSpec::TST>(Record[Idx++]));
5980 TL.setWrittenSignSpec(static_cast<DeclSpec::TSS>(Record[Idx++]));
5981 TL.setWrittenWidthSpec(static_cast<DeclSpec::TSW>(Record[Idx++]));
5982 TL.setModeAttr(Record[Idx++]);
Guy Benyei11169dd2012-12-18 14:30:41 +00005983 }
5984}
Eugene Zelenkoe95e7d52016-09-07 21:53:17 +00005985
Guy Benyei11169dd2012-12-18 14:30:41 +00005986void TypeLocReader::VisitComplexTypeLoc(ComplexTypeLoc 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::VisitPointerTypeLoc(PointerTypeLoc TL) {
David L. Jonesc4808b9e2016-12-15 20:53:26 +00005991 TL.setStarLoc(ReadSourceLocation());
Guy Benyei11169dd2012-12-18 14:30:41 +00005992}
Eugene Zelenkoe95e7d52016-09-07 21:53:17 +00005993
Reid Kleckner8a365022013-06-24 17:51:48 +00005994void TypeLocReader::VisitDecayedTypeLoc(DecayedTypeLoc TL) {
5995 // nothing to do
5996}
Eugene Zelenkoe95e7d52016-09-07 21:53:17 +00005997
Reid Kleckner0503a872013-12-05 01:23:43 +00005998void TypeLocReader::VisitAdjustedTypeLoc(AdjustedTypeLoc TL) {
5999 // nothing to do
6000}
Eugene Zelenkoe95e7d52016-09-07 21:53:17 +00006001
Guy Benyei11169dd2012-12-18 14:30:41 +00006002void TypeLocReader::VisitBlockPointerTypeLoc(BlockPointerTypeLoc TL) {
David L. Jonesc4808b9e2016-12-15 20:53:26 +00006003 TL.setCaretLoc(ReadSourceLocation());
Guy Benyei11169dd2012-12-18 14:30:41 +00006004}
Eugene Zelenkoe95e7d52016-09-07 21:53:17 +00006005
Guy Benyei11169dd2012-12-18 14:30:41 +00006006void TypeLocReader::VisitLValueReferenceTypeLoc(LValueReferenceTypeLoc TL) {
David L. Jonesc4808b9e2016-12-15 20:53:26 +00006007 TL.setAmpLoc(ReadSourceLocation());
Guy Benyei11169dd2012-12-18 14:30:41 +00006008}
Eugene Zelenkoe95e7d52016-09-07 21:53:17 +00006009
Guy Benyei11169dd2012-12-18 14:30:41 +00006010void TypeLocReader::VisitRValueReferenceTypeLoc(RValueReferenceTypeLoc TL) {
David L. Jonesc4808b9e2016-12-15 20:53:26 +00006011 TL.setAmpAmpLoc(ReadSourceLocation());
Guy Benyei11169dd2012-12-18 14:30:41 +00006012}
Eugene Zelenkoe95e7d52016-09-07 21:53:17 +00006013
Guy Benyei11169dd2012-12-18 14:30:41 +00006014void TypeLocReader::VisitMemberPointerTypeLoc(MemberPointerTypeLoc TL) {
David L. Jonesc4808b9e2016-12-15 20:53:26 +00006015 TL.setStarLoc(ReadSourceLocation());
David L. Jonesbe1557a2016-12-21 00:17:49 +00006016 TL.setClassTInfo(GetTypeSourceInfo());
Guy Benyei11169dd2012-12-18 14:30:41 +00006017}
Eugene Zelenkoe95e7d52016-09-07 21:53:17 +00006018
Guy Benyei11169dd2012-12-18 14:30:41 +00006019void TypeLocReader::VisitArrayTypeLoc(ArrayTypeLoc TL) {
David L. Jonesc4808b9e2016-12-15 20:53:26 +00006020 TL.setLBracketLoc(ReadSourceLocation());
6021 TL.setRBracketLoc(ReadSourceLocation());
David L. Jonesbe1557a2016-12-21 00:17:49 +00006022 if (Record[Idx++])
6023 TL.setSizeExpr(Reader->ReadExpr(*F));
Guy Benyei11169dd2012-12-18 14:30:41 +00006024 else
Craig Toppera13603a2014-05-22 05:54:18 +00006025 TL.setSizeExpr(nullptr);
Guy Benyei11169dd2012-12-18 14:30:41 +00006026}
Eugene Zelenkoe95e7d52016-09-07 21:53:17 +00006027
Guy Benyei11169dd2012-12-18 14:30:41 +00006028void TypeLocReader::VisitConstantArrayTypeLoc(ConstantArrayTypeLoc TL) {
6029 VisitArrayTypeLoc(TL);
6030}
Eugene Zelenkoe95e7d52016-09-07 21:53:17 +00006031
Guy Benyei11169dd2012-12-18 14:30:41 +00006032void TypeLocReader::VisitIncompleteArrayTypeLoc(IncompleteArrayTypeLoc TL) {
6033 VisitArrayTypeLoc(TL);
6034}
Eugene Zelenkoe95e7d52016-09-07 21:53:17 +00006035
Guy Benyei11169dd2012-12-18 14:30:41 +00006036void TypeLocReader::VisitVariableArrayTypeLoc(VariableArrayTypeLoc TL) {
6037 VisitArrayTypeLoc(TL);
6038}
Eugene Zelenkoe95e7d52016-09-07 21:53:17 +00006039
Guy Benyei11169dd2012-12-18 14:30:41 +00006040void TypeLocReader::VisitDependentSizedArrayTypeLoc(
6041 DependentSizedArrayTypeLoc TL) {
6042 VisitArrayTypeLoc(TL);
6043}
Eugene Zelenkoe95e7d52016-09-07 21:53:17 +00006044
Guy Benyei11169dd2012-12-18 14:30:41 +00006045void TypeLocReader::VisitDependentSizedExtVectorTypeLoc(
6046 DependentSizedExtVectorTypeLoc TL) {
David L. Jonesc4808b9e2016-12-15 20:53:26 +00006047 TL.setNameLoc(ReadSourceLocation());
Guy Benyei11169dd2012-12-18 14:30:41 +00006048}
Eugene Zelenkoe95e7d52016-09-07 21:53:17 +00006049
Guy Benyei11169dd2012-12-18 14:30:41 +00006050void TypeLocReader::VisitVectorTypeLoc(VectorTypeLoc TL) {
David L. Jonesc4808b9e2016-12-15 20:53:26 +00006051 TL.setNameLoc(ReadSourceLocation());
Guy Benyei11169dd2012-12-18 14:30:41 +00006052}
Eugene Zelenkoe95e7d52016-09-07 21:53:17 +00006053
Guy Benyei11169dd2012-12-18 14:30:41 +00006054void TypeLocReader::VisitExtVectorTypeLoc(ExtVectorTypeLoc TL) {
David L. Jonesc4808b9e2016-12-15 20:53:26 +00006055 TL.setNameLoc(ReadSourceLocation());
Guy Benyei11169dd2012-12-18 14:30:41 +00006056}
Eugene Zelenkoe95e7d52016-09-07 21:53:17 +00006057
Guy Benyei11169dd2012-12-18 14:30:41 +00006058void TypeLocReader::VisitFunctionTypeLoc(FunctionTypeLoc TL) {
David L. Jonesc4808b9e2016-12-15 20:53:26 +00006059 TL.setLocalRangeBegin(ReadSourceLocation());
6060 TL.setLParenLoc(ReadSourceLocation());
6061 TL.setRParenLoc(ReadSourceLocation());
Malcolm Parsonsa3220ce2017-01-12 16:11:28 +00006062 TL.setExceptionSpecRange(SourceRange(Reader->ReadSourceLocation(*F, Record, Idx),
6063 Reader->ReadSourceLocation(*F, Record, Idx)));
David L. Jonesc4808b9e2016-12-15 20:53:26 +00006064 TL.setLocalRangeEnd(ReadSourceLocation());
Alp Tokerb3fd5cf2014-01-21 00:32:38 +00006065 for (unsigned i = 0, e = TL.getNumParams(); i != e; ++i) {
David L. Jonesbe1557a2016-12-21 00:17:49 +00006066 TL.setParam(i, Reader->ReadDeclAs<ParmVarDecl>(*F, Record, Idx));
Guy Benyei11169dd2012-12-18 14:30:41 +00006067 }
6068}
Eugene Zelenkoe95e7d52016-09-07 21:53:17 +00006069
Guy Benyei11169dd2012-12-18 14:30:41 +00006070void TypeLocReader::VisitFunctionProtoTypeLoc(FunctionProtoTypeLoc TL) {
6071 VisitFunctionTypeLoc(TL);
6072}
Eugene Zelenkoe95e7d52016-09-07 21:53:17 +00006073
Guy Benyei11169dd2012-12-18 14:30:41 +00006074void TypeLocReader::VisitFunctionNoProtoTypeLoc(FunctionNoProtoTypeLoc TL) {
6075 VisitFunctionTypeLoc(TL);
6076}
6077void TypeLocReader::VisitUnresolvedUsingTypeLoc(UnresolvedUsingTypeLoc TL) {
David L. Jonesc4808b9e2016-12-15 20:53:26 +00006078 TL.setNameLoc(ReadSourceLocation());
Guy Benyei11169dd2012-12-18 14:30:41 +00006079}
6080void TypeLocReader::VisitTypedefTypeLoc(TypedefTypeLoc TL) {
David L. Jonesc4808b9e2016-12-15 20:53:26 +00006081 TL.setNameLoc(ReadSourceLocation());
Guy Benyei11169dd2012-12-18 14:30:41 +00006082}
6083void TypeLocReader::VisitTypeOfExprTypeLoc(TypeOfExprTypeLoc TL) {
David L. Jonesc4808b9e2016-12-15 20:53:26 +00006084 TL.setTypeofLoc(ReadSourceLocation());
6085 TL.setLParenLoc(ReadSourceLocation());
6086 TL.setRParenLoc(ReadSourceLocation());
Guy Benyei11169dd2012-12-18 14:30:41 +00006087}
6088void TypeLocReader::VisitTypeOfTypeLoc(TypeOfTypeLoc TL) {
David L. Jonesc4808b9e2016-12-15 20:53:26 +00006089 TL.setTypeofLoc(ReadSourceLocation());
6090 TL.setLParenLoc(ReadSourceLocation());
6091 TL.setRParenLoc(ReadSourceLocation());
David L. Jonesbe1557a2016-12-21 00:17:49 +00006092 TL.setUnderlyingTInfo(GetTypeSourceInfo());
Guy Benyei11169dd2012-12-18 14:30:41 +00006093}
6094void TypeLocReader::VisitDecltypeTypeLoc(DecltypeTypeLoc TL) {
David L. Jonesc4808b9e2016-12-15 20:53:26 +00006095 TL.setNameLoc(ReadSourceLocation());
Guy Benyei11169dd2012-12-18 14:30:41 +00006096}
Eugene Zelenkoe95e7d52016-09-07 21:53:17 +00006097
Guy Benyei11169dd2012-12-18 14:30:41 +00006098void TypeLocReader::VisitUnaryTransformTypeLoc(UnaryTransformTypeLoc TL) {
David L. Jonesc4808b9e2016-12-15 20:53:26 +00006099 TL.setKWLoc(ReadSourceLocation());
6100 TL.setLParenLoc(ReadSourceLocation());
6101 TL.setRParenLoc(ReadSourceLocation());
David L. Jonesbe1557a2016-12-21 00:17:49 +00006102 TL.setUnderlyingTInfo(GetTypeSourceInfo());
Guy Benyei11169dd2012-12-18 14:30:41 +00006103}
Eugene Zelenkoe95e7d52016-09-07 21:53:17 +00006104
Guy Benyei11169dd2012-12-18 14:30:41 +00006105void TypeLocReader::VisitAutoTypeLoc(AutoTypeLoc TL) {
David L. Jonesc4808b9e2016-12-15 20:53:26 +00006106 TL.setNameLoc(ReadSourceLocation());
Guy Benyei11169dd2012-12-18 14:30:41 +00006107}
Eugene Zelenkoe95e7d52016-09-07 21:53:17 +00006108
Richard Smith600b5262017-01-26 20:40:47 +00006109void TypeLocReader::VisitDeducedTemplateSpecializationTypeLoc(
6110 DeducedTemplateSpecializationTypeLoc TL) {
6111 TL.setTemplateNameLoc(ReadSourceLocation());
6112}
6113
Guy Benyei11169dd2012-12-18 14:30:41 +00006114void TypeLocReader::VisitRecordTypeLoc(RecordTypeLoc TL) {
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::VisitEnumTypeLoc(EnumTypeLoc TL) {
David L. Jonesc4808b9e2016-12-15 20:53:26 +00006119 TL.setNameLoc(ReadSourceLocation());
Guy Benyei11169dd2012-12-18 14:30:41 +00006120}
Eugene Zelenkoe95e7d52016-09-07 21:53:17 +00006121
Guy Benyei11169dd2012-12-18 14:30:41 +00006122void TypeLocReader::VisitAttributedTypeLoc(AttributedTypeLoc TL) {
David L. Jonesc4808b9e2016-12-15 20:53:26 +00006123 TL.setAttrNameLoc(ReadSourceLocation());
Guy Benyei11169dd2012-12-18 14:30:41 +00006124 if (TL.hasAttrOperand()) {
6125 SourceRange range;
David L. Jonesc4808b9e2016-12-15 20:53:26 +00006126 range.setBegin(ReadSourceLocation());
6127 range.setEnd(ReadSourceLocation());
Guy Benyei11169dd2012-12-18 14:30:41 +00006128 TL.setAttrOperandParensRange(range);
6129 }
6130 if (TL.hasAttrExprOperand()) {
David L. Jonesbe1557a2016-12-21 00:17:49 +00006131 if (Record[Idx++])
6132 TL.setAttrExprOperand(Reader->ReadExpr(*F));
Guy Benyei11169dd2012-12-18 14:30:41 +00006133 else
Craig Toppera13603a2014-05-22 05:54:18 +00006134 TL.setAttrExprOperand(nullptr);
Guy Benyei11169dd2012-12-18 14:30:41 +00006135 } else if (TL.hasAttrEnumOperand())
David L. Jonesc4808b9e2016-12-15 20:53:26 +00006136 TL.setAttrEnumOperandLoc(ReadSourceLocation());
Guy Benyei11169dd2012-12-18 14:30:41 +00006137}
Eugene Zelenkoe95e7d52016-09-07 21:53:17 +00006138
Guy Benyei11169dd2012-12-18 14:30:41 +00006139void TypeLocReader::VisitTemplateTypeParmTypeLoc(TemplateTypeParmTypeLoc TL) {
David L. Jonesc4808b9e2016-12-15 20:53:26 +00006140 TL.setNameLoc(ReadSourceLocation());
Guy Benyei11169dd2012-12-18 14:30:41 +00006141}
Eugene Zelenkoe95e7d52016-09-07 21:53:17 +00006142
Guy Benyei11169dd2012-12-18 14:30:41 +00006143void TypeLocReader::VisitSubstTemplateTypeParmTypeLoc(
6144 SubstTemplateTypeParmTypeLoc TL) {
David L. Jonesc4808b9e2016-12-15 20:53:26 +00006145 TL.setNameLoc(ReadSourceLocation());
Guy Benyei11169dd2012-12-18 14:30:41 +00006146}
6147void TypeLocReader::VisitSubstTemplateTypeParmPackTypeLoc(
6148 SubstTemplateTypeParmPackTypeLoc TL) {
David L. Jonesc4808b9e2016-12-15 20:53:26 +00006149 TL.setNameLoc(ReadSourceLocation());
Guy Benyei11169dd2012-12-18 14:30:41 +00006150}
6151void TypeLocReader::VisitTemplateSpecializationTypeLoc(
6152 TemplateSpecializationTypeLoc TL) {
David L. Jonesc4808b9e2016-12-15 20:53:26 +00006153 TL.setTemplateKeywordLoc(ReadSourceLocation());
6154 TL.setTemplateNameLoc(ReadSourceLocation());
6155 TL.setLAngleLoc(ReadSourceLocation());
6156 TL.setRAngleLoc(ReadSourceLocation());
Guy Benyei11169dd2012-12-18 14:30:41 +00006157 for (unsigned i = 0, e = TL.getNumArgs(); i != e; ++i)
David L. Jonesbe1557a2016-12-21 00:17:49 +00006158 TL.setArgLocInfo(
6159 i,
6160 Reader->GetTemplateArgumentLocInfo(
6161 *F, TL.getTypePtr()->getArg(i).getKind(), Record, Idx));
Guy Benyei11169dd2012-12-18 14:30:41 +00006162}
6163void TypeLocReader::VisitParenTypeLoc(ParenTypeLoc TL) {
David L. Jonesc4808b9e2016-12-15 20:53:26 +00006164 TL.setLParenLoc(ReadSourceLocation());
6165 TL.setRParenLoc(ReadSourceLocation());
Guy Benyei11169dd2012-12-18 14:30:41 +00006166}
Eugene Zelenkoe95e7d52016-09-07 21:53:17 +00006167
Guy Benyei11169dd2012-12-18 14:30:41 +00006168void TypeLocReader::VisitElaboratedTypeLoc(ElaboratedTypeLoc TL) {
David L. Jonesc4808b9e2016-12-15 20:53:26 +00006169 TL.setElaboratedKeywordLoc(ReadSourceLocation());
David L. Jonesbe1557a2016-12-21 00:17:49 +00006170 TL.setQualifierLoc(ReadNestedNameSpecifierLoc());
Guy Benyei11169dd2012-12-18 14:30:41 +00006171}
Eugene Zelenkoe95e7d52016-09-07 21:53:17 +00006172
Guy Benyei11169dd2012-12-18 14:30:41 +00006173void TypeLocReader::VisitInjectedClassNameTypeLoc(InjectedClassNameTypeLoc TL) {
David L. Jonesc4808b9e2016-12-15 20:53:26 +00006174 TL.setNameLoc(ReadSourceLocation());
Guy Benyei11169dd2012-12-18 14:30:41 +00006175}
Eugene Zelenkoe95e7d52016-09-07 21:53:17 +00006176
Guy Benyei11169dd2012-12-18 14:30:41 +00006177void TypeLocReader::VisitDependentNameTypeLoc(DependentNameTypeLoc TL) {
David L. Jonesc4808b9e2016-12-15 20:53:26 +00006178 TL.setElaboratedKeywordLoc(ReadSourceLocation());
David L. Jonesbe1557a2016-12-21 00:17:49 +00006179 TL.setQualifierLoc(ReadNestedNameSpecifierLoc());
David L. Jonesc4808b9e2016-12-15 20:53:26 +00006180 TL.setNameLoc(ReadSourceLocation());
Guy Benyei11169dd2012-12-18 14:30:41 +00006181}
Eugene Zelenkoe95e7d52016-09-07 21:53:17 +00006182
Guy Benyei11169dd2012-12-18 14:30:41 +00006183void TypeLocReader::VisitDependentTemplateSpecializationTypeLoc(
6184 DependentTemplateSpecializationTypeLoc TL) {
David L. Jonesc4808b9e2016-12-15 20:53:26 +00006185 TL.setElaboratedKeywordLoc(ReadSourceLocation());
David L. Jonesbe1557a2016-12-21 00:17:49 +00006186 TL.setQualifierLoc(ReadNestedNameSpecifierLoc());
David L. Jonesc4808b9e2016-12-15 20:53:26 +00006187 TL.setTemplateKeywordLoc(ReadSourceLocation());
6188 TL.setTemplateNameLoc(ReadSourceLocation());
6189 TL.setLAngleLoc(ReadSourceLocation());
6190 TL.setRAngleLoc(ReadSourceLocation());
Guy Benyei11169dd2012-12-18 14:30:41 +00006191 for (unsigned I = 0, E = TL.getNumArgs(); I != E; ++I)
David L. Jonesbe1557a2016-12-21 00:17:49 +00006192 TL.setArgLocInfo(
6193 I,
6194 Reader->GetTemplateArgumentLocInfo(
6195 *F, TL.getTypePtr()->getArg(I).getKind(), Record, Idx));
Guy Benyei11169dd2012-12-18 14:30:41 +00006196}
Eugene Zelenkoe95e7d52016-09-07 21:53:17 +00006197
Guy Benyei11169dd2012-12-18 14:30:41 +00006198void TypeLocReader::VisitPackExpansionTypeLoc(PackExpansionTypeLoc TL) {
David L. Jonesc4808b9e2016-12-15 20:53:26 +00006199 TL.setEllipsisLoc(ReadSourceLocation());
Guy Benyei11169dd2012-12-18 14:30:41 +00006200}
Eugene Zelenkoe95e7d52016-09-07 21:53:17 +00006201
Guy Benyei11169dd2012-12-18 14:30:41 +00006202void TypeLocReader::VisitObjCInterfaceTypeLoc(ObjCInterfaceTypeLoc TL) {
David L. Jonesc4808b9e2016-12-15 20:53:26 +00006203 TL.setNameLoc(ReadSourceLocation());
Guy Benyei11169dd2012-12-18 14:30:41 +00006204}
Eugene Zelenkoe95e7d52016-09-07 21:53:17 +00006205
Manman Rene6be26c2016-09-13 17:25:08 +00006206void TypeLocReader::VisitObjCTypeParamTypeLoc(ObjCTypeParamTypeLoc TL) {
6207 if (TL.getNumProtocols()) {
David L. Jonesc4808b9e2016-12-15 20:53:26 +00006208 TL.setProtocolLAngleLoc(ReadSourceLocation());
6209 TL.setProtocolRAngleLoc(ReadSourceLocation());
Manman Rene6be26c2016-09-13 17:25:08 +00006210 }
6211 for (unsigned i = 0, e = TL.getNumProtocols(); i != e; ++i)
David L. Jonesc4808b9e2016-12-15 20:53:26 +00006212 TL.setProtocolLoc(i, ReadSourceLocation());
Manman Rene6be26c2016-09-13 17:25:08 +00006213}
6214
Guy Benyei11169dd2012-12-18 14:30:41 +00006215void TypeLocReader::VisitObjCObjectTypeLoc(ObjCObjectTypeLoc TL) {
David L. Jonesbe1557a2016-12-21 00:17:49 +00006216 TL.setHasBaseTypeAsWritten(Record[Idx++]);
David L. Jonesc4808b9e2016-12-15 20:53:26 +00006217 TL.setTypeArgsLAngleLoc(ReadSourceLocation());
6218 TL.setTypeArgsRAngleLoc(ReadSourceLocation());
Douglas Gregore9d95f12015-07-07 03:57:35 +00006219 for (unsigned i = 0, e = TL.getNumTypeArgs(); i != e; ++i)
David L. Jonesbe1557a2016-12-21 00:17:49 +00006220 TL.setTypeArgTInfo(i, GetTypeSourceInfo());
David L. Jonesc4808b9e2016-12-15 20:53:26 +00006221 TL.setProtocolLAngleLoc(ReadSourceLocation());
6222 TL.setProtocolRAngleLoc(ReadSourceLocation());
Guy Benyei11169dd2012-12-18 14:30:41 +00006223 for (unsigned i = 0, e = TL.getNumProtocols(); i != e; ++i)
David L. Jonesc4808b9e2016-12-15 20:53:26 +00006224 TL.setProtocolLoc(i, ReadSourceLocation());
Guy Benyei11169dd2012-12-18 14:30:41 +00006225}
Eugene Zelenkoe95e7d52016-09-07 21:53:17 +00006226
Guy Benyei11169dd2012-12-18 14:30:41 +00006227void TypeLocReader::VisitObjCObjectPointerTypeLoc(ObjCObjectPointerTypeLoc TL) {
David L. Jonesc4808b9e2016-12-15 20:53:26 +00006228 TL.setStarLoc(ReadSourceLocation());
Guy Benyei11169dd2012-12-18 14:30:41 +00006229}
Eugene Zelenkoe95e7d52016-09-07 21:53:17 +00006230
Guy Benyei11169dd2012-12-18 14:30:41 +00006231void TypeLocReader::VisitAtomicTypeLoc(AtomicTypeLoc TL) {
David L. Jonesc4808b9e2016-12-15 20:53:26 +00006232 TL.setKWLoc(ReadSourceLocation());
6233 TL.setLParenLoc(ReadSourceLocation());
6234 TL.setRParenLoc(ReadSourceLocation());
Guy Benyei11169dd2012-12-18 14:30:41 +00006235}
Eugene Zelenkoe95e7d52016-09-07 21:53:17 +00006236
Xiuli Pan9c14e282016-01-09 12:53:17 +00006237void TypeLocReader::VisitPipeTypeLoc(PipeTypeLoc TL) {
David L. Jonesc4808b9e2016-12-15 20:53:26 +00006238 TL.setKWLoc(ReadSourceLocation());
Xiuli Pan9c14e282016-01-09 12:53:17 +00006239}
Guy Benyei11169dd2012-12-18 14:30:41 +00006240
David L. Jonesbe1557a2016-12-21 00:17:49 +00006241TypeSourceInfo *
6242ASTReader::GetTypeSourceInfo(ModuleFile &F, const ASTReader::RecordData &Record,
6243 unsigned &Idx) {
Guy Benyei11169dd2012-12-18 14:30:41 +00006244 QualType InfoTy = readType(F, Record, Idx);
6245 if (InfoTy.isNull())
Craig Toppera13603a2014-05-22 05:54:18 +00006246 return nullptr;
Guy Benyei11169dd2012-12-18 14:30:41 +00006247
6248 TypeSourceInfo *TInfo = getContext().CreateTypeSourceInfo(InfoTy);
David L. Jonesbe1557a2016-12-21 00:17:49 +00006249 TypeLocReader TLR(F, *this, Record, Idx);
Guy Benyei11169dd2012-12-18 14:30:41 +00006250 for (TypeLoc TL = TInfo->getTypeLoc(); !TL.isNull(); TL = TL.getNextTypeLoc())
6251 TLR.Visit(TL);
6252 return TInfo;
6253}
6254
6255QualType ASTReader::GetType(TypeID ID) {
6256 unsigned FastQuals = ID & Qualifiers::FastMask;
6257 unsigned Index = ID >> Qualifiers::FastWidth;
6258
6259 if (Index < NUM_PREDEF_TYPE_IDS) {
6260 QualType T;
6261 switch ((PredefinedTypeIDs)Index) {
Alexey Baderbdf7c842015-09-15 12:18:29 +00006262 case PREDEF_TYPE_NULL_ID:
6263 return QualType();
6264 case PREDEF_TYPE_VOID_ID:
6265 T = Context.VoidTy;
6266 break;
6267 case PREDEF_TYPE_BOOL_ID:
6268 T = Context.BoolTy;
6269 break;
Guy Benyei11169dd2012-12-18 14:30:41 +00006270
6271 case PREDEF_TYPE_CHAR_U_ID:
6272 case PREDEF_TYPE_CHAR_S_ID:
6273 // FIXME: Check that the signedness of CharTy is correct!
6274 T = Context.CharTy;
6275 break;
6276
Alexey Baderbdf7c842015-09-15 12:18:29 +00006277 case PREDEF_TYPE_UCHAR_ID:
6278 T = Context.UnsignedCharTy;
6279 break;
6280 case PREDEF_TYPE_USHORT_ID:
6281 T = Context.UnsignedShortTy;
6282 break;
6283 case PREDEF_TYPE_UINT_ID:
6284 T = Context.UnsignedIntTy;
6285 break;
6286 case PREDEF_TYPE_ULONG_ID:
6287 T = Context.UnsignedLongTy;
6288 break;
6289 case PREDEF_TYPE_ULONGLONG_ID:
6290 T = Context.UnsignedLongLongTy;
6291 break;
6292 case PREDEF_TYPE_UINT128_ID:
6293 T = Context.UnsignedInt128Ty;
6294 break;
6295 case PREDEF_TYPE_SCHAR_ID:
6296 T = Context.SignedCharTy;
6297 break;
6298 case PREDEF_TYPE_WCHAR_ID:
6299 T = Context.WCharTy;
6300 break;
6301 case PREDEF_TYPE_SHORT_ID:
6302 T = Context.ShortTy;
6303 break;
6304 case PREDEF_TYPE_INT_ID:
6305 T = Context.IntTy;
6306 break;
6307 case PREDEF_TYPE_LONG_ID:
6308 T = Context.LongTy;
6309 break;
6310 case PREDEF_TYPE_LONGLONG_ID:
6311 T = Context.LongLongTy;
6312 break;
6313 case PREDEF_TYPE_INT128_ID:
6314 T = Context.Int128Ty;
6315 break;
6316 case PREDEF_TYPE_HALF_ID:
6317 T = Context.HalfTy;
6318 break;
6319 case PREDEF_TYPE_FLOAT_ID:
6320 T = Context.FloatTy;
6321 break;
6322 case PREDEF_TYPE_DOUBLE_ID:
6323 T = Context.DoubleTy;
6324 break;
6325 case PREDEF_TYPE_LONGDOUBLE_ID:
6326 T = Context.LongDoubleTy;
6327 break;
Nemanja Ivanovicbb1ea2d2016-05-09 08:52:33 +00006328 case PREDEF_TYPE_FLOAT128_ID:
6329 T = Context.Float128Ty;
6330 break;
Alexey Baderbdf7c842015-09-15 12:18:29 +00006331 case PREDEF_TYPE_OVERLOAD_ID:
6332 T = Context.OverloadTy;
6333 break;
6334 case PREDEF_TYPE_BOUND_MEMBER:
6335 T = Context.BoundMemberTy;
6336 break;
6337 case PREDEF_TYPE_PSEUDO_OBJECT:
6338 T = Context.PseudoObjectTy;
6339 break;
6340 case PREDEF_TYPE_DEPENDENT_ID:
6341 T = Context.DependentTy;
6342 break;
6343 case PREDEF_TYPE_UNKNOWN_ANY:
6344 T = Context.UnknownAnyTy;
6345 break;
6346 case PREDEF_TYPE_NULLPTR_ID:
6347 T = Context.NullPtrTy;
6348 break;
6349 case PREDEF_TYPE_CHAR16_ID:
6350 T = Context.Char16Ty;
6351 break;
6352 case PREDEF_TYPE_CHAR32_ID:
6353 T = Context.Char32Ty;
6354 break;
6355 case PREDEF_TYPE_OBJC_ID:
6356 T = Context.ObjCBuiltinIdTy;
6357 break;
6358 case PREDEF_TYPE_OBJC_CLASS:
6359 T = Context.ObjCBuiltinClassTy;
6360 break;
6361 case PREDEF_TYPE_OBJC_SEL:
6362 T = Context.ObjCBuiltinSelTy;
6363 break;
Alexey Bader954ba212016-04-08 13:40:33 +00006364#define IMAGE_TYPE(ImgType, Id, SingletonId, Access, Suffix) \
6365 case PREDEF_TYPE_##Id##_ID: \
6366 T = Context.SingletonId; \
Alexey Baderbdf7c842015-09-15 12:18:29 +00006367 break;
Alexey Baderb62f1442016-04-13 08:33:41 +00006368#include "clang/Basic/OpenCLImageTypes.def"
Alexey Baderbdf7c842015-09-15 12:18:29 +00006369 case PREDEF_TYPE_SAMPLER_ID:
6370 T = Context.OCLSamplerTy;
6371 break;
6372 case PREDEF_TYPE_EVENT_ID:
6373 T = Context.OCLEventTy;
6374 break;
Alexey Bader9c8453f2015-09-15 11:18:52 +00006375 case PREDEF_TYPE_CLK_EVENT_ID:
6376 T = Context.OCLClkEventTy;
6377 break;
6378 case PREDEF_TYPE_QUEUE_ID:
6379 T = Context.OCLQueueTy;
6380 break;
Alexey Bader9c8453f2015-09-15 11:18:52 +00006381 case PREDEF_TYPE_RESERVE_ID_ID:
6382 T = Context.OCLReserveIDTy;
6383 break;
Alexey Baderbdf7c842015-09-15 12:18:29 +00006384 case PREDEF_TYPE_AUTO_DEDUCT:
6385 T = Context.getAutoDeductType();
6386 break;
6387
6388 case PREDEF_TYPE_AUTO_RREF_DEDUCT:
6389 T = Context.getAutoRRefDeductType();
Guy Benyei11169dd2012-12-18 14:30:41 +00006390 break;
6391
6392 case PREDEF_TYPE_ARC_UNBRIDGED_CAST:
6393 T = Context.ARCUnbridgedCastTy;
6394 break;
6395
Guy Benyei11169dd2012-12-18 14:30:41 +00006396 case PREDEF_TYPE_BUILTIN_FN:
6397 T = Context.BuiltinFnTy;
6398 break;
Alexey Bataev1a3320e2015-08-25 14:24:04 +00006399
6400 case PREDEF_TYPE_OMP_ARRAY_SECTION:
6401 T = Context.OMPArraySectionTy;
6402 break;
Guy Benyei11169dd2012-12-18 14:30:41 +00006403 }
6404
6405 assert(!T.isNull() && "Unknown predefined type");
6406 return T.withFastQualifiers(FastQuals);
6407 }
6408
6409 Index -= NUM_PREDEF_TYPE_IDS;
6410 assert(Index < TypesLoaded.size() && "Type index out-of-range");
6411 if (TypesLoaded[Index].isNull()) {
6412 TypesLoaded[Index] = readTypeRecord(Index);
6413 if (TypesLoaded[Index].isNull())
6414 return QualType();
6415
6416 TypesLoaded[Index]->setFromAST();
6417 if (DeserializationListener)
6418 DeserializationListener->TypeRead(TypeIdx::fromTypeID(ID),
6419 TypesLoaded[Index]);
6420 }
6421
6422 return TypesLoaded[Index].withFastQualifiers(FastQuals);
6423}
6424
6425QualType ASTReader::getLocalType(ModuleFile &F, unsigned LocalID) {
6426 return GetType(getGlobalTypeID(F, LocalID));
6427}
6428
David L. Jonesc4808b9e2016-12-15 20:53:26 +00006429serialization::TypeID
Guy Benyei11169dd2012-12-18 14:30:41 +00006430ASTReader::getGlobalTypeID(ModuleFile &F, unsigned LocalID) const {
6431 unsigned FastQuals = LocalID & Qualifiers::FastMask;
6432 unsigned LocalIndex = LocalID >> Qualifiers::FastWidth;
David L. Jonesc4808b9e2016-12-15 20:53:26 +00006433
Guy Benyei11169dd2012-12-18 14:30:41 +00006434 if (LocalIndex < NUM_PREDEF_TYPE_IDS)
6435 return LocalID;
6436
6437 ContinuousRangeMap<uint32_t, int, 2>::iterator I
6438 = F.TypeRemap.find(LocalIndex - NUM_PREDEF_TYPE_IDS);
6439 assert(I != F.TypeRemap.end() && "Invalid index into type index remap");
David L. Jonesc4808b9e2016-12-15 20:53:26 +00006440
Guy Benyei11169dd2012-12-18 14:30:41 +00006441 unsigned GlobalIndex = LocalIndex + I->second;
6442 return (GlobalIndex << Qualifiers::FastWidth) | FastQuals;
6443}
6444
6445TemplateArgumentLocInfo
6446ASTReader::GetTemplateArgumentLocInfo(ModuleFile &F,
6447 TemplateArgument::ArgKind Kind,
6448 const RecordData &Record,
6449 unsigned &Index) {
6450 switch (Kind) {
6451 case TemplateArgument::Expression:
6452 return ReadExpr(F);
6453 case TemplateArgument::Type:
6454 return GetTypeSourceInfo(F, Record, Index);
6455 case TemplateArgument::Template: {
David L. Jonesc4808b9e2016-12-15 20:53:26 +00006456 NestedNameSpecifierLoc QualifierLoc = ReadNestedNameSpecifierLoc(F, Record,
Guy Benyei11169dd2012-12-18 14:30:41 +00006457 Index);
6458 SourceLocation TemplateNameLoc = ReadSourceLocation(F, Record, Index);
6459 return TemplateArgumentLocInfo(QualifierLoc, TemplateNameLoc,
6460 SourceLocation());
6461 }
6462 case TemplateArgument::TemplateExpansion: {
David L. Jonesc4808b9e2016-12-15 20:53:26 +00006463 NestedNameSpecifierLoc QualifierLoc = ReadNestedNameSpecifierLoc(F, Record,
Guy Benyei11169dd2012-12-18 14:30:41 +00006464 Index);
6465 SourceLocation TemplateNameLoc = ReadSourceLocation(F, Record, Index);
6466 SourceLocation EllipsisLoc = ReadSourceLocation(F, Record, Index);
David L. Jonesc4808b9e2016-12-15 20:53:26 +00006467 return TemplateArgumentLocInfo(QualifierLoc, TemplateNameLoc,
Guy Benyei11169dd2012-12-18 14:30:41 +00006468 EllipsisLoc);
6469 }
6470 case TemplateArgument::Null:
6471 case TemplateArgument::Integral:
6472 case TemplateArgument::Declaration:
6473 case TemplateArgument::NullPtr:
6474 case TemplateArgument::Pack:
6475 // FIXME: Is this right?
6476 return TemplateArgumentLocInfo();
6477 }
6478 llvm_unreachable("unexpected template argument loc");
6479}
6480
6481TemplateArgumentLoc
6482ASTReader::ReadTemplateArgumentLoc(ModuleFile &F,
6483 const RecordData &Record, unsigned &Index) {
6484 TemplateArgument Arg = ReadTemplateArgument(F, Record, Index);
6485
6486 if (Arg.getKind() == TemplateArgument::Expression) {
6487 if (Record[Index++]) // bool InfoHasSameExpr.
6488 return TemplateArgumentLoc(Arg, TemplateArgumentLocInfo(Arg.getAsExpr()));
6489 }
6490 return TemplateArgumentLoc(Arg, GetTemplateArgumentLocInfo(F, Arg.getKind(),
6491 Record, Index));
6492}
6493
Enea Zaffanella6dbe1872013-08-10 07:24:53 +00006494const ASTTemplateArgumentListInfo*
6495ASTReader::ReadASTTemplateArgumentListInfo(ModuleFile &F,
6496 const RecordData &Record,
6497 unsigned &Index) {
6498 SourceLocation LAngleLoc = ReadSourceLocation(F, Record, Index);
6499 SourceLocation RAngleLoc = ReadSourceLocation(F, Record, Index);
6500 unsigned NumArgsAsWritten = Record[Index++];
6501 TemplateArgumentListInfo TemplArgsInfo(LAngleLoc, RAngleLoc);
6502 for (unsigned i = 0; i != NumArgsAsWritten; ++i)
6503 TemplArgsInfo.addArgument(ReadTemplateArgumentLoc(F, Record, Index));
6504 return ASTTemplateArgumentListInfo::Create(getContext(), TemplArgsInfo);
6505}
6506
Guy Benyei11169dd2012-12-18 14:30:41 +00006507Decl *ASTReader::GetExternalDecl(uint32_t ID) {
6508 return GetDecl(ID);
6509}
6510
Richard Smith50895422015-01-31 03:04:55 +00006511template<typename TemplateSpecializationDecl>
6512static void completeRedeclChainForTemplateSpecialization(Decl *D) {
6513 if (auto *TSD = dyn_cast<TemplateSpecializationDecl>(D))
6514 TSD->getSpecializedTemplate()->LoadLazySpecializations();
6515}
6516
Richard Smith053f6c62014-05-16 23:01:30 +00006517void ASTReader::CompleteRedeclChain(const Decl *D) {
Richard Smith851072e2014-05-19 20:59:20 +00006518 if (NumCurrentElementsDeserializing) {
6519 // We arrange to not care about the complete redeclaration chain while we're
6520 // deserializing. Just remember that the AST has marked this one as complete
6521 // but that it's not actually complete yet, so we know we still need to
6522 // complete it later.
6523 PendingIncompleteDeclChains.push_back(const_cast<Decl*>(D));
6524 return;
6525 }
6526
Richard Smith053f6c62014-05-16 23:01:30 +00006527 const DeclContext *DC = D->getDeclContext()->getRedeclContext();
6528
Richard Smith053f6c62014-05-16 23:01:30 +00006529 // If this is a named declaration, complete it by looking it up
6530 // within its context.
6531 //
Richard Smith01bdb7a2014-08-28 05:44:07 +00006532 // FIXME: Merging a function definition should merge
Richard Smith053f6c62014-05-16 23:01:30 +00006533 // all mergeable entities within it.
6534 if (isa<TranslationUnitDecl>(DC) || isa<NamespaceDecl>(DC) ||
6535 isa<CXXRecordDecl>(DC) || isa<EnumDecl>(DC)) {
6536 if (DeclarationName Name = cast<NamedDecl>(D)->getDeclName()) {
Richard Smitha534a312015-07-21 23:54:07 +00006537 if (!getContext().getLangOpts().CPlusPlus &&
6538 isa<TranslationUnitDecl>(DC)) {
Richard Smith053f6c62014-05-16 23:01:30 +00006539 // Outside of C++, we don't have a lookup table for the TU, so update
Richard Smitha534a312015-07-21 23:54:07 +00006540 // the identifier instead. (For C++ modules, we don't store decls
6541 // in the serialized identifier table, so we do the lookup in the TU.)
6542 auto *II = Name.getAsIdentifierInfo();
6543 assert(II && "non-identifier name in C?");
Richard Smith053f6c62014-05-16 23:01:30 +00006544 if (II->isOutOfDate())
6545 updateOutOfDateIdentifier(*II);
6546 } else
6547 DC->lookup(Name);
Richard Smith01bdb7a2014-08-28 05:44:07 +00006548 } else if (needsAnonymousDeclarationNumber(cast<NamedDecl>(D))) {
Richard Smith3cb15722015-08-05 22:41:45 +00006549 // Find all declarations of this kind from the relevant context.
6550 for (auto *DCDecl : cast<Decl>(D->getLexicalDeclContext())->redecls()) {
6551 auto *DC = cast<DeclContext>(DCDecl);
6552 SmallVector<Decl*, 8> Decls;
6553 FindExternalLexicalDecls(
6554 DC, [&](Decl::Kind K) { return K == D->getKind(); }, Decls);
6555 }
Richard Smith053f6c62014-05-16 23:01:30 +00006556 }
6557 }
Richard Smith50895422015-01-31 03:04:55 +00006558
6559 if (auto *CTSD = dyn_cast<ClassTemplateSpecializationDecl>(D))
6560 CTSD->getSpecializedTemplate()->LoadLazySpecializations();
6561 if (auto *VTSD = dyn_cast<VarTemplateSpecializationDecl>(D))
6562 VTSD->getSpecializedTemplate()->LoadLazySpecializations();
6563 if (auto *FD = dyn_cast<FunctionDecl>(D)) {
6564 if (auto *Template = FD->getPrimaryTemplate())
6565 Template->LoadLazySpecializations();
6566 }
Richard Smith053f6c62014-05-16 23:01:30 +00006567}
6568
Richard Smithc2bb8182015-03-24 06:36:48 +00006569CXXCtorInitializer **
6570ASTReader::GetExternalCXXCtorInitializers(uint64_t Offset) {
6571 RecordLocation Loc = getLocalBitOffset(Offset);
6572 BitstreamCursor &Cursor = Loc.F->DeclsCursor;
6573 SavedStreamPosition SavedPosition(Cursor);
6574 Cursor.JumpToBit(Loc.Offset);
6575 ReadingKindTracker ReadingKind(Read_Decl, *this);
6576
6577 RecordData Record;
6578 unsigned Code = Cursor.ReadCode();
6579 unsigned RecCode = Cursor.readRecord(Code, Record);
6580 if (RecCode != DECL_CXX_CTOR_INITIALIZERS) {
6581 Error("malformed AST file: missing C++ ctor initializers");
6582 return nullptr;
6583 }
6584
6585 unsigned Idx = 0;
6586 return ReadCXXCtorInitializers(*Loc.F, Record, Idx);
6587}
6588
Guy Benyei11169dd2012-12-18 14:30:41 +00006589CXXBaseSpecifier *ASTReader::GetExternalCXXBaseSpecifiers(uint64_t Offset) {
6590 RecordLocation Loc = getLocalBitOffset(Offset);
Chris Lattner7fb3bef2013-01-20 00:56:42 +00006591 BitstreamCursor &Cursor = Loc.F->DeclsCursor;
Guy Benyei11169dd2012-12-18 14:30:41 +00006592 SavedStreamPosition SavedPosition(Cursor);
6593 Cursor.JumpToBit(Loc.Offset);
6594 ReadingKindTracker ReadingKind(Read_Decl, *this);
6595 RecordData Record;
6596 unsigned Code = Cursor.ReadCode();
Chris Lattner0e6c9402013-01-20 02:38:54 +00006597 unsigned RecCode = Cursor.readRecord(Code, Record);
Guy Benyei11169dd2012-12-18 14:30:41 +00006598 if (RecCode != DECL_CXX_BASE_SPECIFIERS) {
Richard Smithcd45dbc2014-04-19 03:48:30 +00006599 Error("malformed AST file: missing C++ base specifiers");
Craig Toppera13603a2014-05-22 05:54:18 +00006600 return nullptr;
Guy Benyei11169dd2012-12-18 14:30:41 +00006601 }
6602
6603 unsigned Idx = 0;
6604 unsigned NumBases = Record[Idx++];
6605 void *Mem = Context.Allocate(sizeof(CXXBaseSpecifier) * NumBases);
6606 CXXBaseSpecifier *Bases = new (Mem) CXXBaseSpecifier [NumBases];
6607 for (unsigned I = 0; I != NumBases; ++I)
6608 Bases[I] = ReadCXXBaseSpecifier(*Loc.F, Record, Idx);
6609 return Bases;
6610}
6611
David L. Jonesc4808b9e2016-12-15 20:53:26 +00006612serialization::DeclID
Guy Benyei11169dd2012-12-18 14:30:41 +00006613ASTReader::getGlobalDeclID(ModuleFile &F, LocalDeclID LocalID) const {
6614 if (LocalID < NUM_PREDEF_DECL_IDS)
6615 return LocalID;
6616
6617 ContinuousRangeMap<uint32_t, int, 2>::iterator I
6618 = F.DeclRemap.find(LocalID - NUM_PREDEF_DECL_IDS);
6619 assert(I != F.DeclRemap.end() && "Invalid index into decl index remap");
David L. Jonesc4808b9e2016-12-15 20:53:26 +00006620
Guy Benyei11169dd2012-12-18 14:30:41 +00006621 return LocalID + I->second;
6622}
6623
6624bool ASTReader::isDeclIDFromModule(serialization::GlobalDeclID ID,
6625 ModuleFile &M) const {
Richard Smithfe620d22015-03-05 23:24:12 +00006626 // Predefined decls aren't from any module.
6627 if (ID < NUM_PREDEF_DECL_IDS)
6628 return false;
6629
David L. Jonesc4808b9e2016-12-15 20:53:26 +00006630 return ID - NUM_PREDEF_DECL_IDS >= M.BaseDeclID &&
Richard Smithbcda1a92015-07-12 23:51:20 +00006631 ID - NUM_PREDEF_DECL_IDS < M.BaseDeclID + M.LocalNumDecls;
Guy Benyei11169dd2012-12-18 14:30:41 +00006632}
6633
Douglas Gregor9f782892013-01-21 15:25:38 +00006634ModuleFile *ASTReader::getOwningModuleFile(const Decl *D) {
Guy Benyei11169dd2012-12-18 14:30:41 +00006635 if (!D->isFromASTFile())
Craig Toppera13603a2014-05-22 05:54:18 +00006636 return nullptr;
Guy Benyei11169dd2012-12-18 14:30:41 +00006637 GlobalDeclMapType::const_iterator I = GlobalDeclMap.find(D->getGlobalID());
6638 assert(I != GlobalDeclMap.end() && "Corrupted global declaration map");
6639 return I->second;
6640}
6641
6642SourceLocation ASTReader::getSourceLocationForDeclID(GlobalDeclID ID) {
6643 if (ID < NUM_PREDEF_DECL_IDS)
6644 return SourceLocation();
Richard Smithcd45dbc2014-04-19 03:48:30 +00006645
Guy Benyei11169dd2012-12-18 14:30:41 +00006646 unsigned Index = ID - NUM_PREDEF_DECL_IDS;
6647
6648 if (Index > DeclsLoaded.size()) {
6649 Error("declaration ID out-of-range for AST file");
6650 return SourceLocation();
6651 }
Richard Smithcd45dbc2014-04-19 03:48:30 +00006652
Guy Benyei11169dd2012-12-18 14:30:41 +00006653 if (Decl *D = DeclsLoaded[Index])
6654 return D->getLocation();
6655
Richard Smithcb34bd32016-03-27 07:28:06 +00006656 SourceLocation Loc;
6657 DeclCursorForID(ID, Loc);
6658 return Loc;
Guy Benyei11169dd2012-12-18 14:30:41 +00006659}
6660
Richard Smithfe620d22015-03-05 23:24:12 +00006661static Decl *getPredefinedDecl(ASTContext &Context, PredefinedDeclIDs ID) {
6662 switch (ID) {
6663 case PREDEF_DECL_NULL_ID:
6664 return nullptr;
6665
6666 case PREDEF_DECL_TRANSLATION_UNIT_ID:
6667 return Context.getTranslationUnitDecl();
6668
6669 case PREDEF_DECL_OBJC_ID_ID:
6670 return Context.getObjCIdDecl();
6671
6672 case PREDEF_DECL_OBJC_SEL_ID:
6673 return Context.getObjCSelDecl();
6674
6675 case PREDEF_DECL_OBJC_CLASS_ID:
6676 return Context.getObjCClassDecl();
6677
6678 case PREDEF_DECL_OBJC_PROTOCOL_ID:
6679 return Context.getObjCProtocolDecl();
6680
6681 case PREDEF_DECL_INT_128_ID:
6682 return Context.getInt128Decl();
6683
6684 case PREDEF_DECL_UNSIGNED_INT_128_ID:
6685 return Context.getUInt128Decl();
6686
6687 case PREDEF_DECL_OBJC_INSTANCETYPE_ID:
6688 return Context.getObjCInstanceTypeDecl();
6689
6690 case PREDEF_DECL_BUILTIN_VA_LIST_ID:
6691 return Context.getBuiltinVaListDecl();
Richard Smithf19e1272015-03-07 00:04:49 +00006692
Richard Smith9b88a4c2015-07-27 05:40:23 +00006693 case PREDEF_DECL_VA_LIST_TAG:
6694 return Context.getVaListTagDecl();
6695
Charles Davisc7d5c942015-09-17 20:55:33 +00006696 case PREDEF_DECL_BUILTIN_MS_VA_LIST_ID:
6697 return Context.getBuiltinMSVaListDecl();
6698
Richard Smithf19e1272015-03-07 00:04:49 +00006699 case PREDEF_DECL_EXTERN_C_CONTEXT_ID:
6700 return Context.getExternCContextDecl();
David Majnemerd9b1a4f2015-11-04 03:40:30 +00006701
6702 case PREDEF_DECL_MAKE_INTEGER_SEQ_ID:
6703 return Context.getMakeIntegerSeqDecl();
Quentin Colombet043406b2016-02-03 22:41:00 +00006704
6705 case PREDEF_DECL_CF_CONSTANT_STRING_ID:
6706 return Context.getCFConstantStringDecl();
Ben Langmuirf5416742016-02-04 00:55:24 +00006707
6708 case PREDEF_DECL_CF_CONSTANT_STRING_TAG_ID:
6709 return Context.getCFConstantStringTagDecl();
Eric Fiselier6ad68552016-07-01 01:24:09 +00006710
6711 case PREDEF_DECL_TYPE_PACK_ELEMENT_ID:
6712 return Context.getTypePackElementDecl();
Richard Smithfe620d22015-03-05 23:24:12 +00006713 }
Yaron Keren322bdad2015-03-06 07:49:14 +00006714 llvm_unreachable("PredefinedDeclIDs unknown enum value");
Richard Smithfe620d22015-03-05 23:24:12 +00006715}
6716
Richard Smithcd45dbc2014-04-19 03:48:30 +00006717Decl *ASTReader::GetExistingDecl(DeclID ID) {
6718 if (ID < NUM_PREDEF_DECL_IDS) {
Richard Smithfe620d22015-03-05 23:24:12 +00006719 Decl *D = getPredefinedDecl(Context, (PredefinedDeclIDs)ID);
6720 if (D) {
6721 // Track that we have merged the declaration with ID \p ID into the
6722 // pre-existing predefined declaration \p D.
Richard Smith5fc18a92015-07-12 23:43:21 +00006723 auto &Merged = KeyDecls[D->getCanonicalDecl()];
Richard Smithfe620d22015-03-05 23:24:12 +00006724 if (Merged.empty())
6725 Merged.push_back(ID);
Guy Benyei11169dd2012-12-18 14:30:41 +00006726 }
Richard Smithfe620d22015-03-05 23:24:12 +00006727 return D;
Guy Benyei11169dd2012-12-18 14:30:41 +00006728 }
Richard Smithcd45dbc2014-04-19 03:48:30 +00006729
Guy Benyei11169dd2012-12-18 14:30:41 +00006730 unsigned Index = ID - NUM_PREDEF_DECL_IDS;
6731
6732 if (Index >= DeclsLoaded.size()) {
6733 assert(0 && "declaration ID out-of-range for AST file");
6734 Error("declaration ID out-of-range for AST file");
Craig Toppera13603a2014-05-22 05:54:18 +00006735 return nullptr;
Guy Benyei11169dd2012-12-18 14:30:41 +00006736 }
Richard Smithcd45dbc2014-04-19 03:48:30 +00006737
6738 return DeclsLoaded[Index];
6739}
6740
6741Decl *ASTReader::GetDecl(DeclID ID) {
6742 if (ID < NUM_PREDEF_DECL_IDS)
6743 return GetExistingDecl(ID);
6744
6745 unsigned Index = ID - NUM_PREDEF_DECL_IDS;
6746
6747 if (Index >= DeclsLoaded.size()) {
6748 assert(0 && "declaration ID out-of-range for AST file");
6749 Error("declaration ID out-of-range for AST file");
Craig Toppera13603a2014-05-22 05:54:18 +00006750 return nullptr;
Richard Smithcd45dbc2014-04-19 03:48:30 +00006751 }
6752
Guy Benyei11169dd2012-12-18 14:30:41 +00006753 if (!DeclsLoaded[Index]) {
6754 ReadDeclRecord(ID);
6755 if (DeserializationListener)
6756 DeserializationListener->DeclRead(ID, DeclsLoaded[Index]);
6757 }
6758
6759 return DeclsLoaded[Index];
6760}
6761
David L. Jonesc4808b9e2016-12-15 20:53:26 +00006762DeclID ASTReader::mapGlobalIDToModuleFileGlobalID(ModuleFile &M,
Guy Benyei11169dd2012-12-18 14:30:41 +00006763 DeclID GlobalID) {
6764 if (GlobalID < NUM_PREDEF_DECL_IDS)
6765 return GlobalID;
David L. Jonesc4808b9e2016-12-15 20:53:26 +00006766
Guy Benyei11169dd2012-12-18 14:30:41 +00006767 GlobalDeclMapType::const_iterator I = GlobalDeclMap.find(GlobalID);
6768 assert(I != GlobalDeclMap.end() && "Corrupted global declaration map");
6769 ModuleFile *Owner = I->second;
6770
6771 llvm::DenseMap<ModuleFile *, serialization::DeclID>::iterator Pos
6772 = M.GlobalToLocalDeclIDs.find(Owner);
6773 if (Pos == M.GlobalToLocalDeclIDs.end())
6774 return 0;
David L. Jonesc4808b9e2016-12-15 20:53:26 +00006775
Guy Benyei11169dd2012-12-18 14:30:41 +00006776 return GlobalID - Owner->BaseDeclID + Pos->second;
6777}
6778
David L. Jonesc4808b9e2016-12-15 20:53:26 +00006779serialization::DeclID ASTReader::ReadDeclID(ModuleFile &F,
Guy Benyei11169dd2012-12-18 14:30:41 +00006780 const RecordData &Record,
6781 unsigned &Idx) {
6782 if (Idx >= Record.size()) {
6783 Error("Corrupted AST file");
6784 return 0;
6785 }
David L. Jonesc4808b9e2016-12-15 20:53:26 +00006786
Guy Benyei11169dd2012-12-18 14:30:41 +00006787 return getGlobalDeclID(F, Record[Idx++]);
6788}
6789
6790/// \brief Resolve the offset of a statement into a statement.
6791///
6792/// This operation will read a new statement from the external
6793/// source each time it is called, and is meant to be used via a
6794/// LazyOffsetPtr (which is used by Decls for the body of functions, etc).
6795Stmt *ASTReader::GetExternalDeclStmt(uint64_t Offset) {
6796 // Switch case IDs are per Decl.
6797 ClearSwitchCaseIDs();
6798
6799 // Offset here is a global offset across the entire chain.
6800 RecordLocation Loc = getLocalBitOffset(Offset);
6801 Loc.F->DeclsCursor.JumpToBit(Loc.Offset);
6802 return ReadStmtFromStream(*Loc.F);
6803}
6804
Richard Smith3cb15722015-08-05 22:41:45 +00006805void ASTReader::FindExternalLexicalDecls(
6806 const DeclContext *DC, llvm::function_ref<bool(Decl::Kind)> IsKindWeWant,
6807 SmallVectorImpl<Decl *> &Decls) {
Richard Smith82f8fcd2015-08-06 22:07:25 +00006808 bool PredefsVisited[NUM_PREDEF_DECL_IDS] = {};
6809
Richard Smith9ccdd932015-08-06 22:14:12 +00006810 auto Visit = [&] (ModuleFile *M, LexicalContents LexicalDecls) {
Richard Smith82f8fcd2015-08-06 22:07:25 +00006811 assert(LexicalDecls.size() % 2 == 0 && "expected an even number of entries");
6812 for (int I = 0, N = LexicalDecls.size(); I != N; I += 2) {
6813 auto K = (Decl::Kind)+LexicalDecls[I];
6814 if (!IsKindWeWant(K))
6815 continue;
6816
6817 auto ID = (serialization::DeclID)+LexicalDecls[I + 1];
6818
6819 // Don't add predefined declarations to the lexical context more
6820 // than once.
6821 if (ID < NUM_PREDEF_DECL_IDS) {
6822 if (PredefsVisited[ID])
6823 continue;
6824
6825 PredefsVisited[ID] = true;
6826 }
6827
6828 if (Decl *D = GetLocalDecl(*M, ID)) {
Richard Smith2317a3e2015-08-11 21:21:20 +00006829 assert(D->getKind() == K && "wrong kind for lexical decl");
Richard Smith82f8fcd2015-08-06 22:07:25 +00006830 if (!DC->isDeclInLexicalTraversal(D))
6831 Decls.push_back(D);
6832 }
6833 }
6834 };
6835
6836 if (isa<TranslationUnitDecl>(DC)) {
6837 for (auto Lexical : TULexicalDecls)
6838 Visit(Lexical.first, Lexical.second);
6839 } else {
6840 auto I = LexicalDecls.find(DC);
6841 if (I != LexicalDecls.end())
Richard Smith9c9173d2015-08-11 22:00:24 +00006842 Visit(I->second.first, I->second.second);
Richard Smith82f8fcd2015-08-06 22:07:25 +00006843 }
6844
Guy Benyei11169dd2012-12-18 14:30:41 +00006845 ++NumLexicalDeclContextsRead;
Guy Benyei11169dd2012-12-18 14:30:41 +00006846}
6847
6848namespace {
6849
6850class DeclIDComp {
6851 ASTReader &Reader;
6852 ModuleFile &Mod;
6853
6854public:
6855 DeclIDComp(ASTReader &Reader, ModuleFile &M) : Reader(Reader), Mod(M) {}
6856
6857 bool operator()(LocalDeclID L, LocalDeclID R) const {
6858 SourceLocation LHS = getLocation(L);
6859 SourceLocation RHS = getLocation(R);
6860 return Reader.getSourceManager().isBeforeInTranslationUnit(LHS, RHS);
6861 }
6862
6863 bool operator()(SourceLocation LHS, LocalDeclID R) const {
6864 SourceLocation RHS = getLocation(R);
6865 return Reader.getSourceManager().isBeforeInTranslationUnit(LHS, RHS);
6866 }
6867
6868 bool operator()(LocalDeclID L, SourceLocation RHS) const {
6869 SourceLocation LHS = getLocation(L);
6870 return Reader.getSourceManager().isBeforeInTranslationUnit(LHS, RHS);
6871 }
6872
6873 SourceLocation getLocation(LocalDeclID ID) const {
6874 return Reader.getSourceManager().getFileLoc(
6875 Reader.getSourceLocationForDeclID(Reader.getGlobalDeclID(Mod, ID)));
6876 }
6877};
6878
Eugene Zelenkoe95e7d52016-09-07 21:53:17 +00006879} // end anonymous namespace
Guy Benyei11169dd2012-12-18 14:30:41 +00006880
6881void ASTReader::FindFileRegionDecls(FileID File,
6882 unsigned Offset, unsigned Length,
6883 SmallVectorImpl<Decl *> &Decls) {
6884 SourceManager &SM = getSourceManager();
6885
6886 llvm::DenseMap<FileID, FileDeclsInfo>::iterator I = FileDeclIDs.find(File);
6887 if (I == FileDeclIDs.end())
6888 return;
6889
6890 FileDeclsInfo &DInfo = I->second;
6891 if (DInfo.Decls.empty())
6892 return;
6893
6894 SourceLocation
6895 BeginLoc = SM.getLocForStartOfFile(File).getLocWithOffset(Offset);
6896 SourceLocation EndLoc = BeginLoc.getLocWithOffset(Length);
6897
6898 DeclIDComp DIDComp(*this, *DInfo.Mod);
6899 ArrayRef<serialization::LocalDeclID>::iterator
6900 BeginIt = std::lower_bound(DInfo.Decls.begin(), DInfo.Decls.end(),
6901 BeginLoc, DIDComp);
6902 if (BeginIt != DInfo.Decls.begin())
6903 --BeginIt;
6904
6905 // If we are pointing at a top-level decl inside an objc container, we need
6906 // to backtrack until we find it otherwise we will fail to report that the
6907 // region overlaps with an objc container.
6908 while (BeginIt != DInfo.Decls.begin() &&
6909 GetDecl(getGlobalDeclID(*DInfo.Mod, *BeginIt))
6910 ->isTopLevelDeclInObjCContainer())
6911 --BeginIt;
6912
6913 ArrayRef<serialization::LocalDeclID>::iterator
6914 EndIt = std::upper_bound(DInfo.Decls.begin(), DInfo.Decls.end(),
6915 EndLoc, DIDComp);
6916 if (EndIt != DInfo.Decls.end())
6917 ++EndIt;
David L. Jonesc4808b9e2016-12-15 20:53:26 +00006918
Guy Benyei11169dd2012-12-18 14:30:41 +00006919 for (ArrayRef<serialization::LocalDeclID>::iterator
6920 DIt = BeginIt; DIt != EndIt; ++DIt)
6921 Decls.push_back(GetDecl(getGlobalDeclID(*DInfo.Mod, *DIt)));
6922}
6923
Richard Smith9ce12e32013-02-07 03:30:24 +00006924bool
Guy Benyei11169dd2012-12-18 14:30:41 +00006925ASTReader::FindExternalVisibleDeclsByName(const DeclContext *DC,
6926 DeclarationName Name) {
Richard Smithd88a7f12015-09-01 20:35:42 +00006927 assert(DC->hasExternalVisibleStorage() && DC == DC->getPrimaryContext() &&
Guy Benyei11169dd2012-12-18 14:30:41 +00006928 "DeclContext has no visible decls in storage");
6929 if (!Name)
Richard Smith9ce12e32013-02-07 03:30:24 +00006930 return false;
Guy Benyei11169dd2012-12-18 14:30:41 +00006931
Richard Smithd88a7f12015-09-01 20:35:42 +00006932 auto It = Lookups.find(DC);
6933 if (It == Lookups.end())
6934 return false;
6935
Richard Smith8c913ec2014-08-14 02:21:01 +00006936 Deserializing LookupResults(this);
6937
Richard Smithd88a7f12015-09-01 20:35:42 +00006938 // Load the list of declarations.
Guy Benyei11169dd2012-12-18 14:30:41 +00006939 SmallVector<NamedDecl *, 64> Decls;
Richard Smithd88a7f12015-09-01 20:35:42 +00006940 for (DeclID ID : It->second.Table.find(Name)) {
6941 NamedDecl *ND = cast<NamedDecl>(GetDecl(ID));
6942 if (ND->getDeclName() == Name)
6943 Decls.push_back(ND);
6944 }
Richard Smithcd45dbc2014-04-19 03:48:30 +00006945
Guy Benyei11169dd2012-12-18 14:30:41 +00006946 ++NumVisibleDeclContextsRead;
6947 SetExternalVisibleDeclsForName(DC, Name, Decls);
Richard Smith9ce12e32013-02-07 03:30:24 +00006948 return !Decls.empty();
Guy Benyei11169dd2012-12-18 14:30:41 +00006949}
6950
Guy Benyei11169dd2012-12-18 14:30:41 +00006951void ASTReader::completeVisibleDeclsMap(const DeclContext *DC) {
6952 if (!DC->hasExternalVisibleStorage())
6953 return;
Richard Smithd88a7f12015-09-01 20:35:42 +00006954
6955 auto It = Lookups.find(DC);
6956 assert(It != Lookups.end() &&
6957 "have external visible storage but no lookup tables");
6958
Craig Topper79be4cd2013-07-05 04:33:53 +00006959 DeclsMap Decls;
Guy Benyei11169dd2012-12-18 14:30:41 +00006960
Richard Smithd88a7f12015-09-01 20:35:42 +00006961 for (DeclID ID : It->second.Table.findAll()) {
6962 NamedDecl *ND = cast<NamedDecl>(GetDecl(ID));
6963 Decls[ND->getDeclName()].push_back(ND);
Guy Benyei11169dd2012-12-18 14:30:41 +00006964 }
6965
Guy Benyei11169dd2012-12-18 14:30:41 +00006966 ++NumVisibleDeclContextsRead;
6967
Craig Topper79be4cd2013-07-05 04:33:53 +00006968 for (DeclsMap::iterator I = Decls.begin(), E = Decls.end(); I != E; ++I) {
Guy Benyei11169dd2012-12-18 14:30:41 +00006969 SetExternalVisibleDeclsForName(DC, I->first, I->second);
6970 }
6971 const_cast<DeclContext *>(DC)->setHasExternalVisibleStorage(false);
6972}
6973
Richard Smithd88a7f12015-09-01 20:35:42 +00006974const serialization::reader::DeclContextLookupTable *
6975ASTReader::getLoadedLookupTables(DeclContext *Primary) const {
6976 auto I = Lookups.find(Primary);
6977 return I == Lookups.end() ? nullptr : &I->second;
6978}
6979
Guy Benyei11169dd2012-12-18 14:30:41 +00006980/// \brief Under non-PCH compilation the consumer receives the objc methods
6981/// before receiving the implementation, and codegen depends on this.
6982/// We simulate this by deserializing and passing to consumer the methods of the
6983/// implementation before passing the deserialized implementation decl.
6984static void PassObjCImplDeclToConsumer(ObjCImplDecl *ImplD,
6985 ASTConsumer *Consumer) {
6986 assert(ImplD && Consumer);
6987
Aaron Ballmanaff18c02014-03-13 19:03:34 +00006988 for (auto *I : ImplD->methods())
6989 Consumer->HandleInterestingDecl(DeclGroupRef(I));
Guy Benyei11169dd2012-12-18 14:30:41 +00006990
6991 Consumer->HandleInterestingDecl(DeclGroupRef(ImplD));
6992}
6993
6994void ASTReader::PassInterestingDeclsToConsumer() {
6995 assert(Consumer);
Richard Smith04d05b52014-03-23 00:27:18 +00006996
6997 if (PassingDeclsToConsumer)
6998 return;
6999
7000 // Guard variable to avoid recursively redoing the process of passing
7001 // decls to consumer.
7002 SaveAndRestore<bool> GuardPassingDeclsToConsumer(PassingDeclsToConsumer,
7003 true);
7004
Richard Smith9e2341d2015-03-23 03:25:59 +00007005 // Ensure that we've loaded all potentially-interesting declarations
7006 // that need to be eagerly loaded.
7007 for (auto ID : EagerlyDeserializedDecls)
7008 GetDecl(ID);
7009 EagerlyDeserializedDecls.clear();
7010
Guy Benyei11169dd2012-12-18 14:30:41 +00007011 while (!InterestingDecls.empty()) {
7012 Decl *D = InterestingDecls.front();
7013 InterestingDecls.pop_front();
7014
7015 PassInterestingDeclToConsumer(D);
7016 }
7017}
7018
7019void ASTReader::PassInterestingDeclToConsumer(Decl *D) {
7020 if (ObjCImplDecl *ImplD = dyn_cast<ObjCImplDecl>(D))
7021 PassObjCImplDeclToConsumer(ImplD, Consumer);
7022 else
7023 Consumer->HandleInterestingDecl(DeclGroupRef(D));
7024}
7025
7026void ASTReader::StartTranslationUnit(ASTConsumer *Consumer) {
7027 this->Consumer = Consumer;
7028
Richard Smith9e2341d2015-03-23 03:25:59 +00007029 if (Consumer)
7030 PassInterestingDeclsToConsumer();
Richard Smith7f330cd2015-03-18 01:42:29 +00007031
7032 if (DeserializationListener)
7033 DeserializationListener->ReaderInitialized(this);
Guy Benyei11169dd2012-12-18 14:30:41 +00007034}
7035
7036void ASTReader::PrintStats() {
7037 std::fprintf(stderr, "*** AST File Statistics:\n");
7038
7039 unsigned NumTypesLoaded
7040 = TypesLoaded.size() - std::count(TypesLoaded.begin(), TypesLoaded.end(),
7041 QualType());
7042 unsigned NumDeclsLoaded
7043 = DeclsLoaded.size() - std::count(DeclsLoaded.begin(), DeclsLoaded.end(),
Craig Toppera13603a2014-05-22 05:54:18 +00007044 (Decl *)nullptr);
Guy Benyei11169dd2012-12-18 14:30:41 +00007045 unsigned NumIdentifiersLoaded
7046 = IdentifiersLoaded.size() - std::count(IdentifiersLoaded.begin(),
7047 IdentifiersLoaded.end(),
Craig Toppera13603a2014-05-22 05:54:18 +00007048 (IdentifierInfo *)nullptr);
Guy Benyei11169dd2012-12-18 14:30:41 +00007049 unsigned NumMacrosLoaded
7050 = MacrosLoaded.size() - std::count(MacrosLoaded.begin(),
7051 MacrosLoaded.end(),
Craig Toppera13603a2014-05-22 05:54:18 +00007052 (MacroInfo *)nullptr);
Guy Benyei11169dd2012-12-18 14:30:41 +00007053 unsigned NumSelectorsLoaded
7054 = SelectorsLoaded.size() - std::count(SelectorsLoaded.begin(),
7055 SelectorsLoaded.end(),
7056 Selector());
7057
7058 if (unsigned TotalNumSLocEntries = getTotalNumSLocs())
7059 std::fprintf(stderr, " %u/%u source location entries read (%f%%)\n",
7060 NumSLocEntriesRead, TotalNumSLocEntries,
7061 ((float)NumSLocEntriesRead/TotalNumSLocEntries * 100));
7062 if (!TypesLoaded.empty())
7063 std::fprintf(stderr, " %u/%u types read (%f%%)\n",
7064 NumTypesLoaded, (unsigned)TypesLoaded.size(),
7065 ((float)NumTypesLoaded/TypesLoaded.size() * 100));
7066 if (!DeclsLoaded.empty())
7067 std::fprintf(stderr, " %u/%u declarations read (%f%%)\n",
7068 NumDeclsLoaded, (unsigned)DeclsLoaded.size(),
7069 ((float)NumDeclsLoaded/DeclsLoaded.size() * 100));
7070 if (!IdentifiersLoaded.empty())
7071 std::fprintf(stderr, " %u/%u identifiers read (%f%%)\n",
7072 NumIdentifiersLoaded, (unsigned)IdentifiersLoaded.size(),
7073 ((float)NumIdentifiersLoaded/IdentifiersLoaded.size() * 100));
7074 if (!MacrosLoaded.empty())
7075 std::fprintf(stderr, " %u/%u macros read (%f%%)\n",
7076 NumMacrosLoaded, (unsigned)MacrosLoaded.size(),
7077 ((float)NumMacrosLoaded/MacrosLoaded.size() * 100));
7078 if (!SelectorsLoaded.empty())
7079 std::fprintf(stderr, " %u/%u selectors read (%f%%)\n",
7080 NumSelectorsLoaded, (unsigned)SelectorsLoaded.size(),
7081 ((float)NumSelectorsLoaded/SelectorsLoaded.size() * 100));
7082 if (TotalNumStatements)
7083 std::fprintf(stderr, " %u/%u statements read (%f%%)\n",
7084 NumStatementsRead, TotalNumStatements,
7085 ((float)NumStatementsRead/TotalNumStatements * 100));
7086 if (TotalNumMacros)
7087 std::fprintf(stderr, " %u/%u macros read (%f%%)\n",
7088 NumMacrosRead, TotalNumMacros,
7089 ((float)NumMacrosRead/TotalNumMacros * 100));
7090 if (TotalLexicalDeclContexts)
7091 std::fprintf(stderr, " %u/%u lexical declcontexts read (%f%%)\n",
7092 NumLexicalDeclContextsRead, TotalLexicalDeclContexts,
7093 ((float)NumLexicalDeclContextsRead/TotalLexicalDeclContexts
7094 * 100));
7095 if (TotalVisibleDeclContexts)
7096 std::fprintf(stderr, " %u/%u visible declcontexts read (%f%%)\n",
7097 NumVisibleDeclContextsRead, TotalVisibleDeclContexts,
7098 ((float)NumVisibleDeclContextsRead/TotalVisibleDeclContexts
7099 * 100));
7100 if (TotalNumMethodPoolEntries) {
7101 std::fprintf(stderr, " %u/%u method pool entries read (%f%%)\n",
7102 NumMethodPoolEntriesRead, TotalNumMethodPoolEntries,
7103 ((float)NumMethodPoolEntriesRead/TotalNumMethodPoolEntries
7104 * 100));
Guy Benyei11169dd2012-12-18 14:30:41 +00007105 }
Douglas Gregorad2f7a52013-01-28 17:54:36 +00007106 if (NumMethodPoolLookups) {
7107 std::fprintf(stderr, " %u/%u method pool lookups succeeded (%f%%)\n",
7108 NumMethodPoolHits, NumMethodPoolLookups,
7109 ((float)NumMethodPoolHits/NumMethodPoolLookups * 100.0));
7110 }
7111 if (NumMethodPoolTableLookups) {
7112 std::fprintf(stderr, " %u/%u method pool table lookups succeeded (%f%%)\n",
7113 NumMethodPoolTableHits, NumMethodPoolTableLookups,
7114 ((float)NumMethodPoolTableHits/NumMethodPoolTableLookups
7115 * 100.0));
7116 }
7117
Douglas Gregor00a50f72013-01-25 00:38:33 +00007118 if (NumIdentifierLookupHits) {
7119 std::fprintf(stderr,
7120 " %u / %u identifier table lookups succeeded (%f%%)\n",
7121 NumIdentifierLookupHits, NumIdentifierLookups,
7122 (double)NumIdentifierLookupHits*100.0/NumIdentifierLookups);
7123 }
7124
Douglas Gregore060e572013-01-25 01:03:03 +00007125 if (GlobalIndex) {
7126 std::fprintf(stderr, "\n");
7127 GlobalIndex->printStats();
7128 }
David L. Jonesc4808b9e2016-12-15 20:53:26 +00007129
Guy Benyei11169dd2012-12-18 14:30:41 +00007130 std::fprintf(stderr, "\n");
7131 dump();
7132 std::fprintf(stderr, "\n");
7133}
7134
7135template<typename Key, typename ModuleFile, unsigned InitialCapacity>
David L. Jonesc4808b9e2016-12-15 20:53:26 +00007136static void
Guy Benyei11169dd2012-12-18 14:30:41 +00007137dumpModuleIDMap(StringRef Name,
David L. Jonesc4808b9e2016-12-15 20:53:26 +00007138 const ContinuousRangeMap<Key, ModuleFile *,
Guy Benyei11169dd2012-12-18 14:30:41 +00007139 InitialCapacity> &Map) {
7140 if (Map.begin() == Map.end())
7141 return;
David L. Jonesc4808b9e2016-12-15 20:53:26 +00007142
Guy Benyei11169dd2012-12-18 14:30:41 +00007143 typedef ContinuousRangeMap<Key, ModuleFile *, InitialCapacity> MapType;
7144 llvm::errs() << Name << ":\n";
David L. Jonesc4808b9e2016-12-15 20:53:26 +00007145 for (typename MapType::const_iterator I = Map.begin(), IEnd = Map.end();
Guy Benyei11169dd2012-12-18 14:30:41 +00007146 I != IEnd; ++I) {
7147 llvm::errs() << " " << I->first << " -> " << I->second->FileName
7148 << "\n";
7149 }
7150}
7151
Yaron Kerencdae9412016-01-29 19:38:18 +00007152LLVM_DUMP_METHOD void ASTReader::dump() {
Guy Benyei11169dd2012-12-18 14:30:41 +00007153 llvm::errs() << "*** PCH/ModuleFile Remappings:\n";
7154 dumpModuleIDMap("Global bit offset map", GlobalBitOffsetsMap);
7155 dumpModuleIDMap("Global source location entry map", GlobalSLocEntryMap);
7156 dumpModuleIDMap("Global type map", GlobalTypeMap);
7157 dumpModuleIDMap("Global declaration map", GlobalDeclMap);
7158 dumpModuleIDMap("Global identifier map", GlobalIdentifierMap);
7159 dumpModuleIDMap("Global macro map", GlobalMacroMap);
7160 dumpModuleIDMap("Global submodule map", GlobalSubmoduleMap);
7161 dumpModuleIDMap("Global selector map", GlobalSelectorMap);
David L. Jonesc4808b9e2016-12-15 20:53:26 +00007162 dumpModuleIDMap("Global preprocessed entity map",
Guy Benyei11169dd2012-12-18 14:30:41 +00007163 GlobalPreprocessedEntityMap);
David L. Jonesc4808b9e2016-12-15 20:53:26 +00007164
Guy Benyei11169dd2012-12-18 14:30:41 +00007165 llvm::errs() << "\n*** PCH/Modules Loaded:";
Duncan P. N. Exon Smith96a06e02017-01-28 22:15:22 +00007166 for (ModuleFile &M : ModuleMgr)
7167 M.dump();
Guy Benyei11169dd2012-12-18 14:30:41 +00007168}
7169
7170/// Return the amount of memory used by memory buffers, breaking down
7171/// by heap-backed versus mmap'ed memory.
7172void ASTReader::getMemoryBufferSizes(MemoryBufferSizes &sizes) const {
Duncan P. N. Exon Smith96a06e02017-01-28 22:15:22 +00007173 for (ModuleFile &I : ModuleMgr) {
7174 if (llvm::MemoryBuffer *buf = I.Buffer.get()) {
Guy Benyei11169dd2012-12-18 14:30:41 +00007175 size_t bytes = buf->getBufferSize();
7176 switch (buf->getBufferKind()) {
7177 case llvm::MemoryBuffer::MemoryBuffer_Malloc:
7178 sizes.malloc_bytes += bytes;
7179 break;
7180 case llvm::MemoryBuffer::MemoryBuffer_MMap:
7181 sizes.mmap_bytes += bytes;
7182 break;
7183 }
7184 }
7185 }
7186}
7187
7188void ASTReader::InitializeSema(Sema &S) {
7189 SemaObj = &S;
7190 S.addExternalSource(this);
7191
7192 // Makes sure any declarations that were deserialized "too early"
7193 // still get added to the identifier's declaration chains.
Ben Langmuir5418f402014-09-10 21:29:41 +00007194 for (uint64_t ID : PreloadedDeclIDs) {
7195 NamedDecl *D = cast<NamedDecl>(GetDecl(ID));
7196 pushExternalDeclIntoScope(D, D->getDeclName());
Guy Benyei11169dd2012-12-18 14:30:41 +00007197 }
Ben Langmuir5418f402014-09-10 21:29:41 +00007198 PreloadedDeclIDs.clear();
Guy Benyei11169dd2012-12-18 14:30:41 +00007199
Richard Smith3d8e97e2013-10-18 06:54:39 +00007200 // FIXME: What happens if these are changed by a module import?
Guy Benyei11169dd2012-12-18 14:30:41 +00007201 if (!FPPragmaOptions.empty()) {
7202 assert(FPPragmaOptions.size() == 1 && "Wrong number of FP_PRAGMA_OPTIONS");
7203 SemaObj->FPFeatures.fp_contract = FPPragmaOptions[0];
7204 }
7205
Yaxun Liu5b746652016-12-18 05:18:55 +00007206 SemaObj->OpenCLFeatures.copy(OpenCLExtensions);
7207 SemaObj->OpenCLTypeExtMap = OpenCLTypeExtMap;
7208 SemaObj->OpenCLDeclExtMap = OpenCLDeclExtMap;
Richard Smith3d8e97e2013-10-18 06:54:39 +00007209
7210 UpdateSema();
7211}
7212
7213void ASTReader::UpdateSema() {
7214 assert(SemaObj && "no Sema to update");
7215
7216 // Load the offsets of the declarations that Sema references.
7217 // They will be lazily deserialized when needed.
7218 if (!SemaDeclRefs.empty()) {
Richard Smith96269c52016-09-29 22:49:46 +00007219 assert(SemaDeclRefs.size() % 3 == 0);
7220 for (unsigned I = 0; I != SemaDeclRefs.size(); I += 3) {
Richard Smith3d8e97e2013-10-18 06:54:39 +00007221 if (!SemaObj->StdNamespace)
7222 SemaObj->StdNamespace = SemaDeclRefs[I];
7223 if (!SemaObj->StdBadAlloc)
7224 SemaObj->StdBadAlloc = SemaDeclRefs[I+1];
Richard Smith96269c52016-09-29 22:49:46 +00007225 if (!SemaObj->StdAlignValT)
7226 SemaObj->StdAlignValT = SemaDeclRefs[I+2];
Richard Smith3d8e97e2013-10-18 06:54:39 +00007227 }
7228 SemaDeclRefs.clear();
7229 }
Dario Domizioli13a0a382014-05-23 12:13:25 +00007230
Nico Weber779355f2016-03-02 23:22:00 +00007231 // Update the state of pragmas. Use the same API as if we had encountered the
7232 // pragma in the source.
Dario Domizioli13a0a382014-05-23 12:13:25 +00007233 if(OptimizeOffPragmaLocation.isValid())
7234 SemaObj->ActOnPragmaOptimize(/* IsOn = */ false, OptimizeOffPragmaLocation);
Nico Weber779355f2016-03-02 23:22:00 +00007235 if (PragmaMSStructState != -1)
7236 SemaObj->ActOnPragmaMSStruct((PragmaMSStructKind)PragmaMSStructState);
Nico Weber42932312016-03-03 00:17:35 +00007237 if (PointersToMembersPragmaLocation.isValid()) {
7238 SemaObj->ActOnPragmaMSPointersToMembers(
7239 (LangOptions::PragmaMSPointersToMembersKind)
7240 PragmaMSPointersToMembersState,
7241 PointersToMembersPragmaLocation);
7242 }
Justin Lebar67a78a62016-10-08 22:15:58 +00007243 SemaObj->ForceCUDAHostDeviceDepth = ForceCUDAHostDeviceDepth;
Guy Benyei11169dd2012-12-18 14:30:41 +00007244}
7245
Richard Smitha8d5b6a2015-07-17 19:51:03 +00007246IdentifierInfo *ASTReader::get(StringRef Name) {
Guy Benyei11169dd2012-12-18 14:30:41 +00007247 // Note that we are loading an identifier.
7248 Deserializing AnIdentifier(this);
Douglas Gregore060e572013-01-25 01:03:03 +00007249
Douglas Gregor7211ac12013-01-25 23:32:03 +00007250 IdentifierLookupVisitor Visitor(Name, /*PriorGeneration=*/0,
Douglas Gregor00a50f72013-01-25 00:38:33 +00007251 NumIdentifierLookups,
7252 NumIdentifierLookupHits);
Richard Smith33e0f7e2015-07-22 02:08:40 +00007253
7254 // We don't need to do identifier table lookups in C++ modules (we preload
7255 // all interesting declarations, and don't need to use the scope for name
7256 // lookups). Perform the lookup in PCH files, though, since we don't build
7257 // a complete initial identifier table if we're carrying on from a PCH.
7258 if (Context.getLangOpts().CPlusPlus) {
7259 for (auto F : ModuleMgr.pch_modules())
Benjamin Kramer9a9efba2015-07-25 12:14:04 +00007260 if (Visitor(*F))
Richard Smith33e0f7e2015-07-22 02:08:40 +00007261 break;
7262 } else {
7263 // If there is a global index, look there first to determine which modules
7264 // provably do not have any results for this identifier.
7265 GlobalModuleIndex::HitSet Hits;
7266 GlobalModuleIndex::HitSet *HitsPtr = nullptr;
7267 if (!loadGlobalIndex()) {
7268 if (GlobalIndex->lookupIdentifier(Name, Hits)) {
7269 HitsPtr = &Hits;
7270 }
7271 }
7272
Benjamin Kramer9a9efba2015-07-25 12:14:04 +00007273 ModuleMgr.visit(Visitor, HitsPtr);
Richard Smith33e0f7e2015-07-22 02:08:40 +00007274 }
7275
Guy Benyei11169dd2012-12-18 14:30:41 +00007276 IdentifierInfo *II = Visitor.getIdentifierInfo();
7277 markIdentifierUpToDate(II);
7278 return II;
7279}
7280
7281namespace clang {
Eugene Zelenkoe95e7d52016-09-07 21:53:17 +00007282
Guy Benyei11169dd2012-12-18 14:30:41 +00007283 /// \brief An identifier-lookup iterator that enumerates all of the
7284 /// identifiers stored within a set of AST files.
7285 class ASTIdentifierIterator : public IdentifierIterator {
7286 /// \brief The AST reader whose identifiers are being enumerated.
7287 const ASTReader &Reader;
7288
7289 /// \brief The current index into the chain of AST files stored in
7290 /// the AST reader.
7291 unsigned Index;
7292
7293 /// \brief The current position within the identifier lookup table
7294 /// of the current AST file.
7295 ASTIdentifierLookupTable::key_iterator Current;
7296
7297 /// \brief The end position within the identifier lookup table of
7298 /// the current AST file.
7299 ASTIdentifierLookupTable::key_iterator End;
7300
Ben Langmuir537c5b52016-05-04 00:53:13 +00007301 /// \brief Whether to skip any modules in the ASTReader.
7302 bool SkipModules;
7303
Guy Benyei11169dd2012-12-18 14:30:41 +00007304 public:
Ben Langmuir537c5b52016-05-04 00:53:13 +00007305 explicit ASTIdentifierIterator(const ASTReader &Reader,
7306 bool SkipModules = false);
Guy Benyei11169dd2012-12-18 14:30:41 +00007307
Craig Topper3e89dfe2014-03-13 02:13:41 +00007308 StringRef Next() override;
Guy Benyei11169dd2012-12-18 14:30:41 +00007309 };
Eugene Zelenkoe95e7d52016-09-07 21:53:17 +00007310
7311} // end namespace clang
Guy Benyei11169dd2012-12-18 14:30:41 +00007312
Ben Langmuir537c5b52016-05-04 00:53:13 +00007313ASTIdentifierIterator::ASTIdentifierIterator(const ASTReader &Reader,
7314 bool SkipModules)
7315 : Reader(Reader), Index(Reader.ModuleMgr.size()), SkipModules(SkipModules) {
Guy Benyei11169dd2012-12-18 14:30:41 +00007316}
7317
7318StringRef ASTIdentifierIterator::Next() {
7319 while (Current == End) {
7320 // If we have exhausted all of our AST files, we're done.
7321 if (Index == 0)
7322 return StringRef();
7323
7324 --Index;
Ben Langmuir537c5b52016-05-04 00:53:13 +00007325 ModuleFile &F = Reader.ModuleMgr[Index];
7326 if (SkipModules && F.isModule())
7327 continue;
7328
7329 ASTIdentifierLookupTable *IdTable =
7330 (ASTIdentifierLookupTable *)F.IdentifierLookupTable;
Guy Benyei11169dd2012-12-18 14:30:41 +00007331 Current = IdTable->key_begin();
7332 End = IdTable->key_end();
7333 }
7334
7335 // We have any identifiers remaining in the current AST file; return
7336 // the next one.
Douglas Gregorbfd73d72013-01-23 18:53:14 +00007337 StringRef Result = *Current;
Guy Benyei11169dd2012-12-18 14:30:41 +00007338 ++Current;
Douglas Gregorbfd73d72013-01-23 18:53:14 +00007339 return Result;
Guy Benyei11169dd2012-12-18 14:30:41 +00007340}
7341
Ben Langmuir537c5b52016-05-04 00:53:13 +00007342namespace {
Eugene Zelenkoe95e7d52016-09-07 21:53:17 +00007343
Ben Langmuir537c5b52016-05-04 00:53:13 +00007344/// A utility for appending two IdentifierIterators.
7345class ChainedIdentifierIterator : public IdentifierIterator {
7346 std::unique_ptr<IdentifierIterator> Current;
7347 std::unique_ptr<IdentifierIterator> Queued;
7348
7349public:
7350 ChainedIdentifierIterator(std::unique_ptr<IdentifierIterator> First,
7351 std::unique_ptr<IdentifierIterator> Second)
7352 : Current(std::move(First)), Queued(std::move(Second)) {}
7353
7354 StringRef Next() override {
7355 if (!Current)
7356 return StringRef();
7357
7358 StringRef result = Current->Next();
7359 if (!result.empty())
7360 return result;
7361
7362 // Try the queued iterator, which may itself be empty.
7363 Current.reset();
7364 std::swap(Current, Queued);
7365 return Next();
7366 }
7367};
Eugene Zelenkoe95e7d52016-09-07 21:53:17 +00007368
Ben Langmuir537c5b52016-05-04 00:53:13 +00007369} // end anonymous namespace.
7370
Argyrios Kyrtzidis9aca3c62013-04-17 22:10:55 +00007371IdentifierIterator *ASTReader::getIdentifiers() {
Ben Langmuir537c5b52016-05-04 00:53:13 +00007372 if (!loadGlobalIndex()) {
7373 std::unique_ptr<IdentifierIterator> ReaderIter(
7374 new ASTIdentifierIterator(*this, /*SkipModules=*/true));
7375 std::unique_ptr<IdentifierIterator> ModulesIter(
7376 GlobalIndex->createIdentifierIterator());
7377 return new ChainedIdentifierIterator(std::move(ReaderIter),
7378 std::move(ModulesIter));
7379 }
Argyrios Kyrtzidis9aca3c62013-04-17 22:10:55 +00007380
Guy Benyei11169dd2012-12-18 14:30:41 +00007381 return new ASTIdentifierIterator(*this);
7382}
7383
Eugene Zelenkoe95e7d52016-09-07 21:53:17 +00007384namespace clang {
7385namespace serialization {
7386
Guy Benyei11169dd2012-12-18 14:30:41 +00007387 class ReadMethodPoolVisitor {
7388 ASTReader &Reader;
7389 Selector Sel;
7390 unsigned PriorGeneration;
Argyrios Kyrtzidisd3da6e02013-04-17 00:08:58 +00007391 unsigned InstanceBits;
7392 unsigned FactoryBits;
Nico Weberff4b35e2014-12-27 22:14:15 +00007393 bool InstanceHasMoreThanOneDecl;
7394 bool FactoryHasMoreThanOneDecl;
Dmitri Gribenkof8579502013-01-12 19:30:44 +00007395 SmallVector<ObjCMethodDecl *, 4> InstanceMethods;
7396 SmallVector<ObjCMethodDecl *, 4> FactoryMethods;
Guy Benyei11169dd2012-12-18 14:30:41 +00007397
7398 public:
Nico Weber2e0c8f72014-12-27 03:58:08 +00007399 ReadMethodPoolVisitor(ASTReader &Reader, Selector Sel,
Guy Benyei11169dd2012-12-18 14:30:41 +00007400 unsigned PriorGeneration)
Nico Weber2e0c8f72014-12-27 03:58:08 +00007401 : Reader(Reader), Sel(Sel), PriorGeneration(PriorGeneration),
Nico Weberff4b35e2014-12-27 22:14:15 +00007402 InstanceBits(0), FactoryBits(0), InstanceHasMoreThanOneDecl(false),
7403 FactoryHasMoreThanOneDecl(false) {}
Nico Weber2e0c8f72014-12-27 03:58:08 +00007404
Benjamin Kramer9a9efba2015-07-25 12:14:04 +00007405 bool operator()(ModuleFile &M) {
Guy Benyei11169dd2012-12-18 14:30:41 +00007406 if (!M.SelectorLookupTable)
7407 return false;
David L. Jonesc4808b9e2016-12-15 20:53:26 +00007408
Guy Benyei11169dd2012-12-18 14:30:41 +00007409 // If we've already searched this module file, skip it now.
Richard Smithbdf2d932015-07-30 03:37:16 +00007410 if (M.Generation <= PriorGeneration)
Guy Benyei11169dd2012-12-18 14:30:41 +00007411 return true;
7412
Richard Smithbdf2d932015-07-30 03:37:16 +00007413 ++Reader.NumMethodPoolTableLookups;
Guy Benyei11169dd2012-12-18 14:30:41 +00007414 ASTSelectorLookupTable *PoolTable
7415 = (ASTSelectorLookupTable*)M.SelectorLookupTable;
Richard Smithbdf2d932015-07-30 03:37:16 +00007416 ASTSelectorLookupTable::iterator Pos = PoolTable->find(Sel);
Guy Benyei11169dd2012-12-18 14:30:41 +00007417 if (Pos == PoolTable->end())
7418 return false;
Douglas Gregorad2f7a52013-01-28 17:54:36 +00007419
Richard Smithbdf2d932015-07-30 03:37:16 +00007420 ++Reader.NumMethodPoolTableHits;
7421 ++Reader.NumSelectorsRead;
Guy Benyei11169dd2012-12-18 14:30:41 +00007422 // FIXME: Not quite happy with the statistics here. We probably should
7423 // disable this tracking when called via LoadSelector.
7424 // Also, should entries without methods count as misses?
Richard Smithbdf2d932015-07-30 03:37:16 +00007425 ++Reader.NumMethodPoolEntriesRead;
Guy Benyei11169dd2012-12-18 14:30:41 +00007426 ASTSelectorLookupTrait::data_type Data = *Pos;
Richard Smithbdf2d932015-07-30 03:37:16 +00007427 if (Reader.DeserializationListener)
7428 Reader.DeserializationListener->SelectorRead(Data.ID, Sel);
Benjamin Kramer9a9efba2015-07-25 12:14:04 +00007429
Richard Smithbdf2d932015-07-30 03:37:16 +00007430 InstanceMethods.append(Data.Instance.begin(), Data.Instance.end());
7431 FactoryMethods.append(Data.Factory.begin(), Data.Factory.end());
7432 InstanceBits = Data.InstanceBits;
7433 FactoryBits = Data.FactoryBits;
7434 InstanceHasMoreThanOneDecl = Data.InstanceHasMoreThanOneDecl;
7435 FactoryHasMoreThanOneDecl = Data.FactoryHasMoreThanOneDecl;
Guy Benyei11169dd2012-12-18 14:30:41 +00007436 return true;
7437 }
David L. Jonesc4808b9e2016-12-15 20:53:26 +00007438
Guy Benyei11169dd2012-12-18 14:30:41 +00007439 /// \brief Retrieve the instance methods found by this visitor.
David L. Jonesc4808b9e2016-12-15 20:53:26 +00007440 ArrayRef<ObjCMethodDecl *> getInstanceMethods() const {
7441 return InstanceMethods;
Guy Benyei11169dd2012-12-18 14:30:41 +00007442 }
7443
7444 /// \brief Retrieve the instance methods found by this visitor.
David L. Jonesc4808b9e2016-12-15 20:53:26 +00007445 ArrayRef<ObjCMethodDecl *> getFactoryMethods() const {
Guy Benyei11169dd2012-12-18 14:30:41 +00007446 return FactoryMethods;
7447 }
Argyrios Kyrtzidisd3da6e02013-04-17 00:08:58 +00007448
7449 unsigned getInstanceBits() const { return InstanceBits; }
7450 unsigned getFactoryBits() const { return FactoryBits; }
Nico Weberff4b35e2014-12-27 22:14:15 +00007451 bool instanceHasMoreThanOneDecl() const {
7452 return InstanceHasMoreThanOneDecl;
7453 }
7454 bool factoryHasMoreThanOneDecl() const { return FactoryHasMoreThanOneDecl; }
Guy Benyei11169dd2012-12-18 14:30:41 +00007455 };
Eugene Zelenkoe95e7d52016-09-07 21:53:17 +00007456
7457} // end namespace serialization
7458} // end namespace clang
Guy Benyei11169dd2012-12-18 14:30:41 +00007459
7460/// \brief Add the given set of methods to the method list.
7461static void addMethodsToPool(Sema &S, ArrayRef<ObjCMethodDecl *> Methods,
7462 ObjCMethodList &List) {
7463 for (unsigned I = 0, N = Methods.size(); I != N; ++I) {
7464 S.addMethodToGlobalList(&List, Methods[I]);
7465 }
7466}
David L. Jonesc4808b9e2016-12-15 20:53:26 +00007467
Guy Benyei11169dd2012-12-18 14:30:41 +00007468void ASTReader::ReadMethodPool(Selector Sel) {
7469 // Get the selector generation and update it to the current generation.
7470 unsigned &Generation = SelectorGeneration[Sel];
7471 unsigned PriorGeneration = Generation;
Richard Smith053f6c62014-05-16 23:01:30 +00007472 Generation = getGeneration();
Manman Rena0f31a02016-04-29 19:04:05 +00007473 SelectorOutOfDate[Sel] = false;
David L. Jonesc4808b9e2016-12-15 20:53:26 +00007474
Guy Benyei11169dd2012-12-18 14:30:41 +00007475 // Search for methods defined with this selector.
Douglas Gregorad2f7a52013-01-28 17:54:36 +00007476 ++NumMethodPoolLookups;
Guy Benyei11169dd2012-12-18 14:30:41 +00007477 ReadMethodPoolVisitor Visitor(*this, Sel, PriorGeneration);
Benjamin Kramer9a9efba2015-07-25 12:14:04 +00007478 ModuleMgr.visit(Visitor);
7479
Guy Benyei11169dd2012-12-18 14:30:41 +00007480 if (Visitor.getInstanceMethods().empty() &&
Douglas Gregorad2f7a52013-01-28 17:54:36 +00007481 Visitor.getFactoryMethods().empty())
Guy Benyei11169dd2012-12-18 14:30:41 +00007482 return;
Douglas Gregorad2f7a52013-01-28 17:54:36 +00007483
7484 ++NumMethodPoolHits;
7485
Guy Benyei11169dd2012-12-18 14:30:41 +00007486 if (!getSema())
7487 return;
David L. Jonesc4808b9e2016-12-15 20:53:26 +00007488
Guy Benyei11169dd2012-12-18 14:30:41 +00007489 Sema &S = *getSema();
7490 Sema::GlobalMethodPool::iterator Pos
7491 = S.MethodPool.insert(std::make_pair(Sel, Sema::GlobalMethods())).first;
Ben Langmuira0c32e92015-01-12 19:27:00 +00007492
Argyrios Kyrtzidisd3da6e02013-04-17 00:08:58 +00007493 Pos->second.first.setBits(Visitor.getInstanceBits());
Nico Weberff4b35e2014-12-27 22:14:15 +00007494 Pos->second.first.setHasMoreThanOneDecl(Visitor.instanceHasMoreThanOneDecl());
Argyrios Kyrtzidisd3da6e02013-04-17 00:08:58 +00007495 Pos->second.second.setBits(Visitor.getFactoryBits());
Nico Weberff4b35e2014-12-27 22:14:15 +00007496 Pos->second.second.setHasMoreThanOneDecl(Visitor.factoryHasMoreThanOneDecl());
Ben Langmuira0c32e92015-01-12 19:27:00 +00007497
7498 // Add methods to the global pool *after* setting hasMoreThanOneDecl, since
7499 // when building a module we keep every method individually and may need to
7500 // update hasMoreThanOneDecl as we add the methods.
7501 addMethodsToPool(S, Visitor.getInstanceMethods(), Pos->second.first);
7502 addMethodsToPool(S, Visitor.getFactoryMethods(), Pos->second.second);
Guy Benyei11169dd2012-12-18 14:30:41 +00007503}
7504
Manman Rena0f31a02016-04-29 19:04:05 +00007505void ASTReader::updateOutOfDateSelector(Selector Sel) {
7506 if (SelectorOutOfDate[Sel])
7507 ReadMethodPool(Sel);
7508}
7509
Guy Benyei11169dd2012-12-18 14:30:41 +00007510void ASTReader::ReadKnownNamespaces(
7511 SmallVectorImpl<NamespaceDecl *> &Namespaces) {
7512 Namespaces.clear();
David L. Jonesc4808b9e2016-12-15 20:53:26 +00007513
Guy Benyei11169dd2012-12-18 14:30:41 +00007514 for (unsigned I = 0, N = KnownNamespaces.size(); I != N; ++I) {
David L. Jonesc4808b9e2016-12-15 20:53:26 +00007515 if (NamespaceDecl *Namespace
Guy Benyei11169dd2012-12-18 14:30:41 +00007516 = dyn_cast_or_null<NamespaceDecl>(GetDecl(KnownNamespaces[I])))
7517 Namespaces.push_back(Namespace);
7518 }
7519}
7520
Nick Lewycky9c7eb1d2013-02-01 08:13:20 +00007521void ASTReader::ReadUndefinedButUsed(
Richard Smithd6a04d72016-03-25 21:49:43 +00007522 llvm::MapVector<NamedDecl *, SourceLocation> &Undefined) {
Nick Lewycky9c7eb1d2013-02-01 08:13:20 +00007523 for (unsigned Idx = 0, N = UndefinedButUsed.size(); Idx != N;) {
7524 NamedDecl *D = cast<NamedDecl>(GetDecl(UndefinedButUsed[Idx++]));
Nick Lewycky8334af82013-01-26 00:35:08 +00007525 SourceLocation Loc =
Nick Lewycky9c7eb1d2013-02-01 08:13:20 +00007526 SourceLocation::getFromRawEncoding(UndefinedButUsed[Idx++]);
Nick Lewycky8334af82013-01-26 00:35:08 +00007527 Undefined.insert(std::make_pair(D, Loc));
7528 }
7529}
Nick Lewycky8334af82013-01-26 00:35:08 +00007530
Ismail Pazarbasie5768d12015-05-18 19:59:11 +00007531void ASTReader::ReadMismatchingDeleteExpressions(llvm::MapVector<
7532 FieldDecl *, llvm::SmallVector<std::pair<SourceLocation, bool>, 4>> &
7533 Exprs) {
7534 for (unsigned Idx = 0, N = DelayedDeleteExprs.size(); Idx != N;) {
7535 FieldDecl *FD = cast<FieldDecl>(GetDecl(DelayedDeleteExprs[Idx++]));
7536 uint64_t Count = DelayedDeleteExprs[Idx++];
7537 for (uint64_t C = 0; C < Count; ++C) {
7538 SourceLocation DeleteLoc =
7539 SourceLocation::getFromRawEncoding(DelayedDeleteExprs[Idx++]);
7540 const bool IsArrayForm = DelayedDeleteExprs[Idx++];
7541 Exprs[FD].push_back(std::make_pair(DeleteLoc, IsArrayForm));
7542 }
7543 }
7544}
7545
Guy Benyei11169dd2012-12-18 14:30:41 +00007546void ASTReader::ReadTentativeDefinitions(
7547 SmallVectorImpl<VarDecl *> &TentativeDefs) {
7548 for (unsigned I = 0, N = TentativeDefinitions.size(); I != N; ++I) {
7549 VarDecl *Var = dyn_cast_or_null<VarDecl>(GetDecl(TentativeDefinitions[I]));
7550 if (Var)
7551 TentativeDefs.push_back(Var);
7552 }
7553 TentativeDefinitions.clear();
7554}
7555
7556void ASTReader::ReadUnusedFileScopedDecls(
7557 SmallVectorImpl<const DeclaratorDecl *> &Decls) {
7558 for (unsigned I = 0, N = UnusedFileScopedDecls.size(); I != N; ++I) {
7559 DeclaratorDecl *D
7560 = dyn_cast_or_null<DeclaratorDecl>(GetDecl(UnusedFileScopedDecls[I]));
7561 if (D)
7562 Decls.push_back(D);
7563 }
7564 UnusedFileScopedDecls.clear();
7565}
7566
7567void ASTReader::ReadDelegatingConstructors(
7568 SmallVectorImpl<CXXConstructorDecl *> &Decls) {
7569 for (unsigned I = 0, N = DelegatingCtorDecls.size(); I != N; ++I) {
7570 CXXConstructorDecl *D
7571 = dyn_cast_or_null<CXXConstructorDecl>(GetDecl(DelegatingCtorDecls[I]));
7572 if (D)
7573 Decls.push_back(D);
7574 }
7575 DelegatingCtorDecls.clear();
7576}
7577
7578void ASTReader::ReadExtVectorDecls(SmallVectorImpl<TypedefNameDecl *> &Decls) {
7579 for (unsigned I = 0, N = ExtVectorDecls.size(); I != N; ++I) {
7580 TypedefNameDecl *D
7581 = dyn_cast_or_null<TypedefNameDecl>(GetDecl(ExtVectorDecls[I]));
7582 if (D)
7583 Decls.push_back(D);
7584 }
7585 ExtVectorDecls.clear();
7586}
7587
Nico Weber72889432014-09-06 01:25:55 +00007588void ASTReader::ReadUnusedLocalTypedefNameCandidates(
7589 llvm::SmallSetVector<const TypedefNameDecl *, 4> &Decls) {
7590 for (unsigned I = 0, N = UnusedLocalTypedefNameCandidates.size(); I != N;
7591 ++I) {
7592 TypedefNameDecl *D = dyn_cast_or_null<TypedefNameDecl>(
7593 GetDecl(UnusedLocalTypedefNameCandidates[I]));
7594 if (D)
7595 Decls.insert(D);
7596 }
7597 UnusedLocalTypedefNameCandidates.clear();
7598}
7599
Guy Benyei11169dd2012-12-18 14:30:41 +00007600void ASTReader::ReadReferencedSelectors(
7601 SmallVectorImpl<std::pair<Selector, SourceLocation> > &Sels) {
7602 if (ReferencedSelectorsData.empty())
7603 return;
David L. Jonesc4808b9e2016-12-15 20:53:26 +00007604
Guy Benyei11169dd2012-12-18 14:30:41 +00007605 // If there are @selector references added them to its pool. This is for
7606 // implementation of -Wselector.
7607 unsigned int DataSize = ReferencedSelectorsData.size()-1;
7608 unsigned I = 0;
7609 while (I < DataSize) {
7610 Selector Sel = DecodeSelector(ReferencedSelectorsData[I++]);
7611 SourceLocation SelLoc
7612 = SourceLocation::getFromRawEncoding(ReferencedSelectorsData[I++]);
7613 Sels.push_back(std::make_pair(Sel, SelLoc));
7614 }
7615 ReferencedSelectorsData.clear();
7616}
7617
7618void ASTReader::ReadWeakUndeclaredIdentifiers(
7619 SmallVectorImpl<std::pair<IdentifierInfo *, WeakInfo> > &WeakIDs) {
7620 if (WeakUndeclaredIdentifiers.empty())
7621 return;
7622
7623 for (unsigned I = 0, N = WeakUndeclaredIdentifiers.size(); I < N; /*none*/) {
David L. Jonesc4808b9e2016-12-15 20:53:26 +00007624 IdentifierInfo *WeakId
Guy Benyei11169dd2012-12-18 14:30:41 +00007625 = DecodeIdentifierInfo(WeakUndeclaredIdentifiers[I++]);
David L. Jonesc4808b9e2016-12-15 20:53:26 +00007626 IdentifierInfo *AliasId
Guy Benyei11169dd2012-12-18 14:30:41 +00007627 = DecodeIdentifierInfo(WeakUndeclaredIdentifiers[I++]);
7628 SourceLocation Loc
7629 = SourceLocation::getFromRawEncoding(WeakUndeclaredIdentifiers[I++]);
7630 bool Used = WeakUndeclaredIdentifiers[I++];
7631 WeakInfo WI(AliasId, Loc);
7632 WI.setUsed(Used);
7633 WeakIDs.push_back(std::make_pair(WeakId, WI));
7634 }
7635 WeakUndeclaredIdentifiers.clear();
7636}
7637
7638void ASTReader::ReadUsedVTables(SmallVectorImpl<ExternalVTableUse> &VTables) {
7639 for (unsigned Idx = 0, N = VTableUses.size(); Idx < N; /* In loop */) {
7640 ExternalVTableUse VT;
7641 VT.Record = dyn_cast_or_null<CXXRecordDecl>(GetDecl(VTableUses[Idx++]));
7642 VT.Location = SourceLocation::getFromRawEncoding(VTableUses[Idx++]);
7643 VT.DefinitionRequired = VTableUses[Idx++];
7644 VTables.push_back(VT);
7645 }
David L. Jonesc4808b9e2016-12-15 20:53:26 +00007646
Guy Benyei11169dd2012-12-18 14:30:41 +00007647 VTableUses.clear();
7648}
7649
7650void ASTReader::ReadPendingInstantiations(
7651 SmallVectorImpl<std::pair<ValueDecl *, SourceLocation> > &Pending) {
7652 for (unsigned Idx = 0, N = PendingInstantiations.size(); Idx < N;) {
7653 ValueDecl *D = cast<ValueDecl>(GetDecl(PendingInstantiations[Idx++]));
7654 SourceLocation Loc
7655 = SourceLocation::getFromRawEncoding(PendingInstantiations[Idx++]);
7656
7657 Pending.push_back(std::make_pair(D, Loc));
David L. Jonesc4808b9e2016-12-15 20:53:26 +00007658 }
Guy Benyei11169dd2012-12-18 14:30:41 +00007659 PendingInstantiations.clear();
7660}
7661
Richard Smithe40f2ba2013-08-07 21:41:30 +00007662void ASTReader::ReadLateParsedTemplates(
Justin Lebar28f09c52016-10-10 16:26:08 +00007663 llvm::MapVector<const FunctionDecl *, std::unique_ptr<LateParsedTemplate>>
7664 &LPTMap) {
Richard Smithe40f2ba2013-08-07 21:41:30 +00007665 for (unsigned Idx = 0, N = LateParsedTemplates.size(); Idx < N;
7666 /* In loop */) {
7667 FunctionDecl *FD = cast<FunctionDecl>(GetDecl(LateParsedTemplates[Idx++]));
7668
Justin Lebar28f09c52016-10-10 16:26:08 +00007669 auto LT = llvm::make_unique<LateParsedTemplate>();
Richard Smithe40f2ba2013-08-07 21:41:30 +00007670 LT->D = GetDecl(LateParsedTemplates[Idx++]);
7671
7672 ModuleFile *F = getOwningModuleFile(LT->D);
7673 assert(F && "No module");
7674
7675 unsigned TokN = LateParsedTemplates[Idx++];
7676 LT->Toks.reserve(TokN);
7677 for (unsigned T = 0; T < TokN; ++T)
7678 LT->Toks.push_back(ReadToken(*F, LateParsedTemplates, Idx));
7679
Justin Lebar28f09c52016-10-10 16:26:08 +00007680 LPTMap.insert(std::make_pair(FD, std::move(LT)));
Richard Smithe40f2ba2013-08-07 21:41:30 +00007681 }
7682
7683 LateParsedTemplates.clear();
7684}
7685
Guy Benyei11169dd2012-12-18 14:30:41 +00007686void ASTReader::LoadSelector(Selector Sel) {
7687 // It would be complicated to avoid reading the methods anyway. So don't.
7688 ReadMethodPool(Sel);
7689}
7690
7691void ASTReader::SetIdentifierInfo(IdentifierID ID, IdentifierInfo *II) {
7692 assert(ID && "Non-zero identifier ID required");
7693 assert(ID <= IdentifiersLoaded.size() && "identifier ID out of range");
7694 IdentifiersLoaded[ID - 1] = II;
7695 if (DeserializationListener)
7696 DeserializationListener->IdentifierRead(ID, II);
7697}
7698
7699/// \brief Set the globally-visible declarations associated with the given
7700/// identifier.
7701///
7702/// If the AST reader is currently in a state where the given declaration IDs
7703/// cannot safely be resolved, they are queued until it is safe to resolve
7704/// them.
7705///
7706/// \param II an IdentifierInfo that refers to one or more globally-visible
7707/// declarations.
7708///
7709/// \param DeclIDs the set of declaration IDs with the name @p II that are
7710/// visible at global scope.
7711///
Douglas Gregor6168bd22013-02-18 15:53:43 +00007712/// \param Decls if non-null, this vector will be populated with the set of
7713/// deserialized declarations. These declarations will not be pushed into
7714/// scope.
Guy Benyei11169dd2012-12-18 14:30:41 +00007715void
7716ASTReader::SetGloballyVisibleDecls(IdentifierInfo *II,
7717 const SmallVectorImpl<uint32_t> &DeclIDs,
Douglas Gregor6168bd22013-02-18 15:53:43 +00007718 SmallVectorImpl<Decl *> *Decls) {
7719 if (NumCurrentElementsDeserializing && !Decls) {
7720 PendingIdentifierInfos[II].append(DeclIDs.begin(), DeclIDs.end());
Guy Benyei11169dd2012-12-18 14:30:41 +00007721 return;
7722 }
7723
7724 for (unsigned I = 0, N = DeclIDs.size(); I != N; ++I) {
Ben Langmuir5418f402014-09-10 21:29:41 +00007725 if (!SemaObj) {
Guy Benyei11169dd2012-12-18 14:30:41 +00007726 // Queue this declaration so that it will be added to the
7727 // translation unit scope and identifier's declaration chain
7728 // once a Sema object is known.
Ben Langmuir5418f402014-09-10 21:29:41 +00007729 PreloadedDeclIDs.push_back(DeclIDs[I]);
7730 continue;
Guy Benyei11169dd2012-12-18 14:30:41 +00007731 }
Ben Langmuir5418f402014-09-10 21:29:41 +00007732
7733 NamedDecl *D = cast<NamedDecl>(GetDecl(DeclIDs[I]));
7734
7735 // If we're simply supposed to record the declarations, do so now.
7736 if (Decls) {
7737 Decls->push_back(D);
7738 continue;
7739 }
7740
7741 // Introduce this declaration into the translation-unit scope
7742 // and add it to the declaration chain for this identifier, so
7743 // that (unqualified) name lookup will find it.
7744 pushExternalDeclIntoScope(D, II);
Guy Benyei11169dd2012-12-18 14:30:41 +00007745 }
7746}
7747
Douglas Gregorc8a992f2013-01-21 16:52:34 +00007748IdentifierInfo *ASTReader::DecodeIdentifierInfo(IdentifierID ID) {
Guy Benyei11169dd2012-12-18 14:30:41 +00007749 if (ID == 0)
Craig Toppera13603a2014-05-22 05:54:18 +00007750 return nullptr;
Guy Benyei11169dd2012-12-18 14:30:41 +00007751
7752 if (IdentifiersLoaded.empty()) {
7753 Error("no identifier table in AST file");
Craig Toppera13603a2014-05-22 05:54:18 +00007754 return nullptr;
Guy Benyei11169dd2012-12-18 14:30:41 +00007755 }
7756
7757 ID -= 1;
7758 if (!IdentifiersLoaded[ID]) {
7759 GlobalIdentifierMapType::iterator I = GlobalIdentifierMap.find(ID + 1);
7760 assert(I != GlobalIdentifierMap.end() && "Corrupted global identifier map");
7761 ModuleFile *M = I->second;
7762 unsigned Index = ID - M->BaseIdentifierID;
7763 const char *Str = M->IdentifierTableData + M->IdentifierOffsets[Index];
7764
7765 // All of the strings in the AST file are preceded by a 16-bit length.
7766 // Extract that 16-bit length to avoid having to execute strlen().
7767 // NOTE: 'StrLenPtr' is an 'unsigned char*' so that we load bytes as
7768 // unsigned integers. This is important to avoid integer overflow when
7769 // we cast them to 'unsigned'.
7770 const unsigned char *StrLenPtr = (const unsigned char*) Str - 2;
7771 unsigned StrLen = (((unsigned) StrLenPtr[0])
7772 | (((unsigned) StrLenPtr[1]) << 8)) - 1;
Richard Smitheb4b58f62016-02-05 01:40:54 +00007773 auto &II = PP.getIdentifierTable().get(StringRef(Str, StrLen));
7774 IdentifiersLoaded[ID] = &II;
7775 markIdentifierFromAST(*this, II);
Guy Benyei11169dd2012-12-18 14:30:41 +00007776 if (DeserializationListener)
Richard Smitheb4b58f62016-02-05 01:40:54 +00007777 DeserializationListener->IdentifierRead(ID + 1, &II);
Guy Benyei11169dd2012-12-18 14:30:41 +00007778 }
7779
7780 return IdentifiersLoaded[ID];
7781}
7782
Douglas Gregorc8a992f2013-01-21 16:52:34 +00007783IdentifierInfo *ASTReader::getLocalIdentifier(ModuleFile &M, unsigned LocalID) {
7784 return DecodeIdentifierInfo(getGlobalIdentifierID(M, LocalID));
Guy Benyei11169dd2012-12-18 14:30:41 +00007785}
7786
7787IdentifierID ASTReader::getGlobalIdentifierID(ModuleFile &M, unsigned LocalID) {
7788 if (LocalID < NUM_PREDEF_IDENT_IDS)
7789 return LocalID;
David L. Jonesc4808b9e2016-12-15 20:53:26 +00007790
Guy Benyei11169dd2012-12-18 14:30:41 +00007791 ContinuousRangeMap<uint32_t, int, 2>::iterator I
7792 = M.IdentifierRemap.find(LocalID - NUM_PREDEF_IDENT_IDS);
David L. Jonesc4808b9e2016-12-15 20:53:26 +00007793 assert(I != M.IdentifierRemap.end()
Guy Benyei11169dd2012-12-18 14:30:41 +00007794 && "Invalid index into identifier index remap");
David L. Jonesc4808b9e2016-12-15 20:53:26 +00007795
Guy Benyei11169dd2012-12-18 14:30:41 +00007796 return LocalID + I->second;
7797}
7798
Argyrios Kyrtzidiseb663da2013-03-22 21:12:57 +00007799MacroInfo *ASTReader::getMacro(MacroID ID) {
Guy Benyei11169dd2012-12-18 14:30:41 +00007800 if (ID == 0)
Craig Toppera13603a2014-05-22 05:54:18 +00007801 return nullptr;
Guy Benyei11169dd2012-12-18 14:30:41 +00007802
7803 if (MacrosLoaded.empty()) {
7804 Error("no macro table in AST file");
Craig Toppera13603a2014-05-22 05:54:18 +00007805 return nullptr;
Guy Benyei11169dd2012-12-18 14:30:41 +00007806 }
7807
7808 ID -= NUM_PREDEF_MACRO_IDS;
7809 if (!MacrosLoaded[ID]) {
7810 GlobalMacroMapType::iterator I
7811 = GlobalMacroMap.find(ID + NUM_PREDEF_MACRO_IDS);
7812 assert(I != GlobalMacroMap.end() && "Corrupted global macro map");
7813 ModuleFile *M = I->second;
7814 unsigned Index = ID - M->BaseMacroID;
Argyrios Kyrtzidiseb663da2013-03-22 21:12:57 +00007815 MacrosLoaded[ID] = ReadMacroRecord(*M, M->MacroOffsets[Index]);
David L. Jonesc4808b9e2016-12-15 20:53:26 +00007816
Argyrios Kyrtzidiseb663da2013-03-22 21:12:57 +00007817 if (DeserializationListener)
7818 DeserializationListener->MacroRead(ID + NUM_PREDEF_MACRO_IDS,
7819 MacrosLoaded[ID]);
Guy Benyei11169dd2012-12-18 14:30:41 +00007820 }
7821
7822 return MacrosLoaded[ID];
7823}
7824
7825MacroID ASTReader::getGlobalMacroID(ModuleFile &M, unsigned LocalID) {
7826 if (LocalID < NUM_PREDEF_MACRO_IDS)
7827 return LocalID;
7828
7829 ContinuousRangeMap<uint32_t, int, 2>::iterator I
7830 = M.MacroRemap.find(LocalID - NUM_PREDEF_MACRO_IDS);
7831 assert(I != M.MacroRemap.end() && "Invalid index into macro index remap");
7832
7833 return LocalID + I->second;
7834}
7835
7836serialization::SubmoduleID
7837ASTReader::getGlobalSubmoduleID(ModuleFile &M, unsigned LocalID) {
7838 if (LocalID < NUM_PREDEF_SUBMODULE_IDS)
7839 return LocalID;
David L. Jonesc4808b9e2016-12-15 20:53:26 +00007840
Guy Benyei11169dd2012-12-18 14:30:41 +00007841 ContinuousRangeMap<uint32_t, int, 2>::iterator I
7842 = M.SubmoduleRemap.find(LocalID - NUM_PREDEF_SUBMODULE_IDS);
David L. Jonesc4808b9e2016-12-15 20:53:26 +00007843 assert(I != M.SubmoduleRemap.end()
Guy Benyei11169dd2012-12-18 14:30:41 +00007844 && "Invalid index into submodule index remap");
David L. Jonesc4808b9e2016-12-15 20:53:26 +00007845
Guy Benyei11169dd2012-12-18 14:30:41 +00007846 return LocalID + I->second;
7847}
7848
7849Module *ASTReader::getSubmodule(SubmoduleID GlobalID) {
7850 if (GlobalID < NUM_PREDEF_SUBMODULE_IDS) {
7851 assert(GlobalID == 0 && "Unhandled global submodule ID");
Craig Toppera13603a2014-05-22 05:54:18 +00007852 return nullptr;
Guy Benyei11169dd2012-12-18 14:30:41 +00007853 }
David L. Jonesc4808b9e2016-12-15 20:53:26 +00007854
Guy Benyei11169dd2012-12-18 14:30:41 +00007855 if (GlobalID > SubmodulesLoaded.size()) {
7856 Error("submodule ID out of range in AST file");
Craig Toppera13603a2014-05-22 05:54:18 +00007857 return nullptr;
Guy Benyei11169dd2012-12-18 14:30:41 +00007858 }
David L. Jonesc4808b9e2016-12-15 20:53:26 +00007859
Guy Benyei11169dd2012-12-18 14:30:41 +00007860 return SubmodulesLoaded[GlobalID - NUM_PREDEF_SUBMODULE_IDS];
7861}
Douglas Gregorc147b0b2013-01-12 01:29:50 +00007862
7863Module *ASTReader::getModule(unsigned ID) {
7864 return getSubmodule(ID);
7865}
7866
Richard Smithd88a7f12015-09-01 20:35:42 +00007867ModuleFile *ASTReader::getLocalModuleFile(ModuleFile &F, unsigned ID) {
7868 if (ID & 1) {
7869 // It's a module, look it up by submodule ID.
7870 auto I = GlobalSubmoduleMap.find(getGlobalSubmoduleID(F, ID >> 1));
7871 return I == GlobalSubmoduleMap.end() ? nullptr : I->second;
7872 } else {
7873 // It's a prefix (preamble, PCH, ...). Look it up by index.
7874 unsigned IndexFromEnd = ID >> 1;
7875 assert(IndexFromEnd && "got reference to unknown module file");
7876 return getModuleManager().pch_modules().end()[-IndexFromEnd];
7877 }
7878}
7879
7880unsigned ASTReader::getModuleFileID(ModuleFile *F) {
7881 if (!F)
7882 return 1;
7883
7884 // For a file representing a module, use the submodule ID of the top-level
7885 // module as the file ID. For any other kind of file, the number of such
7886 // files loaded beforehand will be the same on reload.
7887 // FIXME: Is this true even if we have an explicit module file and a PCH?
7888 if (F->isModule())
7889 return ((F->BaseSubmoduleID + NUM_PREDEF_SUBMODULE_IDS) << 1) | 1;
7890
7891 auto PCHModules = getModuleManager().pch_modules();
7892 auto I = std::find(PCHModules.begin(), PCHModules.end(), F);
7893 assert(I != PCHModules.end() && "emitting reference to unknown file");
7894 return (I - PCHModules.end()) << 1;
7895}
7896
Adrian Prantl15bcf702015-06-30 17:39:43 +00007897llvm::Optional<ExternalASTSource::ASTSourceDescriptor>
7898ASTReader::getSourceDescriptor(unsigned ID) {
7899 if (const Module *M = getSubmodule(ID))
Adrian Prantlc6458d62015-09-19 00:10:32 +00007900 return ExternalASTSource::ASTSourceDescriptor(*M);
Adrian Prantl15bcf702015-06-30 17:39:43 +00007901
7902 // If there is only a single PCH, return it instead.
7903 // Chained PCH are not suported.
7904 if (ModuleMgr.size() == 1) {
7905 ModuleFile &MF = ModuleMgr.getPrimaryModule();
Adrian Prantl3a2d4942016-01-22 23:30:56 +00007906 StringRef ModuleName = llvm::sys::path::filename(MF.OriginalSourceFileName);
Adrian Prantl9bc3c4f2016-04-27 17:06:22 +00007907 StringRef FileName = llvm::sys::path::filename(MF.FileName);
7908 return ASTReader::ASTSourceDescriptor(ModuleName, MF.OriginalDir, FileName,
7909 MF.Signature);
Adrian Prantl15bcf702015-06-30 17:39:43 +00007910 }
7911 return None;
7912}
7913
David Blaikie9ffe5a32017-01-30 05:00:26 +00007914ExternalASTSource::ExtKind ASTReader::hasExternalDefinitions(unsigned ID) {
7915 const Module *M = getSubmodule(ID);
7916 if (!M || !M->WithCodegen)
7917 return EK_ReplyHazy;
7918
7919 ModuleFile *MF = ModuleMgr.lookup(M->getASTFile());
7920 assert(MF); // ?
7921 if (MF->Kind == ModuleKind::MK_MainFile)
7922 return EK_Never;
7923 return EK_Always;
7924}
7925
Guy Benyei11169dd2012-12-18 14:30:41 +00007926Selector ASTReader::getLocalSelector(ModuleFile &M, unsigned LocalID) {
7927 return DecodeSelector(getGlobalSelectorID(M, LocalID));
7928}
7929
7930Selector ASTReader::DecodeSelector(serialization::SelectorID ID) {
7931 if (ID == 0)
7932 return Selector();
7933
7934 if (ID > SelectorsLoaded.size()) {
7935 Error("selector ID out of range in AST file");
7936 return Selector();
7937 }
7938
Craig Toppera13603a2014-05-22 05:54:18 +00007939 if (SelectorsLoaded[ID - 1].getAsOpaquePtr() == nullptr) {
Guy Benyei11169dd2012-12-18 14:30:41 +00007940 // Load this selector from the selector table.
7941 GlobalSelectorMapType::iterator I = GlobalSelectorMap.find(ID);
7942 assert(I != GlobalSelectorMap.end() && "Corrupted global selector map");
7943 ModuleFile &M = *I->second;
7944 ASTSelectorLookupTrait Trait(*this, M);
7945 unsigned Idx = ID - M.BaseSelectorID - NUM_PREDEF_SELECTOR_IDS;
7946 SelectorsLoaded[ID - 1] =
7947 Trait.ReadKey(M.SelectorLookupTableData + M.SelectorOffsets[Idx], 0);
7948 if (DeserializationListener)
7949 DeserializationListener->SelectorRead(ID, SelectorsLoaded[ID - 1]);
7950 }
7951
7952 return SelectorsLoaded[ID - 1];
7953}
7954
7955Selector ASTReader::GetExternalSelector(serialization::SelectorID ID) {
7956 return DecodeSelector(ID);
7957}
7958
7959uint32_t ASTReader::GetNumExternalSelectors() {
7960 // ID 0 (the null selector) is considered an external selector.
7961 return getTotalNumSelectors() + 1;
7962}
7963
7964serialization::SelectorID
7965ASTReader::getGlobalSelectorID(ModuleFile &M, unsigned LocalID) const {
7966 if (LocalID < NUM_PREDEF_SELECTOR_IDS)
7967 return LocalID;
David L. Jonesc4808b9e2016-12-15 20:53:26 +00007968
Guy Benyei11169dd2012-12-18 14:30:41 +00007969 ContinuousRangeMap<uint32_t, int, 2>::iterator I
7970 = M.SelectorRemap.find(LocalID - NUM_PREDEF_SELECTOR_IDS);
David L. Jonesc4808b9e2016-12-15 20:53:26 +00007971 assert(I != M.SelectorRemap.end()
Guy Benyei11169dd2012-12-18 14:30:41 +00007972 && "Invalid index into selector index remap");
David L. Jonesc4808b9e2016-12-15 20:53:26 +00007973
Guy Benyei11169dd2012-12-18 14:30:41 +00007974 return LocalID + I->second;
7975}
7976
7977DeclarationName
David L. Jonesc4808b9e2016-12-15 20:53:26 +00007978ASTReader::ReadDeclarationName(ModuleFile &F,
Guy Benyei11169dd2012-12-18 14:30:41 +00007979 const RecordData &Record, unsigned &Idx) {
7980 DeclarationName::NameKind Kind = (DeclarationName::NameKind)Record[Idx++];
7981 switch (Kind) {
7982 case DeclarationName::Identifier:
Douglas Gregorc8a992f2013-01-21 16:52:34 +00007983 return DeclarationName(GetIdentifierInfo(F, Record, Idx));
Guy Benyei11169dd2012-12-18 14:30:41 +00007984
7985 case DeclarationName::ObjCZeroArgSelector:
7986 case DeclarationName::ObjCOneArgSelector:
7987 case DeclarationName::ObjCMultiArgSelector:
7988 return DeclarationName(ReadSelector(F, Record, Idx));
7989
7990 case DeclarationName::CXXConstructorName:
7991 return Context.DeclarationNames.getCXXConstructorName(
7992 Context.getCanonicalType(readType(F, Record, Idx)));
7993
7994 case DeclarationName::CXXDestructorName:
7995 return Context.DeclarationNames.getCXXDestructorName(
7996 Context.getCanonicalType(readType(F, Record, Idx)));
7997
Richard Smith35845152017-02-07 01:37:30 +00007998 case DeclarationName::CXXDeductionGuideName:
7999 return Context.DeclarationNames.getCXXDeductionGuideName(
8000 ReadDeclAs<TemplateDecl>(F, Record, Idx));
8001
Guy Benyei11169dd2012-12-18 14:30:41 +00008002 case DeclarationName::CXXConversionFunctionName:
8003 return Context.DeclarationNames.getCXXConversionFunctionName(
8004 Context.getCanonicalType(readType(F, Record, Idx)));
8005
8006 case DeclarationName::CXXOperatorName:
8007 return Context.DeclarationNames.getCXXOperatorName(
8008 (OverloadedOperatorKind)Record[Idx++]);
8009
8010 case DeclarationName::CXXLiteralOperatorName:
8011 return Context.DeclarationNames.getCXXLiteralOperatorName(
8012 GetIdentifierInfo(F, Record, Idx));
8013
8014 case DeclarationName::CXXUsingDirective:
8015 return DeclarationName::getUsingDirectiveName();
8016 }
8017
8018 llvm_unreachable("Invalid NameKind!");
8019}
8020
8021void ASTReader::ReadDeclarationNameLoc(ModuleFile &F,
8022 DeclarationNameLoc &DNLoc,
8023 DeclarationName Name,
8024 const RecordData &Record, unsigned &Idx) {
8025 switch (Name.getNameKind()) {
8026 case DeclarationName::CXXConstructorName:
8027 case DeclarationName::CXXDestructorName:
8028 case DeclarationName::CXXConversionFunctionName:
8029 DNLoc.NamedType.TInfo = GetTypeSourceInfo(F, Record, Idx);
8030 break;
8031
8032 case DeclarationName::CXXOperatorName:
8033 DNLoc.CXXOperatorName.BeginOpNameLoc
8034 = ReadSourceLocation(F, Record, Idx).getRawEncoding();
8035 DNLoc.CXXOperatorName.EndOpNameLoc
8036 = ReadSourceLocation(F, Record, Idx).getRawEncoding();
8037 break;
8038
8039 case DeclarationName::CXXLiteralOperatorName:
8040 DNLoc.CXXLiteralOperatorName.OpNameLoc
8041 = ReadSourceLocation(F, Record, Idx).getRawEncoding();
8042 break;
8043
8044 case DeclarationName::Identifier:
8045 case DeclarationName::ObjCZeroArgSelector:
8046 case DeclarationName::ObjCOneArgSelector:
8047 case DeclarationName::ObjCMultiArgSelector:
8048 case DeclarationName::CXXUsingDirective:
Richard Smith35845152017-02-07 01:37:30 +00008049 case DeclarationName::CXXDeductionGuideName:
Guy Benyei11169dd2012-12-18 14:30:41 +00008050 break;
8051 }
8052}
8053
8054void ASTReader::ReadDeclarationNameInfo(ModuleFile &F,
8055 DeclarationNameInfo &NameInfo,
8056 const RecordData &Record, unsigned &Idx) {
8057 NameInfo.setName(ReadDeclarationName(F, Record, Idx));
8058 NameInfo.setLoc(ReadSourceLocation(F, Record, Idx));
8059 DeclarationNameLoc DNLoc;
8060 ReadDeclarationNameLoc(F, DNLoc, NameInfo.getName(), Record, Idx);
8061 NameInfo.setInfo(DNLoc);
8062}
8063
8064void ASTReader::ReadQualifierInfo(ModuleFile &F, QualifierInfo &Info,
8065 const RecordData &Record, unsigned &Idx) {
8066 Info.QualifierLoc = ReadNestedNameSpecifierLoc(F, Record, Idx);
8067 unsigned NumTPLists = Record[Idx++];
8068 Info.NumTemplParamLists = NumTPLists;
8069 if (NumTPLists) {
8070 Info.TemplParamLists = new (Context) TemplateParameterList*[NumTPLists];
Eugene Zelenkoe95e7d52016-09-07 21:53:17 +00008071 for (unsigned i = 0; i != NumTPLists; ++i)
Guy Benyei11169dd2012-12-18 14:30:41 +00008072 Info.TemplParamLists[i] = ReadTemplateParameterList(F, Record, Idx);
8073 }
8074}
8075
8076TemplateName
David L. Jonesc4808b9e2016-12-15 20:53:26 +00008077ASTReader::ReadTemplateName(ModuleFile &F, const RecordData &Record,
Guy Benyei11169dd2012-12-18 14:30:41 +00008078 unsigned &Idx) {
8079 TemplateName::NameKind Kind = (TemplateName::NameKind)Record[Idx++];
8080 switch (Kind) {
8081 case TemplateName::Template:
8082 return TemplateName(ReadDeclAs<TemplateDecl>(F, Record, Idx));
8083
8084 case TemplateName::OverloadedTemplate: {
8085 unsigned size = Record[Idx++];
8086 UnresolvedSet<8> Decls;
8087 while (size--)
8088 Decls.addDecl(ReadDeclAs<NamedDecl>(F, Record, Idx));
8089
8090 return Context.getOverloadedTemplateName(Decls.begin(), Decls.end());
8091 }
8092
8093 case TemplateName::QualifiedTemplate: {
8094 NestedNameSpecifier *NNS = ReadNestedNameSpecifier(F, Record, Idx);
8095 bool hasTemplKeyword = Record[Idx++];
8096 TemplateDecl *Template = ReadDeclAs<TemplateDecl>(F, Record, Idx);
8097 return Context.getQualifiedTemplateName(NNS, hasTemplKeyword, Template);
8098 }
8099
8100 case TemplateName::DependentTemplate: {
8101 NestedNameSpecifier *NNS = ReadNestedNameSpecifier(F, Record, Idx);
8102 if (Record[Idx++]) // isIdentifier
8103 return Context.getDependentTemplateName(NNS,
David L. Jonesc4808b9e2016-12-15 20:53:26 +00008104 GetIdentifierInfo(F, Record,
Guy Benyei11169dd2012-12-18 14:30:41 +00008105 Idx));
8106 return Context.getDependentTemplateName(NNS,
8107 (OverloadedOperatorKind)Record[Idx++]);
8108 }
8109
8110 case TemplateName::SubstTemplateTemplateParm: {
8111 TemplateTemplateParmDecl *param
8112 = ReadDeclAs<TemplateTemplateParmDecl>(F, Record, Idx);
8113 if (!param) return TemplateName();
8114 TemplateName replacement = ReadTemplateName(F, Record, Idx);
8115 return Context.getSubstTemplateTemplateParm(param, replacement);
8116 }
David L. Jonesc4808b9e2016-12-15 20:53:26 +00008117
Guy Benyei11169dd2012-12-18 14:30:41 +00008118 case TemplateName::SubstTemplateTemplateParmPack: {
David L. Jonesc4808b9e2016-12-15 20:53:26 +00008119 TemplateTemplateParmDecl *Param
Guy Benyei11169dd2012-12-18 14:30:41 +00008120 = ReadDeclAs<TemplateTemplateParmDecl>(F, Record, Idx);
8121 if (!Param)
8122 return TemplateName();
David L. Jonesc4808b9e2016-12-15 20:53:26 +00008123
Guy Benyei11169dd2012-12-18 14:30:41 +00008124 TemplateArgument ArgPack = ReadTemplateArgument(F, Record, Idx);
8125 if (ArgPack.getKind() != TemplateArgument::Pack)
8126 return TemplateName();
David L. Jonesc4808b9e2016-12-15 20:53:26 +00008127
Guy Benyei11169dd2012-12-18 14:30:41 +00008128 return Context.getSubstTemplateTemplateParmPack(Param, ArgPack);
8129 }
8130 }
8131
8132 llvm_unreachable("Unhandled template name kind!");
8133}
8134
Richard Smith2bb3c342015-08-09 01:05:31 +00008135TemplateArgument ASTReader::ReadTemplateArgument(ModuleFile &F,
8136 const RecordData &Record,
8137 unsigned &Idx,
8138 bool Canonicalize) {
8139 if (Canonicalize) {
8140 // The caller wants a canonical template argument. Sometimes the AST only
8141 // wants template arguments in canonical form (particularly as the template
8142 // argument lists of template specializations) so ensure we preserve that
8143 // canonical form across serialization.
8144 TemplateArgument Arg = ReadTemplateArgument(F, Record, Idx, false);
8145 return Context.getCanonicalTemplateArgument(Arg);
8146 }
8147
Guy Benyei11169dd2012-12-18 14:30:41 +00008148 TemplateArgument::ArgKind Kind = (TemplateArgument::ArgKind)Record[Idx++];
8149 switch (Kind) {
8150 case TemplateArgument::Null:
8151 return TemplateArgument();
8152 case TemplateArgument::Type:
8153 return TemplateArgument(readType(F, Record, Idx));
8154 case TemplateArgument::Declaration: {
8155 ValueDecl *D = ReadDeclAs<ValueDecl>(F, Record, Idx);
David Blaikie0f62c8d2014-10-16 04:21:25 +00008156 return TemplateArgument(D, readType(F, Record, Idx));
Guy Benyei11169dd2012-12-18 14:30:41 +00008157 }
8158 case TemplateArgument::NullPtr:
8159 return TemplateArgument(readType(F, Record, Idx), /*isNullPtr*/true);
8160 case TemplateArgument::Integral: {
8161 llvm::APSInt Value = ReadAPSInt(Record, Idx);
8162 QualType T = readType(F, Record, Idx);
8163 return TemplateArgument(Context, Value, T);
8164 }
David L. Jonesc4808b9e2016-12-15 20:53:26 +00008165 case TemplateArgument::Template:
Guy Benyei11169dd2012-12-18 14:30:41 +00008166 return TemplateArgument(ReadTemplateName(F, Record, Idx));
8167 case TemplateArgument::TemplateExpansion: {
8168 TemplateName Name = ReadTemplateName(F, Record, Idx);
David Blaikie05785d12013-02-20 22:23:23 +00008169 Optional<unsigned> NumTemplateExpansions;
Guy Benyei11169dd2012-12-18 14:30:41 +00008170 if (unsigned NumExpansions = Record[Idx++])
8171 NumTemplateExpansions = NumExpansions - 1;
8172 return TemplateArgument(Name, NumTemplateExpansions);
8173 }
8174 case TemplateArgument::Expression:
8175 return TemplateArgument(ReadExpr(F));
8176 case TemplateArgument::Pack: {
8177 unsigned NumArgs = Record[Idx++];
8178 TemplateArgument *Args = new (Context) TemplateArgument[NumArgs];
8179 for (unsigned I = 0; I != NumArgs; ++I)
8180 Args[I] = ReadTemplateArgument(F, Record, Idx);
Benjamin Kramercce63472015-08-05 09:40:22 +00008181 return TemplateArgument(llvm::makeArrayRef(Args, NumArgs));
Guy Benyei11169dd2012-12-18 14:30:41 +00008182 }
8183 }
8184
8185 llvm_unreachable("Unhandled template argument kind!");
8186}
8187
8188TemplateParameterList *
8189ASTReader::ReadTemplateParameterList(ModuleFile &F,
8190 const RecordData &Record, unsigned &Idx) {
8191 SourceLocation TemplateLoc = ReadSourceLocation(F, Record, Idx);
8192 SourceLocation LAngleLoc = ReadSourceLocation(F, Record, Idx);
8193 SourceLocation RAngleLoc = ReadSourceLocation(F, Record, Idx);
8194
8195 unsigned NumParams = Record[Idx++];
8196 SmallVector<NamedDecl *, 16> Params;
8197 Params.reserve(NumParams);
8198 while (NumParams--)
8199 Params.push_back(ReadDeclAs<NamedDecl>(F, Record, Idx));
8200
Hubert Tonge4a0c0e2016-07-30 22:33:34 +00008201 // TODO: Concepts
Guy Benyei11169dd2012-12-18 14:30:41 +00008202 TemplateParameterList* TemplateParams =
8203 TemplateParameterList::Create(Context, TemplateLoc, LAngleLoc,
Hubert Tonge4a0c0e2016-07-30 22:33:34 +00008204 Params, RAngleLoc, nullptr);
Guy Benyei11169dd2012-12-18 14:30:41 +00008205 return TemplateParams;
8206}
8207
8208void
8209ASTReader::
Craig Topper5603df42013-07-05 19:34:19 +00008210ReadTemplateArgumentList(SmallVectorImpl<TemplateArgument> &TemplArgs,
Guy Benyei11169dd2012-12-18 14:30:41 +00008211 ModuleFile &F, const RecordData &Record,
Richard Smith2bb3c342015-08-09 01:05:31 +00008212 unsigned &Idx, bool Canonicalize) {
Guy Benyei11169dd2012-12-18 14:30:41 +00008213 unsigned NumTemplateArgs = Record[Idx++];
8214 TemplArgs.reserve(NumTemplateArgs);
8215 while (NumTemplateArgs--)
Richard Smith2bb3c342015-08-09 01:05:31 +00008216 TemplArgs.push_back(ReadTemplateArgument(F, Record, Idx, Canonicalize));
Guy Benyei11169dd2012-12-18 14:30:41 +00008217}
8218
8219/// \brief Read a UnresolvedSet structure.
Richard Smitha4ba74c2013-08-30 04:46:40 +00008220void ASTReader::ReadUnresolvedSet(ModuleFile &F, LazyASTUnresolvedSet &Set,
Guy Benyei11169dd2012-12-18 14:30:41 +00008221 const RecordData &Record, unsigned &Idx) {
8222 unsigned NumDecls = Record[Idx++];
8223 Set.reserve(Context, NumDecls);
8224 while (NumDecls--) {
Richard Smitha4ba74c2013-08-30 04:46:40 +00008225 DeclID ID = ReadDeclID(F, Record, Idx);
Guy Benyei11169dd2012-12-18 14:30:41 +00008226 AccessSpecifier AS = (AccessSpecifier)Record[Idx++];
Richard Smitha4ba74c2013-08-30 04:46:40 +00008227 Set.addLazyDecl(Context, ID, AS);
Guy Benyei11169dd2012-12-18 14:30:41 +00008228 }
8229}
8230
8231CXXBaseSpecifier
8232ASTReader::ReadCXXBaseSpecifier(ModuleFile &F,
8233 const RecordData &Record, unsigned &Idx) {
8234 bool isVirtual = static_cast<bool>(Record[Idx++]);
8235 bool isBaseOfClass = static_cast<bool>(Record[Idx++]);
8236 AccessSpecifier AS = static_cast<AccessSpecifier>(Record[Idx++]);
8237 bool inheritConstructors = static_cast<bool>(Record[Idx++]);
8238 TypeSourceInfo *TInfo = GetTypeSourceInfo(F, Record, Idx);
8239 SourceRange Range = ReadSourceRange(F, Record, Idx);
8240 SourceLocation EllipsisLoc = ReadSourceLocation(F, Record, Idx);
David L. Jonesc4808b9e2016-12-15 20:53:26 +00008241 CXXBaseSpecifier Result(Range, isVirtual, isBaseOfClass, AS, TInfo,
Guy Benyei11169dd2012-12-18 14:30:41 +00008242 EllipsisLoc);
8243 Result.setInheritConstructors(inheritConstructors);
8244 return Result;
8245}
8246
Richard Smithc2bb8182015-03-24 06:36:48 +00008247CXXCtorInitializer **
Guy Benyei11169dd2012-12-18 14:30:41 +00008248ASTReader::ReadCXXCtorInitializers(ModuleFile &F, const RecordData &Record,
8249 unsigned &Idx) {
Guy Benyei11169dd2012-12-18 14:30:41 +00008250 unsigned NumInitializers = Record[Idx++];
Richard Smithc2bb8182015-03-24 06:36:48 +00008251 assert(NumInitializers && "wrote ctor initializers but have no inits");
8252 auto **CtorInitializers = new (Context) CXXCtorInitializer*[NumInitializers];
8253 for (unsigned i = 0; i != NumInitializers; ++i) {
8254 TypeSourceInfo *TInfo = nullptr;
8255 bool IsBaseVirtual = false;
8256 FieldDecl *Member = nullptr;
8257 IndirectFieldDecl *IndirectMember = nullptr;
Guy Benyei11169dd2012-12-18 14:30:41 +00008258
Richard Smithc2bb8182015-03-24 06:36:48 +00008259 CtorInitializerType Type = (CtorInitializerType)Record[Idx++];
8260 switch (Type) {
8261 case CTOR_INITIALIZER_BASE:
8262 TInfo = GetTypeSourceInfo(F, Record, Idx);
8263 IsBaseVirtual = Record[Idx++];
8264 break;
Guy Benyei11169dd2012-12-18 14:30:41 +00008265
Richard Smithc2bb8182015-03-24 06:36:48 +00008266 case CTOR_INITIALIZER_DELEGATING:
8267 TInfo = GetTypeSourceInfo(F, Record, Idx);
8268 break;
Guy Benyei11169dd2012-12-18 14:30:41 +00008269
Richard Smithc2bb8182015-03-24 06:36:48 +00008270 case CTOR_INITIALIZER_MEMBER:
8271 Member = ReadDeclAs<FieldDecl>(F, Record, Idx);
8272 break;
Guy Benyei11169dd2012-12-18 14:30:41 +00008273
Richard Smithc2bb8182015-03-24 06:36:48 +00008274 case CTOR_INITIALIZER_INDIRECT_MEMBER:
8275 IndirectMember = ReadDeclAs<IndirectFieldDecl>(F, Record, Idx);
8276 break;
Guy Benyei11169dd2012-12-18 14:30:41 +00008277 }
Richard Smithc2bb8182015-03-24 06:36:48 +00008278
8279 SourceLocation MemberOrEllipsisLoc = ReadSourceLocation(F, Record, Idx);
8280 Expr *Init = ReadExpr(F);
8281 SourceLocation LParenLoc = ReadSourceLocation(F, Record, Idx);
8282 SourceLocation RParenLoc = ReadSourceLocation(F, Record, Idx);
Richard Smithc2bb8182015-03-24 06:36:48 +00008283
8284 CXXCtorInitializer *BOMInit;
Richard Smith30e304e2016-12-14 00:03:17 +00008285 if (Type == CTOR_INITIALIZER_BASE)
Richard Smithc2bb8182015-03-24 06:36:48 +00008286 BOMInit = new (Context)
8287 CXXCtorInitializer(Context, TInfo, IsBaseVirtual, LParenLoc, Init,
8288 RParenLoc, MemberOrEllipsisLoc);
Richard Smith30e304e2016-12-14 00:03:17 +00008289 else if (Type == CTOR_INITIALIZER_DELEGATING)
Richard Smithc2bb8182015-03-24 06:36:48 +00008290 BOMInit = new (Context)
8291 CXXCtorInitializer(Context, TInfo, LParenLoc, Init, RParenLoc);
Richard Smith30e304e2016-12-14 00:03:17 +00008292 else if (Member)
8293 BOMInit = new (Context)
8294 CXXCtorInitializer(Context, Member, MemberOrEllipsisLoc, LParenLoc,
8295 Init, RParenLoc);
8296 else
8297 BOMInit = new (Context)
8298 CXXCtorInitializer(Context, IndirectMember, MemberOrEllipsisLoc,
8299 LParenLoc, Init, RParenLoc);
8300
Richard Smith418ed822016-12-14 19:45:03 +00008301 if (/*IsWritten*/Record[Idx++]) {
Richard Smith30e304e2016-12-14 00:03:17 +00008302 unsigned SourceOrder = Record[Idx++];
8303 BOMInit->setSourceOrder(SourceOrder);
Richard Smithc2bb8182015-03-24 06:36:48 +00008304 }
8305
Richard Smithc2bb8182015-03-24 06:36:48 +00008306 CtorInitializers[i] = BOMInit;
Guy Benyei11169dd2012-12-18 14:30:41 +00008307 }
8308
Richard Smithc2bb8182015-03-24 06:36:48 +00008309 return CtorInitializers;
Guy Benyei11169dd2012-12-18 14:30:41 +00008310}
8311
8312NestedNameSpecifier *
8313ASTReader::ReadNestedNameSpecifier(ModuleFile &F,
8314 const RecordData &Record, unsigned &Idx) {
8315 unsigned N = Record[Idx++];
Craig Toppera13603a2014-05-22 05:54:18 +00008316 NestedNameSpecifier *NNS = nullptr, *Prev = nullptr;
Guy Benyei11169dd2012-12-18 14:30:41 +00008317 for (unsigned I = 0; I != N; ++I) {
8318 NestedNameSpecifier::SpecifierKind Kind
8319 = (NestedNameSpecifier::SpecifierKind)Record[Idx++];
8320 switch (Kind) {
8321 case NestedNameSpecifier::Identifier: {
8322 IdentifierInfo *II = GetIdentifierInfo(F, Record, Idx);
8323 NNS = NestedNameSpecifier::Create(Context, Prev, II);
8324 break;
8325 }
8326
8327 case NestedNameSpecifier::Namespace: {
8328 NamespaceDecl *NS = ReadDeclAs<NamespaceDecl>(F, Record, Idx);
8329 NNS = NestedNameSpecifier::Create(Context, Prev, NS);
8330 break;
8331 }
8332
8333 case NestedNameSpecifier::NamespaceAlias: {
8334 NamespaceAliasDecl *Alias =ReadDeclAs<NamespaceAliasDecl>(F, Record, Idx);
8335 NNS = NestedNameSpecifier::Create(Context, Prev, Alias);
8336 break;
8337 }
8338
8339 case NestedNameSpecifier::TypeSpec:
8340 case NestedNameSpecifier::TypeSpecWithTemplate: {
8341 const Type *T = readType(F, Record, Idx).getTypePtrOrNull();
8342 if (!T)
Craig Toppera13603a2014-05-22 05:54:18 +00008343 return nullptr;
8344
Guy Benyei11169dd2012-12-18 14:30:41 +00008345 bool Template = Record[Idx++];
8346 NNS = NestedNameSpecifier::Create(Context, Prev, Template, T);
8347 break;
8348 }
8349
8350 case NestedNameSpecifier::Global: {
8351 NNS = NestedNameSpecifier::GlobalSpecifier(Context);
8352 // No associated value, and there can't be a prefix.
8353 break;
8354 }
Nikola Smiljanic67860242014-09-26 00:28:20 +00008355
8356 case NestedNameSpecifier::Super: {
8357 CXXRecordDecl *RD = ReadDeclAs<CXXRecordDecl>(F, Record, Idx);
8358 NNS = NestedNameSpecifier::SuperSpecifier(Context, RD);
8359 break;
8360 }
Guy Benyei11169dd2012-12-18 14:30:41 +00008361 }
8362 Prev = NNS;
8363 }
8364 return NNS;
8365}
8366
8367NestedNameSpecifierLoc
David L. Jonesc4808b9e2016-12-15 20:53:26 +00008368ASTReader::ReadNestedNameSpecifierLoc(ModuleFile &F, const RecordData &Record,
Guy Benyei11169dd2012-12-18 14:30:41 +00008369 unsigned &Idx) {
8370 unsigned N = Record[Idx++];
8371 NestedNameSpecifierLocBuilder Builder;
8372 for (unsigned I = 0; I != N; ++I) {
8373 NestedNameSpecifier::SpecifierKind Kind
8374 = (NestedNameSpecifier::SpecifierKind)Record[Idx++];
8375 switch (Kind) {
8376 case NestedNameSpecifier::Identifier: {
David L. Jonesc4808b9e2016-12-15 20:53:26 +00008377 IdentifierInfo *II = GetIdentifierInfo(F, Record, Idx);
Guy Benyei11169dd2012-12-18 14:30:41 +00008378 SourceRange Range = ReadSourceRange(F, Record, Idx);
8379 Builder.Extend(Context, II, Range.getBegin(), Range.getEnd());
8380 break;
8381 }
8382
8383 case NestedNameSpecifier::Namespace: {
8384 NamespaceDecl *NS = ReadDeclAs<NamespaceDecl>(F, Record, Idx);
8385 SourceRange Range = ReadSourceRange(F, Record, Idx);
8386 Builder.Extend(Context, NS, Range.getBegin(), Range.getEnd());
8387 break;
8388 }
8389
8390 case NestedNameSpecifier::NamespaceAlias: {
8391 NamespaceAliasDecl *Alias =ReadDeclAs<NamespaceAliasDecl>(F, Record, Idx);
8392 SourceRange Range = ReadSourceRange(F, Record, Idx);
8393 Builder.Extend(Context, Alias, Range.getBegin(), Range.getEnd());
8394 break;
8395 }
8396
8397 case NestedNameSpecifier::TypeSpec:
8398 case NestedNameSpecifier::TypeSpecWithTemplate: {
8399 bool Template = Record[Idx++];
8400 TypeSourceInfo *T = GetTypeSourceInfo(F, Record, Idx);
8401 if (!T)
8402 return NestedNameSpecifierLoc();
8403 SourceLocation ColonColonLoc = ReadSourceLocation(F, Record, Idx);
8404
8405 // FIXME: 'template' keyword location not saved anywhere, so we fake it.
David L. Jonesc4808b9e2016-12-15 20:53:26 +00008406 Builder.Extend(Context,
Guy Benyei11169dd2012-12-18 14:30:41 +00008407 Template? T->getTypeLoc().getBeginLoc() : SourceLocation(),
8408 T->getTypeLoc(), ColonColonLoc);
8409 break;
8410 }
8411
8412 case NestedNameSpecifier::Global: {
8413 SourceLocation ColonColonLoc = ReadSourceLocation(F, Record, Idx);
8414 Builder.MakeGlobal(Context, ColonColonLoc);
8415 break;
8416 }
Nikola Smiljanic67860242014-09-26 00:28:20 +00008417
8418 case NestedNameSpecifier::Super: {
8419 CXXRecordDecl *RD = ReadDeclAs<CXXRecordDecl>(F, Record, Idx);
8420 SourceRange Range = ReadSourceRange(F, Record, Idx);
8421 Builder.MakeSuper(Context, RD, Range.getBegin(), Range.getEnd());
8422 break;
8423 }
Guy Benyei11169dd2012-12-18 14:30:41 +00008424 }
8425 }
Nikola Smiljanic67860242014-09-26 00:28:20 +00008426
Guy Benyei11169dd2012-12-18 14:30:41 +00008427 return Builder.getWithLocInContext(Context);
8428}
8429
8430SourceRange
8431ASTReader::ReadSourceRange(ModuleFile &F, const RecordData &Record,
8432 unsigned &Idx) {
8433 SourceLocation beg = ReadSourceLocation(F, Record, Idx);
8434 SourceLocation end = ReadSourceLocation(F, Record, Idx);
8435 return SourceRange(beg, end);
8436}
8437
8438/// \brief Read an integral value
8439llvm::APInt ASTReader::ReadAPInt(const RecordData &Record, unsigned &Idx) {
8440 unsigned BitWidth = Record[Idx++];
8441 unsigned NumWords = llvm::APInt::getNumWords(BitWidth);
8442 llvm::APInt Result(BitWidth, NumWords, &Record[Idx]);
8443 Idx += NumWords;
8444 return Result;
8445}
8446
8447/// \brief Read a signed integral value
8448llvm::APSInt ASTReader::ReadAPSInt(const RecordData &Record, unsigned &Idx) {
8449 bool isUnsigned = Record[Idx++];
8450 return llvm::APSInt(ReadAPInt(Record, Idx), isUnsigned);
8451}
8452
8453/// \brief Read a floating-point value
Tim Northover178723a2013-01-22 09:46:51 +00008454llvm::APFloat ASTReader::ReadAPFloat(const RecordData &Record,
8455 const llvm::fltSemantics &Sem,
8456 unsigned &Idx) {
8457 return llvm::APFloat(Sem, ReadAPInt(Record, Idx));
Guy Benyei11169dd2012-12-18 14:30:41 +00008458}
8459
8460// \brief Read a string
8461std::string ASTReader::ReadString(const RecordData &Record, unsigned &Idx) {
8462 unsigned Len = Record[Idx++];
8463 std::string Result(Record.data() + Idx, Record.data() + Idx + Len);
8464 Idx += Len;
8465 return Result;
8466}
8467
Richard Smith7ed1bc92014-12-05 22:42:13 +00008468std::string ASTReader::ReadPath(ModuleFile &F, const RecordData &Record,
8469 unsigned &Idx) {
8470 std::string Filename = ReadString(Record, Idx);
8471 ResolveImportedPath(F, Filename);
8472 return Filename;
8473}
8474
David L. Jonesc4808b9e2016-12-15 20:53:26 +00008475VersionTuple ASTReader::ReadVersionTuple(const RecordData &Record,
Guy Benyei11169dd2012-12-18 14:30:41 +00008476 unsigned &Idx) {
8477 unsigned Major = Record[Idx++];
8478 unsigned Minor = Record[Idx++];
8479 unsigned Subminor = Record[Idx++];
8480 if (Minor == 0)
8481 return VersionTuple(Major);
8482 if (Subminor == 0)
8483 return VersionTuple(Major, Minor - 1);
8484 return VersionTuple(Major, Minor - 1, Subminor - 1);
8485}
8486
David L. Jonesc4808b9e2016-12-15 20:53:26 +00008487CXXTemporary *ASTReader::ReadCXXTemporary(ModuleFile &F,
Guy Benyei11169dd2012-12-18 14:30:41 +00008488 const RecordData &Record,
8489 unsigned &Idx) {
8490 CXXDestructorDecl *Decl = ReadDeclAs<CXXDestructorDecl>(F, Record, Idx);
8491 return CXXTemporary::Create(Context, Decl);
8492}
8493
8494DiagnosticBuilder ASTReader::Diag(unsigned DiagID) {
Argyrios Kyrtzidisdc9fdaf2013-05-24 05:44:08 +00008495 return Diag(CurrentImportLoc, DiagID);
Guy Benyei11169dd2012-12-18 14:30:41 +00008496}
8497
8498DiagnosticBuilder ASTReader::Diag(SourceLocation Loc, unsigned DiagID) {
8499 return Diags.Report(Loc, DiagID);
8500}
8501
8502/// \brief Retrieve the identifier table associated with the
8503/// preprocessor.
8504IdentifierTable &ASTReader::getIdentifierTable() {
8505 return PP.getIdentifierTable();
8506}
8507
8508/// \brief Record that the given ID maps to the given switch-case
8509/// statement.
8510void ASTReader::RecordSwitchCaseID(SwitchCase *SC, unsigned ID) {
Craig Toppera13603a2014-05-22 05:54:18 +00008511 assert((*CurrSwitchCaseStmts)[ID] == nullptr &&
Guy Benyei11169dd2012-12-18 14:30:41 +00008512 "Already have a SwitchCase with this ID");
8513 (*CurrSwitchCaseStmts)[ID] = SC;
8514}
8515
8516/// \brief Retrieve the switch-case statement with the given ID.
8517SwitchCase *ASTReader::getSwitchCaseWithID(unsigned ID) {
Craig Toppera13603a2014-05-22 05:54:18 +00008518 assert((*CurrSwitchCaseStmts)[ID] != nullptr && "No SwitchCase with this ID");
Guy Benyei11169dd2012-12-18 14:30:41 +00008519 return (*CurrSwitchCaseStmts)[ID];
8520}
8521
8522void ASTReader::ClearSwitchCaseIDs() {
8523 CurrSwitchCaseStmts->clear();
8524}
8525
8526void ASTReader::ReadComments() {
8527 std::vector<RawComment *> Comments;
Chris Lattner7fb3bef2013-01-20 00:56:42 +00008528 for (SmallVectorImpl<std::pair<BitstreamCursor,
Guy Benyei11169dd2012-12-18 14:30:41 +00008529 serialization::ModuleFile *> >::iterator
8530 I = CommentsCursors.begin(),
8531 E = CommentsCursors.end();
8532 I != E; ++I) {
Dmitri Gribenko9ee0e302014-03-27 15:40:39 +00008533 Comments.clear();
Chris Lattner7fb3bef2013-01-20 00:56:42 +00008534 BitstreamCursor &Cursor = I->first;
Guy Benyei11169dd2012-12-18 14:30:41 +00008535 serialization::ModuleFile &F = *I->second;
8536 SavedStreamPosition SavedPosition(Cursor);
8537
8538 RecordData Record;
8539 while (true) {
Chris Lattner7fb3bef2013-01-20 00:56:42 +00008540 llvm::BitstreamEntry Entry =
8541 Cursor.advanceSkippingSubblocks(BitstreamCursor::AF_DontPopBlockAtEnd);
Dmitri Gribenko9ee0e302014-03-27 15:40:39 +00008542
Chris Lattner7fb3bef2013-01-20 00:56:42 +00008543 switch (Entry.Kind) {
8544 case llvm::BitstreamEntry::SubBlock: // Handled for us already.
8545 case llvm::BitstreamEntry::Error:
8546 Error("malformed block record in AST file");
8547 return;
8548 case llvm::BitstreamEntry::EndBlock:
8549 goto NextCursor;
8550 case llvm::BitstreamEntry::Record:
8551 // The interesting case.
Guy Benyei11169dd2012-12-18 14:30:41 +00008552 break;
Guy Benyei11169dd2012-12-18 14:30:41 +00008553 }
8554
8555 // Read a record.
8556 Record.clear();
Chris Lattner0e6c9402013-01-20 02:38:54 +00008557 switch ((CommentRecordTypes)Cursor.readRecord(Entry.ID, Record)) {
Guy Benyei11169dd2012-12-18 14:30:41 +00008558 case COMMENTS_RAW_COMMENT: {
8559 unsigned Idx = 0;
8560 SourceRange SR = ReadSourceRange(F, Record, Idx);
8561 RawComment::CommentKind Kind =
8562 (RawComment::CommentKind) Record[Idx++];
8563 bool IsTrailingComment = Record[Idx++];
8564 bool IsAlmostTrailingComment = Record[Idx++];
Dmitri Gribenkoa7d16ce2013-04-10 15:35:17 +00008565 Comments.push_back(new (Context) RawComment(
8566 SR, Kind, IsTrailingComment, IsAlmostTrailingComment,
8567 Context.getLangOpts().CommentOpts.ParseAllComments));
Guy Benyei11169dd2012-12-18 14:30:41 +00008568 break;
8569 }
8570 }
8571 }
Dmitri Gribenko9ee0e302014-03-27 15:40:39 +00008572 NextCursor:
Bruno Cardoso Lopesc23af572016-12-19 21:06:06 +00008573 // De-serialized SourceLocations get negative FileIDs for other modules,
8574 // potentially invalidating the original order. Sort it again.
8575 std::sort(Comments.begin(), Comments.end(),
8576 BeforeThanCompare<RawComment>(SourceMgr));
Dmitri Gribenko9ee0e302014-03-27 15:40:39 +00008577 Context.Comments.addDeserializedComments(Comments);
Guy Benyei11169dd2012-12-18 14:30:41 +00008578 }
Guy Benyei11169dd2012-12-18 14:30:41 +00008579}
8580
Argyrios Kyrtzidisa38cb202017-01-30 06:05:58 +00008581void ASTReader::visitInputFiles(serialization::ModuleFile &MF,
8582 bool IncludeSystem, bool Complain,
8583 llvm::function_ref<void(const serialization::InputFile &IF,
8584 bool isSystem)> Visitor) {
8585 unsigned NumUserInputs = MF.NumUserInputFiles;
8586 unsigned NumInputs = MF.InputFilesLoaded.size();
8587 assert(NumUserInputs <= NumInputs);
8588 unsigned N = IncludeSystem ? NumInputs : NumUserInputs;
8589 for (unsigned I = 0; I < N; ++I) {
8590 bool IsSystem = I >= NumUserInputs;
8591 InputFile IF = getInputFile(MF, I+1, Complain);
8592 Visitor(IF, IsSystem);
8593 }
8594}
8595
Richard Smithcd45dbc2014-04-19 03:48:30 +00008596std::string ASTReader::getOwningModuleNameForDiagnostic(const Decl *D) {
8597 // If we know the owning module, use it.
Richard Smith42413142015-05-15 20:05:43 +00008598 if (Module *M = D->getImportedOwningModule())
Richard Smithcd45dbc2014-04-19 03:48:30 +00008599 return M->getFullModuleName();
8600
8601 // Otherwise, use the name of the top-level module the decl is within.
8602 if (ModuleFile *M = getOwningModuleFile(D))
8603 return M->ModuleName;
8604
8605 // Not from a module.
8606 return "";
8607}
8608
Guy Benyei11169dd2012-12-18 14:30:41 +00008609void ASTReader::finishPendingActions() {
Richard Smith851072e2014-05-19 20:59:20 +00008610 while (!PendingIdentifierInfos.empty() ||
8611 !PendingIncompleteDeclChains.empty() || !PendingDeclChains.empty() ||
Richard Smith2b9e3e32013-10-18 06:05:18 +00008612 !PendingMacroIDs.empty() || !PendingDeclContextInfos.empty() ||
Richard Smitha0ce9c42014-07-29 23:23:27 +00008613 !PendingUpdateRecords.empty()) {
Guy Benyei11169dd2012-12-18 14:30:41 +00008614 // If any identifiers with corresponding top-level declarations have
8615 // been loaded, load those declarations now.
Craig Topper79be4cd2013-07-05 04:33:53 +00008616 typedef llvm::DenseMap<IdentifierInfo *, SmallVector<Decl *, 2> >
8617 TopLevelDeclsMap;
8618 TopLevelDeclsMap TopLevelDecls;
8619
Guy Benyei11169dd2012-12-18 14:30:41 +00008620 while (!PendingIdentifierInfos.empty()) {
Douglas Gregor6168bd22013-02-18 15:53:43 +00008621 IdentifierInfo *II = PendingIdentifierInfos.back().first;
Richard Smithf0ae3c2d2014-03-28 17:31:23 +00008622 SmallVector<uint32_t, 4> DeclIDs =
8623 std::move(PendingIdentifierInfos.back().second);
Douglas Gregorcb15f082013-02-19 18:26:28 +00008624 PendingIdentifierInfos.pop_back();
Douglas Gregor6168bd22013-02-18 15:53:43 +00008625
8626 SetGloballyVisibleDecls(II, DeclIDs, &TopLevelDecls[II]);
Guy Benyei11169dd2012-12-18 14:30:41 +00008627 }
Richard Smithf0ae3c2d2014-03-28 17:31:23 +00008628
Richard Smith851072e2014-05-19 20:59:20 +00008629 // For each decl chain that we wanted to complete while deserializing, mark
8630 // it as "still needs to be completed".
8631 for (unsigned I = 0; I != PendingIncompleteDeclChains.size(); ++I) {
8632 markIncompleteDeclChain(PendingIncompleteDeclChains[I]);
8633 }
8634 PendingIncompleteDeclChains.clear();
8635
Guy Benyei11169dd2012-12-18 14:30:41 +00008636 // Load pending declaration chains.
Richard Smithd8a83712015-08-22 01:47:18 +00008637 for (unsigned I = 0; I != PendingDeclChains.size(); ++I)
Richard Smithd61d4ac2015-08-22 20:13:39 +00008638 loadPendingDeclChain(PendingDeclChains[I].first, PendingDeclChains[I].second);
Guy Benyei11169dd2012-12-18 14:30:41 +00008639 PendingDeclChains.clear();
8640
Douglas Gregor6168bd22013-02-18 15:53:43 +00008641 // Make the most recent of the top-level declarations visible.
Craig Topper79be4cd2013-07-05 04:33:53 +00008642 for (TopLevelDeclsMap::iterator TLD = TopLevelDecls.begin(),
8643 TLDEnd = TopLevelDecls.end(); TLD != TLDEnd; ++TLD) {
Douglas Gregor6168bd22013-02-18 15:53:43 +00008644 IdentifierInfo *II = TLD->first;
8645 for (unsigned I = 0, N = TLD->second.size(); I != N; ++I) {
Argyrios Kyrtzidise5edbf92013-04-26 21:33:35 +00008646 pushExternalDeclIntoScope(cast<NamedDecl>(TLD->second[I]), II);
Douglas Gregor6168bd22013-02-18 15:53:43 +00008647 }
8648 }
8649
Guy Benyei11169dd2012-12-18 14:30:41 +00008650 // Load any pending macro definitions.
8651 for (unsigned I = 0; I != PendingMacroIDs.size(); ++I) {
Argyrios Kyrtzidiseb663da2013-03-22 21:12:57 +00008652 IdentifierInfo *II = PendingMacroIDs.begin()[I].first;
8653 SmallVector<PendingMacroInfo, 2> GlobalIDs;
8654 GlobalIDs.swap(PendingMacroIDs.begin()[I].second);
8655 // Initialize the macro history from chained-PCHs ahead of module imports.
Richard Smith49f906a2014-03-01 00:08:04 +00008656 for (unsigned IDIdx = 0, NumIDs = GlobalIDs.size(); IDIdx != NumIDs;
Argyrios Kyrtzidis719736c2013-01-19 03:14:56 +00008657 ++IDIdx) {
Argyrios Kyrtzidiseb663da2013-03-22 21:12:57 +00008658 const PendingMacroInfo &Info = GlobalIDs[IDIdx];
Manman Ren11f2a472016-08-18 17:42:15 +00008659 if (!Info.M->isModule())
Argyrios Kyrtzidiseb663da2013-03-22 21:12:57 +00008660 resolvePendingMacro(II, Info);
8661 }
8662 // Handle module imports.
Richard Smith49f906a2014-03-01 00:08:04 +00008663 for (unsigned IDIdx = 0, NumIDs = GlobalIDs.size(); IDIdx != NumIDs;
Argyrios Kyrtzidiseb663da2013-03-22 21:12:57 +00008664 ++IDIdx) {
8665 const PendingMacroInfo &Info = GlobalIDs[IDIdx];
Manman Ren11f2a472016-08-18 17:42:15 +00008666 if (Info.M->isModule())
Argyrios Kyrtzidiseb663da2013-03-22 21:12:57 +00008667 resolvePendingMacro(II, Info);
Guy Benyei11169dd2012-12-18 14:30:41 +00008668 }
8669 }
8670 PendingMacroIDs.clear();
Argyrios Kyrtzidis83a6e3b2013-02-16 00:48:59 +00008671
8672 // Wire up the DeclContexts for Decls that we delayed setting until
8673 // recursive loading is completed.
8674 while (!PendingDeclContextInfos.empty()) {
8675 PendingDeclContextInfo Info = PendingDeclContextInfos.front();
8676 PendingDeclContextInfos.pop_front();
8677 DeclContext *SemaDC = cast<DeclContext>(GetDecl(Info.SemaDC));
8678 DeclContext *LexicalDC = cast<DeclContext>(GetDecl(Info.LexicalDC));
8679 Info.D->setDeclContextsImpl(SemaDC, LexicalDC, getContext());
8680 }
Richard Smith2b9e3e32013-10-18 06:05:18 +00008681
Richard Smithd1c46742014-04-30 02:24:17 +00008682 // Perform any pending declaration updates.
Richard Smithd6db68c2014-08-07 20:58:41 +00008683 while (!PendingUpdateRecords.empty()) {
Richard Smithd1c46742014-04-30 02:24:17 +00008684 auto Update = PendingUpdateRecords.pop_back_val();
8685 ReadingKindTracker ReadingKind(Read_Decl, *this);
8686 loadDeclUpdateRecords(Update.first, Update.second);
8687 }
Guy Benyei11169dd2012-12-18 14:30:41 +00008688 }
Richard Smith8a639892015-01-24 01:07:20 +00008689
8690 // At this point, all update records for loaded decls are in place, so any
8691 // fake class definitions should have become real.
8692 assert(PendingFakeDefinitionData.empty() &&
8693 "faked up a class definition but never saw the real one");
8694
Guy Benyei11169dd2012-12-18 14:30:41 +00008695 // If we deserialized any C++ or Objective-C class definitions, any
8696 // Objective-C protocol definitions, or any redeclarable templates, make sure
David L. Jonesc4808b9e2016-12-15 20:53:26 +00008697 // that all redeclarations point to the definitions. Note that this can only
Guy Benyei11169dd2012-12-18 14:30:41 +00008698 // happen now, after the redeclaration chains have been fully wired.
Craig Topperc6914d02014-08-25 04:15:02 +00008699 for (Decl *D : PendingDefinitions) {
8700 if (TagDecl *TD = dyn_cast<TagDecl>(D)) {
Richard Smith5b21db82014-04-23 18:20:42 +00008701 if (const TagType *TagT = dyn_cast<TagType>(TD->getTypeForDecl())) {
Guy Benyei11169dd2012-12-18 14:30:41 +00008702 // Make sure that the TagType points at the definition.
8703 const_cast<TagType*>(TagT)->decl = TD;
8704 }
Richard Smith8ce51082015-03-11 01:44:51 +00008705
Craig Topperc6914d02014-08-25 04:15:02 +00008706 if (auto RD = dyn_cast<CXXRecordDecl>(D)) {
Richard Smith8ce51082015-03-11 01:44:51 +00008707 for (auto *R = getMostRecentExistingDecl(RD); R;
8708 R = R->getPreviousDecl()) {
8709 assert((R == D) ==
8710 cast<CXXRecordDecl>(R)->isThisDeclarationADefinition() &&
Richard Smith2c381642014-08-27 23:11:59 +00008711 "declaration thinks it's the definition but it isn't");
Aaron Ballman86c93902014-03-06 23:45:36 +00008712 cast<CXXRecordDecl>(R)->DefinitionData = RD->DefinitionData;
Richard Smith2c381642014-08-27 23:11:59 +00008713 }
Guy Benyei11169dd2012-12-18 14:30:41 +00008714 }
8715
8716 continue;
8717 }
Richard Smith8ce51082015-03-11 01:44:51 +00008718
Craig Topperc6914d02014-08-25 04:15:02 +00008719 if (auto ID = dyn_cast<ObjCInterfaceDecl>(D)) {
Guy Benyei11169dd2012-12-18 14:30:41 +00008720 // Make sure that the ObjCInterfaceType points at the definition.
8721 const_cast<ObjCInterfaceType *>(cast<ObjCInterfaceType>(ID->TypeForDecl))
8722 ->Decl = ID;
Richard Smith8ce51082015-03-11 01:44:51 +00008723
8724 for (auto *R = getMostRecentExistingDecl(ID); R; R = R->getPreviousDecl())
8725 cast<ObjCInterfaceDecl>(R)->Data = ID->Data;
8726
Guy Benyei11169dd2012-12-18 14:30:41 +00008727 continue;
8728 }
Richard Smith8ce51082015-03-11 01:44:51 +00008729
Craig Topperc6914d02014-08-25 04:15:02 +00008730 if (auto PD = dyn_cast<ObjCProtocolDecl>(D)) {
Richard Smith8ce51082015-03-11 01:44:51 +00008731 for (auto *R = getMostRecentExistingDecl(PD); R; R = R->getPreviousDecl())
8732 cast<ObjCProtocolDecl>(R)->Data = PD->Data;
8733
Guy Benyei11169dd2012-12-18 14:30:41 +00008734 continue;
8735 }
Richard Smith8ce51082015-03-11 01:44:51 +00008736
Craig Topperc6914d02014-08-25 04:15:02 +00008737 auto RTD = cast<RedeclarableTemplateDecl>(D)->getCanonicalDecl();
Richard Smith8ce51082015-03-11 01:44:51 +00008738 for (auto *R = getMostRecentExistingDecl(RTD); R; R = R->getPreviousDecl())
8739 cast<RedeclarableTemplateDecl>(R)->Common = RTD->Common;
Guy Benyei11169dd2012-12-18 14:30:41 +00008740 }
8741 PendingDefinitions.clear();
8742
8743 // Load the bodies of any functions or methods we've encountered. We do
8744 // this now (delayed) so that we can be sure that the declaration chains
Richard Smithb9fa9962015-08-21 03:04:33 +00008745 // have been fully wired up (hasBody relies on this).
8746 // FIXME: We shouldn't require complete redeclaration chains here.
Guy Benyei11169dd2012-12-18 14:30:41 +00008747 for (PendingBodiesMap::iterator PB = PendingBodies.begin(),
8748 PBEnd = PendingBodies.end();
8749 PB != PBEnd; ++PB) {
8750 if (FunctionDecl *FD = dyn_cast<FunctionDecl>(PB->first)) {
8751 // FIXME: Check for =delete/=default?
8752 // FIXME: Complain about ODR violations here?
Richard Smith6561f922016-09-12 21:06:40 +00008753 const FunctionDecl *Defn = nullptr;
8754 if (!getContext().getLangOpts().Modules || !FD->hasBody(Defn))
Guy Benyei11169dd2012-12-18 14:30:41 +00008755 FD->setLazyBody(PB->second);
Benjamin Kramera72a70a2016-10-17 13:00:44 +00008756 else
Richard Smith6561f922016-09-12 21:06:40 +00008757 mergeDefinitionVisibility(const_cast<FunctionDecl*>(Defn), FD);
Guy Benyei11169dd2012-12-18 14:30:41 +00008758 continue;
8759 }
8760
8761 ObjCMethodDecl *MD = cast<ObjCMethodDecl>(PB->first);
8762 if (!getContext().getLangOpts().Modules || !MD->hasBody())
8763 MD->setLazyBody(PB->second);
8764 }
8765 PendingBodies.clear();
Richard Smith42413142015-05-15 20:05:43 +00008766
8767 // Do some cleanup.
8768 for (auto *ND : PendingMergedDefinitionsToDeduplicate)
8769 getContext().deduplicateMergedDefinitonsFor(ND);
8770 PendingMergedDefinitionsToDeduplicate.clear();
Richard Smitha0ce9c42014-07-29 23:23:27 +00008771}
8772
8773void ASTReader::diagnoseOdrViolations() {
Richard Smithbb853c72014-08-13 01:23:33 +00008774 if (PendingOdrMergeFailures.empty() && PendingOdrMergeChecks.empty())
8775 return;
8776
Richard Smitha0ce9c42014-07-29 23:23:27 +00008777 // Trigger the import of the full definition of each class that had any
8778 // odr-merging problems, so we can produce better diagnostics for them.
Richard Smithbb853c72014-08-13 01:23:33 +00008779 // These updates may in turn find and diagnose some ODR failures, so take
8780 // ownership of the set first.
8781 auto OdrMergeFailures = std::move(PendingOdrMergeFailures);
8782 PendingOdrMergeFailures.clear();
8783 for (auto &Merge : OdrMergeFailures) {
Richard Smitha0ce9c42014-07-29 23:23:27 +00008784 Merge.first->buildLookup();
8785 Merge.first->decls_begin();
8786 Merge.first->bases_begin();
8787 Merge.first->vbases_begin();
8788 for (auto *RD : Merge.second) {
8789 RD->decls_begin();
8790 RD->bases_begin();
8791 RD->vbases_begin();
8792 }
8793 }
8794
8795 // For each declaration from a merged context, check that the canonical
8796 // definition of that context also contains a declaration of the same
8797 // entity.
8798 //
8799 // Caution: this loop does things that might invalidate iterators into
8800 // PendingOdrMergeChecks. Don't turn this into a range-based for loop!
8801 while (!PendingOdrMergeChecks.empty()) {
8802 NamedDecl *D = PendingOdrMergeChecks.pop_back_val();
8803
8804 // FIXME: Skip over implicit declarations for now. This matters for things
8805 // like implicitly-declared special member functions. This isn't entirely
8806 // correct; we can end up with multiple unmerged declarations of the same
8807 // implicit entity.
8808 if (D->isImplicit())
8809 continue;
8810
8811 DeclContext *CanonDef = D->getDeclContext();
Richard Smitha0ce9c42014-07-29 23:23:27 +00008812
8813 bool Found = false;
8814 const Decl *DCanon = D->getCanonicalDecl();
8815
Richard Smith01bdb7a2014-08-28 05:44:07 +00008816 for (auto RI : D->redecls()) {
8817 if (RI->getLexicalDeclContext() == CanonDef) {
8818 Found = true;
8819 break;
8820 }
8821 }
8822 if (Found)
8823 continue;
8824
Richard Smith0f4e2c42015-08-06 04:23:48 +00008825 // Quick check failed, time to do the slow thing. Note, we can't just
8826 // look up the name of D in CanonDef here, because the member that is
8827 // in CanonDef might not be found by name lookup (it might have been
8828 // replaced by a more recent declaration in the lookup table), and we
8829 // can't necessarily find it in the redeclaration chain because it might
8830 // be merely mergeable, not redeclarable.
Richard Smitha0ce9c42014-07-29 23:23:27 +00008831 llvm::SmallVector<const NamedDecl*, 4> Candidates;
Richard Smith0f4e2c42015-08-06 04:23:48 +00008832 for (auto *CanonMember : CanonDef->decls()) {
8833 if (CanonMember->getCanonicalDecl() == DCanon) {
8834 // This can happen if the declaration is merely mergeable and not
8835 // actually redeclarable (we looked for redeclarations earlier).
8836 //
8837 // FIXME: We should be able to detect this more efficiently, without
8838 // pulling in all of the members of CanonDef.
8839 Found = true;
8840 break;
Richard Smitha0ce9c42014-07-29 23:23:27 +00008841 }
Richard Smith0f4e2c42015-08-06 04:23:48 +00008842 if (auto *ND = dyn_cast<NamedDecl>(CanonMember))
8843 if (ND->getDeclName() == D->getDeclName())
8844 Candidates.push_back(ND);
Richard Smitha0ce9c42014-07-29 23:23:27 +00008845 }
8846
8847 if (!Found) {
Richard Smithd08aeb62014-08-28 01:33:39 +00008848 // The AST doesn't like TagDecls becoming invalid after they've been
8849 // completed. We only really need to mark FieldDecls as invalid here.
8850 if (!isa<TagDecl>(D))
8851 D->setInvalidDecl();
David L. Jonesc4808b9e2016-12-15 20:53:26 +00008852
Richard Smith4ab3dbd2015-02-13 22:43:51 +00008853 // Ensure we don't accidentally recursively enter deserialization while
8854 // we're producing our diagnostic.
8855 Deserializing RecursionGuard(this);
Richard Smitha0ce9c42014-07-29 23:23:27 +00008856
8857 std::string CanonDefModule =
8858 getOwningModuleNameForDiagnostic(cast<Decl>(CanonDef));
8859 Diag(D->getLocation(), diag::err_module_odr_violation_missing_decl)
8860 << D << getOwningModuleNameForDiagnostic(D)
8861 << CanonDef << CanonDefModule.empty() << CanonDefModule;
8862
8863 if (Candidates.empty())
8864 Diag(cast<Decl>(CanonDef)->getLocation(),
8865 diag::note_module_odr_violation_no_possible_decls) << D;
8866 else {
8867 for (unsigned I = 0, N = Candidates.size(); I != N; ++I)
8868 Diag(Candidates[I]->getLocation(),
8869 diag::note_module_odr_violation_possible_decl)
8870 << Candidates[I];
8871 }
8872
8873 DiagnosedOdrMergeFailures.insert(CanonDef);
8874 }
8875 }
Richard Smithcd45dbc2014-04-19 03:48:30 +00008876
Richard Smith4ab3dbd2015-02-13 22:43:51 +00008877 if (OdrMergeFailures.empty())
8878 return;
8879
8880 // Ensure we don't accidentally recursively enter deserialization while
8881 // we're producing our diagnostics.
8882 Deserializing RecursionGuard(this);
8883
Richard Smithcd45dbc2014-04-19 03:48:30 +00008884 // Issue any pending ODR-failure diagnostics.
Richard Smithbb853c72014-08-13 01:23:33 +00008885 for (auto &Merge : OdrMergeFailures) {
Richard Smitha0ce9c42014-07-29 23:23:27 +00008886 // If we've already pointed out a specific problem with this class, don't
8887 // bother issuing a general "something's different" diagnostic.
David Blaikie82e95a32014-11-19 07:49:47 +00008888 if (!DiagnosedOdrMergeFailures.insert(Merge.first).second)
Richard Smithcd45dbc2014-04-19 03:48:30 +00008889 continue;
8890
8891 bool Diagnosed = false;
8892 for (auto *RD : Merge.second) {
8893 // Multiple different declarations got merged together; tell the user
8894 // where they came from.
Richard Trieudc4cb022017-02-17 07:19:24 +00008895 if (Merge.first != RD) {
8896 // FIXME: Walk the definition, figure out what's different,
8897 // and diagnose that.
8898 if (!Diagnosed) {
8899 std::string Module = getOwningModuleNameForDiagnostic(Merge.first);
8900 Diag(Merge.first->getLocation(),
8901 diag::err_module_odr_violation_different_definitions)
Richard Trieucb6b7262017-02-17 05:54:30 +00008902 << Merge.first << Module.empty() << Module;
Richard Trieudc4cb022017-02-17 07:19:24 +00008903 Diagnosed = true;
8904 }
Richard Smithcd45dbc2014-04-19 03:48:30 +00008905
8906 Diag(RD->getLocation(),
8907 diag::note_module_odr_violation_different_definitions)
Richard Trieudc4cb022017-02-17 07:19:24 +00008908 << getOwningModuleNameForDiagnostic(RD);
Richard Smithcd45dbc2014-04-19 03:48:30 +00008909 }
8910 }
8911
8912 if (!Diagnosed) {
8913 // All definitions are updates to the same declaration. This happens if a
8914 // module instantiates the declaration of a class template specialization
8915 // and two or more other modules instantiate its definition.
8916 //
8917 // FIXME: Indicate which modules had instantiations of this definition.
8918 // FIXME: How can this even happen?
8919 Diag(Merge.first->getLocation(),
8920 diag::err_module_odr_violation_different_instantiations)
8921 << Merge.first;
8922 }
8923 }
Guy Benyei11169dd2012-12-18 14:30:41 +00008924}
8925
Richard Smithce18a182015-07-14 00:26:00 +00008926void ASTReader::StartedDeserializing() {
David L. Jonesc4808b9e2016-12-15 20:53:26 +00008927 if (++NumCurrentElementsDeserializing == 1 && ReadTimer.get())
Richard Smithce18a182015-07-14 00:26:00 +00008928 ReadTimer->startTimer();
8929}
8930
Guy Benyei11169dd2012-12-18 14:30:41 +00008931void ASTReader::FinishedDeserializing() {
8932 assert(NumCurrentElementsDeserializing &&
8933 "FinishedDeserializing not paired with StartedDeserializing");
8934 if (NumCurrentElementsDeserializing == 1) {
8935 // We decrease NumCurrentElementsDeserializing only after pending actions
8936 // are finished, to avoid recursively re-calling finishPendingActions().
8937 finishPendingActions();
8938 }
8939 --NumCurrentElementsDeserializing;
8940
Richard Smitha0ce9c42014-07-29 23:23:27 +00008941 if (NumCurrentElementsDeserializing == 0) {
Richard Smith9e2341d2015-03-23 03:25:59 +00008942 // Propagate exception specification updates along redeclaration chains.
Richard Smith7226f2a2015-03-23 19:54:56 +00008943 while (!PendingExceptionSpecUpdates.empty()) {
8944 auto Updates = std::move(PendingExceptionSpecUpdates);
8945 PendingExceptionSpecUpdates.clear();
8946 for (auto Update : Updates) {
Vassil Vassilev19765fb2016-07-22 21:08:24 +00008947 ProcessingUpdatesRAIIObj ProcessingUpdates(*this);
Richard Smith7226f2a2015-03-23 19:54:56 +00008948 auto *FPT = Update.second->getType()->castAs<FunctionProtoType>();
Richard Smith1d0f1992015-08-19 21:09:32 +00008949 auto ESI = FPT->getExtProtoInfo().ExceptionSpec;
Richard Smithd88a7f12015-09-01 20:35:42 +00008950 if (auto *Listener = Context.getASTMutationListener())
8951 Listener->ResolvedExceptionSpec(cast<FunctionDecl>(Update.second));
Richard Smith1d0f1992015-08-19 21:09:32 +00008952 for (auto *Redecl : Update.second->redecls())
8953 Context.adjustExceptionSpec(cast<FunctionDecl>(Redecl), ESI);
Richard Smith7226f2a2015-03-23 19:54:56 +00008954 }
Richard Smith9e2341d2015-03-23 03:25:59 +00008955 }
8956
Richard Smithce18a182015-07-14 00:26:00 +00008957 if (ReadTimer)
8958 ReadTimer->stopTimer();
8959
Richard Smith0f4e2c42015-08-06 04:23:48 +00008960 diagnoseOdrViolations();
8961
Richard Smith04d05b52014-03-23 00:27:18 +00008962 // We are not in recursive loading, so it's safe to pass the "interesting"
8963 // decls to the consumer.
Richard Smitha0ce9c42014-07-29 23:23:27 +00008964 if (Consumer)
8965 PassInterestingDeclsToConsumer();
Guy Benyei11169dd2012-12-18 14:30:41 +00008966 }
8967}
8968
Argyrios Kyrtzidise5edbf92013-04-26 21:33:35 +00008969void ASTReader::pushExternalDeclIntoScope(NamedDecl *D, DeclarationName Name) {
Richard Smith9e2341d2015-03-23 03:25:59 +00008970 if (IdentifierInfo *II = Name.getAsIdentifierInfo()) {
8971 // Remove any fake results before adding any real ones.
8972 auto It = PendingFakeLookupResults.find(II);
8973 if (It != PendingFakeLookupResults.end()) {
Richard Smitha534a312015-07-21 23:54:07 +00008974 for (auto *ND : It->second)
Richard Smith9e2341d2015-03-23 03:25:59 +00008975 SemaObj->IdResolver.RemoveDecl(ND);
Ben Langmuireb8bd2d2015-04-10 22:25:42 +00008976 // FIXME: this works around module+PCH performance issue.
8977 // Rather than erase the result from the map, which is O(n), just clear
8978 // the vector of NamedDecls.
8979 It->second.clear();
Richard Smith9e2341d2015-03-23 03:25:59 +00008980 }
8981 }
Argyrios Kyrtzidise5edbf92013-04-26 21:33:35 +00008982
8983 if (SemaObj->IdResolver.tryAddTopLevelDecl(D, Name) && SemaObj->TUScope) {
8984 SemaObj->TUScope->AddDecl(D);
8985 } else if (SemaObj->TUScope) {
8986 // Adding the decl to IdResolver may have failed because it was already in
8987 // (even though it was not added in scope). If it is already in, make sure
8988 // it gets in the scope as well.
8989 if (std::find(SemaObj->IdResolver.begin(Name),
8990 SemaObj->IdResolver.end(), D) != SemaObj->IdResolver.end())
8991 SemaObj->TUScope->AddDecl(D);
8992 }
8993}
8994
David Blaikie61137e12017-01-05 18:23:18 +00008995ASTReader::ASTReader(Preprocessor &PP, ASTContext &Context,
8996 const PCHContainerReader &PCHContainerRdr,
8997 ArrayRef<std::shared_ptr<ModuleFileExtension>> Extensions,
8998 StringRef isysroot, bool DisableValidation,
8999 bool AllowASTWithCompilerErrors,
9000 bool AllowConfigurationMismatch, bool ValidateSystemInputs,
9001 bool UseGlobalIndex,
9002 std::unique_ptr<llvm::Timer> ReadTimer)
9003 : Listener(DisableValidation
9004 ? cast<ASTReaderListener>(new SimpleASTReaderListener(PP))
9005 : cast<ASTReaderListener>(new PCHValidator(PP, *this))),
David Blaikie61137e12017-01-05 18:23:18 +00009006 SourceMgr(PP.getSourceManager()), FileMgr(PP.getFileManager()),
David Blaikie9d7c1ba2017-01-05 18:45:43 +00009007 PCHContainerRdr(PCHContainerRdr), Diags(PP.getDiagnostics()), PP(PP),
9008 Context(Context), ModuleMgr(PP.getFileManager(), PCHContainerRdr),
9009 DummyIdResolver(PP), ReadTimer(std::move(ReadTimer)), isysroot(isysroot),
David Blaikie61137e12017-01-05 18:23:18 +00009010 DisableValidation(DisableValidation),
Nico Weber824285e2014-05-08 04:26:47 +00009011 AllowASTWithCompilerErrors(AllowASTWithCompilerErrors),
9012 AllowConfigurationMismatch(AllowConfigurationMismatch),
9013 ValidateSystemInputs(ValidateSystemInputs),
David Blaikie9d7c1ba2017-01-05 18:45:43 +00009014 UseGlobalIndex(UseGlobalIndex), CurrSwitchCaseStmts(&SwitchCaseStmts) {
Guy Benyei11169dd2012-12-18 14:30:41 +00009015 SourceMgr.setExternalSLocEntrySource(this);
Douglas Gregor6623e1f2015-11-03 18:33:07 +00009016
9017 for (const auto &Ext : Extensions) {
9018 auto BlockName = Ext->getExtensionMetadata().BlockName;
9019 auto Known = ModuleFileExtensions.find(BlockName);
9020 if (Known != ModuleFileExtensions.end()) {
9021 Diags.Report(diag::warn_duplicate_module_file_extension)
9022 << BlockName;
9023 continue;
9024 }
9025
9026 ModuleFileExtensions.insert({BlockName, Ext});
9027 }
Guy Benyei11169dd2012-12-18 14:30:41 +00009028}
9029
9030ASTReader::~ASTReader() {
Nico Weber824285e2014-05-08 04:26:47 +00009031 if (OwnsDeserializationListener)
9032 delete DeserializationListener;
Guy Benyei11169dd2012-12-18 14:30:41 +00009033}
Richard Smith10379092016-05-06 23:14:07 +00009034
9035IdentifierResolver &ASTReader::getIdResolver() {
9036 return SemaObj ? SemaObj->IdResolver : DummyIdResolver;
9037}
David L. Jonesbe1557a2016-12-21 00:17:49 +00009038
9039unsigned ASTRecordReader::readRecord(llvm::BitstreamCursor &Cursor,
9040 unsigned AbbrevID) {
9041 Idx = 0;
9042 Record.clear();
9043 return Cursor.readRecord(AbbrevID, Record);
9044}